1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1075.2.140 2019/11/20 23:05:45 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:
87: # ---------------------------------------------- Designs
88: use vars qw(%defaultdesign);
89:
90: my $readit;
91:
92:
93: ##
94: ## Global Variables
95: ##
96:
97:
98: # ----------------------------------------------- SSI with retries:
99: #
100:
101: =pod
102:
103: =head1 Server Side include with retries:
104:
105: =over 4
106:
107: =item * &ssi_with_retries(resource,retries form)
108:
109: Performs an ssi with some number of retries. Retries continue either
110: until the result is ok or until the retry count supplied by the
111: caller is exhausted.
112:
113: Inputs:
114:
115: =over 4
116:
117: resource - Identifies the resource to insert.
118:
119: retries - Count of the number of retries allowed.
120:
121: form - Hash that identifies the rendering options.
122:
123: =back
124:
125: Returns:
126:
127: =over 4
128:
129: content - The content of the response. If retries were exhausted this is empty.
130:
131: response - The response from the last attempt (which may or may not have been successful.
132:
133: =back
134:
135: =back
136:
137: =cut
138:
139: sub ssi_with_retries {
140: my ($resource, $retries, %form) = @_;
141:
142:
143: my $ok = 0; # True if we got a good response.
144: my $content;
145: my $response;
146:
147: # Try to get the ssi done. within the retries count:
148:
149: do {
150: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
151: $ok = $response->is_success;
152: if (!$ok) {
153: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
154: }
155: $retries--;
156: } while (!$ok && ($retries > 0));
157:
158: if (!$ok) {
159: $content = ''; # On error return an empty content.
160: }
161: return ($content, $response);
162:
163: }
164:
165:
166:
167: # ----------------------------------------------- Filetypes/Languages/Copyright
168: my %language;
169: my %supported_language;
170: my %latex_language; # For choosing hyphenation in <transl..>
171: my %latex_language_bykey; # for choosing hyphenation from metadata
172: my %cprtag;
173: my %scprtag;
174: my %fe; my %fd; my %fm;
175: my %category_extensions;
176:
177: # ---------------------------------------------- Thesaurus variables
178: #
179: # %Keywords:
180: # A hash used by &keyword to determine if a word is considered a keyword.
181: # $thesaurus_db_file
182: # Scalar containing the full path to the thesaurus database.
183:
184: my %Keywords;
185: my $thesaurus_db_file;
186:
187: #
188: # Initialize values from language.tab, copyright.tab, filetypes.tab,
189: # thesaurus.tab, and filecategories.tab.
190: #
191: BEGIN {
192: # Variable initialization
193: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
194: #
195: unless ($readit) {
196: # ------------------------------------------------------------------- languages
197: {
198: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
199: '/language.tab';
200: if ( open(my $fh,'<',$langtabfile) ) {
201: while (my $line = <$fh>) {
202: next if ($line=~/^\#/);
203: chomp($line);
204: my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
205: $language{$key}=$val.' - '.$enc;
206: if ($sup) {
207: $supported_language{$key}=$sup;
208: }
209: if ($latex) {
210: $latex_language_bykey{$key} = $latex;
211: $latex_language{$two} = $latex;
212: }
213: }
214: close($fh);
215: }
216: }
217: # ------------------------------------------------------------------ copyrights
218: {
219: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
220: '/copyright.tab';
221: if ( open (my $fh,'<',$copyrightfile) ) {
222: while (my $line = <$fh>) {
223: next if ($line=~/^\#/);
224: chomp($line);
225: my ($key,$val)=(split(/\s+/,$line,2));
226: $cprtag{$key}=$val;
227: }
228: close($fh);
229: }
230: }
231: # ----------------------------------------------------------- source copyrights
232: {
233: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
234: '/source_copyright.tab';
235: if ( open (my $fh,'<',$sourcecopyrightfile) ) {
236: while (my $line = <$fh>) {
237: next if ($line =~ /^\#/);
238: chomp($line);
239: my ($key,$val)=(split(/\s+/,$line,2));
240: $scprtag{$key}=$val;
241: }
242: close($fh);
243: }
244: }
245:
246: # -------------------------------------------------------------- default domain designs
247: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
248: my $designfile = $designdir.'/default.tab';
249: if ( open (my $fh,'<',$designfile) ) {
250: while (my $line = <$fh>) {
251: next if ($line =~ /^\#/);
252: chomp($line);
253: my ($key,$val)=(split(/\=/,$line));
254: if ($val) { $defaultdesign{$key}=$val; }
255: }
256: close($fh);
257: }
258:
259: # ------------------------------------------------------------- file categories
260: {
261: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
262: '/filecategories.tab';
263: if ( open (my $fh,'<',$categoryfile) ) {
264: while (my $line = <$fh>) {
265: next if ($line =~ /^\#/);
266: chomp($line);
267: my ($extension,$category)=(split(/\s+/,$line,2));
268: push(@{$category_extensions{lc($category)}},$extension);
269: }
270: close($fh);
271: }
272:
273: }
274: # ------------------------------------------------------------------ file types
275: {
276: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
277: '/filetypes.tab';
278: if ( open (my $fh,'<',$typesfile) ) {
279: while (my $line = <$fh>) {
280: next if ($line =~ /^\#/);
281: chomp($line);
282: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
283: if ($descr ne '') {
284: $fe{$ending}=lc($emb);
285: $fd{$ending}=$descr;
286: if ($mime ne 'unk') { $fm{$ending}=$mime; }
287: }
288: }
289: close($fh);
290: }
291: }
292: &Apache::lonnet::logthis(
293: "<span style='color:yellow;'>INFO: Read file types</span>");
294: $readit=1;
295: } # end of unless($readit)
296:
297: }
298:
299: ###############################################################
300: ## HTML and Javascript Helper Functions ##
301: ###############################################################
302:
303: =pod
304:
305: =head1 HTML and Javascript Functions
306:
307: =over 4
308:
309: =item * &browser_and_searcher_javascript()
310:
311: X<browsing, javascript>X<searching, javascript>Returns a string
312: containing javascript with two functions, C<openbrowser> and
313: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
314: tags.
315:
316: =item * &openbrowser(formname,elementname,only,omit) [javascript]
317:
318: inputs: formname, elementname, only, omit
319:
320: formname and elementname indicate the name of the html form and name of
321: the element that the results of the browsing selection are to be placed in.
322:
323: Specifying 'only' will restrict the browser to displaying only files
324: with the given extension. Can be a comma separated list.
325:
326: Specifying 'omit' will restrict the browser to NOT displaying files
327: with the given extension. Can be a comma separated list.
328:
329: =item * &opensearcher(formname,elementname) [javascript]
330:
331: Inputs: formname, elementname
332:
333: formname and elementname specify the name of the html form and the name
334: of the element the selection from the search results will be placed in.
335:
336: =cut
337:
338: sub browser_and_searcher_javascript {
339: my ($mode)=@_;
340: if (!defined($mode)) { $mode='edit'; }
341: my $resurl=&escape_single(&lastresurl());
342: return <<END;
343: // <!-- BEGIN LON-CAPA Internal
344: var editbrowser = null;
345: function openbrowser(formname,elementname,only,omit,titleelement) {
346: var url = '$resurl/?';
347: if (editbrowser == null) {
348: url += 'launch=1&';
349: }
350: url += 'catalogmode=interactive&';
351: url += 'mode=$mode&';
352: url += 'inhibitmenu=yes&';
353: url += 'form=' + formname + '&';
354: if (only != null) {
355: url += 'only=' + only + '&';
356: } else {
357: url += 'only=&';
358: }
359: if (omit != null) {
360: url += 'omit=' + omit + '&';
361: } else {
362: url += 'omit=&';
363: }
364: if (titleelement != null) {
365: url += 'titleelement=' + titleelement + '&';
366: } else {
367: url += 'titleelement=&';
368: }
369: url += 'element=' + elementname + '';
370: var title = 'Browser';
371: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
372: options += ',width=700,height=600';
373: editbrowser = open(url,title,options,'1');
374: editbrowser.focus();
375: }
376: var editsearcher;
377: function opensearcher(formname,elementname,titleelement) {
378: var url = '/adm/searchcat?';
379: if (editsearcher == null) {
380: url += 'launch=1&';
381: }
382: url += 'catalogmode=interactive&';
383: url += 'mode=$mode&';
384: url += 'form=' + formname + '&';
385: if (titleelement != null) {
386: url += 'titleelement=' + titleelement + '&';
387: } else {
388: url += 'titleelement=&';
389: }
390: url += 'element=' + elementname + '';
391: var title = 'Search';
392: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
393: options += ',width=700,height=600';
394: editsearcher = open(url,title,options,'1');
395: editsearcher.focus();
396: }
397: // END LON-CAPA Internal -->
398: END
399: }
400:
401: sub lastresurl {
402: if ($env{'environment.lastresurl'}) {
403: return $env{'environment.lastresurl'}
404: } else {
405: return '/res';
406: }
407: }
408:
409: sub storeresurl {
410: my $resurl=&Apache::lonnet::clutter(shift);
411: unless ($resurl=~/^\/res/) { return 0; }
412: $resurl=~s/\/$//;
413: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
414: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
415: return 1;
416: }
417:
418: sub studentbrowser_javascript {
419: unless (
420: (($env{'request.course.id'}) &&
421: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
422: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
423: '/'.$env{'request.course.sec'})
424: ))
425: || ($env{'request.role'}=~/^(au|dc|su)/)
426: ) { return ''; }
427: return (<<'ENDSTDBRW');
428: <script type="text/javascript" language="Javascript">
429: // <![CDATA[
430: var stdeditbrowser;
431: function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
432: var url = '/adm/pickstudent?';
433: var filter;
434: if (!ignorefilter) {
435: eval('filter=document.'+formname+'.'+uname+'.value;');
436: }
437: if (filter != null) {
438: if (filter != '') {
439: url += 'filter='+filter+'&';
440: }
441: }
442: url += 'form=' + formname + '&unameelement='+uname+
443: '&udomelement='+udom+
444: '&clicker='+clicker;
445: if (roleflag) { url+="&roles=1"; }
446: if (courseadvonly) { url+="&courseadvonly=1"; }
447: var title = 'Student_Browser';
448: var options = 'scrollbars=1,resizable=1,menubar=0';
449: options += ',width=700,height=600';
450: stdeditbrowser = open(url,title,options,'1');
451: stdeditbrowser.focus();
452: }
453: // ]]>
454: </script>
455: ENDSTDBRW
456: }
457:
458: sub resourcebrowser_javascript {
459: unless ($env{'request.course.id'}) { return ''; }
460: return (<<'ENDRESBRW');
461: <script type="text/javascript" language="Javascript">
462: // <![CDATA[
463: var reseditbrowser;
464: function openresbrowser(formname,reslink) {
465: var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
466: var title = 'Resource_Browser';
467: var options = 'scrollbars=1,resizable=1,menubar=0';
468: options += ',width=700,height=500';
469: reseditbrowser = open(url,title,options,'1');
470: reseditbrowser.focus();
471: }
472: // ]]>
473: </script>
474: ENDRESBRW
475: }
476:
477: sub selectstudent_link {
478: my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
479: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
480: &Apache::lonhtmlcommon::entity_encode($unameele)."','".
481: &Apache::lonhtmlcommon::entity_encode($udomele)."'";
482: if ($env{'request.course.id'}) {
483: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
484: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
485: '/'.$env{'request.course.sec'})) {
486: return '';
487: }
488: $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
489: if ($courseadvonly) {
490: $callargs .= ",'',1,1";
491: }
492: return '<span class="LC_nobreak">'.
493: '<a href="javascript:openstdbrowser('.$callargs.');">'.
494: &mt('Select User').'</a></span>';
495: }
496: if ($env{'request.role'}=~/^(au|dc|su)/) {
497: $callargs .= ",'',1";
498: return '<span class="LC_nobreak">'.
499: '<a href="javascript:openstdbrowser('.$callargs.');">'.
500: &mt('Select User').'</a></span>';
501: }
502: return '';
503: }
504:
505: sub selectresource_link {
506: my ($form,$reslink,$arg)=@_;
507:
508: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
509: &Apache::lonhtmlcommon::entity_encode($reslink)."'";
510: unless ($env{'request.course.id'}) { return $arg; }
511: return '<span class="LC_nobreak">'.
512: '<a href="javascript:openresbrowser('.$callargs.');">'.
513: $arg.'</a></span>';
514: }
515:
516:
517:
518: sub authorbrowser_javascript {
519: return <<"ENDAUTHORBRW";
520: <script type="text/javascript" language="JavaScript">
521: // <![CDATA[
522: var stdeditbrowser;
523:
524: function openauthorbrowser(formname,udom) {
525: var url = '/adm/pickauthor?';
526: url += 'form='+formname+'&roledom='+udom;
527: var title = 'Author_Browser';
528: var options = 'scrollbars=1,resizable=1,menubar=0';
529: options += ',width=700,height=600';
530: stdeditbrowser = open(url,title,options,'1');
531: stdeditbrowser.focus();
532: }
533:
534: // ]]>
535: </script>
536: ENDAUTHORBRW
537: }
538:
539: sub coursebrowser_javascript {
540: my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
541: $credits_element,$instcode) = @_;
542: my $wintitle = 'Course_Browser';
543: if ($crstype eq 'Community') {
544: $wintitle = 'Community_Browser';
545: }
546: my $id_functions = &javascript_index_functions();
547: my $output = '
548: <script type="text/javascript" language="JavaScript">
549: // <![CDATA[
550: var stdeditbrowser;'."\n";
551:
552: $output .= <<"ENDSTDBRW";
553: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
554: var url = '/adm/pickcourse?';
555: var formid = getFormIdByName(formname);
556: var domainfilter = getDomainFromSelectbox(formname,udom);
557: if (domainfilter != null) {
558: if (domainfilter != '') {
559: url += 'domainfilter='+domainfilter+'&';
560: }
561: }
562: url += 'form=' + formname + '&cnumelement='+uname+
563: '&cdomelement='+udom+
564: '&cnameelement='+desc;
565: if (extra_element !=null && extra_element != '') {
566: if (formname == 'rolechoice' || formname == 'studentform') {
567: url += '&roleelement='+extra_element;
568: if (domainfilter == null || domainfilter == '') {
569: url += '&domainfilter='+extra_element;
570: }
571: }
572: else {
573: if (formname == 'portform') {
574: url += '&setroles='+extra_element;
575: } else {
576: if (formname == 'rules') {
577: url += '&fixeddom='+extra_element;
578: }
579: }
580: }
581: }
582: if (type != null && type != '') {
583: url += '&type='+type;
584: }
585: if (type_elem != null && type_elem != '') {
586: url += '&typeelement='+type_elem;
587: }
588: if (formname == 'ccrs') {
589: var ownername = document.forms[formid].ccuname.value;
590: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
591: url += '&cloner='+ownername+':'+ownerdom;
592: if (type == 'Course') {
593: url += '&crscode='+document.forms[formid].crscode.value;
594: }
595: }
596: if (formname == 'requestcrs') {
597: url += '&crsdom=$domainfilter&crscode=$instcode';
598: }
599: if (multflag !=null && multflag != '') {
600: url += '&multiple='+multflag;
601: }
602: var title = '$wintitle';
603: var options = 'scrollbars=1,resizable=1,menubar=0';
604: options += ',width=700,height=600';
605: stdeditbrowser = open(url,title,options,'1');
606: stdeditbrowser.focus();
607: }
608: $id_functions
609: ENDSTDBRW
610: if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
611: $output .= &setsec_javascript($sec_element,$formname,$role_element,
612: $credits_element);
613: }
614: $output .= '
615: // ]]>
616: </script>';
617: return $output;
618: }
619:
620: sub javascript_index_functions {
621: return <<"ENDJS";
622:
623: function getFormIdByName(formname) {
624: for (var i=0;i<document.forms.length;i++) {
625: if (document.forms[i].name == formname) {
626: return i;
627: }
628: }
629: return -1;
630: }
631:
632: function getIndexByName(formid,item) {
633: for (var i=0;i<document.forms[formid].elements.length;i++) {
634: if (document.forms[formid].elements[i].name == item) {
635: return i;
636: }
637: }
638: return -1;
639: }
640:
641: function getDomainFromSelectbox(formname,udom) {
642: var userdom;
643: var formid = getFormIdByName(formname);
644: if (formid > -1) {
645: var domid = getIndexByName(formid,udom);
646: if (domid > -1) {
647: if (document.forms[formid].elements[domid].type == 'select-one') {
648: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
649: }
650: if (document.forms[formid].elements[domid].type == 'hidden') {
651: userdom=document.forms[formid].elements[domid].value;
652: }
653: }
654: }
655: return userdom;
656: }
657:
658: ENDJS
659:
660: }
661:
662: sub javascript_array_indexof {
663: return <<ENDJS;
664: <script type="text/javascript" language="JavaScript">
665: // <![CDATA[
666:
667: if (!Array.prototype.indexOf) {
668: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
669: "use strict";
670: if (this === void 0 || this === null) {
671: throw new TypeError();
672: }
673: var t = Object(this);
674: var len = t.length >>> 0;
675: if (len === 0) {
676: return -1;
677: }
678: var n = 0;
679: if (arguments.length > 0) {
680: n = Number(arguments[1]);
681: if (n !== n) { // shortcut for verifying if it's NaN
682: n = 0;
683: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
684: n = (n > 0 || -1) * Math.floor(Math.abs(n));
685: }
686: }
687: if (n >= len) {
688: return -1;
689: }
690: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
691: for (; k < len; k++) {
692: if (k in t && t[k] === searchElement) {
693: return k;
694: }
695: }
696: return -1;
697: }
698: }
699:
700: // ]]>
701: </script>
702:
703: ENDJS
704:
705: }
706:
707: sub userbrowser_javascript {
708: my $id_functions = &javascript_index_functions();
709: return <<"ENDUSERBRW";
710:
711: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
712: var url = '/adm/pickuser?';
713: var userdom = getDomainFromSelectbox(formname,udom);
714: if (userdom != null) {
715: if (userdom != '') {
716: url += 'srchdom='+userdom+'&';
717: }
718: }
719: url += 'form=' + formname + '&unameelement='+uname+
720: '&udomelement='+udom+
721: '&ulastelement='+ulast+
722: '&ufirstelement='+ufirst+
723: '&uemailelement='+uemail+
724: '&hideudomelement='+hideudom+
725: '&coursedom='+crsdom;
726: if ((caller != null) && (caller != undefined)) {
727: url += '&caller='+caller;
728: }
729: var title = 'User_Browser';
730: var options = 'scrollbars=1,resizable=1,menubar=0';
731: options += ',width=700,height=600';
732: var stdeditbrowser = open(url,title,options,'1');
733: stdeditbrowser.focus();
734: }
735:
736: function fix_domain (formname,udom,origdom,uname) {
737: var formid = getFormIdByName(formname);
738: if (formid > -1) {
739: var unameid = getIndexByName(formid,uname);
740: var domid = getIndexByName(formid,udom);
741: var hidedomid = getIndexByName(formid,origdom);
742: if (hidedomid > -1) {
743: var fixeddom = document.forms[formid].elements[hidedomid].value;
744: var unameval = document.forms[formid].elements[unameid].value;
745: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
746: if (domid > -1) {
747: var slct = document.forms[formid].elements[domid];
748: if (slct.type == 'select-one') {
749: var i;
750: for (i=0;i<slct.length;i++) {
751: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
752: }
753: }
754: if (slct.type == 'hidden') {
755: slct.value = fixeddom;
756: }
757: }
758: }
759: }
760: }
761: return;
762: }
763:
764: $id_functions
765: ENDUSERBRW
766: }
767:
768: sub setsec_javascript {
769: my ($sec_element,$formname,$role_element,$credits_element) = @_;
770: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
771: $communityrolestr);
772: if ($role_element ne '') {
773: my @allroles = ('st','ta','ep','in','ad');
774: foreach my $crstype ('Course','Community') {
775: if ($crstype eq 'Community') {
776: foreach my $role (@allroles) {
777: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
778: }
779: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
780: } else {
781: foreach my $role (@allroles) {
782: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
783: }
784: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
785: }
786: }
787: $rolestr = '"'.join('","',@allroles).'"';
788: $courserolestr = '"'.join('","',@courserolenames).'"';
789: $communityrolestr = '"'.join('","',@communityrolenames).'"';
790: }
791: my $setsections = qq|
792: function setSect(sectionlist) {
793: var sectionsArray = new Array();
794: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
795: sectionsArray = sectionlist.split(",");
796: }
797: var numSections = sectionsArray.length;
798: document.$formname.$sec_element.length = 0;
799: if (numSections == 0) {
800: document.$formname.$sec_element.multiple=false;
801: document.$formname.$sec_element.size=1;
802: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
803: } else {
804: if (numSections == 1) {
805: document.$formname.$sec_element.multiple=false;
806: document.$formname.$sec_element.size=1;
807: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
808: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
809: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
810: } else {
811: for (var i=0; i<numSections; i++) {
812: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
813: }
814: document.$formname.$sec_element.multiple=true
815: if (numSections < 3) {
816: document.$formname.$sec_element.size=numSections;
817: } else {
818: document.$formname.$sec_element.size=3;
819: }
820: document.$formname.$sec_element.options[0].selected = false
821: }
822: }
823: }
824:
825: function setRole(crstype) {
826: |;
827: if ($role_element eq '') {
828: $setsections .= ' return;
829: }
830: ';
831: } else {
832: $setsections .= qq|
833: var elementLength = document.$formname.$role_element.length;
834: var allroles = Array($rolestr);
835: var courserolenames = Array($courserolestr);
836: var communityrolenames = Array($communityrolestr);
837: if (elementLength != undefined) {
838: if (document.$formname.$role_element.options[5].value == 'cc') {
839: if (crstype == 'Course') {
840: return;
841: } else {
842: allroles[5] = 'co';
843: for (var i=0; i<6; i++) {
844: document.$formname.$role_element.options[i].value = allroles[i];
845: document.$formname.$role_element.options[i].text = communityrolenames[i];
846: }
847: }
848: } else {
849: if (crstype == 'Community') {
850: return;
851: } else {
852: allroles[5] = 'cc';
853: for (var i=0; i<6; i++) {
854: document.$formname.$role_element.options[i].value = allroles[i];
855: document.$formname.$role_element.options[i].text = courserolenames[i];
856: }
857: }
858: }
859: }
860: return;
861: }
862: |;
863: }
864: if ($credits_element) {
865: $setsections .= qq|
866: function setCredits(defaultcredits) {
867: document.$formname.$credits_element.value = defaultcredits;
868: return;
869: }
870: |;
871: }
872: return $setsections;
873: }
874:
875: sub selectcourse_link {
876: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
877: $typeelement) = @_;
878: my $type = $selecttype;
879: my $linktext = &mt('Select Course');
880: if ($selecttype eq 'Community') {
881: $linktext = &mt('Select Community');
882: } elsif ($selecttype eq 'Course/Community') {
883: $linktext = &mt('Select Course/Community');
884: $type = '';
885: } elsif ($selecttype eq 'Select') {
886: $linktext = &mt('Select');
887: $type = '';
888: }
889: return '<span class="LC_nobreak">'
890: ."<a href='"
891: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
892: .'","'.$udomele.'","'.$desc.'","'.$extra_element
893: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
894: ."'>".$linktext.'</a>'
895: .'</span>';
896: }
897:
898: sub selectauthor_link {
899: my ($form,$udom)=@_;
900: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
901: &mt('Select Author').'</a>';
902: }
903:
904: sub selectuser_link {
905: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
906: $coursedom,$linktext,$caller) = @_;
907: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
908: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
909: ');">'.$linktext.'</a>';
910: }
911:
912: sub check_uncheck_jscript {
913: my $jscript = <<"ENDSCRT";
914: function checkAll(field) {
915: if (field.length > 0) {
916: for (i = 0; i < field.length; i++) {
917: if (!field[i].disabled) {
918: field[i].checked = true;
919: }
920: }
921: } else {
922: if (!field.disabled) {
923: field.checked = true;
924: }
925: }
926: }
927:
928: function uncheckAll(field) {
929: if (field.length > 0) {
930: for (i = 0; i < field.length; i++) {
931: field[i].checked = false ;
932: }
933: } else {
934: field.checked = false ;
935: }
936: }
937: ENDSCRT
938: return $jscript;
939: }
940:
941: sub select_timezone {
942: my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
943: my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
944: if ($includeempty) {
945: $output .= '<option value=""';
946: if (($selected eq '') || ($selected eq 'local')) {
947: $output .= ' selected="selected" ';
948: }
949: $output .= '> </option>';
950: }
951: my @timezones = DateTime::TimeZone->all_names;
952: foreach my $tzone (@timezones) {
953: $output.= '<option value="'.$tzone.'"';
954: if ($tzone eq $selected) {
955: $output.=' selected="selected"';
956: }
957: $output.=">$tzone</option>\n";
958: }
959: $output.="</select>";
960: return $output;
961: }
962:
963: sub select_datelocale {
964: my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
965: my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
966: if ($includeempty) {
967: $output .= '<option value=""';
968: if ($selected eq '') {
969: $output .= ' selected="selected" ';
970: }
971: $output .= '> </option>';
972: }
973: my @languages = &Apache::lonlocal::preferred_languages();
974: my (@possibles,%locale_names);
975: my @locales = DateTime::Locale->ids();
976: foreach my $id (@locales) {
977: if ($id ne '') {
978: my ($en_terr,$native_terr);
979: my $loc = DateTime::Locale->load($id);
980: if (ref($loc)) {
981: $en_terr = $loc->name();
982: $native_terr = $loc->native_name();
983: if (grep(/^en$/,@languages) || !@languages) {
984: if ($en_terr ne '') {
985: $locale_names{$id} = '('.$en_terr.')';
986: } elsif ($native_terr ne '') {
987: $locale_names{$id} = $native_terr;
988: }
989: } else {
990: if ($native_terr ne '') {
991: $locale_names{$id} = $native_terr.' ';
992: } elsif ($en_terr ne '') {
993: $locale_names{$id} = '('.$en_terr.')';
994: }
995: }
996: $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
997: push(@possibles,$id);
998: }
999: }
1000: }
1001: foreach my $item (sort(@possibles)) {
1002: $output.= '<option value="'.$item.'"';
1003: if ($item eq $selected) {
1004: $output.=' selected="selected"';
1005: }
1006: $output.=">$item";
1007: if ($locale_names{$item} ne '') {
1008: $output.=' '.$locale_names{$item};
1009: }
1010: $output.="</option>\n";
1011: }
1012: $output.="</select>";
1013: return $output;
1014: }
1015:
1016: sub select_language {
1017: my ($name,$selected,$includeempty,$noedit) = @_;
1018: my %langchoices;
1019: if ($includeempty) {
1020: %langchoices = ('' => 'No language preference');
1021: }
1022: foreach my $id (&languageids()) {
1023: my $code = &supportedlanguagecode($id);
1024: if ($code) {
1025: $langchoices{$code} = &plainlanguagedescription($id);
1026: }
1027: }
1028: %langchoices = &Apache::lonlocal::texthash(%langchoices);
1029: return &select_form($selected,$name,\%langchoices,undef,$noedit);
1030: }
1031:
1032: =pod
1033:
1034: =item * &linked_select_forms(...)
1035:
1036: linked_select_forms returns a string containing a <script></script> block
1037: and html for two <select> menus. The select menus will be linked in that
1038: changing the value of the first menu will result in new values being placed
1039: in the second menu. The values in the select menu will appear in alphabetical
1040: order unless a defined order is provided.
1041:
1042: linked_select_forms takes the following ordered inputs:
1043:
1044: =over 4
1045:
1046: =item * $formname, the name of the <form> tag
1047:
1048: =item * $middletext, the text which appears between the <select> tags
1049:
1050: =item * $firstdefault, the default value for the first menu
1051:
1052: =item * $firstselectname, the name of the first <select> tag
1053:
1054: =item * $secondselectname, the name of the second <select> tag
1055:
1056: =item * $hashref, a reference to a hash containing the data for the menus.
1057:
1058: =item * $menuorder, the order of values in the first menu
1059:
1060: =item * $onchangefirst, additional javascript call to execute for an onchange
1061: event for the first <select> tag
1062:
1063: =item * $onchangesecond, additional javascript call to execute for an onchange
1064: event for the second <select> tag
1065:
1066: =back
1067:
1068: Below is an example of such a hash. Only the 'text', 'default', and
1069: 'select2' keys must appear as stated. keys(%menu) are the possible
1070: values for the first select menu. The text that coincides with the
1071: first menu value is given in $menu{$choice1}->{'text'}. The values
1072: and text for the second menu are given in the hash pointed to by
1073: $menu{$choice1}->{'select2'}.
1074:
1075: my %menu = ( A1 => { text =>"Choice A1" ,
1076: default => "B3",
1077: select2 => {
1078: B1 => "Choice B1",
1079: B2 => "Choice B2",
1080: B3 => "Choice B3",
1081: B4 => "Choice B4"
1082: },
1083: order => ['B4','B3','B1','B2'],
1084: },
1085: A2 => { text =>"Choice A2" ,
1086: default => "C2",
1087: select2 => {
1088: C1 => "Choice C1",
1089: C2 => "Choice C2",
1090: C3 => "Choice C3"
1091: },
1092: order => ['C2','C1','C3'],
1093: },
1094: A3 => { text =>"Choice A3" ,
1095: default => "D6",
1096: select2 => {
1097: D1 => "Choice D1",
1098: D2 => "Choice D2",
1099: D3 => "Choice D3",
1100: D4 => "Choice D4",
1101: D5 => "Choice D5",
1102: D6 => "Choice D6",
1103: D7 => "Choice D7"
1104: },
1105: order => ['D4','D3','D2','D1','D7','D6','D5'],
1106: }
1107: );
1108:
1109: =cut
1110:
1111: sub linked_select_forms {
1112: my ($formname,
1113: $middletext,
1114: $firstdefault,
1115: $firstselectname,
1116: $secondselectname,
1117: $hashref,
1118: $menuorder,
1119: $onchangefirst,
1120: $onchangesecond
1121: ) = @_;
1122: my $second = "document.$formname.$secondselectname";
1123: my $first = "document.$formname.$firstselectname";
1124: # output the javascript to do the changing
1125: my $result = '';
1126: $result.='<script type="text/javascript" language="JavaScript">'."\n";
1127: $result.="// <![CDATA[\n";
1128: $result.="var select2data = new Object();\n";
1129: $" = '","';
1130: my $debug = '';
1131: foreach my $s1 (sort(keys(%$hashref))) {
1132: $result.="select2data.d_$s1 = new Object();\n";
1133: $result.="select2data.d_$s1.def = new String('".
1134: $hashref->{$s1}->{'default'}."');\n";
1135: $result.="select2data.d_$s1.values = new Array(";
1136: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1137: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1138: @s2values = @{$hashref->{$s1}->{'order'}};
1139: }
1140: $result.="\"@s2values\");\n";
1141: $result.="select2data.d_$s1.texts = new Array(";
1142: my @s2texts;
1143: foreach my $value (@s2values) {
1144: push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1145: }
1146: $result.="\"@s2texts\");\n";
1147: }
1148: $"=' ';
1149: $result.= <<"END";
1150:
1151: function select1_changed() {
1152: // Determine new choice
1153: var newvalue = "d_" + $first.value;
1154: // update select2
1155: var values = select2data[newvalue].values;
1156: var texts = select2data[newvalue].texts;
1157: var select2def = select2data[newvalue].def;
1158: var i;
1159: // out with the old
1160: for (i = 0; i < $second.options.length; i++) {
1161: $second.options[i] = null;
1162: }
1163: // in with the nuclear
1164: for (i=0;i<values.length; i++) {
1165: $second.options[i] = new Option(values[i]);
1166: $second.options[i].value = values[i];
1167: $second.options[i].text = texts[i];
1168: if (values[i] == select2def) {
1169: $second.options[i].selected = true;
1170: }
1171: }
1172: }
1173: // ]]>
1174: </script>
1175: END
1176: # output the initial values for the selection lists
1177: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1178: my @order = sort(keys(%{$hashref}));
1179: if (ref($menuorder) eq 'ARRAY') {
1180: @order = @{$menuorder};
1181: }
1182: foreach my $value (@order) {
1183: $result.=" <option value=\"$value\" ";
1184: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1185: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1186: }
1187: $result .= "</select>\n";
1188: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1189: $result .= $middletext;
1190: $result .= "<select size=\"1\" name=\"$secondselectname\"";
1191: if ($onchangesecond) {
1192: $result .= ' onchange="'.$onchangesecond.'"';
1193: }
1194: $result .= ">\n";
1195: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1196:
1197: my @secondorder = sort(keys(%select2));
1198: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1199: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1200: }
1201: foreach my $value (@secondorder) {
1202: $result.=" <option value=\"$value\" ";
1203: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1204: $result.=">".&mt($select2{$value})."</option>\n";
1205: }
1206: $result .= "</select>\n";
1207: # return $debug;
1208: return $result;
1209: } # end of sub linked_select_forms {
1210:
1211: =pod
1212:
1213: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1214:
1215: Returns a string corresponding to an HTML link to the given help
1216: $topic, where $topic corresponds to the name of a .tex file in
1217: /home/httpd/html/adm/help/tex, with underscores replaced by
1218: spaces.
1219:
1220: $text will optionally be linked to the same topic, allowing you to
1221: link text in addition to the graphic. If you do not want to link
1222: text, but wish to specify one of the later parameters, pass an
1223: empty string.
1224:
1225: $stayOnPage is a value that will be interpreted as a boolean. If true,
1226: the link will not open a new window. If false, the link will open
1227: a new window using Javascript. (Default is false.)
1228:
1229: $width and $height are optional numerical parameters that will
1230: override the width and height of the popped up window, which may
1231: be useful for certain help topics with big pictures included.
1232:
1233: $imgid is the id of the img tag used for the help icon. This may be
1234: used in a javascript call to switch the image src. See
1235: lonhtmlcommon::htmlareaselectactive() for an example.
1236:
1237: =cut
1238:
1239: sub help_open_topic {
1240: my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1241: $text = "" if (not defined $text);
1242: $stayOnPage = 0 if (not defined $stayOnPage);
1243: $width = 500 if (not defined $width);
1244: $height = 400 if (not defined $height);
1245: my $filename = $topic;
1246: $filename =~ s/ /_/g;
1247:
1248: my $template = "";
1249: my $link;
1250:
1251: $topic=~s/\W/\_/g;
1252:
1253: if (!$stayOnPage) {
1254: if ($env{'browser.mobile'}) {
1255: $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1256: } else {
1257: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1258: }
1259: } elsif ($stayOnPage eq 'popup') {
1260: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1261: } else {
1262: $link = "/adm/help/${filename}.hlp";
1263: }
1264:
1265: # Add the text
1266: if ($text ne "") {
1267: $template.='<span class="LC_help_open_topic">'
1268: .'<a target="_top" href="'.$link.'">'
1269: .$text.'</a>';
1270: }
1271:
1272: # (Always) Add the graphic
1273: my $title = &mt('Online Help');
1274: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1275: if ($imgid ne '') {
1276: $imgid = ' id="'.$imgid.'"';
1277: }
1278: $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
1279: .'<img src="'.$helpicon.'" border="0"'
1280: .' alt="'.&mt('Help: [_1]',$topic).'"'
1281: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
1282: .' /></a>';
1283: if ($text ne "") {
1284: $template.='</span>';
1285: }
1286: return $template;
1287:
1288: }
1289:
1290: # This is a quicky function for Latex cheatsheet editing, since it
1291: # appears in at least four places
1292: sub helpLatexCheatsheet {
1293: my ($topic,$text,$not_author,$stayOnPage) = @_;
1294: my $out;
1295: my $addOther = '';
1296: if ($topic) {
1297: $addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1298: }
1299: $out = '<span>' # Start cheatsheet
1300: .$addOther
1301: .'<span>'
1302: .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1303: .'</span> <span>'
1304: .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1305: .'</span>';
1306: unless ($not_author) {
1307: $out .= ' <span>'
1308: .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1309: .'</span> <span>'
1310: .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1311: .'</span>';
1312: }
1313: $out .= '</span>'; # End cheatsheet
1314: return $out;
1315: }
1316:
1317: sub general_help {
1318: my $helptopic='Student_Intro';
1319: if ($env{'request.role'}=~/^(ca|au)/) {
1320: $helptopic='Authoring_Intro';
1321: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1322: $helptopic='Course_Coordination_Intro';
1323: } elsif ($env{'request.role'}=~/^dc/) {
1324: $helptopic='Domain_Coordination_Intro';
1325: }
1326: return $helptopic;
1327: }
1328:
1329: sub update_help_link {
1330: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1331: my $origurl = $ENV{'REQUEST_URI'};
1332: $origurl=~s|^/~|/priv/|;
1333: my $timestamp = time;
1334: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1335: $$datum = &escape($$datum);
1336: }
1337:
1338: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1339: my $output .= <<"ENDOUTPUT";
1340: <script type="text/javascript">
1341: // <![CDATA[
1342: banner_link = '$banner_link';
1343: // ]]>
1344: </script>
1345: ENDOUTPUT
1346: return $output;
1347: }
1348:
1349: # now just updates the help link and generates a blue icon
1350: sub help_open_menu {
1351: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
1352: = @_;
1353: $stayOnPage = 1;
1354: my $output;
1355: if ($component_help) {
1356: if (!$text) {
1357: $output=&help_open_topic($component_help,undef,$stayOnPage,
1358: $width,$height);
1359: } else {
1360: my $help_text;
1361: $help_text=&unescape($topic);
1362: $output='<table><tr><td>'.
1363: &help_open_topic($component_help,$help_text,$stayOnPage,
1364: $width,$height).'</td></tr></table>';
1365: }
1366: }
1367: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1368: return $output.$banner_link;
1369: }
1370:
1371: sub top_nav_help {
1372: my ($text) = @_;
1373: $text = &mt($text);
1374: my $stay_on_page;
1375: unless ($env{'environment.remote'} eq 'on') {
1376: $stay_on_page = 1;
1377: }
1378: my ($link,$banner_link);
1379: unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
1380: $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1381: : "javascript:helpMenu('open')";
1382: $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1383: }
1384: my $title = &mt('Get help');
1385: if ($link) {
1386: return <<"END";
1387: $banner_link
1388: <a href="$link" title="$title">$text</a>
1389: END
1390: } else {
1391: return ' '.$text.' ';
1392: }
1393: }
1394:
1395: sub help_menu_js {
1396: my ($httphost) = @_;
1397: my $stayOnPage = 1;
1398: my $width = 620;
1399: my $height = 600;
1400: my $helptopic=&general_help();
1401: my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1402: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1403: my $start_page =
1404: &Apache::loncommon::start_page('Help Menu', undef,
1405: {'frameset' => 1,
1406: 'js_ready' => 1,
1407: 'use_absolute' => $httphost,
1408: 'add_entries' => {
1409: 'border' => '0',
1410: 'rows' => "110,*",},});
1411: my $end_page =
1412: &Apache::loncommon::end_page({'frameset' => 1,
1413: 'js_ready' => 1,});
1414:
1415: my $template .= <<"ENDTEMPLATE";
1416: <script type="text/javascript">
1417: // <![CDATA[
1418: // <!-- BEGIN LON-CAPA Internal
1419: var banner_link = '';
1420: function helpMenu(target) {
1421: var caller = this;
1422: if (target == 'open') {
1423: var newWindow = null;
1424: try {
1425: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1426: }
1427: catch(error) {
1428: writeHelp(caller);
1429: return;
1430: }
1431: if (newWindow) {
1432: caller = newWindow;
1433: }
1434: }
1435: writeHelp(caller);
1436: return;
1437: }
1438: function writeHelp(caller) {
1439: caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
1440: caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
1441: caller.document.close();
1442: caller.focus();
1443: }
1444: // END LON-CAPA Internal -->
1445: // ]]>
1446: </script>
1447: ENDTEMPLATE
1448: return $template;
1449: }
1450:
1451: sub help_open_bug {
1452: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1453: unless ($env{'user.adv'}) { return ''; }
1454: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1455: $text = "" if (not defined $text);
1456: $stayOnPage=1;
1457: $width = 600 if (not defined $width);
1458: $height = 600 if (not defined $height);
1459:
1460: $topic=~s/\W+/\+/g;
1461: my $link='';
1462: my $template='';
1463: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1464: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1465: if (!$stayOnPage)
1466: {
1467: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1468: }
1469: else
1470: {
1471: $link = $url;
1472: }
1473: # Add the text
1474: if ($text ne "")
1475: {
1476: $template .=
1477: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1478: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1479: }
1480:
1481: # Add the graphic
1482: my $title = &mt('Report a Bug');
1483: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1484: $template .= <<"ENDTEMPLATE";
1485: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1486: ENDTEMPLATE
1487: if ($text ne '') { $template.='</td></tr></table>' };
1488: return $template;
1489:
1490: }
1491:
1492: sub help_open_faq {
1493: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1494: unless ($env{'user.adv'}) { return ''; }
1495: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1496: $text = "" if (not defined $text);
1497: $stayOnPage=1;
1498: $width = 350 if (not defined $width);
1499: $height = 400 if (not defined $height);
1500:
1501: $topic=~s/\W+/\+/g;
1502: my $link='';
1503: my $template='';
1504: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1505: if (!$stayOnPage)
1506: {
1507: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1508: }
1509: else
1510: {
1511: $link = $url;
1512: }
1513:
1514: # Add the text
1515: if ($text ne "")
1516: {
1517: $template .=
1518: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1519: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1520: }
1521:
1522: # Add the graphic
1523: my $title = &mt('View the FAQ');
1524: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1525: $template .= <<"ENDTEMPLATE";
1526: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1527: ENDTEMPLATE
1528: if ($text ne '') { $template.='</td></tr></table>' };
1529: return $template;
1530:
1531: }
1532:
1533: ###############################################################
1534: ###############################################################
1535:
1536: =pod
1537:
1538: =item * &change_content_javascript():
1539:
1540: This and the next function allow you to create small sections of an
1541: otherwise static HTML page that you can update on the fly with
1542: Javascript, even in Netscape 4.
1543:
1544: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1545: must be written to the HTML page once. It will prove the Javascript
1546: function "change(name, content)". Calling the change function with the
1547: name of the section
1548: you want to update, matching the name passed to C<changable_area>, and
1549: the new content you want to put in there, will put the content into
1550: that area.
1551:
1552: B<Note>: Netscape 4 only reserves enough space for the changable area
1553: to contain room for the original contents. You need to "make space"
1554: for whatever changes you wish to make, and be B<sure> to check your
1555: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1556: it's adequate for updating a one-line status display, but little more.
1557: This script will set the space to 100% width, so you only need to
1558: worry about height in Netscape 4.
1559:
1560: Modern browsers are much less limiting, and if you can commit to the
1561: user not using Netscape 4, this feature may be used freely with
1562: pretty much any HTML.
1563:
1564: =cut
1565:
1566: sub change_content_javascript {
1567: # If we're on Netscape 4, we need to use Layer-based code
1568: if ($env{'browser.type'} eq 'netscape' &&
1569: $env{'browser.version'} =~ /^4\./) {
1570: return (<<NETSCAPE4);
1571: function change(name, content) {
1572: doc = document.layers[name+"___escape"].layers[0].document;
1573: doc.open();
1574: doc.write(content);
1575: doc.close();
1576: }
1577: NETSCAPE4
1578: } else {
1579: # Otherwise, we need to use semi-standards-compliant code
1580: # (technically, "innerHTML" isn't standard but the equivalent
1581: # is really scary, and every useful browser supports it
1582: return (<<DOMBASED);
1583: function change(name, content) {
1584: element = document.getElementById(name);
1585: element.innerHTML = content;
1586: }
1587: DOMBASED
1588: }
1589: }
1590:
1591: =pod
1592:
1593: =item * &changable_area($name,$origContent):
1594:
1595: This provides a "changable area" that can be modified on the fly via
1596: the Javascript code provided in C<change_content_javascript>. $name is
1597: the name you will use to reference the area later; do not repeat the
1598: same name on a given HTML page more then once. $origContent is what
1599: the area will originally contain, which can be left blank.
1600:
1601: =cut
1602:
1603: sub changable_area {
1604: my ($name, $origContent) = @_;
1605:
1606: if ($env{'browser.type'} eq 'netscape' &&
1607: $env{'browser.version'} =~ /^4\./) {
1608: # If this is netscape 4, we need to use the Layer tag
1609: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1610: } else {
1611: return "<span id='$name'>$origContent</span>";
1612: }
1613: }
1614:
1615: =pod
1616:
1617: =item * &viewport_geometry_js
1618:
1619: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1620:
1621: =cut
1622:
1623:
1624: sub viewport_geometry_js {
1625: return <<"GEOMETRY";
1626: var Geometry = {};
1627: function init_geometry() {
1628: if (Geometry.init) { return };
1629: Geometry.init=1;
1630: if (window.innerHeight) {
1631: Geometry.getViewportHeight = function() { return window.innerHeight; };
1632: Geometry.getViewportWidth = function() { return window.innerWidth; };
1633: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1634: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1635: }
1636: else if (document.documentElement && document.documentElement.clientHeight) {
1637: Geometry.getViewportHeight =
1638: function() { return document.documentElement.clientHeight; };
1639: Geometry.getViewportWidth =
1640: function() { return document.documentElement.clientWidth; };
1641:
1642: Geometry.getHorizontalScroll =
1643: function() { return document.documentElement.scrollLeft; };
1644: Geometry.getVerticalScroll =
1645: function() { return document.documentElement.scrollTop; };
1646: }
1647: else if (document.body.clientHeight) {
1648: Geometry.getViewportHeight =
1649: function() { return document.body.clientHeight; };
1650: Geometry.getViewportWidth =
1651: function() { return document.body.clientWidth; };
1652: Geometry.getHorizontalScroll =
1653: function() { return document.body.scrollLeft; };
1654: Geometry.getVerticalScroll =
1655: function() { return document.body.scrollTop; };
1656: }
1657: }
1658:
1659: GEOMETRY
1660: }
1661:
1662: =pod
1663:
1664: =item * &viewport_size_js()
1665:
1666: 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.
1667:
1668: =cut
1669:
1670: sub viewport_size_js {
1671: my $geometry = &viewport_geometry_js();
1672: return <<"DIMS";
1673:
1674: $geometry
1675:
1676: function getViewportDims(width,height) {
1677: init_geometry();
1678: width.value = Geometry.getViewportWidth();
1679: height.value = Geometry.getViewportHeight();
1680: return;
1681: }
1682:
1683: DIMS
1684: }
1685:
1686: =pod
1687:
1688: =item * &resize_textarea_js()
1689:
1690: emits the needed javascript to resize a textarea to be as big as possible
1691:
1692: creates a function resize_textrea that takes two IDs first should be
1693: the id of the element to resize, second should be the id of a div that
1694: surrounds everything that comes after the textarea, this routine needs
1695: to be attached to the <body> for the onload and onresize events.
1696:
1697: =back
1698:
1699: =cut
1700:
1701: sub resize_textarea_js {
1702: my $geometry = &viewport_geometry_js();
1703: return <<"RESIZE";
1704: <script type="text/javascript">
1705: // <![CDATA[
1706: $geometry
1707:
1708: function getX(element) {
1709: var x = 0;
1710: while (element) {
1711: x += element.offsetLeft;
1712: element = element.offsetParent;
1713: }
1714: return x;
1715: }
1716: function getY(element) {
1717: var y = 0;
1718: while (element) {
1719: y += element.offsetTop;
1720: element = element.offsetParent;
1721: }
1722: return y;
1723: }
1724:
1725:
1726: function resize_textarea(textarea_id,bottom_id) {
1727: init_geometry();
1728: var textarea = document.getElementById(textarea_id);
1729: //alert(textarea);
1730:
1731: var textarea_top = getY(textarea);
1732: var textarea_height = textarea.offsetHeight;
1733: var bottom = document.getElementById(bottom_id);
1734: var bottom_top = getY(bottom);
1735: var bottom_height = bottom.offsetHeight;
1736: var window_height = Geometry.getViewportHeight();
1737: var fudge = 23;
1738: var new_height = window_height-fudge-textarea_top-bottom_height;
1739: if (new_height < 300) {
1740: new_height = 300;
1741: }
1742: textarea.style.height=new_height+'px';
1743: }
1744: // ]]>
1745: </script>
1746: RESIZE
1747:
1748: }
1749:
1750: sub colorfuleditor_js {
1751: return <<"COLORFULEDIT"
1752: <script type="text/javascript">
1753: // <![CDATA[>
1754: function fold_box(curDepth, lastresource){
1755:
1756: // we need a list because there can be several blocks you need to fold in one tag
1757: var block = document.getElementsByName('foldblock_'+curDepth);
1758: // but there is only one folding button per tag
1759: var foldbutton = document.getElementById('folding_btn_'+curDepth);
1760:
1761: if(block.item(0).style.display == 'none'){
1762:
1763: foldbutton.value = '@{[&mt("Hide")]}';
1764: for (i = 0; i < block.length; i++){
1765: block.item(i).style.display = '';
1766: }
1767: }else{
1768:
1769: foldbutton.value = '@{[&mt("Show")]}';
1770: for (i = 0; i < block.length; i++){
1771: // block.item(i).style.visibility = 'collapse';
1772: block.item(i).style.display = 'none';
1773: }
1774: };
1775: saveState(lastresource);
1776: }
1777:
1778: function saveState (lastresource) {
1779:
1780: var tag_list = getTagList();
1781: if(tag_list != null){
1782: var timestamp = new Date().getTime();
1783: var key = lastresource;
1784:
1785: // the value pattern is: 'time;key1,value1;key2,value2; ... '
1786: // starting with timestamp
1787: var value = timestamp+';';
1788:
1789: // building the list of key-value pairs
1790: for(var i = 0; i < tag_list.length; i++){
1791: value += tag_list[i]+',';
1792: value += document.getElementsByName(tag_list[i])[0].style.display+';';
1793: }
1794:
1795: // only iterate whole storage if nothing to override
1796: if(localStorage.getItem(key) == null){
1797:
1798: // prevent storage from growing large
1799: if(localStorage.length > 50){
1800: var regex_getTimestamp = /^(?:\d)+;/;
1801: var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
1802: var oldest_key;
1803:
1804: for(var i = 1; i < localStorage.length; i++){
1805: if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
1806: oldest_key = localStorage.key(i);
1807: oldest_timestamp = regex_getTimestamp.exec(oldest_key);
1808: }
1809: }
1810: localStorage.removeItem(oldest_key);
1811: }
1812: }
1813: localStorage.setItem(key,value);
1814: }
1815: }
1816:
1817: // restore folding status of blocks (on page load)
1818: function restoreState (lastresource) {
1819: if(localStorage.getItem(lastresource) != null){
1820: var key = lastresource;
1821: var value = localStorage.getItem(key);
1822: var regex_delTimestamp = /^\d+;/;
1823:
1824: value.replace(regex_delTimestamp, '');
1825:
1826: var valueArr = value.split(';');
1827: var pairs;
1828: var elements;
1829: for (var i = 0; i < valueArr.length; i++){
1830: pairs = valueArr[i].split(',');
1831: elements = document.getElementsByName(pairs[0]);
1832:
1833: for (var j = 0; j < elements.length; j++){
1834: elements[j].style.display = pairs[1];
1835: if (pairs[1] == "none"){
1836: var regex_id = /([_\\d]+)\$/;
1837: regex_id.exec(pairs[0]);
1838: document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
1839: }
1840: }
1841: }
1842: }
1843: }
1844:
1845: function getTagList () {
1846:
1847: var stringToSearch = document.lonhomework.innerHTML;
1848:
1849: var ret = new Array();
1850: var regex_findBlock = /(foldblock_.*?)"/g;
1851: var tag_list = stringToSearch.match(regex_findBlock);
1852:
1853: if(tag_list != null){
1854: for(var i = 0; i < tag_list.length; i++){
1855: ret.push(tag_list[i].replace(/"/, ''));
1856: }
1857: }
1858: return ret;
1859: }
1860:
1861: function saveScrollPosition (resource) {
1862: var tag_list = getTagList();
1863:
1864: // we dont always want to jump to the first block
1865: // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
1866: if(\$(window).scrollTop() > 170){
1867: if(tag_list != null){
1868: var result;
1869: for(var i = 0; i < tag_list.length; i++){
1870: if(isElementInViewport(tag_list[i])){
1871: result += tag_list[i]+';';
1872: }
1873: }
1874: sessionStorage.setItem('anchor_'+resource, result);
1875: }
1876: } else {
1877: // we dont need to save zero, just delete the item to leave everything tidy
1878: sessionStorage.removeItem('anchor_'+resource);
1879: }
1880: }
1881:
1882: function restoreScrollPosition(resource){
1883:
1884: var elem = sessionStorage.getItem('anchor_'+resource);
1885: if(elem != null){
1886: var tag_list = elem.split(';');
1887: var elem_list;
1888:
1889: for(var i = 0; i < tag_list.length; i++){
1890: elem_list = document.getElementsByName(tag_list[i]);
1891:
1892: if(elem_list.length > 0){
1893: elem = elem_list[0];
1894: break;
1895: }
1896: }
1897: elem.scrollIntoView();
1898: }
1899: }
1900:
1901: function isElementInViewport(el) {
1902:
1903: // change to last element instead of first
1904: var elem = document.getElementsByName(el);
1905: var rect = elem[0].getBoundingClientRect();
1906:
1907: return (
1908: rect.top >= 0 &&
1909: rect.left >= 0 &&
1910: rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
1911: rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
1912: );
1913: }
1914:
1915: function autosize(depth){
1916: var cmInst = window['cm'+depth];
1917: var fitsizeButton = document.getElementById('fitsize'+depth);
1918:
1919: // is fixed size, switching to dynamic
1920: if (sessionStorage.getItem("autosized_"+depth) == null) {
1921: cmInst.setSize("","auto");
1922: fitsizeButton.value = "@{[&mt('Fixed size')]}";
1923: sessionStorage.setItem("autosized_"+depth, "yes");
1924:
1925: // is dynamic size, switching to fixed
1926: } else {
1927: cmInst.setSize("","300px");
1928: fitsizeButton.value = "@{[&mt('Dynamic size')]}";
1929: sessionStorage.removeItem("autosized_"+depth);
1930: }
1931: }
1932:
1933:
1934:
1935: // ]]>
1936: </script>
1937: COLORFULEDIT
1938: }
1939:
1940: sub xmleditor_js {
1941: return <<XMLEDIT
1942: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
1943: <script type="text/javascript">
1944: // <![CDATA[>
1945:
1946: function saveScrollPosition (resource) {
1947:
1948: var scrollPos = \$(window).scrollTop();
1949: sessionStorage.setItem(resource,scrollPos);
1950: }
1951:
1952: function restoreScrollPosition(resource){
1953:
1954: var scrollPos = sessionStorage.getItem(resource);
1955: \$(window).scrollTop(scrollPos);
1956: }
1957:
1958: // unless internet explorer
1959: if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
1960:
1961: \$(document).ready(function() {
1962: \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
1963: });
1964: }
1965:
1966: // inserts text at cursor position into codemirror (xml editor only)
1967: function insertText(text){
1968: cm.focus();
1969: var curPos = cm.getCursor();
1970: cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
1971: }
1972: // ]]>
1973: </script>
1974: XMLEDIT
1975: }
1976:
1977: sub insert_folding_button {
1978: my $curDepth = $Apache::lonxml::curdepth;
1979: my $lastresource = $env{'request.ambiguous'};
1980:
1981: return "<input type=\"button\" id=\"folding_btn_$curDepth\"
1982: value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
1983: }
1984:
1985:
1986: =pod
1987:
1988: =head1 Excel and CSV file utility routines
1989:
1990: =cut
1991:
1992: ###############################################################
1993: ###############################################################
1994:
1995: =pod
1996:
1997: =over 4
1998:
1999: =item * &csv_translate($text)
2000:
2001: Translate $text to allow it to be output as a 'comma separated values'
2002: format.
2003:
2004: =cut
2005:
2006: ###############################################################
2007: ###############################################################
2008: sub csv_translate {
2009: my $text = shift;
2010: $text =~ s/\"/\"\"/g;
2011: $text =~ s/\n/ /g;
2012: return $text;
2013: }
2014:
2015: ###############################################################
2016: ###############################################################
2017:
2018: =pod
2019:
2020: =item * &define_excel_formats()
2021:
2022: Define some commonly used Excel cell formats.
2023:
2024: Currently supported formats:
2025:
2026: =over 4
2027:
2028: =item header
2029:
2030: =item bold
2031:
2032: =item h1
2033:
2034: =item h2
2035:
2036: =item h3
2037:
2038: =item h4
2039:
2040: =item i
2041:
2042: =item date
2043:
2044: =back
2045:
2046: Inputs: $workbook
2047:
2048: Returns: $format, a hash reference.
2049:
2050:
2051: =cut
2052:
2053: ###############################################################
2054: ###############################################################
2055: sub define_excel_formats {
2056: my ($workbook) = @_;
2057: my $format;
2058: $format->{'header'} = $workbook->add_format(bold => 1,
2059: bottom => 1,
2060: align => 'center');
2061: $format->{'bold'} = $workbook->add_format(bold=>1);
2062: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
2063: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
2064: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
2065: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
2066: $format->{'i'} = $workbook->add_format(italic=>1);
2067: $format->{'date'} = $workbook->add_format(num_format=>
2068: 'mm/dd/yyyy hh:mm:ss');
2069: return $format;
2070: }
2071:
2072: ###############################################################
2073: ###############################################################
2074:
2075: =pod
2076:
2077: =item * &create_workbook()
2078:
2079: Create an Excel worksheet. If it fails, output message on the
2080: request object and return undefs.
2081:
2082: Inputs: Apache request object
2083:
2084: Returns (undef) on failure,
2085: Excel worksheet object, scalar with filename, and formats
2086: from &Apache::loncommon::define_excel_formats on success
2087:
2088: =cut
2089:
2090: ###############################################################
2091: ###############################################################
2092: sub create_workbook {
2093: my ($r) = @_;
2094: #
2095: # Create the excel spreadsheet
2096: my $filename = '/prtspool/'.
2097: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2098: time.'_'.rand(1000000000).'.xls';
2099: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
2100: if (! defined($workbook)) {
2101: $r->log_error("Error creating excel spreadsheet $filename: $!");
2102: $r->print(
2103: '<p class="LC_error">'
2104: .&mt('Problems occurred in creating the new Excel file.')
2105: .' '.&mt('This error has been logged.')
2106: .' '.&mt('Please alert your LON-CAPA administrator.')
2107: .'</p>'
2108: );
2109: return (undef);
2110: }
2111: #
2112: $workbook->set_tempdir(LONCAPA::tempdir());
2113: #
2114: my $format = &Apache::loncommon::define_excel_formats($workbook);
2115: return ($workbook,$filename,$format);
2116: }
2117:
2118: ###############################################################
2119: ###############################################################
2120:
2121: =pod
2122:
2123: =item * &create_text_file()
2124:
2125: Create a file to write to and eventually make available to the user.
2126: If file creation fails, outputs an error message on the request object and
2127: return undefs.
2128:
2129: Inputs: Apache request object, and file suffix
2130:
2131: Returns (undef) on failure,
2132: Filehandle and filename on success.
2133:
2134: =cut
2135:
2136: ###############################################################
2137: ###############################################################
2138: sub create_text_file {
2139: my ($r,$suffix) = @_;
2140: if (! defined($suffix)) { $suffix = 'txt'; };
2141: my $fh;
2142: my $filename = '/prtspool/'.
2143: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2144: time.'_'.rand(1000000000).'.'.$suffix;
2145: $fh = Apache::File->new('>/home/httpd'.$filename);
2146: if (! defined($fh)) {
2147: $r->log_error("Couldn't open $filename for output $!");
2148: $r->print(
2149: '<p class="LC_error">'
2150: .&mt('Problems occurred in creating the output file.')
2151: .' '.&mt('This error has been logged.')
2152: .' '.&mt('Please alert your LON-CAPA administrator.')
2153: .'</p>'
2154: );
2155: }
2156: return ($fh,$filename)
2157: }
2158:
2159:
2160: =pod
2161:
2162: =back
2163:
2164: =cut
2165:
2166: ###############################################################
2167: ## Home server <option> list generating code ##
2168: ###############################################################
2169:
2170: # ------------------------------------------
2171:
2172: sub domain_select {
2173: my ($name,$value,$multiple)=@_;
2174: my %domains=map {
2175: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
2176: } &Apache::lonnet::all_domains();
2177: if ($multiple) {
2178: $domains{''}=&mt('Any domain');
2179: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2180: return &multiple_select_form($name,$value,4,\%domains);
2181: } else {
2182: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2183: return &select_form($name,$value,\%domains);
2184: }
2185: }
2186:
2187: #-------------------------------------------
2188:
2189: =pod
2190:
2191: =head1 Routines for form select boxes
2192:
2193: =over 4
2194:
2195: =item * &multiple_select_form($name,$value,$size,$hash,$order)
2196:
2197: Returns a string containing a <select> element int multiple mode
2198:
2199:
2200: Args:
2201: $name - name of the <select> element
2202: $value - scalar or array ref of values that should already be selected
2203: $size - number of rows long the select element is
2204: $hash - the elements should be 'option' => 'shown text'
2205: (shown text should already have been &mt())
2206: $order - (optional) array ref of the order to show the elements in
2207:
2208: =cut
2209:
2210: #-------------------------------------------
2211: sub multiple_select_form {
2212: my ($name,$value,$size,$hash,$order)=@_;
2213: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
2214: my $output='';
2215: if (! defined($size)) {
2216: $size = 4;
2217: if (scalar(keys(%$hash))<4) {
2218: $size = scalar(keys(%$hash));
2219: }
2220: }
2221: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
2222: my @order;
2223: if (ref($order) eq 'ARRAY') {
2224: @order = @{$order};
2225: } else {
2226: @order = sort(keys(%$hash));
2227: }
2228: if (exists($$hash{'select_form_order'})) {
2229: @order = @{$$hash{'select_form_order'}};
2230: }
2231:
2232: foreach my $key (@order) {
2233: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
2234: $output.='selected="selected" ' if ($selected{$key});
2235: $output.='>'.$hash->{$key}."</option>\n";
2236: }
2237: $output.="</select>\n";
2238: return $output;
2239: }
2240:
2241: #-------------------------------------------
2242:
2243: =pod
2244:
2245: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
2246:
2247: Returns a string containing a <select name='$name' size='1'> form to
2248: allow a user to select options from a ref to a hash containing:
2249: option_name => displayed text. An optional $onchange can include
2250: a javascript onchange item, e.g., onchange="this.form.submit();".
2251: An optional arg -- $readonly -- if true will cause the select form
2252: to be disabled, e.g., for the case where an instructor has a section-
2253: specific role, and is viewing/modifying parameters.
2254:
2255: See lonrights.pm for an example invocation and use.
2256:
2257: =cut
2258:
2259: #-------------------------------------------
2260: sub select_form {
2261: my ($def,$name,$hashref,$onchange,$readonly) = @_;
2262: return unless (ref($hashref) eq 'HASH');
2263: if ($onchange) {
2264: $onchange = ' onchange="'.$onchange.'"';
2265: }
2266: my $disabled;
2267: if ($readonly) {
2268: $disabled = ' disabled="disabled"';
2269: }
2270: my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2271: my @keys;
2272: if (exists($hashref->{'select_form_order'})) {
2273: @keys=@{$hashref->{'select_form_order'}};
2274: } else {
2275: @keys=sort(keys(%{$hashref}));
2276: }
2277: foreach my $key (@keys) {
2278: $selectform.=
2279: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
2280: ($key eq $def ? 'selected="selected" ' : '').
2281: ">".$hashref->{$key}."</option>\n";
2282: }
2283: $selectform.="</select>";
2284: return $selectform;
2285: }
2286:
2287: # For display filters
2288:
2289: sub display_filter {
2290: my ($context) = @_;
2291: if (!$env{'form.show'}) { $env{'form.show'}=10; }
2292: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
2293: my $phraseinput = 'hidden';
2294: my $includeinput = 'hidden';
2295: my ($checked,$includetypestext);
2296: if ($env{'form.displayfilter'} eq 'containing') {
2297: $phraseinput = 'text';
2298: if ($context eq 'parmslog') {
2299: $includeinput = 'checkbox';
2300: if ($env{'form.includetypes'}) {
2301: $checked = ' checked="checked"';
2302: }
2303: $includetypestext = &mt('Include parameter types');
2304: }
2305: } else {
2306: $includetypestext = ' ';
2307: }
2308: my ($additional,$secondid,$thirdid);
2309: if ($context eq 'parmslog') {
2310: $additional =
2311: '<label><input type="'.$includeinput.'" name="includetypes"'.
2312: $checked.' name="includetypes" value="1" id="includetypes" />'.
2313: ' <span id="includetypestext">'.$includetypestext.'</span>'.
2314: '</label>';
2315: $secondid = 'includetypes';
2316: $thirdid = 'includetypestext';
2317: }
2318: my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
2319: '$secondid','$thirdid')";
2320: return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
2321: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
2322: (&mt('all'),10,20,50,100,1000,10000))).
2323: '</label></span> <span class="LC_nobreak">'.
2324: &mt('Filter: [_1]',
2325: &select_form($env{'form.displayfilter'},
2326: 'displayfilter',
2327: {'currentfolder' => 'Current folder/page',
2328: 'containing' => 'Containing phrase',
2329: 'none' => 'None'},$onchange)).' '.
2330: '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
2331: &HTML::Entities::encode($env{'form.containingphrase'}).
2332: '" />'.$additional;
2333: }
2334:
2335: sub display_filter_js {
2336: my $includetext = &mt('Include parameter types');
2337: return <<"ENDJS";
2338:
2339: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
2340: var firstType = 'hidden';
2341: if (setter.options[setter.selectedIndex].value == 'containing') {
2342: firstType = 'text';
2343: }
2344: firstObject = document.getElementById(firstid);
2345: if (typeof(firstObject) == 'object') {
2346: if (firstObject.type != firstType) {
2347: changeInputType(firstObject,firstType);
2348: }
2349: }
2350: if (context == 'parmslog') {
2351: var secondType = 'hidden';
2352: if (firstType == 'text') {
2353: secondType = 'checkbox';
2354: }
2355: secondObject = document.getElementById(secondid);
2356: if (typeof(secondObject) == 'object') {
2357: if (secondObject.type != secondType) {
2358: changeInputType(secondObject,secondType);
2359: }
2360: }
2361: var textItem = document.getElementById(thirdid);
2362: var currtext = textItem.innerHTML;
2363: var newtext;
2364: if (firstType == 'text') {
2365: newtext = '$includetext';
2366: } else {
2367: newtext = ' ';
2368: }
2369: if (currtext != newtext) {
2370: textItem.innerHTML = newtext;
2371: }
2372: }
2373: return;
2374: }
2375:
2376: function changeInputType(oldObject,newType) {
2377: var newObject = document.createElement('input');
2378: newObject.type = newType;
2379: if (oldObject.size) {
2380: newObject.size = oldObject.size;
2381: }
2382: if (oldObject.value) {
2383: newObject.value = oldObject.value;
2384: }
2385: if (oldObject.name) {
2386: newObject.name = oldObject.name;
2387: }
2388: if (oldObject.id) {
2389: newObject.id = oldObject.id;
2390: }
2391: oldObject.parentNode.replaceChild(newObject,oldObject);
2392: return;
2393: }
2394:
2395: ENDJS
2396: }
2397:
2398: sub gradeleveldescription {
2399: my $gradelevel=shift;
2400: my %gradelevels=(0 => 'Not specified',
2401: 1 => 'Grade 1',
2402: 2 => 'Grade 2',
2403: 3 => 'Grade 3',
2404: 4 => 'Grade 4',
2405: 5 => 'Grade 5',
2406: 6 => 'Grade 6',
2407: 7 => 'Grade 7',
2408: 8 => 'Grade 8',
2409: 9 => 'Grade 9',
2410: 10 => 'Grade 10',
2411: 11 => 'Grade 11',
2412: 12 => 'Grade 12',
2413: 13 => 'Grade 13',
2414: 14 => '100 Level',
2415: 15 => '200 Level',
2416: 16 => '300 Level',
2417: 17 => '400 Level',
2418: 18 => 'Graduate Level');
2419: return &mt($gradelevels{$gradelevel});
2420: }
2421:
2422: sub select_level_form {
2423: my ($deflevel,$name)=@_;
2424: unless ($deflevel) { $deflevel=0; }
2425: my $selectform = "<select name=\"$name\" size=\"1\">\n";
2426: for (my $i=0; $i<=18; $i++) {
2427: $selectform.="<option value=\"$i\" ".
2428: ($i==$deflevel ? 'selected="selected" ' : '').
2429: ">".&gradeleveldescription($i)."</option>\n";
2430: }
2431: $selectform.="</select>";
2432: return $selectform;
2433: }
2434:
2435: #-------------------------------------------
2436:
2437: =pod
2438:
2439: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
2440:
2441: Returns a string containing a <select name='$name' size='1'> form to
2442: allow a user to select the domain to preform an operation in.
2443: See loncreateuser.pm for an example invocation and use.
2444:
2445: If the $includeempty flag is set, it also includes an empty choice ("no domain
2446: selected");
2447:
2448: If the $showdomdesc flag is set, the domain name is followed by the domain description.
2449:
2450: 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.
2451:
2452: The optional $incdoms is a reference to an array of domains which will be the only available options.
2453:
2454: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
2455:
2456: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
2457:
2458: =cut
2459:
2460: #-------------------------------------------
2461: sub select_dom_form {
2462: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
2463: if ($onchange) {
2464: $onchange = ' onchange="'.$onchange.'"';
2465: }
2466: if ($disabled) {
2467: $disabled = ' disabled="disabled"';
2468: }
2469: my (@domains,%exclude);
2470: if (ref($incdoms) eq 'ARRAY') {
2471: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
2472: } else {
2473: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
2474: }
2475: if ($includeempty) { @domains=('',@domains); }
2476: if (ref($excdoms) eq 'ARRAY') {
2477: map { $exclude{$_} = 1; } @{$excdoms};
2478: }
2479: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2480: foreach my $dom (@domains) {
2481: next if ($exclude{$dom});
2482: $selectdomain.="<option value=\"$dom\" ".
2483: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
2484: if ($showdomdesc) {
2485: if ($dom ne '') {
2486: my $domdesc = &Apache::lonnet::domain($dom,'description');
2487: if ($domdesc ne '') {
2488: $selectdomain .= ' ('.$domdesc.')';
2489: }
2490: }
2491: }
2492: $selectdomain .= "</option>\n";
2493: }
2494: $selectdomain.="</select>";
2495: return $selectdomain;
2496: }
2497:
2498: #-------------------------------------------
2499:
2500: =pod
2501:
2502: =item * &home_server_form_item($domain,$name,$defaultflag)
2503:
2504: input: 4 arguments (two required, two optional) -
2505: $domain - domain of new user
2506: $name - name of form element
2507: $default - Value of 'default' causes a default item to be first
2508: option, and selected by default.
2509: $hide - Value of 'hide' causes hiding of the name of the server,
2510: if 1 server found, or default, if 0 found.
2511: output: returns 2 items:
2512: (a) form element which contains either:
2513: (i) <select name="$name">
2514: <option value="$hostid1">$hostid $servers{$hostid}</option>
2515: <option value="$hostid2">$hostid $servers{$hostid}</option>
2516: </select>
2517: form item if there are multiple library servers in $domain, or
2518: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2519: if there is only one library server in $domain.
2520:
2521: (b) number of library servers found.
2522:
2523: See loncreateuser.pm for example of use.
2524:
2525: =cut
2526:
2527: #-------------------------------------------
2528: sub home_server_form_item {
2529: my ($domain,$name,$default,$hide) = @_;
2530: my %servers = &Apache::lonnet::get_servers($domain,'library');
2531: my $result;
2532: my $numlib = keys(%servers);
2533: if ($numlib > 1) {
2534: $result .= '<select name="'.$name.'" />'."\n";
2535: if ($default) {
2536: $result .= '<option value="default" selected="selected">'.&mt('default').
2537: '</option>'."\n";
2538: }
2539: foreach my $hostid (sort(keys(%servers))) {
2540: $result.= '<option value="'.$hostid.'">'.
2541: $hostid.' '.$servers{$hostid}."</option>\n";
2542: }
2543: $result .= '</select>'."\n";
2544: } elsif ($numlib == 1) {
2545: my $hostid;
2546: foreach my $item (keys(%servers)) {
2547: $hostid = $item;
2548: }
2549: $result .= '<input type="hidden" name="'.$name.'" value="'.
2550: $hostid.'" />';
2551: if (!$hide) {
2552: $result .= $hostid.' '.$servers{$hostid};
2553: }
2554: $result .= "\n";
2555: } elsif ($default) {
2556: $result .= '<input type="hidden" name="'.$name.
2557: '" value="default" />';
2558: if (!$hide) {
2559: $result .= &mt('default');
2560: }
2561: $result .= "\n";
2562: }
2563: return ($result,$numlib);
2564: }
2565:
2566: =pod
2567:
2568: =back
2569:
2570: =cut
2571:
2572: ###############################################################
2573: ## Decoding User Agent ##
2574: ###############################################################
2575:
2576: =pod
2577:
2578: =head1 Decoding the User Agent
2579:
2580: =over 4
2581:
2582: =item * &decode_user_agent()
2583:
2584: Inputs: $r
2585:
2586: Outputs:
2587:
2588: =over 4
2589:
2590: =item * $httpbrowser
2591:
2592: =item * $clientbrowser
2593:
2594: =item * $clientversion
2595:
2596: =item * $clientmathml
2597:
2598: =item * $clientunicode
2599:
2600: =item * $clientos
2601:
2602: =item * $clientmobile
2603:
2604: =item * $clientinfo
2605:
2606: =item * $clientosversion
2607:
2608: =back
2609:
2610: =back
2611:
2612: =cut
2613:
2614: ###############################################################
2615: ###############################################################
2616: sub decode_user_agent {
2617: my ($r)=@_;
2618: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
2619: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
2620: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
2621: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
2622: my $clientbrowser='unknown';
2623: my $clientversion='0';
2624: my $clientmathml='';
2625: my $clientunicode='0';
2626: my $clientmobile=0;
2627: my $clientosversion='';
2628: for (my $i=0;$i<=$#browsertype;$i++) {
2629: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
2630: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
2631: $clientbrowser=$bname;
2632: $httpbrowser=~/$vreg/i;
2633: $clientversion=$1;
2634: $clientmathml=($clientversion>=$minv);
2635: $clientunicode=($clientversion>=$univ);
2636: }
2637: }
2638: my $clientos='unknown';
2639: my $clientinfo;
2640: if (($httpbrowser=~/linux/i) ||
2641: ($httpbrowser=~/unix/i) ||
2642: ($httpbrowser=~/ux/i) ||
2643: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
2644: if (($httpbrowser=~/vax/i) ||
2645: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
2646: if ($httpbrowser=~/next/i) { $clientos='next'; }
2647: if (($httpbrowser=~/mac/i) ||
2648: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
2649: if ($httpbrowser=~/win/i) {
2650: $clientos='win';
2651: if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
2652: $clientosversion = $1;
2653: }
2654: }
2655: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
2656: if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
2657: $clientmobile=lc($1);
2658: }
2659: if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
2660: $clientinfo = 'firefox-'.$1;
2661: } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
2662: $clientinfo = 'chromeframe-'.$1;
2663: }
2664: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
2665: $clientunicode,$clientos,$clientmobile,$clientinfo,
2666: $clientosversion);
2667: }
2668:
2669: ###############################################################
2670: ## Authentication changing form generation subroutines ##
2671: ###############################################################
2672: ##
2673: ## All of the authform_xxxxxxx subroutines take their inputs in a
2674: ## hash, and have reasonable default values.
2675: ##
2676: ## formname = the name given in the <form> tag.
2677: #-------------------------------------------
2678:
2679: =pod
2680:
2681: =head1 Authentication Routines
2682:
2683: =over 4
2684:
2685: =item * &authform_xxxxxx()
2686:
2687: The authform_xxxxxx subroutines provide javascript and html forms which
2688: handle some of the conveniences required for authentication forms.
2689: This is not an optimal method, but it works.
2690:
2691: =over 4
2692:
2693: =item * authform_header
2694:
2695: =item * authform_authorwarning
2696:
2697: =item * authform_nochange
2698:
2699: =item * authform_kerberos
2700:
2701: =item * authform_internal
2702:
2703: =item * authform_filesystem
2704:
2705: =back
2706:
2707: See loncreateuser.pm for invocation and use examples.
2708:
2709: =cut
2710:
2711: #-------------------------------------------
2712: sub authform_header{
2713: my %in = (
2714: formname => 'cu',
2715: kerb_def_dom => '',
2716: @_,
2717: );
2718: $in{'formname'} = 'document.' . $in{'formname'};
2719: my $result='';
2720:
2721: #---------------------------------------------- Code for upper case translation
2722: my $Javascript_toUpperCase;
2723: unless ($in{kerb_def_dom}) {
2724: $Javascript_toUpperCase =<<"END";
2725: switch (choice) {
2726: case 'krb': currentform.elements[choicearg].value =
2727: currentform.elements[choicearg].value.toUpperCase();
2728: break;
2729: default:
2730: }
2731: END
2732: } else {
2733: $Javascript_toUpperCase = "";
2734: }
2735:
2736: my $radioval = "'nochange'";
2737: if (defined($in{'curr_authtype'})) {
2738: if ($in{'curr_authtype'} ne '') {
2739: $radioval = "'".$in{'curr_authtype'}."arg'";
2740: }
2741: }
2742: my $argfield = 'null';
2743: if (defined($in{'mode'})) {
2744: if ($in{'mode'} eq 'modifycourse') {
2745: if (defined($in{'curr_autharg'})) {
2746: if ($in{'curr_autharg'} ne '') {
2747: $argfield = "'$in{'curr_autharg'}'";
2748: }
2749: }
2750: }
2751: }
2752:
2753: $result.=<<"END";
2754: var current = new Object();
2755: current.radiovalue = $radioval;
2756: current.argfield = $argfield;
2757:
2758: function changed_radio(choice,currentform) {
2759: var choicearg = choice + 'arg';
2760: // If a radio button in changed, we need to change the argfield
2761: if (current.radiovalue != choice) {
2762: current.radiovalue = choice;
2763: if (current.argfield != null) {
2764: currentform.elements[current.argfield].value = '';
2765: }
2766: if (choice == 'nochange') {
2767: current.argfield = null;
2768: } else {
2769: current.argfield = choicearg;
2770: switch(choice) {
2771: case 'krb':
2772: currentform.elements[current.argfield].value =
2773: "$in{'kerb_def_dom'}";
2774: break;
2775: default:
2776: break;
2777: }
2778: }
2779: }
2780: return;
2781: }
2782:
2783: function changed_text(choice,currentform) {
2784: var choicearg = choice + 'arg';
2785: if (currentform.elements[choicearg].value !='') {
2786: $Javascript_toUpperCase
2787: // clear old field
2788: if ((current.argfield != choicearg) && (current.argfield != null)) {
2789: currentform.elements[current.argfield].value = '';
2790: }
2791: current.argfield = choicearg;
2792: }
2793: set_auth_radio_buttons(choice,currentform);
2794: return;
2795: }
2796:
2797: function set_auth_radio_buttons(newvalue,currentform) {
2798: var numauthchoices = currentform.login.length;
2799: if (typeof numauthchoices == "undefined") {
2800: return;
2801: }
2802: var i=0;
2803: while (i < numauthchoices) {
2804: if (currentform.login[i].value == newvalue) { break; }
2805: i++;
2806: }
2807: if (i == numauthchoices) {
2808: return;
2809: }
2810: current.radiovalue = newvalue;
2811: currentform.login[i].checked = true;
2812: return;
2813: }
2814: END
2815: return $result;
2816: }
2817:
2818: sub authform_authorwarning {
2819: my $result='';
2820: $result='<i>'.
2821: &mt('As a general rule, only authors or co-authors should be '.
2822: 'filesystem authenticated '.
2823: '(which allows access to the server filesystem).')."</i>\n";
2824: return $result;
2825: }
2826:
2827: sub authform_nochange {
2828: my %in = (
2829: formname => 'document.cu',
2830: kerb_def_dom => 'MSU.EDU',
2831: @_,
2832: );
2833: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2834: my $result;
2835: if (!$authnum) {
2836: $result = &mt('Under your current role you are not permitted to change login settings for this user');
2837: } else {
2838: $result = '<label>'.&mt('[_1] Do not change login data',
2839: '<input type="radio" name="login" value="nochange" '.
2840: 'checked="checked" onclick="'.
2841: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
2842: '</label>';
2843: }
2844: return $result;
2845: }
2846:
2847: sub authform_kerberos {
2848: my %in = (
2849: formname => 'document.cu',
2850: kerb_def_dom => 'MSU.EDU',
2851: kerb_def_auth => 'krb4',
2852: @_,
2853: );
2854: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2855: $autharg,$jscall,$disabled);
2856: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2857: if ($in{'kerb_def_auth'} eq 'krb5') {
2858: $check5 = ' checked="checked"';
2859: } else {
2860: $check4 = ' checked="checked"';
2861: }
2862: if ($in{'readonly'}) {
2863: $disabled = ' disabled="disabled"';
2864: }
2865: $krbarg = $in{'kerb_def_dom'};
2866: if (defined($in{'curr_authtype'})) {
2867: if ($in{'curr_authtype'} eq 'krb') {
2868: $krbcheck = ' checked="checked"';
2869: if (defined($in{'mode'})) {
2870: if ($in{'mode'} eq 'modifyuser') {
2871: $krbcheck = '';
2872: }
2873: }
2874: if (defined($in{'curr_kerb_ver'})) {
2875: if ($in{'curr_krb_ver'} eq '5') {
2876: $check5 = ' checked="checked"';
2877: $check4 = '';
2878: } else {
2879: $check4 = ' checked="checked"';
2880: $check5 = '';
2881: }
2882: }
2883: if (defined($in{'curr_autharg'})) {
2884: $krbarg = $in{'curr_autharg'};
2885: }
2886: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2887: if (defined($in{'curr_autharg'})) {
2888: $result =
2889: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
2890: $in{'curr_autharg'},$krbver);
2891: } else {
2892: $result =
2893: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
2894: }
2895: return $result;
2896: }
2897: }
2898: } else {
2899: if ($authnum == 1) {
2900: $authtype = '<input type="hidden" name="login" value="krb" />';
2901: }
2902: }
2903: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2904: return;
2905: } elsif ($authtype eq '') {
2906: if (defined($in{'mode'})) {
2907: if ($in{'mode'} eq 'modifycourse') {
2908: if ($authnum == 1) {
2909: $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
2910: }
2911: }
2912: }
2913: }
2914: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
2915: if ($authtype eq '') {
2916: $authtype = '<input type="radio" name="login" value="krb" '.
2917: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
2918: $krbcheck.$disabled.' />';
2919: }
2920: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
2921: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
2922: $in{'curr_authtype'} eq 'krb5') ||
2923: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
2924: $in{'curr_authtype'} eq 'krb4')) {
2925: $result .= &mt
2926: ('[_1] Kerberos authenticated with domain [_2] '.
2927: '[_3] Version 4 [_4] Version 5 [_5]',
2928: '<label>'.$authtype,
2929: '</label><input type="text" size="10" name="krbarg" '.
2930: 'value="'.$krbarg.'" '.
2931: 'onchange="'.$jscall.'"'.$disabled.' />',
2932: '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
2933: '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
2934: '</label>');
2935: } elsif ($can_assign{'krb4'}) {
2936: $result .= &mt
2937: ('[_1] Kerberos authenticated with domain [_2] '.
2938: '[_3] Version 4 [_4]',
2939: '<label>'.$authtype,
2940: '</label><input type="text" size="10" name="krbarg" '.
2941: 'value="'.$krbarg.'" '.
2942: 'onchange="'.$jscall.'"'.$disabled.' />',
2943: '<label><input type="hidden" name="krbver" value="4" />',
2944: '</label>');
2945: } elsif ($can_assign{'krb5'}) {
2946: $result .= &mt
2947: ('[_1] Kerberos authenticated with domain [_2] '.
2948: '[_3] Version 5 [_4]',
2949: '<label>'.$authtype,
2950: '</label><input type="text" size="10" name="krbarg" '.
2951: 'value="'.$krbarg.'" '.
2952: 'onchange="'.$jscall.'"'.$disabled.' />',
2953: '<label><input type="hidden" name="krbver" value="5" />',
2954: '</label>');
2955: }
2956: return $result;
2957: }
2958:
2959: sub authform_internal {
2960: my %in = (
2961: formname => 'document.cu',
2962: kerb_def_dom => 'MSU.EDU',
2963: @_,
2964: );
2965: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
2966: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2967: if ($in{'readonly'}) {
2968: $disabled = ' disabled="disabled"';
2969: }
2970: if (defined($in{'curr_authtype'})) {
2971: if ($in{'curr_authtype'} eq 'int') {
2972: if ($can_assign{'int'}) {
2973: $intcheck = 'checked="checked" ';
2974: if (defined($in{'mode'})) {
2975: if ($in{'mode'} eq 'modifyuser') {
2976: $intcheck = '';
2977: }
2978: }
2979: if (defined($in{'curr_autharg'})) {
2980: $intarg = $in{'curr_autharg'};
2981: }
2982: } else {
2983: $result = &mt('Currently internally authenticated.');
2984: return $result;
2985: }
2986: }
2987: } else {
2988: if ($authnum == 1) {
2989: $authtype = '<input type="hidden" name="login" value="int" />';
2990: }
2991: }
2992: if (!$can_assign{'int'}) {
2993: return;
2994: } elsif ($authtype eq '') {
2995: if (defined($in{'mode'})) {
2996: if ($in{'mode'} eq 'modifycourse') {
2997: if ($authnum == 1) {
2998: $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
2999: }
3000: }
3001: }
3002: }
3003: $jscall = "javascript:changed_radio('int',$in{'formname'});";
3004: if ($authtype eq '') {
3005: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
3006: ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
3007: }
3008: $autharg = '<input type="password" size="10" name="intarg" value="'.
3009: $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3010: $result = &mt
3011: ('[_1] Internally authenticated (with initial password [_2])',
3012: '<label>'.$authtype,'</label>'.$autharg);
3013: $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>';
3014: return $result;
3015: }
3016:
3017: sub authform_local {
3018: my %in = (
3019: formname => 'document.cu',
3020: kerb_def_dom => 'MSU.EDU',
3021: @_,
3022: );
3023: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
3024: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3025: if ($in{'readonly'}) {
3026: $disabled = ' disabled="disabled"';
3027: }
3028: if (defined($in{'curr_authtype'})) {
3029: if ($in{'curr_authtype'} eq 'loc') {
3030: if ($can_assign{'loc'}) {
3031: $loccheck = 'checked="checked" ';
3032: if (defined($in{'mode'})) {
3033: if ($in{'mode'} eq 'modifyuser') {
3034: $loccheck = '';
3035: }
3036: }
3037: if (defined($in{'curr_autharg'})) {
3038: $locarg = $in{'curr_autharg'};
3039: }
3040: } else {
3041: $result = &mt('Currently using local (institutional) authentication.');
3042: return $result;
3043: }
3044: }
3045: } else {
3046: if ($authnum == 1) {
3047: $authtype = '<input type="hidden" name="login" value="loc" />';
3048: }
3049: }
3050: if (!$can_assign{'loc'}) {
3051: return;
3052: } elsif ($authtype eq '') {
3053: if (defined($in{'mode'})) {
3054: if ($in{'mode'} eq 'modifycourse') {
3055: if ($authnum == 1) {
3056: $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
3057: }
3058: }
3059: }
3060: }
3061: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
3062: if ($authtype eq '') {
3063: $authtype = '<input type="radio" name="login" value="loc" '.
3064: $loccheck.' onchange="'.$jscall.'" onclick="'.
3065: $jscall.'"'.$disabled.' />';
3066: }
3067: $autharg = '<input type="text" size="10" name="locarg" value="'.
3068: $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3069: $result = &mt('[_1] Local Authentication with argument [_2]',
3070: '<label>'.$authtype,'</label>'.$autharg);
3071: return $result;
3072: }
3073:
3074: sub authform_filesystem {
3075: my %in = (
3076: formname => 'document.cu',
3077: kerb_def_dom => 'MSU.EDU',
3078: @_,
3079: );
3080: my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
3081: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3082: if ($in{'readonly'}) {
3083: $disabled = ' disabled="disabled"';
3084: }
3085: if (defined($in{'curr_authtype'})) {
3086: if ($in{'curr_authtype'} eq 'fsys') {
3087: if ($can_assign{'fsys'}) {
3088: $fsyscheck = 'checked="checked" ';
3089: if (defined($in{'mode'})) {
3090: if ($in{'mode'} eq 'modifyuser') {
3091: $fsyscheck = '';
3092: }
3093: }
3094: } else {
3095: $result = &mt('Currently Filesystem Authenticated.');
3096: return $result;
3097: }
3098: }
3099: } else {
3100: if ($authnum == 1) {
3101: $authtype = '<input type="hidden" name="login" value="fsys" />';
3102: }
3103: }
3104: if (!$can_assign{'fsys'}) {
3105: return;
3106: } elsif ($authtype eq '') {
3107: if (defined($in{'mode'})) {
3108: if ($in{'mode'} eq 'modifycourse') {
3109: if ($authnum == 1) {
3110: $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
3111: }
3112: }
3113: }
3114: }
3115: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
3116: if ($authtype eq '') {
3117: $authtype = '<input type="radio" name="login" value="fsys" '.
3118: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
3119: $jscall.'"'.$disabled.' />';
3120: }
3121: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
3122: ' onchange="'.$jscall.'"'.$disabled.' />';
3123: $result = &mt
3124: ('[_1] Filesystem Authenticated (with initial password [_2])',
3125: '<label><input type="radio" name="login" value="fsys" '.
3126: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
3127: '</label><input type="password" size="10" name="fsysarg" value="" '.
3128: 'onchange="'.$jscall.'"'.$disabled.' />');
3129: return $result;
3130: }
3131:
3132: sub get_assignable_auth {
3133: my ($dom) = @_;
3134: if ($dom eq '') {
3135: $dom = $env{'request.role.domain'};
3136: }
3137: my %can_assign = (
3138: krb4 => 1,
3139: krb5 => 1,
3140: int => 1,
3141: loc => 1,
3142: );
3143: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
3144: if (ref($domconfig{'usercreation'}) eq 'HASH') {
3145: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
3146: my $authhash = $domconfig{'usercreation'}{'authtypes'};
3147: my $context;
3148: if ($env{'request.role'} =~ /^au/) {
3149: $context = 'author';
3150: } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
3151: $context = 'domain';
3152: } elsif ($env{'request.course.id'}) {
3153: $context = 'course';
3154: }
3155: if ($context) {
3156: if (ref($authhash->{$context}) eq 'HASH') {
3157: %can_assign = %{$authhash->{$context}};
3158: }
3159: }
3160: }
3161: }
3162: my $authnum = 0;
3163: foreach my $key (keys(%can_assign)) {
3164: if ($can_assign{$key}) {
3165: $authnum ++;
3166: }
3167: }
3168: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
3169: $authnum --;
3170: }
3171: return ($authnum,%can_assign);
3172: }
3173:
3174: sub check_passwd_rules {
3175: my ($domain,$plainpass) = @_;
3176: my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
3177: my ($min,$max,@chars,@brokerule,$warning);
3178: $min = $Apache::lonnet::passwdmin;
3179: if (ref($passwdconf{'chars'}) eq 'ARRAY') {
3180: if ($passwdconf{'min'} =~ /^\d+$/) {
3181: if ($passwdconf{'min'} > $min) {
3182: $min = $passwdconf{'min'};
3183: }
3184: }
3185: if ($passwdconf{'max'} =~ /^\d+$/) {
3186: $max = $passwdconf{'max'};
3187: }
3188: @chars = @{$passwdconf{'chars'}};
3189: }
3190: if (($min) && (length($plainpass) < $min)) {
3191: push(@brokerule,'min');
3192: }
3193: if (($max) && (length($plainpass) > $max)) {
3194: push(@brokerule,'max');
3195: }
3196: if (@chars) {
3197: my %rules;
3198: map { $rules{$_} = 1; } @chars;
3199: if ($rules{'uc'}) {
3200: unless ($plainpass =~ /[A-Z]/) {
3201: push(@brokerule,'uc');
3202: }
3203: }
3204: if ($rules{'lc'}) {
3205: unless ($plainpass =~ /[a-z]/) {
3206: push(@brokerule,'lc');
3207: }
3208: }
3209: if ($rules{'num'}) {
3210: unless ($plainpass =~ /\d/) {
3211: push(@brokerule,'num');
3212: }
3213: }
3214: if ($rules{'spec'}) {
3215: unless ($plainpass =~ /[!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/) {
3216: push(@brokerule,'spec');
3217: }
3218: }
3219: }
3220: if (@brokerule) {
3221: my %rulenames = &Apache::lonlocal::texthash(
3222: uc => 'At least one upper case letter',
3223: lc => 'At least one lower case letter',
3224: num => 'At least one number',
3225: spec => 'At least one non-alphanumeric',
3226: );
3227: $rulenames{'uc'} .= ': ABCDEFGHIJKLMNOPQRSTUVWXYZ';
3228: $rulenames{'lc'} .= ': abcdefghijklmnopqrstuvwxyz';
3229: $rulenames{'num'} .= ': 0123456789';
3230: $rulenames{'spec'} .= ': !"\#$%&\'()*+,-./:;<=>?@[\]^_\`{|}~';
3231: $rulenames{'min'} = &mt('Minimum password length: [_1]',$min);
3232: $rulenames{'max'} = &mt('Maximum password length: [_1]',$max);
3233: $warning = &mt('Password did not satisfy the following:').'<ul>';
3234: foreach my $rule ('min','max','uc','ls','num','spec') {
3235: if (grep(/^$rule$/,@brokerule)) {
3236: $warning .= '<li>'.$rulenames{$rule}.'</li>';
3237: }
3238: }
3239: $warning .= '</ul>';
3240: }
3241: if (wantarray) {
3242: return @brokerule;
3243: }
3244: return $warning;
3245: }
3246:
3247: ###############################################################
3248: ## Get Kerberos Defaults for Domain ##
3249: ###############################################################
3250: ##
3251: ## Returns default kerberos version and an associated argument
3252: ## as listed in file domain.tab. If not listed, provides
3253: ## appropriate default domain and kerberos version.
3254: ##
3255: #-------------------------------------------
3256:
3257: =pod
3258:
3259: =item * &get_kerberos_defaults()
3260:
3261: get_kerberos_defaults($target_domain) returns the default kerberos
3262: version and domain. If not found, it defaults to version 4 and the
3263: domain of the server.
3264:
3265: =over 4
3266:
3267: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
3268:
3269: =back
3270:
3271: =back
3272:
3273: =cut
3274:
3275: #-------------------------------------------
3276: sub get_kerberos_defaults {
3277: my $domain=shift;
3278: my ($krbdef,$krbdefdom);
3279: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
3280: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
3281: $krbdef = $domdefaults{'auth_def'};
3282: $krbdefdom = $domdefaults{'auth_arg_def'};
3283: } else {
3284: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
3285: my $krbdefdom=$1;
3286: $krbdefdom=~tr/a-z/A-Z/;
3287: $krbdef = "krb4";
3288: }
3289: return ($krbdef,$krbdefdom);
3290: }
3291:
3292:
3293: ###############################################################
3294: ## Thesaurus Functions ##
3295: ###############################################################
3296:
3297: =pod
3298:
3299: =head1 Thesaurus Functions
3300:
3301: =over 4
3302:
3303: =item * &initialize_keywords()
3304:
3305: Initializes the package variable %Keywords if it is empty. Uses the
3306: package variable $thesaurus_db_file.
3307:
3308: =cut
3309:
3310: ###################################################
3311:
3312: sub initialize_keywords {
3313: return 1 if (scalar keys(%Keywords));
3314: # If we are here, %Keywords is empty, so fill it up
3315: # Make sure the file we need exists...
3316: if (! -e $thesaurus_db_file) {
3317: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
3318: " failed because it does not exist");
3319: return 0;
3320: }
3321: # Set up the hash as a database
3322: my %thesaurus_db;
3323: if (! tie(%thesaurus_db,'GDBM_File',
3324: $thesaurus_db_file,&GDBM_READER(),0640)){
3325: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
3326: $thesaurus_db_file);
3327: return 0;
3328: }
3329: # Get the average number of appearances of a word.
3330: my $avecount = $thesaurus_db{'average.count'};
3331: # Put keywords (those that appear > average) into %Keywords
3332: while (my ($word,$data)=each (%thesaurus_db)) {
3333: my ($count,undef) = split /:/,$data;
3334: $Keywords{$word}++ if ($count > $avecount);
3335: }
3336: untie %thesaurus_db;
3337: # Remove special values from %Keywords.
3338: foreach my $value ('total.count','average.count') {
3339: delete($Keywords{$value}) if (exists($Keywords{$value}));
3340: }
3341: return 1;
3342: }
3343:
3344: ###################################################
3345:
3346: =pod
3347:
3348: =item * &keyword($word)
3349:
3350: Returns true if $word is a keyword. A keyword is a word that appears more
3351: than the average number of times in the thesaurus database. Calls
3352: &initialize_keywords
3353:
3354: =cut
3355:
3356: ###################################################
3357:
3358: sub keyword {
3359: return if (!&initialize_keywords());
3360: my $word=lc(shift());
3361: $word=~s/\W//g;
3362: return exists($Keywords{$word});
3363: }
3364:
3365: ###############################################################
3366:
3367: =pod
3368:
3369: =item * &get_related_words()
3370:
3371: Look up a word in the thesaurus. Takes a scalar argument and returns
3372: an array of words. If the keyword is not in the thesaurus, an empty array
3373: will be returned. The order of the words returned is determined by the
3374: database which holds them.
3375:
3376: Uses global $thesaurus_db_file.
3377:
3378:
3379: =cut
3380:
3381: ###############################################################
3382: sub get_related_words {
3383: my $keyword = shift;
3384: my %thesaurus_db;
3385: if (! -e $thesaurus_db_file) {
3386: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
3387: "failed because the file does not exist");
3388: return ();
3389: }
3390: if (! tie(%thesaurus_db,'GDBM_File',
3391: $thesaurus_db_file,&GDBM_READER(),0640)){
3392: return ();
3393: }
3394: my @Words=();
3395: my $count=0;
3396: if (exists($thesaurus_db{$keyword})) {
3397: # The first element is the number of times
3398: # the word appears. We do not need it now.
3399: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
3400: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
3401: my $threshold=$mostfrequentcount/10;
3402: foreach my $possibleword (@RelatedWords) {
3403: my ($word,$wordcount)=split(/\,/,$possibleword);
3404: if ($wordcount>$threshold) {
3405: push(@Words,$word);
3406: $count++;
3407: if ($count>10) { last; }
3408: }
3409: }
3410: }
3411: untie %thesaurus_db;
3412: return @Words;
3413: }
3414:
3415: =pod
3416:
3417: =back
3418:
3419: =cut
3420:
3421: # -------------------------------------------------------------- Plaintext name
3422: =pod
3423:
3424: =head1 User Name Functions
3425:
3426: =over 4
3427:
3428: =item * &plainname($uname,$udom,$first)
3429:
3430: Takes a users logon name and returns it as a string in
3431: "first middle last generation" form
3432: if $first is set to 'lastname' then it returns it as
3433: 'lastname generation, firstname middlename' if their is a lastname
3434:
3435: =cut
3436:
3437:
3438: ###############################################################
3439: sub plainname {
3440: my ($uname,$udom,$first)=@_;
3441: return if (!defined($uname) || !defined($udom));
3442: my %names=&getnames($uname,$udom);
3443: my $name=&Apache::lonnet::format_name($names{'firstname'},
3444: $names{'middlename'},
3445: $names{'lastname'},
3446: $names{'generation'},$first);
3447: $name=~s/^\s+//;
3448: $name=~s/\s+$//;
3449: $name=~s/\s+/ /g;
3450: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
3451: return $name;
3452: }
3453:
3454: # -------------------------------------------------------------------- Nickname
3455: =pod
3456:
3457: =item * &nickname($uname,$udom)
3458:
3459: Gets a users name and returns it as a string as
3460:
3461: ""nickname""
3462:
3463: if the user has a nickname or
3464:
3465: "first middle last generation"
3466:
3467: if the user does not
3468:
3469: =cut
3470:
3471: sub nickname {
3472: my ($uname,$udom)=@_;
3473: return if (!defined($uname) || !defined($udom));
3474: my %names=&getnames($uname,$udom);
3475: my $name=$names{'nickname'};
3476: if ($name) {
3477: $name='"'.$name.'"';
3478: } else {
3479: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
3480: $names{'lastname'}.' '.$names{'generation'};
3481: $name=~s/\s+$//;
3482: $name=~s/\s+/ /g;
3483: }
3484: return $name;
3485: }
3486:
3487: sub getnames {
3488: my ($uname,$udom)=@_;
3489: return if (!defined($uname) || !defined($udom));
3490: if ($udom eq 'public' && $uname eq 'public') {
3491: return ('lastname' => &mt('Public'));
3492: }
3493: my $id=$uname.':'.$udom;
3494: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
3495: if ($cached) {
3496: return %{$names};
3497: } else {
3498: my %loadnames=&Apache::lonnet::get('environment',
3499: ['firstname','middlename','lastname','generation','nickname'],
3500: $udom,$uname);
3501: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
3502: return %loadnames;
3503: }
3504: }
3505:
3506: # -------------------------------------------------------------------- getemails
3507:
3508: =pod
3509:
3510: =item * &getemails($uname,$udom)
3511:
3512: Gets a user's email information and returns it as a hash with keys:
3513: notification, critnotification, permanentemail
3514:
3515: For notification and critnotification, values are comma-separated lists
3516: of e-mail addresses; for permanentemail, value is a single e-mail address.
3517:
3518:
3519: =cut
3520:
3521:
3522: sub getemails {
3523: my ($uname,$udom)=@_;
3524: if ($udom eq 'public' && $uname eq 'public') {
3525: return;
3526: }
3527: if (!$udom) { $udom=$env{'user.domain'}; }
3528: if (!$uname) { $uname=$env{'user.name'}; }
3529: my $id=$uname.':'.$udom;
3530: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
3531: if ($cached) {
3532: return %{$names};
3533: } else {
3534: my %loadnames=&Apache::lonnet::get('environment',
3535: ['notification','critnotification',
3536: 'permanentemail'],
3537: $udom,$uname);
3538: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
3539: return %loadnames;
3540: }
3541: }
3542:
3543: sub flush_email_cache {
3544: my ($uname,$udom)=@_;
3545: if (!$udom) { $udom =$env{'user.domain'}; }
3546: if (!$uname) { $uname=$env{'user.name'}; }
3547: return if ($udom eq 'public' && $uname eq 'public');
3548: my $id=$uname.':'.$udom;
3549: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
3550: }
3551:
3552: # -------------------------------------------------------------------- getlangs
3553:
3554: =pod
3555:
3556: =item * &getlangs($uname,$udom)
3557:
3558: Gets a user's language preference and returns it as a hash with key:
3559: language.
3560:
3561: =cut
3562:
3563:
3564: sub getlangs {
3565: my ($uname,$udom) = @_;
3566: if (!$udom) { $udom =$env{'user.domain'}; }
3567: if (!$uname) { $uname=$env{'user.name'}; }
3568: my $id=$uname.':'.$udom;
3569: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
3570: if ($cached) {
3571: return %{$langs};
3572: } else {
3573: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
3574: $udom,$uname);
3575: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
3576: return %loadlangs;
3577: }
3578: }
3579:
3580: sub flush_langs_cache {
3581: my ($uname,$udom)=@_;
3582: if (!$udom) { $udom =$env{'user.domain'}; }
3583: if (!$uname) { $uname=$env{'user.name'}; }
3584: return if ($udom eq 'public' && $uname eq 'public');
3585: my $id=$uname.':'.$udom;
3586: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
3587: }
3588:
3589: # ------------------------------------------------------------------ Screenname
3590:
3591: =pod
3592:
3593: =item * &screenname($uname,$udom)
3594:
3595: Gets a users screenname and returns it as a string
3596:
3597: =cut
3598:
3599: sub screenname {
3600: my ($uname,$udom)=@_;
3601: if ($uname eq $env{'user.name'} &&
3602: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
3603: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
3604: return $names{'screenname'};
3605: }
3606:
3607:
3608: # ------------------------------------------------------------- Confirm Wrapper
3609: =pod
3610:
3611: =item * &confirmwrapper($message)
3612:
3613: Wrap messages about completion of operation in box
3614:
3615: =cut
3616:
3617: sub confirmwrapper {
3618: my ($message)=@_;
3619: if ($message) {
3620: return "\n".'<div class="LC_confirm_box">'."\n"
3621: .$message."\n"
3622: .'</div>'."\n";
3623: } else {
3624: return $message;
3625: }
3626: }
3627:
3628: # ------------------------------------------------------------- Message Wrapper
3629:
3630: sub messagewrapper {
3631: my ($link,$username,$domain,$subject,$text)=@_;
3632: return
3633: '<a href="/adm/email?compose=individual&'.
3634: 'recname='.$username.'&recdom='.$domain.
3635: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
3636: 'title="'.&mt('Send message').'">'.$link.'</a>';
3637: }
3638:
3639: # --------------------------------------------------------------- Notes Wrapper
3640:
3641: sub noteswrapper {
3642: my ($link,$un,$do)=@_;
3643: return
3644: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
3645: }
3646:
3647: # ------------------------------------------------------------- Aboutme Wrapper
3648:
3649: sub aboutmewrapper {
3650: my ($link,$username,$domain,$target,$class)=@_;
3651: if (!defined($username) && !defined($domain)) {
3652: return;
3653: }
3654: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
3655: ($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
3656: }
3657:
3658: # ------------------------------------------------------------ Syllabus Wrapper
3659:
3660: sub syllabuswrapper {
3661: my ($linktext,$coursedir,$domain)=@_;
3662: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
3663: }
3664:
3665: # -----------------------------------------------------------------------------
3666:
3667: sub track_student_link {
3668: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
3669: my $link ="/adm/trackstudent?";
3670: my $title = 'View recent activity';
3671: if (defined($sname) && $sname !~ /^\s*$/ &&
3672: defined($sdom) && $sdom !~ /^\s*$/) {
3673: $link .= "selected_student=$sname:$sdom";
3674: $title .= ' of this student';
3675: }
3676: if (defined($target) && $target !~ /^\s*$/) {
3677: $target = qq{target="$target"};
3678: } else {
3679: $target = '';
3680: }
3681: if ($start) { $link.='&start='.$start; }
3682: if ($only_body) { $link .= '&only_body=1'; }
3683: $title = &mt($title);
3684: $linktext = &mt($linktext);
3685: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
3686: &help_open_topic('View_recent_activity');
3687: }
3688:
3689: sub slot_reservations_link {
3690: my ($linktext,$sname,$sdom,$target) = @_;
3691: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
3692: my $title = 'View slot reservation history';
3693: if (defined($sname) && $sname !~ /^\s*$/ &&
3694: defined($sdom) && $sdom !~ /^\s*$/) {
3695: $link .= "&uname=$sname&udom=$sdom";
3696: $title .= ' of this student';
3697: }
3698: if (defined($target) && $target !~ /^\s*$/) {
3699: $target = qq{target="$target"};
3700: } else {
3701: $target = '';
3702: }
3703: $title = &mt($title);
3704: $linktext = &mt($linktext);
3705: return qq{<a href="$link" title="$title" $target>$linktext</a>};
3706: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
3707:
3708: }
3709:
3710: # ===================================================== Display a student photo
3711:
3712:
3713: sub student_image_tag {
3714: my ($domain,$user)=@_;
3715: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
3716: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
3717: return '<img src="'.$imgsrc.'" align="right" />';
3718: } else {
3719: return '';
3720: }
3721: }
3722:
3723: =pod
3724:
3725: =back
3726:
3727: =head1 Access .tab File Data
3728:
3729: =over 4
3730:
3731: =item * &languageids()
3732:
3733: returns list of all language ids
3734:
3735: =cut
3736:
3737: sub languageids {
3738: return sort(keys(%language));
3739: }
3740:
3741: =pod
3742:
3743: =item * &languagedescription()
3744:
3745: returns description of a specified language id
3746:
3747: =cut
3748:
3749: sub languagedescription {
3750: my $code=shift;
3751: return ($supported_language{$code}?'* ':'').
3752: $language{$code}.
3753: ($supported_language{$code}?' ('.&mt('interface available').')':'');
3754: }
3755:
3756: =pod
3757:
3758: =item * &plainlanguagedescription
3759:
3760: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
3761: and the language character encoding (e.g. ISO) separated by a ' - ' string.
3762:
3763: =cut
3764:
3765: sub plainlanguagedescription {
3766: my $code=shift;
3767: return $language{$code};
3768: }
3769:
3770: =pod
3771:
3772: =item * &supportedlanguagecode
3773:
3774: Returns the supported language code (e.g. sptutf maps to pt) given a language
3775: code.
3776:
3777: =cut
3778:
3779: sub supportedlanguagecode {
3780: my $code=shift;
3781: return $supported_language{$code};
3782: }
3783:
3784: =pod
3785:
3786: =item * &latexlanguage()
3787:
3788: Given a language key code returns the correspondnig language to use
3789: to select the correct hyphenation on LaTeX printouts. This is undef if there
3790: is no supported hyphenation for the language code.
3791:
3792: =cut
3793:
3794: sub latexlanguage {
3795: my $code = shift;
3796: return $latex_language{$code};
3797: }
3798:
3799: =pod
3800:
3801: =item * &latexhyphenation()
3802:
3803: Same as above but what's supplied is the language as it might be stored
3804: in the metadata.
3805:
3806: =cut
3807:
3808: sub latexhyphenation {
3809: my $key = shift;
3810: return $latex_language_bykey{$key};
3811: }
3812:
3813: =pod
3814:
3815: =item * ©rightids()
3816:
3817: returns list of all copyrights
3818:
3819: =cut
3820:
3821: sub copyrightids {
3822: return sort(keys(%cprtag));
3823: }
3824:
3825: =pod
3826:
3827: =item * ©rightdescription()
3828:
3829: returns description of a specified copyright id
3830:
3831: =cut
3832:
3833: sub copyrightdescription {
3834: return &mt($cprtag{shift(@_)});
3835: }
3836:
3837: =pod
3838:
3839: =item * &source_copyrightids()
3840:
3841: returns list of all source copyrights
3842:
3843: =cut
3844:
3845: sub source_copyrightids {
3846: return sort(keys(%scprtag));
3847: }
3848:
3849: =pod
3850:
3851: =item * &source_copyrightdescription()
3852:
3853: returns description of a specified source copyright id
3854:
3855: =cut
3856:
3857: sub source_copyrightdescription {
3858: return &mt($scprtag{shift(@_)});
3859: }
3860:
3861: =pod
3862:
3863: =item * &filecategories()
3864:
3865: returns list of all file categories
3866:
3867: =cut
3868:
3869: sub filecategories {
3870: return sort(keys(%category_extensions));
3871: }
3872:
3873: =pod
3874:
3875: =item * &filecategorytypes()
3876:
3877: returns list of file types belonging to a given file
3878: category
3879:
3880: =cut
3881:
3882: sub filecategorytypes {
3883: my ($cat) = @_;
3884: return @{$category_extensions{lc($cat)}};
3885: }
3886:
3887: =pod
3888:
3889: =item * &fileembstyle()
3890:
3891: returns embedding style for a specified file type
3892:
3893: =cut
3894:
3895: sub fileembstyle {
3896: return $fe{lc(shift(@_))};
3897: }
3898:
3899: sub filemimetype {
3900: return $fm{lc(shift(@_))};
3901: }
3902:
3903:
3904: sub filecategoryselect {
3905: my ($name,$value)=@_;
3906: return &select_form($value,$name,
3907: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
3908: }
3909:
3910: =pod
3911:
3912: =item * &filedescription()
3913:
3914: returns description for a specified file type
3915:
3916: =cut
3917:
3918: sub filedescription {
3919: my $file_description = $fd{lc(shift())};
3920: $file_description =~ s:([\[\]]):~$1:g;
3921: return &mt($file_description);
3922: }
3923:
3924: =pod
3925:
3926: =item * &filedescriptionex()
3927:
3928: returns description for a specified file type with
3929: extra formatting
3930:
3931: =cut
3932:
3933: sub filedescriptionex {
3934: my $ex=shift;
3935: my $file_description = $fd{lc($ex)};
3936: $file_description =~ s:([\[\]]):~$1:g;
3937: return '.'.$ex.' '.&mt($file_description);
3938: }
3939:
3940: # End of .tab access
3941: =pod
3942:
3943: =back
3944:
3945: =cut
3946:
3947: # ------------------------------------------------------------------ File Types
3948: sub fileextensions {
3949: return sort(keys(%fe));
3950: }
3951:
3952: # ----------------------------------------------------------- Display Languages
3953: # returns a hash with all desired display languages
3954: #
3955:
3956: sub display_languages {
3957: my %languages=();
3958: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
3959: $languages{$lang}=1;
3960: }
3961: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3962: if ($env{'form.displaylanguage'}) {
3963: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3964: $languages{$lang}=1;
3965: }
3966: }
3967: return %languages;
3968: }
3969:
3970: sub languages {
3971: my ($possible_langs) = @_;
3972: my @preferred_langs = &Apache::lonlocal::preferred_languages();
3973: if (!ref($possible_langs)) {
3974: if( wantarray ) {
3975: return @preferred_langs;
3976: } else {
3977: return $preferred_langs[0];
3978: }
3979: }
3980: my %possibilities = map { $_ => 1 } (@$possible_langs);
3981: my @preferred_possibilities;
3982: foreach my $preferred_lang (@preferred_langs) {
3983: if (exists($possibilities{$preferred_lang})) {
3984: push(@preferred_possibilities, $preferred_lang);
3985: }
3986: }
3987: if( wantarray ) {
3988: return @preferred_possibilities;
3989: }
3990: return $preferred_possibilities[0];
3991: }
3992:
3993: sub user_lang {
3994: my ($touname,$toudom,$fromcid) = @_;
3995: my @userlangs;
3996: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
3997: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
3998: $env{'course.'.$fromcid.'.languages'}));
3999: } else {
4000: my %langhash = &getlangs($touname,$toudom);
4001: if ($langhash{'languages'} ne '') {
4002: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
4003: } else {
4004: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
4005: if ($domdefs{'lang_def'} ne '') {
4006: @userlangs = ($domdefs{'lang_def'});
4007: }
4008: }
4009: }
4010: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
4011: my $user_lh = Apache::localize->get_handle(@languages);
4012: return $user_lh;
4013: }
4014:
4015:
4016: ###############################################################
4017: ## Student Answer Attempts ##
4018: ###############################################################
4019:
4020: =pod
4021:
4022: =head1 Alternate Problem Views
4023:
4024: =over 4
4025:
4026: =item * &get_previous_attempt($symb, $username, $domain, $course,
4027: $getattempt, $regexp, $gradesub, $usec, $identifier)
4028:
4029: Return string with previous attempt on problem. Arguments:
4030:
4031: =over 4
4032:
4033: =item * $symb: Problem, including path
4034:
4035: =item * $username: username of the desired student
4036:
4037: =item * $domain: domain of the desired student
4038:
4039: =item * $course: Course ID
4040:
4041: =item * $getattempt: Leave blank for all attempts, otherwise put
4042: something
4043:
4044: =item * $regexp: if string matches this regexp, the string will be
4045: sent to $gradesub
4046:
4047: =item * $gradesub: routine that processes the string if it matches $regexp
4048:
4049: =item * $usec: section of the desired student
4050:
4051: =item * $identifier: counter for student (multiple students one problem) or
4052: problem (one student; whole sequence).
4053:
4054: =back
4055:
4056: The output string is a table containing all desired attempts, if any.
4057:
4058: =cut
4059:
4060: sub get_previous_attempt {
4061: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
4062: my $prevattempts='';
4063: no strict 'refs';
4064: if ($symb) {
4065: my (%returnhash)=
4066: &Apache::lonnet::restore($symb,$course,$domain,$username);
4067: if ($returnhash{'version'}) {
4068: my %lasthash=();
4069: my $version;
4070: for ($version=1;$version<=$returnhash{'version'};$version++) {
4071: foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
4072: if ($key =~ /\.rawrndseed$/) {
4073: my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
4074: $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
4075: } else {
4076: $lasthash{$key}=$returnhash{$version.':'.$key};
4077: }
4078: }
4079: }
4080: $prevattempts=&start_data_table().&start_data_table_header_row();
4081: $prevattempts.='<th>'.&mt('History').'</th>';
4082: my (%typeparts,%lasthidden,%regraded,%hidestatus);
4083: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
4084: foreach my $key (sort(keys(%lasthash))) {
4085: my ($ign,@parts) = split(/\./,$key);
4086: if ($#parts > 0) {
4087: my $data=$parts[-1];
4088: next if ($data eq 'foilorder');
4089: pop(@parts);
4090: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
4091: if ($data eq 'type') {
4092: unless ($showsurv) {
4093: my $id = join(',',@parts);
4094: $typeparts{$ign.'.'.$id} = $lasthash{$key};
4095: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
4096: $lasthidden{$ign.'.'.$id} = 1;
4097: }
4098: }
4099: if ($identifier ne '') {
4100: my $id = join(',',@parts);
4101: if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
4102: $domain,$username,$usec,undef,$course) =~ /^no/) {
4103: $hidestatus{$ign.'.'.$id} = 1;
4104: }
4105: }
4106: } elsif ($data eq 'regrader') {
4107: if (($identifier ne '') && (@parts)) {
4108: my $id = join(',',@parts);
4109: $regraded{$ign.'.'.$id} = 1;
4110: }
4111: }
4112: } else {
4113: if ($#parts == 0) {
4114: $prevattempts.='<th>'.$parts[0].'</th>';
4115: } else {
4116: $prevattempts.='<th>'.$ign.'</th>';
4117: }
4118: }
4119: }
4120: $prevattempts.=&end_data_table_header_row();
4121: if ($getattempt eq '') {
4122: my (%solved,%resets,%probstatus);
4123: if (($identifier ne '') && (keys(%regraded) > 0)) {
4124: for ($version=1;$version<=$returnhash{'version'};$version++) {
4125: foreach my $id (keys(%regraded)) {
4126: if (($returnhash{$version.':'.$id.'.regrader'}) &&
4127: ($returnhash{$version.':'.$id.'.tries'} eq '') &&
4128: ($returnhash{$version.':'.$id.'.award'} eq '')) {
4129: push(@{$resets{$id}},$version);
4130: }
4131: }
4132: }
4133: }
4134: for ($version=1;$version<=$returnhash{'version'};$version++) {
4135: my (@hidden,@unsolved);
4136: if (%typeparts) {
4137: foreach my $id (keys(%typeparts)) {
4138: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
4139: ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
4140: push(@hidden,$id);
4141: } elsif ($identifier ne '') {
4142: unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
4143: ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
4144: ($hidestatus{$id})) {
4145: next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
4146: if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
4147: push(@{$solved{$id}},$version);
4148: } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
4149: (ref($solved{$id}) eq 'ARRAY')) {
4150: my $skip;
4151: if (ref($resets{$id}) eq 'ARRAY') {
4152: foreach my $reset (@{$resets{$id}}) {
4153: if ($reset > $solved{$id}[-1]) {
4154: $skip=1;
4155: last;
4156: }
4157: }
4158: }
4159: unless ($skip) {
4160: my ($ign,$partslist) = split(/\./,$id,2);
4161: push(@unsolved,$partslist);
4162: }
4163: }
4164: }
4165: }
4166: }
4167: }
4168: $prevattempts.=&start_data_table_row().
4169: '<td>'.&mt('Transaction [_1]',$version);
4170: if (@unsolved) {
4171: $prevattempts .= '<span class="LC_nobreak"><label>'.
4172: '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
4173: &mt('Hide').'</label></span>';
4174: }
4175: $prevattempts .= '</td>';
4176: if (@hidden) {
4177: foreach my $key (sort(keys(%lasthash))) {
4178: next if ($key =~ /\.foilorder$/);
4179: my $hide;
4180: foreach my $id (@hidden) {
4181: if ($key =~ /^\Q$id\E/) {
4182: $hide = 1;
4183: last;
4184: }
4185: }
4186: if ($hide) {
4187: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4188: if (($data eq 'award') || ($data eq 'awarddetail')) {
4189: my $value = &format_previous_attempt_value($key,
4190: $returnhash{$version.':'.$key});
4191: $prevattempts.='<td>'.$value.' </td>';
4192: } else {
4193: $prevattempts.='<td> </td>';
4194: }
4195: } else {
4196: if ($key =~ /\./) {
4197: my $value = $returnhash{$version.':'.$key};
4198: if ($key =~ /\.rndseed$/) {
4199: my ($id) = ($key =~ /^(.+)\.rndseed$/);
4200: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4201: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4202: }
4203: }
4204: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4205: ' </td>';
4206: } else {
4207: $prevattempts.='<td> </td>';
4208: }
4209: }
4210: }
4211: } else {
4212: foreach my $key (sort(keys(%lasthash))) {
4213: next if ($key =~ /\.foilorder$/);
4214: my $value = $returnhash{$version.':'.$key};
4215: if ($key =~ /\.rndseed$/) {
4216: my ($id) = ($key =~ /^(.+)\.rndseed$/);
4217: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4218: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4219: }
4220: }
4221: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4222: ' </td>';
4223: }
4224: }
4225: $prevattempts.=&end_data_table_row();
4226: }
4227: }
4228: my @currhidden = keys(%lasthidden);
4229: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
4230: foreach my $key (sort(keys(%lasthash))) {
4231: next if ($key =~ /\.foilorder$/);
4232: if (%typeparts) {
4233: my $hidden;
4234: foreach my $id (@currhidden) {
4235: if ($key =~ /^\Q$id\E/) {
4236: $hidden = 1;
4237: last;
4238: }
4239: }
4240: if ($hidden) {
4241: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4242: if (($data eq 'award') || ($data eq 'awarddetail')) {
4243: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4244: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4245: $value = &$gradesub($value);
4246: }
4247: $prevattempts.='<td>'.$value.' </td>';
4248: } else {
4249: $prevattempts.='<td> </td>';
4250: }
4251: } else {
4252: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4253: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4254: $value = &$gradesub($value);
4255: }
4256: $prevattempts.='<td>'.$value.' </td>';
4257: }
4258: } else {
4259: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4260: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4261: $value = &$gradesub($value);
4262: }
4263: $prevattempts.='<td>'.$value.' </td>';
4264: }
4265: }
4266: $prevattempts.= &end_data_table_row().&end_data_table();
4267: } else {
4268: $prevattempts=
4269: &start_data_table().&start_data_table_row().
4270: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
4271: &end_data_table_row().&end_data_table();
4272: }
4273: } else {
4274: $prevattempts=
4275: &start_data_table().&start_data_table_row().
4276: '<td>'.&mt('No data.').'</td>'.
4277: &end_data_table_row().&end_data_table();
4278: }
4279: }
4280:
4281: sub format_previous_attempt_value {
4282: my ($key,$value) = @_;
4283: if (($key =~ /timestamp/) || ($key=~/duedate/)) {
4284: $value = &Apache::lonlocal::locallocaltime($value);
4285: } elsif (ref($value) eq 'ARRAY') {
4286: $value = '('.join(', ', @{ $value }).')';
4287: } elsif ($key =~ /answerstring$/) {
4288: my %answers = &Apache::lonnet::str2hash($value);
4289: my @anskeys = sort(keys(%answers));
4290: if (@anskeys == 1) {
4291: my $answer = $answers{$anskeys[0]};
4292: if ($answer =~ m{\0}) {
4293: $answer =~ s{\0}{,}g;
4294: }
4295: my $tag_internal_answer_name = 'INTERNAL';
4296: if ($anskeys[0] eq $tag_internal_answer_name) {
4297: $value = $answer;
4298: } else {
4299: $value = $anskeys[0].'='.$answer;
4300: }
4301: } else {
4302: foreach my $ans (@anskeys) {
4303: my $answer = $answers{$ans};
4304: if ($answer =~ m{\0}) {
4305: $answer =~ s{\0}{,}g;
4306: }
4307: $value .= $ans.'='.$answer.'<br />';;
4308: }
4309: }
4310: } else {
4311: $value = &unescape($value);
4312: }
4313: return $value;
4314: }
4315:
4316:
4317: sub relative_to_absolute {
4318: my ($url,$output)=@_;
4319: my $parser=HTML::TokeParser->new(\$output);
4320: my $token;
4321: my $thisdir=$url;
4322: my @rlinks=();
4323: while ($token=$parser->get_token) {
4324: if ($token->[0] eq 'S') {
4325: if ($token->[1] eq 'a') {
4326: if ($token->[2]->{'href'}) {
4327: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
4328: }
4329: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
4330: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
4331: } elsif ($token->[1] eq 'base') {
4332: $thisdir=$token->[2]->{'href'};
4333: }
4334: }
4335: }
4336: $thisdir=~s-/[^/]*$--;
4337: foreach my $link (@rlinks) {
4338: unless (($link=~/^https?\:\/\//i) ||
4339: ($link=~/^\//) ||
4340: ($link=~/^javascript:/i) ||
4341: ($link=~/^mailto:/i) ||
4342: ($link=~/^\#/)) {
4343: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
4344: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
4345: }
4346: }
4347: # -------------------------------------------------- Deal with Applet codebases
4348: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
4349: return $output;
4350: }
4351:
4352: =pod
4353:
4354: =item * &get_student_view()
4355:
4356: show a snapshot of what student was looking at
4357:
4358: =cut
4359:
4360: sub get_student_view {
4361: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
4362: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4363: my (%form);
4364: my @elements=('symb','courseid','domain','username');
4365: foreach my $element (@elements) {
4366: $form{'grade_'.$element}=eval '$'.$element #'
4367: }
4368: if (defined($moreenv)) {
4369: %form=(%form,%{$moreenv});
4370: }
4371: if (defined($target)) { $form{'grade_target'} = $target; }
4372: $feedurl=&Apache::lonnet::clutter($feedurl);
4373: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
4374: $userview=~s/\<body[^\>]*\>//gi;
4375: $userview=~s/\<\/body\>//gi;
4376: $userview=~s/\<html\>//gi;
4377: $userview=~s/\<\/html\>//gi;
4378: $userview=~s/\<head\>//gi;
4379: $userview=~s/\<\/head\>//gi;
4380: $userview=~s/action\s*\=/would_be_action\=/gi;
4381: $userview=&relative_to_absolute($feedurl,$userview);
4382: if (wantarray) {
4383: return ($userview,$response);
4384: } else {
4385: return $userview;
4386: }
4387: }
4388:
4389: sub get_student_view_with_retries {
4390: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
4391:
4392: my $ok = 0; # True if we got a good response.
4393: my $content;
4394: my $response;
4395:
4396: # Try to get the student_view done. within the retries count:
4397:
4398: do {
4399: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
4400: $ok = $response->is_success;
4401: if (!$ok) {
4402: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
4403: }
4404: $retries--;
4405: } while (!$ok && ($retries > 0));
4406:
4407: if (!$ok) {
4408: $content = ''; # On error return an empty content.
4409: }
4410: if (wantarray) {
4411: return ($content, $response);
4412: } else {
4413: return $content;
4414: }
4415: }
4416:
4417: =pod
4418:
4419: =item * &get_student_answers()
4420:
4421: show a snapshot of how student was answering problem
4422:
4423: =cut
4424:
4425: sub get_student_answers {
4426: my ($symb,$username,$domain,$courseid,%form) = @_;
4427: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4428: my (%moreenv);
4429: my @elements=('symb','courseid','domain','username');
4430: foreach my $element (@elements) {
4431: $moreenv{'grade_'.$element}=eval '$'.$element #'
4432: }
4433: $moreenv{'grade_target'}='answer';
4434: %moreenv=(%form,%moreenv);
4435: $feedurl = &Apache::lonnet::clutter($feedurl);
4436: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
4437: return $userview;
4438: }
4439:
4440: =pod
4441:
4442: =item * &submlink()
4443:
4444: Inputs: $text $uname $udom $symb $target
4445:
4446: Returns: A link to grades.pm such as to see the SUBM view of a student
4447:
4448: =cut
4449:
4450: ###############################################
4451: sub submlink {
4452: my ($text,$uname,$udom,$symb,$target)=@_;
4453: if (!($uname && $udom)) {
4454: (my $cursymb, my $courseid,$udom,$uname)=
4455: &Apache::lonnet::whichuser($symb);
4456: if (!$symb) { $symb=$cursymb; }
4457: }
4458: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4459: $symb=&escape($symb);
4460: if ($target) { $target=" target=\"$target\""; }
4461: return
4462: '<a href="/adm/grades?command=submission'.
4463: '&symb='.$symb.
4464: '&student='.$uname.
4465: '&userdom='.$udom.'"'.
4466: $target.'>'.$text.'</a>';
4467: }
4468: ##############################################
4469:
4470: =pod
4471:
4472: =item * &pgrdlink()
4473:
4474: Inputs: $text $uname $udom $symb $target
4475:
4476: Returns: A link to grades.pm such as to see the PGRD view of a student
4477:
4478: =cut
4479:
4480: ###############################################
4481: sub pgrdlink {
4482: my $link=&submlink(@_);
4483: $link=~s/(&command=submission)/$1&showgrading=yes/;
4484: return $link;
4485: }
4486: ##############################################
4487:
4488: =pod
4489:
4490: =item * &pprmlink()
4491:
4492: Inputs: $text $uname $udom $symb $target
4493:
4494: Returns: A link to parmset.pm such as to see the PPRM view of a
4495: student and a specific resource
4496:
4497: =cut
4498:
4499: ###############################################
4500: sub pprmlink {
4501: my ($text,$uname,$udom,$symb,$target)=@_;
4502: if (!($uname && $udom)) {
4503: (my $cursymb, my $courseid,$udom,$uname)=
4504: &Apache::lonnet::whichuser($symb);
4505: if (!$symb) { $symb=$cursymb; }
4506: }
4507: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4508: $symb=&escape($symb);
4509: if ($target) { $target="target=\"$target\""; }
4510: return '<a href="/adm/parmset?command=set&'.
4511: 'symb='.$symb.'&uname='.$uname.
4512: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
4513: }
4514: ##############################################
4515:
4516: =pod
4517:
4518: =back
4519:
4520: =cut
4521:
4522: ###############################################
4523:
4524:
4525: sub timehash {
4526: my ($thistime) = @_;
4527: my $timezone = &Apache::lonlocal::gettimezone();
4528: my $dt = DateTime->from_epoch(epoch => $thistime)
4529: ->set_time_zone($timezone);
4530: my $wday = $dt->day_of_week();
4531: if ($wday == 7) { $wday = 0; }
4532: return ( 'second' => $dt->second(),
4533: 'minute' => $dt->minute(),
4534: 'hour' => $dt->hour(),
4535: 'day' => $dt->day_of_month(),
4536: 'month' => $dt->month(),
4537: 'year' => $dt->year(),
4538: 'weekday' => $wday,
4539: 'dayyear' => $dt->day_of_year(),
4540: 'dlsav' => $dt->is_dst() );
4541: }
4542:
4543: sub utc_string {
4544: my ($date)=@_;
4545: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
4546: }
4547:
4548: sub maketime {
4549: my %th=@_;
4550: my ($epoch_time,$timezone,$dt);
4551: $timezone = &Apache::lonlocal::gettimezone();
4552: eval {
4553: $dt = DateTime->new( year => $th{'year'},
4554: month => $th{'month'},
4555: day => $th{'day'},
4556: hour => $th{'hour'},
4557: minute => $th{'minute'},
4558: second => $th{'second'},
4559: time_zone => $timezone,
4560: );
4561: };
4562: if (!$@) {
4563: $epoch_time = $dt->epoch;
4564: if ($epoch_time) {
4565: return $epoch_time;
4566: }
4567: }
4568: return POSIX::mktime(
4569: ($th{'seconds'},$th{'minutes'},$th{'hours'},
4570: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
4571: }
4572:
4573: #########################################
4574:
4575: sub findallcourses {
4576: my ($roles,$uname,$udom) = @_;
4577: my %roles;
4578: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
4579: my %courses;
4580: my $now=time;
4581: if (!defined($uname)) {
4582: $uname = $env{'user.name'};
4583: }
4584: if (!defined($udom)) {
4585: $udom = $env{'user.domain'};
4586: }
4587: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
4588: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
4589: if (!%roles) {
4590: %roles = (
4591: cc => 1,
4592: co => 1,
4593: in => 1,
4594: ep => 1,
4595: ta => 1,
4596: cr => 1,
4597: st => 1,
4598: );
4599: }
4600: foreach my $entry (keys(%roleshash)) {
4601: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
4602: if ($trole =~ /^cr/) {
4603: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
4604: } else {
4605: next if (!exists($roles{$trole}));
4606: }
4607: if ($tend) {
4608: next if ($tend < $now);
4609: }
4610: if ($tstart) {
4611: next if ($tstart > $now);
4612: }
4613: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
4614: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
4615: my $value = $trole.'/'.$cdom.'/';
4616: if ($secpart eq '') {
4617: ($cnum,$role) = split(/_/,$cnumpart);
4618: $sec = 'none';
4619: $value .= $cnum.'/';
4620: } else {
4621: $cnum = $cnumpart;
4622: ($sec,$role) = split(/_/,$secpart);
4623: $value .= $cnum.'/'.$sec;
4624: }
4625: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4626: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4627: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4628: }
4629: } else {
4630: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4631: }
4632: }
4633: } else {
4634: foreach my $key (keys(%env)) {
4635: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
4636: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
4637: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
4638: next if ($role eq 'ca' || $role eq 'aa');
4639: next if (%roles && !exists($roles{$role}));
4640: my ($starttime,$endtime)=split(/\./,$env{$key});
4641: my $active=1;
4642: if ($starttime) {
4643: if ($now<$starttime) { $active=0; }
4644: }
4645: if ($endtime) {
4646: if ($now>$endtime) { $active=0; }
4647: }
4648: if ($active) {
4649: my $value = $role.'/'.$cdom.'/'.$cnum.'/';
4650: if ($sec eq '') {
4651: $sec = 'none';
4652: } else {
4653: $value .= $sec;
4654: }
4655: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4656: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4657: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4658: }
4659: } else {
4660: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4661: }
4662: }
4663: }
4664: }
4665: }
4666: return %courses;
4667: }
4668:
4669: ###############################################
4670:
4671: sub blockcheck {
4672: my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
4673:
4674: if (defined($udom) && defined($uname)) {
4675: # If uname and udom are for a course, check for blocks in the course.
4676: if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
4677: my ($startblock,$endblock,$triggerblock) =
4678: &get_blocks($setters,$activity,$udom,$uname,$url);
4679: return ($startblock,$endblock,$triggerblock);
4680: }
4681: } else {
4682: $udom = $env{'user.domain'};
4683: $uname = $env{'user.name'};
4684: }
4685:
4686: my $startblock = 0;
4687: my $endblock = 0;
4688: my $triggerblock = '';
4689: my %live_courses = &findallcourses(undef,$uname,$udom);
4690:
4691: # If uname is for a user, and activity is course-specific, i.e.,
4692: # boards, chat or groups, check for blocking in current course only.
4693:
4694: if (($activity eq 'boards' || $activity eq 'chat' ||
4695: $activity eq 'groups' || $activity eq 'printout') &&
4696: ($env{'request.course.id'})) {
4697: foreach my $key (keys(%live_courses)) {
4698: if ($key ne $env{'request.course.id'}) {
4699: delete($live_courses{$key});
4700: }
4701: }
4702: }
4703:
4704: my $otheruser = 0;
4705: my %own_courses;
4706: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
4707: # Resource belongs to user other than current user.
4708: $otheruser = 1;
4709: # Gather courses for current user
4710: %own_courses =
4711: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
4712: }
4713:
4714: # Gather active course roles - course coordinator, instructor,
4715: # exam proctor, ta, student, or custom role.
4716:
4717: foreach my $course (keys(%live_courses)) {
4718: my ($cdom,$cnum);
4719: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
4720: $cdom = $env{'course.'.$course.'.domain'};
4721: $cnum = $env{'course.'.$course.'.num'};
4722: } else {
4723: ($cdom,$cnum) = split(/_/,$course);
4724: }
4725: my $no_ownblock = 0;
4726: my $no_userblock = 0;
4727: if ($otheruser && $activity ne 'com') {
4728: # Check if current user has 'evb' priv for this
4729: if (defined($own_courses{$course})) {
4730: foreach my $sec (keys(%{$own_courses{$course}})) {
4731: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4732: if ($sec ne 'none') {
4733: $checkrole .= '/'.$sec;
4734: }
4735: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4736: $no_ownblock = 1;
4737: last;
4738: }
4739: }
4740: }
4741: # if they have 'evb' priv and are currently not playing student
4742: next if (($no_ownblock) &&
4743: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
4744: }
4745: foreach my $sec (keys(%{$live_courses{$course}})) {
4746: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4747: if ($sec ne 'none') {
4748: $checkrole .= '/'.$sec;
4749: }
4750: if ($otheruser) {
4751: # Resource belongs to user other than current user.
4752: # Assemble privs for that user, and check for 'evb' priv.
4753: my (%allroles,%userroles);
4754: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
4755: foreach my $entry (@{$live_courses{$course}{$sec}}) {
4756: my ($trole,$tdom,$tnum,$tsec);
4757: if ($entry =~ /^cr/) {
4758: ($trole,$tdom,$tnum,$tsec) =
4759: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
4760: } else {
4761: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
4762: }
4763: my ($spec,$area,$trest);
4764: $area = '/'.$tdom.'/'.$tnum;
4765: $trest = $tnum;
4766: if ($tsec ne '') {
4767: $area .= '/'.$tsec;
4768: $trest .= '/'.$tsec;
4769: }
4770: $spec = $trole.'.'.$area;
4771: if ($trole =~ /^cr/) {
4772: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
4773: $tdom,$spec,$trest,$area);
4774: } else {
4775: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
4776: $tdom,$spec,$trest,$area);
4777: }
4778: }
4779: my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
4780: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
4781: if ($1) {
4782: $no_userblock = 1;
4783: last;
4784: }
4785: }
4786: }
4787: } else {
4788: # Resource belongs to current user
4789: # Check for 'evb' priv via lonnet::allowed().
4790: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4791: $no_ownblock = 1;
4792: last;
4793: }
4794: }
4795: }
4796: # if they have the evb priv and are currently not playing student
4797: next if (($no_ownblock) &&
4798: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
4799: next if ($no_userblock);
4800:
4801: # Retrieve blocking times and identity of blocker for course
4802: # of specified user, unless user has 'evb' privilege.
4803:
4804: my ($start,$end,$trigger) =
4805: &get_blocks($setters,$activity,$cdom,$cnum,$url);
4806: if (($start != 0) &&
4807: (($startblock == 0) || ($startblock > $start))) {
4808: $startblock = $start;
4809: if ($trigger ne '') {
4810: $triggerblock = $trigger;
4811: }
4812: }
4813: if (($end != 0) &&
4814: (($endblock == 0) || ($endblock < $end))) {
4815: $endblock = $end;
4816: if ($trigger ne '') {
4817: $triggerblock = $trigger;
4818: }
4819: }
4820: }
4821: return ($startblock,$endblock,$triggerblock);
4822: }
4823:
4824: sub get_blocks {
4825: my ($setters,$activity,$cdom,$cnum,$url) = @_;
4826: my $startblock = 0;
4827: my $endblock = 0;
4828: my $triggerblock = '';
4829: my $course = $cdom.'_'.$cnum;
4830: $setters->{$course} = {};
4831: $setters->{$course}{'staff'} = [];
4832: $setters->{$course}{'times'} = [];
4833: $setters->{$course}{'triggers'} = [];
4834: my (@blockers,%triggered);
4835: my $now = time;
4836: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
4837: if ($activity eq 'docs') {
4838: @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
4839: foreach my $block (@blockers) {
4840: if ($block =~ /^firstaccess____(.+)$/) {
4841: my $item = $1;
4842: my $type = 'map';
4843: my $timersymb = $item;
4844: if ($item eq 'course') {
4845: $type = 'course';
4846: } elsif ($item =~ /___\d+___/) {
4847: $type = 'resource';
4848: } else {
4849: $timersymb = &Apache::lonnet::symbread($item);
4850: }
4851: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4852: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4853: $triggered{$block} = {
4854: start => $start,
4855: end => $end,
4856: type => $type,
4857: };
4858: }
4859: }
4860: } else {
4861: foreach my $block (keys(%commblocks)) {
4862: if ($block =~ m/^(\d+)____(\d+)$/) {
4863: my ($start,$end) = ($1,$2);
4864: if ($start <= time && $end >= time) {
4865: if (ref($commblocks{$block}) eq 'HASH') {
4866: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
4867: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
4868: unless(grep(/^\Q$block\E$/,@blockers)) {
4869: push(@blockers,$block);
4870: }
4871: }
4872: }
4873: }
4874: }
4875: } elsif ($block =~ /^firstaccess____(.+)$/) {
4876: my $item = $1;
4877: my $timersymb = $item;
4878: my $type = 'map';
4879: if ($item eq 'course') {
4880: $type = 'course';
4881: } elsif ($item =~ /___\d+___/) {
4882: $type = 'resource';
4883: } else {
4884: $timersymb = &Apache::lonnet::symbread($item);
4885: }
4886: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4887: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4888: if ($start && $end) {
4889: if (($start <= time) && ($end >= time)) {
4890: unless (grep(/^\Q$block\E$/,@blockers)) {
4891: push(@blockers,$block);
4892: $triggered{$block} = {
4893: start => $start,
4894: end => $end,
4895: type => $type,
4896: };
4897: }
4898: }
4899: }
4900: }
4901: }
4902: }
4903: foreach my $blocker (@blockers) {
4904: my ($staff_name,$staff_dom,$title,$blocks) =
4905: &parse_block_record($commblocks{$blocker});
4906: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
4907: my ($start,$end,$triggertype);
4908: if ($blocker =~ m/^(\d+)____(\d+)$/) {
4909: ($start,$end) = ($1,$2);
4910: } elsif (ref($triggered{$blocker}) eq 'HASH') {
4911: $start = $triggered{$blocker}{'start'};
4912: $end = $triggered{$blocker}{'end'};
4913: $triggertype = $triggered{$blocker}{'type'};
4914: }
4915: if ($start) {
4916: push(@{$$setters{$course}{'times'}}, [$start,$end]);
4917: if ($triggertype) {
4918: push(@{$$setters{$course}{'triggers'}},$triggertype);
4919: } else {
4920: push(@{$$setters{$course}{'triggers'}},0);
4921: }
4922: if ( ($startblock == 0) || ($startblock > $start) ) {
4923: $startblock = $start;
4924: if ($triggertype) {
4925: $triggerblock = $blocker;
4926: }
4927: }
4928: if ( ($endblock == 0) || ($endblock < $end) ) {
4929: $endblock = $end;
4930: if ($triggertype) {
4931: $triggerblock = $blocker;
4932: }
4933: }
4934: }
4935: }
4936: return ($startblock,$endblock,$triggerblock);
4937: }
4938:
4939: sub parse_block_record {
4940: my ($record) = @_;
4941: my ($setuname,$setudom,$title,$blocks);
4942: if (ref($record) eq 'HASH') {
4943: ($setuname,$setudom) = split(/:/,$record->{'setter'});
4944: $title = &unescape($record->{'event'});
4945: $blocks = $record->{'blocks'};
4946: } else {
4947: my @data = split(/:/,$record,3);
4948: if (scalar(@data) eq 2) {
4949: $title = $data[1];
4950: ($setuname,$setudom) = split(/@/,$data[0]);
4951: } else {
4952: ($setuname,$setudom,$title) = @data;
4953: }
4954: $blocks = { 'com' => 'on' };
4955: }
4956: return ($setuname,$setudom,$title,$blocks);
4957: }
4958:
4959: sub blocking_status {
4960: my ($activity,$uname,$udom,$url,$is_course) = @_;
4961: my %setters;
4962:
4963: # check for active blocking
4964: my ($startblock,$endblock,$triggerblock) =
4965: &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
4966: my $blocked = 0;
4967: if ($startblock && $endblock) {
4968: $blocked = 1;
4969: }
4970:
4971: # caller just wants to know whether a block is active
4972: if (!wantarray) { return $blocked; }
4973:
4974: # build a link to a popup window containing the details
4975: my $querystring = "?activity=$activity";
4976: # $uname and $udom decide whose portfolio the user is trying to look at
4977: if (($activity eq 'port') || ($activity eq 'passwd')) {
4978: $querystring .= "&udom=$udom" if ($udom =~ /^$match_domain$/);
4979: $querystring .= "&uname=$uname" if ($uname =~ /^$match_username$/);
4980: } elsif ($activity eq 'docs') {
4981: $querystring .= '&url='.&HTML::Entities::encode($url,'&"');
4982: }
4983:
4984: my $output .= <<'END_MYBLOCK';
4985: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
4986: var options = "width=" + w + ",height=" + h + ",";
4987: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
4988: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
4989: var newWin = window.open(url, wdwName, options);
4990: newWin.focus();
4991: }
4992: END_MYBLOCK
4993:
4994: $output = Apache::lonhtmlcommon::scripttag($output);
4995:
4996: my $popupUrl = "/adm/blockingstatus/$querystring";
4997: my $text = &mt('Communication Blocked');
4998: my $class = 'LC_comblock';
4999: if ($activity eq 'docs') {
5000: $text = &mt('Content Access Blocked');
5001: $class = '';
5002: } elsif ($activity eq 'printout') {
5003: $text = &mt('Printing Blocked');
5004: } elsif ($activity eq 'passwd') {
5005: $text = &mt('Password Changing Blocked');
5006: }
5007: $output .= <<"END_BLOCK";
5008: <div class='$class'>
5009: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
5010: title='$text'>
5011: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
5012: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
5013: title='$text'>$text</a>
5014: </div>
5015:
5016: END_BLOCK
5017:
5018: return ($blocked, $output);
5019: }
5020:
5021: ###############################################
5022:
5023: sub check_ip_acc {
5024: my ($acc,$clientip)=@_;
5025: &Apache::lonxml::debug("acc is $acc");
5026: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
5027: return 1;
5028: }
5029: my $allowed=0;
5030: my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
5031:
5032: my $name;
5033: foreach my $pattern (split(',',$acc)) {
5034: $pattern =~ s/^\s*//;
5035: $pattern =~ s/\s*$//;
5036: if ($pattern =~ /\*$/) {
5037: #35.8.*
5038: $pattern=~s/\*//;
5039: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
5040: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
5041: #35.8.3.[34-56]
5042: my $low=$2;
5043: my $high=$3;
5044: $pattern=$1;
5045: if ($ip =~ /^\Q$pattern\E/) {
5046: my $last=(split(/\./,$ip))[3];
5047: if ($last <=$high && $last >=$low) { $allowed=1; }
5048: }
5049: } elsif ($pattern =~ /^\*/) {
5050: #*.msu.edu
5051: $pattern=~s/\*//;
5052: if (!defined($name)) {
5053: use Socket;
5054: my $netaddr=inet_aton($ip);
5055: ($name)=gethostbyaddr($netaddr,AF_INET);
5056: }
5057: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
5058: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
5059: #127.0.0.1
5060: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
5061: } else {
5062: #some.name.com
5063: if (!defined($name)) {
5064: use Socket;
5065: my $netaddr=inet_aton($ip);
5066: ($name)=gethostbyaddr($netaddr,AF_INET);
5067: }
5068: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
5069: }
5070: if ($allowed) { last; }
5071: }
5072: return $allowed;
5073: }
5074:
5075: ###############################################
5076:
5077: =pod
5078:
5079: =head1 Domain Template Functions
5080:
5081: =over 4
5082:
5083: =item * &determinedomain()
5084:
5085: Inputs: $domain (usually will be undef)
5086:
5087: Returns: Determines which domain should be used for designs
5088:
5089: =cut
5090:
5091: ###############################################
5092: sub determinedomain {
5093: my $domain=shift;
5094: if (! $domain) {
5095: # Determine domain if we have not been given one
5096: $domain = &Apache::lonnet::default_login_domain();
5097: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
5098: if ($env{'request.role.domain'}) {
5099: $domain=$env{'request.role.domain'};
5100: }
5101: }
5102: return $domain;
5103: }
5104: ###############################################
5105:
5106: sub devalidate_domconfig_cache {
5107: my ($udom)=@_;
5108: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
5109: }
5110:
5111: # ---------------------- Get domain configuration for a domain
5112: sub get_domainconf {
5113: my ($udom) = @_;
5114: my $cachetime=1800;
5115: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
5116: if (defined($cached)) { return %{$result}; }
5117:
5118: my %domconfig = &Apache::lonnet::get_dom('configuration',
5119: ['login','rolecolors','autoenroll'],$udom);
5120: my (%designhash,%legacy);
5121: if (keys(%domconfig) > 0) {
5122: if (ref($domconfig{'login'}) eq 'HASH') {
5123: if (keys(%{$domconfig{'login'}})) {
5124: foreach my $key (keys(%{$domconfig{'login'}})) {
5125: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5126: if (($key eq 'loginvia') || ($key eq 'headtag')) {
5127: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5128: foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
5129: if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
5130: if ($key eq 'loginvia') {
5131: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
5132: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
5133: $designhash{$udom.'.login.loginvia'} = $server;
5134: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
5135: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
5136: } else {
5137: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
5138: }
5139: }
5140: } elsif ($key eq 'headtag') {
5141: if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
5142: $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
5143: }
5144: }
5145: if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
5146: $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
5147: }
5148: }
5149: }
5150: }
5151: } else {
5152: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
5153: $designhash{$udom.'.login.'.$key.'_'.$img} =
5154: $domconfig{'login'}{$key}{$img};
5155: }
5156: }
5157: } else {
5158: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
5159: }
5160: }
5161: } else {
5162: $legacy{'login'} = 1;
5163: }
5164: } else {
5165: $legacy{'login'} = 1;
5166: }
5167: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
5168: if (keys(%{$domconfig{'rolecolors'}})) {
5169: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
5170: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
5171: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
5172: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
5173: }
5174: }
5175: }
5176: } else {
5177: $legacy{'rolecolors'} = 1;
5178: }
5179: } else {
5180: $legacy{'rolecolors'} = 1;
5181: }
5182: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5183: if ($domconfig{'autoenroll'}{'co-owners'}) {
5184: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
5185: }
5186: }
5187: if (keys(%legacy) > 0) {
5188: my %legacyhash = &get_legacy_domconf($udom);
5189: foreach my $item (keys(%legacyhash)) {
5190: if ($item =~ /^\Q$udom\E\.login/) {
5191: if ($legacy{'login'}) {
5192: $designhash{$item} = $legacyhash{$item};
5193: }
5194: } else {
5195: if ($legacy{'rolecolors'}) {
5196: $designhash{$item} = $legacyhash{$item};
5197: }
5198: }
5199: }
5200: }
5201: } else {
5202: %designhash = &get_legacy_domconf($udom);
5203: }
5204: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
5205: $cachetime);
5206: return %designhash;
5207: }
5208:
5209: sub get_legacy_domconf {
5210: my ($udom) = @_;
5211: my %legacyhash;
5212: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
5213: my $designfile = $designdir.'/'.$udom.'.tab';
5214: if (-e $designfile) {
5215: if ( open (my $fh,'<',$designfile) ) {
5216: while (my $line = <$fh>) {
5217: next if ($line =~ /^\#/);
5218: chomp($line);
5219: my ($key,$val)=(split(/\=/,$line));
5220: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
5221: }
5222: close($fh);
5223: }
5224: }
5225: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
5226: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
5227: }
5228: return %legacyhash;
5229: }
5230:
5231: =pod
5232:
5233: =item * &domainlogo()
5234:
5235: Inputs: $domain (usually will be undef)
5236:
5237: Returns: A link to a domain logo, if the domain logo exists.
5238: If the domain logo does not exist, a description of the domain.
5239:
5240: =cut
5241:
5242: ###############################################
5243: sub domainlogo {
5244: my $domain = &determinedomain(shift);
5245: my %designhash = &get_domainconf($domain);
5246: # See if there is a logo
5247: if ($designhash{$domain.'.login.domlogo'} ne '') {
5248: my $imgsrc = $designhash{$domain.'.login.domlogo'};
5249: if ($imgsrc =~ m{^/(adm|res)/}) {
5250: if ($imgsrc =~ m{^/res/}) {
5251: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
5252: &Apache::lonnet::repcopy($local_name);
5253: }
5254: $imgsrc = &lonhttpdurl($imgsrc);
5255: }
5256: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
5257: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
5258: return &Apache::lonnet::domain($domain,'description');
5259: } else {
5260: return '';
5261: }
5262: }
5263: ##############################################
5264:
5265: =pod
5266:
5267: =item * &designparm()
5268:
5269: Inputs: $which parameter; $domain (usually will be undef)
5270:
5271: Returns: value of designparamter $which
5272:
5273: =cut
5274:
5275:
5276: ##############################################
5277: sub designparm {
5278: my ($which,$domain)=@_;
5279: if (exists($env{'environment.color.'.$which})) {
5280: return $env{'environment.color.'.$which};
5281: }
5282: $domain=&determinedomain($domain);
5283: my %domdesign;
5284: unless ($domain eq 'public') {
5285: %domdesign = &get_domainconf($domain);
5286: }
5287: my $output;
5288: if ($domdesign{$domain.'.'.$which} ne '') {
5289: $output = $domdesign{$domain.'.'.$which};
5290: } else {
5291: $output = $defaultdesign{$which};
5292: }
5293: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
5294: ($which =~ /login\.(img|logo|domlogo|login)/)) {
5295: if ($output =~ m{^/(adm|res)/}) {
5296: if ($output =~ m{^/res/}) {
5297: my $local_name = &Apache::lonnet::filelocation('',$output);
5298: &Apache::lonnet::repcopy($local_name);
5299: }
5300: $output = &lonhttpdurl($output);
5301: }
5302: }
5303: return $output;
5304: }
5305:
5306: ##############################################
5307: =pod
5308:
5309: =item * &authorspace()
5310:
5311: Inputs: $url (usually will be undef).
5312:
5313: Returns: Path to Authoring Space containing the resource or
5314: directory being viewed (or for which action is being taken).
5315: If $url is provided, and begins /priv/<domain>/<uname>
5316: the path will be that portion of the $context argument.
5317: Otherwise the path will be for the author space of the current
5318: user when the current role is author, or for that of the
5319: co-author/assistant co-author space when the current role
5320: is co-author or assistant co-author.
5321:
5322: =cut
5323:
5324: sub authorspace {
5325: my ($url) = @_;
5326: if ($url ne '') {
5327: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
5328: return $1;
5329: }
5330: }
5331: my $caname = '';
5332: my $cadom = '';
5333: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
5334: ($cadom,$caname) =
5335: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
5336: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
5337: $caname = $env{'user.name'};
5338: $cadom = $env{'user.domain'};
5339: }
5340: if (($caname ne '') && ($cadom ne '')) {
5341: return "/priv/$cadom/$caname/";
5342: }
5343: return;
5344: }
5345:
5346: ##############################################
5347: =pod
5348:
5349: =item * &head_subbox()
5350:
5351: Inputs: $content (contains HTML code with page functions, etc.)
5352:
5353: Returns: HTML div with $content
5354: To be included in page header
5355:
5356: =cut
5357:
5358: sub head_subbox {
5359: my ($content)=@_;
5360: my $output =
5361: '<div class="LC_head_subbox">'
5362: .$content
5363: .'</div>'
5364: }
5365:
5366: ##############################################
5367: =pod
5368:
5369: =item * &CSTR_pageheader()
5370:
5371: Input: (optional) filename from which breadcrumb trail is built.
5372: In most cases no input as needed, as $env{'request.filename'}
5373: is appropriate for use in building the breadcrumb trail.
5374:
5375: Returns: HTML div with CSTR path and recent box
5376: To be included on Authoring Space pages
5377:
5378: =cut
5379:
5380: sub CSTR_pageheader {
5381: my ($trailfile) = @_;
5382: if ($trailfile eq '') {
5383: $trailfile = $env{'request.filename'};
5384: }
5385:
5386: # this is for resources; directories have customtitle, and crumbs
5387: # and select recent are created in lonpubdir.pm
5388:
5389: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
5390: my ($udom,$uname,$thisdisfn)=
5391: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
5392: my $formaction = "/priv/$udom/$uname/$thisdisfn";
5393: $formaction =~ s{/+}{/}g;
5394:
5395: my $parentpath = '';
5396: my $lastitem = '';
5397: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
5398: $parentpath = $1;
5399: $lastitem = $2;
5400: } else {
5401: $lastitem = $thisdisfn;
5402: }
5403:
5404: my $output =
5405: '<div>'
5406: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
5407: .'<b>'.&mt('Authoring Space:').'</b> '
5408: .'<form name="dirs" method="post" action="'.$formaction
5409: .'" target="_top">' #FIXME lonpubdir: target="_parent"
5410: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
5411:
5412: if ($lastitem) {
5413: $output .=
5414: '<span class="LC_filename">'
5415: .$lastitem
5416: .'</span>';
5417: }
5418: $output .=
5419: '<br />'
5420: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
5421: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
5422: .'</form>'
5423: .&Apache::lonmenu::constspaceform()
5424: .'</div>';
5425:
5426: return $output;
5427: }
5428:
5429: ###############################################
5430: ###############################################
5431:
5432: =pod
5433:
5434: =back
5435:
5436: =head1 HTML Helpers
5437:
5438: =over 4
5439:
5440: =item * &bodytag()
5441:
5442: Returns a uniform header for LON-CAPA web pages.
5443:
5444: Inputs:
5445:
5446: =over 4
5447:
5448: =item * $title, A title to be displayed on the page.
5449:
5450: =item * $function, the current role (can be undef).
5451:
5452: =item * $addentries, extra parameters for the <body> tag.
5453:
5454: =item * $bodyonly, if defined, only return the <body> tag.
5455:
5456: =item * $domain, if defined, force a given domain.
5457:
5458: =item * $forcereg, if page should register as content page (relevant for
5459: text interface only)
5460:
5461: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
5462: navigational links
5463:
5464: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
5465:
5466: =item * $no_inline_link, if true and in remote mode, don't show the
5467: 'Switch To Inline Menu' link
5468:
5469: =item * $args, optional argument valid values are
5470: no_auto_mt_title -> prevents &mt()ing the title arg
5471: use_absolute -> for external resource or syllabus, this will
5472: contain https://<hostname> if server uses
5473: https (as per hosts.tab), but request is for http
5474: hostname -> hostname, from $r->hostname().
5475:
5476: =item * $advtoolsref, optional argument, ref to an array containing
5477: inlineremote items to be added in "Functions" menu below
5478: breadcrumbs.
5479:
5480: =back
5481:
5482: Returns: A uniform header for LON-CAPA web pages.
5483: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
5484: If $bodyonly is undef or zero, an html string containing a <body> tag and
5485: other decorations will be returned.
5486:
5487: =cut
5488:
5489: sub bodytag {
5490: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
5491: $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
5492:
5493: my $public;
5494: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
5495: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
5496: $public = 1;
5497: }
5498: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
5499: my $httphost = $args->{'use_absolute'};
5500: my $hostname = $args->{'hostname'};
5501:
5502: $function = &get_users_function() if (!$function);
5503: my $img = &designparm($function.'.img',$domain);
5504: my $font = &designparm($function.'.font',$domain);
5505: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
5506:
5507: my %design = ( 'style' => 'margin-top: 0',
5508: 'bgcolor' => $pgbg,
5509: 'text' => $font,
5510: 'alink' => &designparm($function.'.alink',$domain),
5511: 'vlink' => &designparm($function.'.vlink',$domain),
5512: 'link' => &designparm($function.'.link',$domain),);
5513: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
5514:
5515: # role and realm
5516: my ($role,$realm) = split(m{\./},$env{'request.role'},2);
5517: if ($realm) {
5518: $realm = '/'.$realm;
5519: }
5520: if ($role eq 'ca') {
5521: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
5522: $realm = &plainname($rname,$rdom);
5523: }
5524: # realm
5525: if ($env{'request.course.id'}) {
5526: if ($env{'request.role'} !~ /^cr/) {
5527: $role = &Apache::lonnet::plaintext($role,&course_type());
5528: } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
5529: if ($env{'request.role.desc'}) {
5530: $role = $env{'request.role.desc'};
5531: } else {
5532: $role = &mt('Helpdesk[_1]',' '.$2);
5533: }
5534: } else {
5535: $role = (split(/\//,$role,4))[-1];
5536: }
5537: if ($env{'request.course.sec'}) {
5538: $role .= (' 'x2).'- '.&mt('section:').' '.$env{'request.course.sec'};
5539: }
5540: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
5541: } else {
5542: $role = &Apache::lonnet::plaintext($role);
5543: }
5544:
5545: if (!$realm) { $realm=' '; }
5546:
5547: my $extra_body_attr = &make_attr_string($forcereg,\%design);
5548:
5549: # construct main body tag
5550: my $bodytag = "<body $extra_body_attr>".
5551: &Apache::lontexconvert::init_math_support();
5552:
5553: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
5554:
5555: if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
5556: return $bodytag;
5557: }
5558:
5559: if ($public) {
5560: undef($role);
5561: }
5562:
5563: my $titleinfo = '<h1>'.$title.'</h1>';
5564: #
5565: # Extra info if you are the DC
5566: my $dc_info = '';
5567: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
5568: $env{'course.'.$env{'request.course.id'}.
5569: '.domain'}.'/'})) {
5570: my $cid = $env{'request.course.id'};
5571: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
5572: $dc_info =~ s/\s+$//;
5573: }
5574:
5575: $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
5576:
5577: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
5578:
5579:
5580:
5581: my $funclist;
5582: if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
5583: $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
5584: Apache::lonmenu::serverform();
5585: my $forbodytag;
5586: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
5587: $forcereg,$args->{'group'},
5588: $args->{'bread_crumbs'},
5589: $advtoolsref,'','',\$forbodytag);
5590: unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
5591: $funclist = $forbodytag;
5592: }
5593: } else {
5594:
5595: # if ($env{'request.state'} eq 'construct') {
5596: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
5597: # }
5598:
5599: $bodytag .= Apache::lonhtmlcommon::scripttag(
5600: Apache::lonmenu::utilityfunctions($httphost), 'start');
5601:
5602: my ($left,$right) = Apache::lonmenu::primary_menu();
5603:
5604: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
5605: if ($dc_info) {
5606: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
5607: }
5608: $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
5609: <em>$realm</em> $dc_info</div>|;
5610: return $bodytag;
5611: }
5612:
5613: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
5614: $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
5615: }
5616:
5617: $bodytag .= $right;
5618:
5619: if ($dc_info) {
5620: $dc_info = &dc_courseid_toggle($dc_info);
5621: }
5622: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
5623:
5624: #if directed to not display the secondary menu, don't.
5625: if ($args->{'no_secondary_menu'}) {
5626: return $bodytag;
5627: }
5628: #don't show menus for public users
5629: if (!$public){
5630: $bodytag .= Apache::lonmenu::secondary_menu($httphost);
5631: $bodytag .= Apache::lonmenu::serverform();
5632: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5633: if ($env{'request.state'} eq 'construct') {
5634: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
5635: $args->{'bread_crumbs'},'','',$hostname);
5636: } elsif ($forcereg) {
5637: $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
5638: $args->{'group'},
5639: $args->{'hide_buttons',
5640: $hostname});
5641: } else {
5642: my $forbodytag;
5643: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
5644: $forcereg,$args->{'group'},
5645: $args->{'bread_crumbs'},
5646: $advtoolsref,'',$hostname,
5647: \$forbodytag);
5648: unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
5649: $bodytag .= $forbodytag;
5650: }
5651: }
5652: }else{
5653: # this is to seperate menu from content when there's no secondary
5654: # menu. Especially needed for public accessible ressources.
5655: $bodytag .= '<hr style="clear:both" />';
5656: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5657: }
5658:
5659: return $bodytag;
5660: }
5661:
5662: #
5663: # Top frame rendering, Remote is up
5664: #
5665:
5666: my $imgsrc = $img;
5667: if ($img =~ /^\/adm/) {
5668: $imgsrc = &lonhttpdurl($img);
5669: }
5670: my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
5671:
5672: my $help=($no_inline_link?''
5673: :&Apache::loncommon::top_nav_help('Help'));
5674:
5675: # Explicit link to get inline menu
5676: my $menu= ($no_inline_link?''
5677: :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
5678:
5679: if ($dc_info) {
5680: $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
5681: }
5682:
5683: my $name = &plainname($env{'user.name'},$env{'user.domain'});
5684: unless ($public) {
5685: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
5686: undef,'LC_menubuttons_link');
5687: }
5688:
5689: unless ($env{'form.inhibitmenu'}) {
5690: $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
5691: <ol class="LC_primary_menu LC_floatright LC_right">
5692: <li>$help</li>
5693: <li>$menu</li>
5694: </ol><div id="LC_realm"> $realm $dc_info</div>|;
5695: }
5696: if ($env{'request.state'} eq 'construct') {
5697: if (!$public){
5698: if ($env{'request.state'} eq 'construct') {
5699: $funclist = &Apache::lonhtmlcommon::scripttag(
5700: &Apache::lonmenu::utilityfunctions($httphost), 'start').
5701: &Apache::lonhtmlcommon::scripttag('','end').
5702: &Apache::lonmenu::innerregister($forcereg,
5703: $args->{'bread_crumbs'});
5704: }
5705: }
5706: }
5707: return $bodytag."\n".$funclist;
5708: }
5709:
5710: sub dc_courseid_toggle {
5711: my ($dc_info) = @_;
5712: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
5713: '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
5714: &mt('(More ...)').'</a></span>'.
5715: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
5716: }
5717:
5718: sub make_attr_string {
5719: my ($register,$attr_ref) = @_;
5720:
5721: if ($attr_ref && !ref($attr_ref)) {
5722: die("addentries Must be a hash ref ".
5723: join(':',caller(1))." ".
5724: join(':',caller(0))." ");
5725: }
5726:
5727: if ($register) {
5728: my ($on_load,$on_unload);
5729: foreach my $key (keys(%{$attr_ref})) {
5730: if (lc($key) eq 'onload') {
5731: $on_load.=$attr_ref->{$key}.';';
5732: delete($attr_ref->{$key});
5733:
5734: } elsif (lc($key) eq 'onunload') {
5735: $on_unload.=$attr_ref->{$key}.';';
5736: delete($attr_ref->{$key});
5737: }
5738: }
5739: if ($env{'environment.remote'} eq 'on') {
5740: $attr_ref->{'onload'} =
5741: &Apache::lonmenu::loadevents(). $on_load;
5742: $attr_ref->{'onunload'}=
5743: &Apache::lonmenu::unloadevents().$on_unload;
5744: } else {
5745: $attr_ref->{'onload'} = $on_load;
5746: $attr_ref->{'onunload'}= $on_unload;
5747: }
5748: }
5749:
5750: my $attr_string;
5751: foreach my $attr (sort(keys(%$attr_ref))) {
5752: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
5753: }
5754: return $attr_string;
5755: }
5756:
5757:
5758: ###############################################
5759: ###############################################
5760:
5761: =pod
5762:
5763: =item * &endbodytag()
5764:
5765: Returns a uniform footer for LON-CAPA web pages.
5766:
5767: Inputs: 1 - optional reference to an args hash
5768: If in the hash, key for noredirectlink has a value which evaluates to true,
5769: a 'Continue' link is not displayed if the page contains an
5770: internal redirect in the <head></head> section,
5771: i.e., $env{'internal.head.redirect'} exists
5772:
5773: =cut
5774:
5775: sub endbodytag {
5776: my ($args) = @_;
5777: my $endbodytag;
5778: unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
5779: $endbodytag='</body>';
5780: }
5781: if ( exists( $env{'internal.head.redirect'} ) ) {
5782: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
5783: $endbodytag=
5784: "<br /><a href=\"$env{'internal.head.redirect'}\">".
5785: &mt('Continue').'</a>'.
5786: $endbodytag;
5787: }
5788: }
5789: return $endbodytag;
5790: }
5791:
5792: =pod
5793:
5794: =item * &standard_css()
5795:
5796: Returns a style sheet
5797:
5798: Inputs: (all optional)
5799: domain -> force to color decorate a page for a specific
5800: domain
5801: function -> force usage of a specific rolish color scheme
5802: bgcolor -> override the default page bgcolor
5803:
5804: =cut
5805:
5806: sub standard_css {
5807: my ($function,$domain,$bgcolor) = @_;
5808: $function = &get_users_function() if (!$function);
5809: my $img = &designparm($function.'.img', $domain);
5810: my $tabbg = &designparm($function.'.tabbg', $domain);
5811: my $font = &designparm($function.'.font', $domain);
5812: my $fontmenu = &designparm($function.'.fontmenu', $domain);
5813: #second colour for later usage
5814: my $sidebg = &designparm($function.'.sidebg',$domain);
5815: my $pgbg_or_bgcolor =
5816: $bgcolor ||
5817: &designparm($function.'.pgbg', $domain);
5818: my $pgbg = &designparm($function.'.pgbg', $domain);
5819: my $alink = &designparm($function.'.alink', $domain);
5820: my $vlink = &designparm($function.'.vlink', $domain);
5821: my $link = &designparm($function.'.link', $domain);
5822:
5823: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
5824: my $mono = 'monospace';
5825: my $data_table_head = $sidebg;
5826: my $data_table_light = '#FAFAFA';
5827: my $data_table_dark = '#E0E0E0';
5828: my $data_table_darker = '#CCCCCC';
5829: my $data_table_highlight = '#FFFF00';
5830: my $mail_new = '#FFBB77';
5831: my $mail_new_hover = '#DD9955';
5832: my $mail_read = '#BBBB77';
5833: my $mail_read_hover = '#999944';
5834: my $mail_replied = '#AAAA88';
5835: my $mail_replied_hover = '#888855';
5836: my $mail_other = '#99BBBB';
5837: my $mail_other_hover = '#669999';
5838: my $table_header = '#DDDDDD';
5839: my $feedback_link_bg = '#BBBBBB';
5840: my $lg_border_color = '#C8C8C8';
5841: my $button_hover = '#BF2317';
5842:
5843: my $border = ($env{'browser.type'} eq 'explorer' ||
5844: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
5845: : '0 3px 0 4px';
5846:
5847:
5848: return <<END;
5849:
5850: /* needed for iframe to allow 100% height in FF */
5851: body, html {
5852: margin: 0;
5853: padding: 0 0.5%;
5854: height: 99%; /* to avoid scrollbars */
5855: }
5856:
5857: body {
5858: font-family: $sans;
5859: line-height:130%;
5860: font-size:0.83em;
5861: color:$font;
5862: }
5863:
5864: a:focus,
5865: a:focus img {
5866: color: red;
5867: }
5868:
5869: form, .inline {
5870: display: inline;
5871: }
5872:
5873: .LC_right {
5874: text-align:right;
5875: }
5876:
5877: .LC_middle {
5878: vertical-align:middle;
5879: }
5880:
5881: .LC_floatleft {
5882: float: left;
5883: }
5884:
5885: .LC_floatright {
5886: float: right;
5887: }
5888:
5889: .LC_400Box {
5890: width:400px;
5891: }
5892:
5893: .LC_iframecontainer {
5894: width: 98%;
5895: margin: 0;
5896: position: fixed;
5897: top: 8.5em;
5898: bottom: 0;
5899: }
5900:
5901: .LC_iframecontainer iframe{
5902: border: none;
5903: width: 100%;
5904: height: 100%;
5905: }
5906:
5907: .LC_filename {
5908: font-family: $mono;
5909: white-space:pre;
5910: font-size: 120%;
5911: }
5912:
5913: .LC_fileicon {
5914: border: none;
5915: height: 1.3em;
5916: vertical-align: text-bottom;
5917: margin-right: 0.3em;
5918: text-decoration:none;
5919: }
5920:
5921: .LC_setting {
5922: text-decoration:underline;
5923: }
5924:
5925: .LC_error {
5926: color: red;
5927: }
5928:
5929: .LC_warning {
5930: color: darkorange;
5931: }
5932:
5933: .LC_diff_removed {
5934: color: red;
5935: }
5936:
5937: .LC_info,
5938: .LC_success,
5939: .LC_diff_added {
5940: color: green;
5941: }
5942:
5943: div.LC_confirm_box {
5944: background-color: #FAFAFA;
5945: border: 1px solid $lg_border_color;
5946: margin-right: 0;
5947: padding: 5px;
5948: }
5949:
5950: div.LC_confirm_box .LC_error img,
5951: div.LC_confirm_box .LC_success img {
5952: vertical-align: middle;
5953: }
5954:
5955: .LC_maxwidth {
5956: max-width: 100%;
5957: height: auto;
5958: }
5959:
5960: .LC_textsize_mobile {
5961: \@media only screen and (max-device-width: 480px) {
5962: -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
5963: }
5964: }
5965:
5966: .LC_icon {
5967: border: none;
5968: vertical-align: middle;
5969: }
5970:
5971: .LC_docs_spacer {
5972: width: 25px;
5973: height: 1px;
5974: border: none;
5975: }
5976:
5977: .LC_internal_info {
5978: color: #999999;
5979: }
5980:
5981: .LC_discussion {
5982: background: $data_table_dark;
5983: border: 1px solid black;
5984: margin: 2px;
5985: }
5986:
5987: .LC_disc_action_left {
5988: background: $sidebg;
5989: text-align: left;
5990: padding: 4px;
5991: margin: 2px;
5992: }
5993:
5994: .LC_disc_action_right {
5995: background: $sidebg;
5996: text-align: right;
5997: padding: 4px;
5998: margin: 2px;
5999: }
6000:
6001: .LC_disc_new_item {
6002: background: white;
6003: border: 2px solid red;
6004: margin: 4px;
6005: padding: 4px;
6006: }
6007:
6008: .LC_disc_old_item {
6009: background: white;
6010: margin: 4px;
6011: padding: 4px;
6012: }
6013:
6014: table.LC_pastsubmission {
6015: border: 1px solid black;
6016: margin: 2px;
6017: }
6018:
6019: table#LC_menubuttons {
6020: width: 100%;
6021: background: $pgbg;
6022: border: 2px;
6023: border-collapse: separate;
6024: padding: 0;
6025: }
6026:
6027: table#LC_title_bar a {
6028: color: $fontmenu;
6029: }
6030:
6031: table#LC_title_bar {
6032: clear: both;
6033: display: none;
6034: }
6035:
6036: table#LC_title_bar,
6037: table.LC_breadcrumbs, /* obsolete? */
6038: table#LC_title_bar.LC_with_remote {
6039: width: 100%;
6040: border-color: $pgbg;
6041: border-style: solid;
6042: border-width: $border;
6043: background: $pgbg;
6044: color: $fontmenu;
6045: border-collapse: collapse;
6046: padding: 0;
6047: margin: 0;
6048: }
6049:
6050: ul.LC_breadcrumb_tools_outerlist {
6051: margin: 0;
6052: padding: 0;
6053: position: relative;
6054: list-style: none;
6055: }
6056: ul.LC_breadcrumb_tools_outerlist li {
6057: display: inline;
6058: }
6059:
6060: .LC_breadcrumb_tools_navigation {
6061: padding: 0;
6062: margin: 0;
6063: float: left;
6064: }
6065: .LC_breadcrumb_tools_tools {
6066: padding: 0;
6067: margin: 0;
6068: float: right;
6069: }
6070:
6071: table#LC_title_bar td {
6072: background: $tabbg;
6073: }
6074:
6075: table#LC_menubuttons img {
6076: border: none;
6077: }
6078:
6079: .LC_breadcrumbs_component {
6080: float: right;
6081: margin: 0 1em;
6082: }
6083: .LC_breadcrumbs_component img {
6084: vertical-align: middle;
6085: }
6086:
6087: .LC_breadcrumbs_hoverable {
6088: background: $sidebg;
6089: }
6090:
6091: td.LC_table_cell_checkbox {
6092: text-align: center;
6093: }
6094:
6095: .LC_fontsize_small {
6096: font-size: 70%;
6097: }
6098:
6099: #LC_breadcrumbs {
6100: clear:both;
6101: background: $sidebg;
6102: border-bottom: 1px solid $lg_border_color;
6103: line-height: 2.5em;
6104: overflow: hidden;
6105: margin: 0;
6106: padding: 0;
6107: text-align: left;
6108: }
6109:
6110: .LC_head_subbox, .LC_actionbox {
6111: clear:both;
6112: background: #F8F8F8; /* $sidebg; */
6113: border: 1px solid $sidebg;
6114: margin: 0 0 10px 0;
6115: padding: 3px;
6116: text-align: left;
6117: }
6118:
6119: .LC_fontsize_medium {
6120: font-size: 85%;
6121: }
6122:
6123: .LC_fontsize_large {
6124: font-size: 120%;
6125: }
6126:
6127: .LC_menubuttons_inline_text {
6128: color: $font;
6129: font-size: 90%;
6130: padding-left:3px;
6131: }
6132:
6133: .LC_menubuttons_inline_text img{
6134: vertical-align: middle;
6135: }
6136:
6137: li.LC_menubuttons_inline_text img {
6138: cursor:pointer;
6139: text-decoration: none;
6140: }
6141:
6142: .LC_menubuttons_link {
6143: text-decoration: none;
6144: }
6145:
6146: .LC_menubuttons_category {
6147: color: $font;
6148: background: $pgbg;
6149: font-size: larger;
6150: font-weight: bold;
6151: }
6152:
6153: td.LC_menubuttons_text {
6154: color: $font;
6155: }
6156:
6157: .LC_current_location {
6158: background: $tabbg;
6159: }
6160:
6161: td.LC_zero_height {
6162: line-height: 0;
6163: cellpadding: 0;
6164: }
6165:
6166: table.LC_data_table {
6167: border: 1px solid #000000;
6168: border-collapse: separate;
6169: border-spacing: 1px;
6170: background: $pgbg;
6171: }
6172:
6173: .LC_data_table_dense {
6174: font-size: small;
6175: }
6176:
6177: table.LC_nested_outer {
6178: border: 1px solid #000000;
6179: border-collapse: collapse;
6180: border-spacing: 0;
6181: width: 100%;
6182: }
6183:
6184: table.LC_innerpickbox,
6185: table.LC_nested {
6186: border: none;
6187: border-collapse: collapse;
6188: border-spacing: 0;
6189: width: 100%;
6190: }
6191:
6192: table.LC_data_table tr th,
6193: table.LC_calendar tr th,
6194: table.LC_prior_tries tr th,
6195: table.LC_innerpickbox tr th {
6196: font-weight: bold;
6197: background-color: $data_table_head;
6198: color:$fontmenu;
6199: font-size:90%;
6200: }
6201:
6202: table.LC_innerpickbox tr th,
6203: table.LC_innerpickbox tr td {
6204: vertical-align: top;
6205: }
6206:
6207: table.LC_data_table tr.LC_info_row > td {
6208: background-color: #CCCCCC;
6209: font-weight: bold;
6210: text-align: left;
6211: }
6212:
6213: table.LC_data_table tr.LC_odd_row > td {
6214: background-color: $data_table_light;
6215: padding: 2px;
6216: vertical-align: top;
6217: }
6218:
6219: table.LC_pick_box tr > td.LC_odd_row {
6220: background-color: $data_table_light;
6221: vertical-align: top;
6222: }
6223:
6224: table.LC_data_table tr.LC_even_row > td {
6225: background-color: $data_table_dark;
6226: padding: 2px;
6227: vertical-align: top;
6228: }
6229:
6230: table.LC_pick_box tr > td.LC_even_row {
6231: background-color: $data_table_dark;
6232: vertical-align: top;
6233: }
6234:
6235: table.LC_data_table tr.LC_data_table_highlight td {
6236: background-color: $data_table_darker;
6237: }
6238:
6239: table.LC_data_table tr td.LC_leftcol_header {
6240: background-color: $data_table_head;
6241: font-weight: bold;
6242: }
6243:
6244: table.LC_data_table tr.LC_empty_row td,
6245: table.LC_nested tr.LC_empty_row td {
6246: font-weight: bold;
6247: font-style: italic;
6248: text-align: center;
6249: padding: 8px;
6250: }
6251:
6252: table.LC_data_table tr.LC_empty_row td,
6253: table.LC_data_table tr.LC_footer_row td {
6254: background-color: $sidebg;
6255: }
6256:
6257: table.LC_nested tr.LC_empty_row td {
6258: background-color: #FFFFFF;
6259: }
6260:
6261: table.LC_caption {
6262: }
6263:
6264: table.LC_nested tr.LC_empty_row td {
6265: padding: 4ex
6266: }
6267:
6268: table.LC_nested_outer tr th {
6269: font-weight: bold;
6270: color:$fontmenu;
6271: background-color: $data_table_head;
6272: font-size: small;
6273: border-bottom: 1px solid #000000;
6274: }
6275:
6276: table.LC_nested_outer tr td.LC_subheader {
6277: background-color: $data_table_head;
6278: font-weight: bold;
6279: font-size: small;
6280: border-bottom: 1px solid #000000;
6281: text-align: right;
6282: }
6283:
6284: table.LC_nested tr.LC_info_row td {
6285: background-color: #CCCCCC;
6286: font-weight: bold;
6287: font-size: small;
6288: text-align: center;
6289: }
6290:
6291: table.LC_nested tr.LC_info_row td.LC_left_item,
6292: table.LC_nested_outer tr th.LC_left_item {
6293: text-align: left;
6294: }
6295:
6296: table.LC_nested td {
6297: background-color: #FFFFFF;
6298: font-size: small;
6299: }
6300:
6301: table.LC_nested_outer tr th.LC_right_item,
6302: table.LC_nested tr.LC_info_row td.LC_right_item,
6303: table.LC_nested tr.LC_odd_row td.LC_right_item,
6304: table.LC_nested tr td.LC_right_item {
6305: text-align: right;
6306: }
6307:
6308: table.LC_nested tr.LC_odd_row td {
6309: background-color: #EEEEEE;
6310: }
6311:
6312: table.LC_createuser {
6313: }
6314:
6315: table.LC_createuser tr.LC_section_row td {
6316: font-size: small;
6317: }
6318:
6319: table.LC_createuser tr.LC_info_row td {
6320: background-color: #CCCCCC;
6321: font-weight: bold;
6322: text-align: center;
6323: }
6324:
6325: table.LC_calendar {
6326: border: 1px solid #000000;
6327: border-collapse: collapse;
6328: width: 98%;
6329: }
6330:
6331: table.LC_calendar_pickdate {
6332: font-size: xx-small;
6333: }
6334:
6335: table.LC_calendar tr td {
6336: border: 1px solid #000000;
6337: vertical-align: top;
6338: width: 14%;
6339: }
6340:
6341: table.LC_calendar tr td.LC_calendar_day_empty {
6342: background-color: $data_table_dark;
6343: }
6344:
6345: table.LC_calendar tr td.LC_calendar_day_current {
6346: background-color: $data_table_highlight;
6347: }
6348:
6349: table.LC_data_table tr td.LC_mail_new {
6350: background-color: $mail_new;
6351: }
6352:
6353: table.LC_data_table tr.LC_mail_new:hover {
6354: background-color: $mail_new_hover;
6355: }
6356:
6357: table.LC_data_table tr td.LC_mail_read {
6358: background-color: $mail_read;
6359: }
6360:
6361: /*
6362: table.LC_data_table tr.LC_mail_read:hover {
6363: background-color: $mail_read_hover;
6364: }
6365: */
6366:
6367: table.LC_data_table tr td.LC_mail_replied {
6368: background-color: $mail_replied;
6369: }
6370:
6371: /*
6372: table.LC_data_table tr.LC_mail_replied:hover {
6373: background-color: $mail_replied_hover;
6374: }
6375: */
6376:
6377: table.LC_data_table tr td.LC_mail_other {
6378: background-color: $mail_other;
6379: }
6380:
6381: /*
6382: table.LC_data_table tr.LC_mail_other:hover {
6383: background-color: $mail_other_hover;
6384: }
6385: */
6386:
6387: table.LC_data_table tr > td.LC_browser_file,
6388: table.LC_data_table tr > td.LC_browser_file_published {
6389: background: #AAEE77;
6390: }
6391:
6392: table.LC_data_table tr > td.LC_browser_file_locked,
6393: table.LC_data_table tr > td.LC_browser_file_unpublished {
6394: background: #FFAA99;
6395: }
6396:
6397: table.LC_data_table tr > td.LC_browser_file_obsolete {
6398: background: #888888;
6399: }
6400:
6401: table.LC_data_table tr > td.LC_browser_file_modified,
6402: table.LC_data_table tr > td.LC_browser_file_metamodified {
6403: background: #F8F866;
6404: }
6405:
6406: table.LC_data_table tr.LC_browser_folder > td {
6407: background: #E0E8FF;
6408: }
6409:
6410: table.LC_data_table tr > td.LC_roles_is {
6411: /* background: #77FF77; */
6412: }
6413:
6414: table.LC_data_table tr > td.LC_roles_future {
6415: border-right: 8px solid #FFFF77;
6416: }
6417:
6418: table.LC_data_table tr > td.LC_roles_will {
6419: border-right: 8px solid #FFAA77;
6420: }
6421:
6422: table.LC_data_table tr > td.LC_roles_expired {
6423: border-right: 8px solid #FF7777;
6424: }
6425:
6426: table.LC_data_table tr > td.LC_roles_will_not {
6427: border-right: 8px solid #AAFF77;
6428: }
6429:
6430: table.LC_data_table tr > td.LC_roles_selected {
6431: border-right: 8px solid #11CC55;
6432: }
6433:
6434: span.LC_current_location {
6435: font-size:larger;
6436: background: $pgbg;
6437: }
6438:
6439: span.LC_current_nav_location {
6440: font-weight:bold;
6441: background: $sidebg;
6442: }
6443:
6444: span.LC_parm_menu_item {
6445: font-size: larger;
6446: }
6447:
6448: span.LC_parm_scope_all {
6449: color: red;
6450: }
6451:
6452: span.LC_parm_scope_folder {
6453: color: green;
6454: }
6455:
6456: span.LC_parm_scope_resource {
6457: color: orange;
6458: }
6459:
6460: span.LC_parm_part {
6461: color: blue;
6462: }
6463:
6464: span.LC_parm_folder,
6465: span.LC_parm_symb {
6466: font-size: x-small;
6467: font-family: $mono;
6468: color: #AAAAAA;
6469: }
6470:
6471: ul.LC_parm_parmlist li {
6472: display: inline-block;
6473: padding: 0.3em 0.8em;
6474: vertical-align: top;
6475: width: 150px;
6476: border-top:1px solid $lg_border_color;
6477: }
6478:
6479: td.LC_parm_overview_level_menu,
6480: td.LC_parm_overview_map_menu,
6481: td.LC_parm_overview_parm_selectors,
6482: td.LC_parm_overview_restrictions {
6483: border: 1px solid black;
6484: border-collapse: collapse;
6485: }
6486:
6487: table.LC_parm_overview_restrictions td {
6488: border-width: 1px 4px 1px 4px;
6489: border-style: solid;
6490: border-color: $pgbg;
6491: text-align: center;
6492: }
6493:
6494: table.LC_parm_overview_restrictions th {
6495: background: $tabbg;
6496: border-width: 1px 4px 1px 4px;
6497: border-style: solid;
6498: border-color: $pgbg;
6499: }
6500:
6501: table#LC_helpmenu {
6502: border: none;
6503: height: 55px;
6504: border-spacing: 0;
6505: }
6506:
6507: table#LC_helpmenu fieldset legend {
6508: font-size: larger;
6509: }
6510:
6511: table#LC_helpmenu_links {
6512: width: 100%;
6513: border: 1px solid black;
6514: background: $pgbg;
6515: padding: 0;
6516: border-spacing: 1px;
6517: }
6518:
6519: table#LC_helpmenu_links tr td {
6520: padding: 1px;
6521: background: $tabbg;
6522: text-align: center;
6523: font-weight: bold;
6524: }
6525:
6526: table#LC_helpmenu_links a:link,
6527: table#LC_helpmenu_links a:visited,
6528: table#LC_helpmenu_links a:active {
6529: text-decoration: none;
6530: color: $font;
6531: }
6532:
6533: table#LC_helpmenu_links a:hover {
6534: text-decoration: underline;
6535: color: $vlink;
6536: }
6537:
6538: .LC_chrt_popup_exists {
6539: border: 1px solid #339933;
6540: margin: -1px;
6541: }
6542:
6543: .LC_chrt_popup_up {
6544: border: 1px solid yellow;
6545: margin: -1px;
6546: }
6547:
6548: .LC_chrt_popup {
6549: border: 1px solid #8888FF;
6550: background: #CCCCFF;
6551: }
6552:
6553: table.LC_pick_box {
6554: border-collapse: separate;
6555: background: white;
6556: border: 1px solid black;
6557: border-spacing: 1px;
6558: }
6559:
6560: table.LC_pick_box td.LC_pick_box_title {
6561: background: $sidebg;
6562: font-weight: bold;
6563: text-align: left;
6564: vertical-align: top;
6565: width: 184px;
6566: padding: 8px;
6567: }
6568:
6569: table.LC_pick_box td.LC_pick_box_value {
6570: text-align: left;
6571: padding: 8px;
6572: }
6573:
6574: table.LC_pick_box td.LC_pick_box_select {
6575: text-align: left;
6576: padding: 8px;
6577: }
6578:
6579: table.LC_pick_box td.LC_pick_box_separator {
6580: padding: 0;
6581: height: 1px;
6582: background: black;
6583: }
6584:
6585: table.LC_pick_box td.LC_pick_box_submit {
6586: text-align: right;
6587: }
6588:
6589: table.LC_pick_box td.LC_evenrow_value {
6590: text-align: left;
6591: padding: 8px;
6592: background-color: $data_table_light;
6593: }
6594:
6595: table.LC_pick_box td.LC_oddrow_value {
6596: text-align: left;
6597: padding: 8px;
6598: background-color: $data_table_light;
6599: }
6600:
6601: span.LC_helpform_receipt_cat {
6602: font-weight: bold;
6603: }
6604:
6605: table.LC_group_priv_box {
6606: background: white;
6607: border: 1px solid black;
6608: border-spacing: 1px;
6609: }
6610:
6611: table.LC_group_priv_box td.LC_pick_box_title {
6612: background: $tabbg;
6613: font-weight: bold;
6614: text-align: right;
6615: width: 184px;
6616: }
6617:
6618: table.LC_group_priv_box td.LC_groups_fixed {
6619: background: $data_table_light;
6620: text-align: center;
6621: }
6622:
6623: table.LC_group_priv_box td.LC_groups_optional {
6624: background: $data_table_dark;
6625: text-align: center;
6626: }
6627:
6628: table.LC_group_priv_box td.LC_groups_functionality {
6629: background: $data_table_darker;
6630: text-align: center;
6631: font-weight: bold;
6632: }
6633:
6634: table.LC_group_priv td {
6635: text-align: left;
6636: padding: 0;
6637: }
6638:
6639: .LC_navbuttons {
6640: margin: 2ex 0ex 2ex 0ex;
6641: }
6642:
6643: .LC_topic_bar {
6644: font-weight: bold;
6645: background: $tabbg;
6646: margin: 1em 0em 1em 2em;
6647: padding: 3px;
6648: font-size: 1.2em;
6649: }
6650:
6651: .LC_topic_bar span {
6652: left: 0.5em;
6653: position: absolute;
6654: vertical-align: middle;
6655: font-size: 1.2em;
6656: }
6657:
6658: table.LC_course_group_status {
6659: margin: 20px;
6660: }
6661:
6662: table.LC_status_selector td {
6663: vertical-align: top;
6664: text-align: center;
6665: padding: 4px;
6666: }
6667:
6668: div.LC_feedback_link {
6669: clear: both;
6670: background: $sidebg;
6671: width: 100%;
6672: padding-bottom: 10px;
6673: border: 1px $tabbg solid;
6674: height: 22px;
6675: line-height: 22px;
6676: padding-top: 5px;
6677: }
6678:
6679: div.LC_feedback_link img {
6680: height: 22px;
6681: vertical-align:middle;
6682: }
6683:
6684: div.LC_feedback_link a {
6685: text-decoration: none;
6686: }
6687:
6688: div.LC_comblock {
6689: display:inline;
6690: color:$font;
6691: font-size:90%;
6692: }
6693:
6694: div.LC_feedback_link div.LC_comblock {
6695: padding-left:5px;
6696: }
6697:
6698: div.LC_feedback_link div.LC_comblock a {
6699: color:$font;
6700: }
6701:
6702: span.LC_feedback_link {
6703: /* background: $feedback_link_bg; */
6704: font-size: larger;
6705: }
6706:
6707: span.LC_message_link {
6708: /* background: $feedback_link_bg; */
6709: font-size: larger;
6710: position: absolute;
6711: right: 1em;
6712: }
6713:
6714: table.LC_prior_tries {
6715: border: 1px solid #000000;
6716: border-collapse: separate;
6717: border-spacing: 1px;
6718: }
6719:
6720: table.LC_prior_tries td {
6721: padding: 2px;
6722: }
6723:
6724: .LC_answer_correct {
6725: background: lightgreen;
6726: color: darkgreen;
6727: padding: 6px;
6728: }
6729:
6730: .LC_answer_charged_try {
6731: background: #FFAAAA;
6732: color: darkred;
6733: padding: 6px;
6734: }
6735:
6736: .LC_answer_not_charged_try,
6737: .LC_answer_no_grade,
6738: .LC_answer_late {
6739: background: lightyellow;
6740: color: black;
6741: padding: 6px;
6742: }
6743:
6744: .LC_answer_previous {
6745: background: lightblue;
6746: color: darkblue;
6747: padding: 6px;
6748: }
6749:
6750: .LC_answer_no_message {
6751: background: #FFFFFF;
6752: color: black;
6753: padding: 6px;
6754: }
6755:
6756: .LC_answer_unknown,
6757: .LC_answer_warning {
6758: background: orange;
6759: color: black;
6760: padding: 6px;
6761: }
6762:
6763: span.LC_prior_numerical,
6764: span.LC_prior_string,
6765: span.LC_prior_custom,
6766: span.LC_prior_reaction,
6767: span.LC_prior_math {
6768: font-family: $mono;
6769: white-space: pre;
6770: }
6771:
6772: span.LC_prior_string {
6773: font-family: $mono;
6774: white-space: pre;
6775: }
6776:
6777: table.LC_prior_option {
6778: width: 100%;
6779: border-collapse: collapse;
6780: }
6781:
6782: table.LC_prior_rank,
6783: table.LC_prior_match {
6784: border-collapse: collapse;
6785: }
6786:
6787: table.LC_prior_option tr td,
6788: table.LC_prior_rank tr td,
6789: table.LC_prior_match tr td {
6790: border: 1px solid #000000;
6791: }
6792:
6793: .LC_nobreak {
6794: white-space: nowrap;
6795: }
6796:
6797: span.LC_cusr_emph {
6798: font-style: italic;
6799: }
6800:
6801: span.LC_cusr_subheading {
6802: font-weight: normal;
6803: font-size: 85%;
6804: }
6805:
6806: div.LC_docs_entry_move {
6807: border: 1px solid #BBBBBB;
6808: background: #DDDDDD;
6809: width: 22px;
6810: padding: 1px;
6811: margin: 0;
6812: }
6813:
6814: table.LC_data_table tr > td.LC_docs_entry_commands,
6815: table.LC_data_table tr > td.LC_docs_entry_parameter {
6816: font-size: x-small;
6817: }
6818:
6819: .LC_docs_entry_parameter {
6820: white-space: nowrap;
6821: }
6822:
6823: .LC_docs_copy {
6824: color: #000099;
6825: }
6826:
6827: .LC_docs_cut {
6828: color: #550044;
6829: }
6830:
6831: .LC_docs_rename {
6832: color: #009900;
6833: }
6834:
6835: .LC_docs_remove {
6836: color: #990000;
6837: }
6838:
6839: .LC_domprefs_email,
6840: .LC_docs_reinit_warn,
6841: .LC_docs_ext_edit {
6842: font-size: x-small;
6843: }
6844:
6845: table.LC_docs_adddocs td,
6846: table.LC_docs_adddocs th {
6847: border: 1px solid #BBBBBB;
6848: padding: 4px;
6849: background: #DDDDDD;
6850: }
6851:
6852: table.LC_sty_begin {
6853: background: #BBFFBB;
6854: }
6855:
6856: table.LC_sty_end {
6857: background: #FFBBBB;
6858: }
6859:
6860: table.LC_double_column {
6861: border-width: 0;
6862: border-collapse: collapse;
6863: width: 100%;
6864: padding: 2px;
6865: }
6866:
6867: table.LC_double_column tr td.LC_left_col {
6868: top: 2px;
6869: left: 2px;
6870: width: 47%;
6871: vertical-align: top;
6872: }
6873:
6874: table.LC_double_column tr td.LC_right_col {
6875: top: 2px;
6876: right: 2px;
6877: width: 47%;
6878: vertical-align: top;
6879: }
6880:
6881: div.LC_left_float {
6882: float: left;
6883: padding-right: 5%;
6884: padding-bottom: 4px;
6885: }
6886:
6887: div.LC_clear_float_header {
6888: padding-bottom: 2px;
6889: }
6890:
6891: div.LC_clear_float_footer {
6892: padding-top: 10px;
6893: clear: both;
6894: }
6895:
6896: div.LC_grade_show_user {
6897: /* border-left: 5px solid $sidebg; */
6898: border-top: 5px solid #000000;
6899: margin: 50px 0 0 0;
6900: padding: 15px 0 5px 10px;
6901: }
6902:
6903: div.LC_grade_show_user_odd_row {
6904: /* border-left: 5px solid #000000; */
6905: }
6906:
6907: div.LC_grade_show_user div.LC_Box {
6908: margin-right: 50px;
6909: }
6910:
6911: div.LC_grade_submissions,
6912: div.LC_grade_message_center,
6913: div.LC_grade_info_links {
6914: margin: 5px;
6915: width: 99%;
6916: background: #FFFFFF;
6917: }
6918:
6919: div.LC_grade_submissions_header,
6920: div.LC_grade_message_center_header {
6921: font-weight: bold;
6922: font-size: large;
6923: }
6924:
6925: div.LC_grade_submissions_body,
6926: div.LC_grade_message_center_body {
6927: border: 1px solid black;
6928: width: 99%;
6929: background: #FFFFFF;
6930: }
6931:
6932: table.LC_scantron_action {
6933: width: 100%;
6934: }
6935:
6936: table.LC_scantron_action tr th {
6937: font-weight:bold;
6938: font-style:normal;
6939: }
6940:
6941: .LC_edit_problem_header,
6942: div.LC_edit_problem_footer {
6943: font-weight: normal;
6944: font-size: medium;
6945: margin: 2px;
6946: background-color: $sidebg;
6947: }
6948:
6949: div.LC_edit_problem_header,
6950: div.LC_edit_problem_header div,
6951: div.LC_edit_problem_footer,
6952: div.LC_edit_problem_footer div,
6953: div.LC_edit_problem_editxml_header,
6954: div.LC_edit_problem_editxml_header div {
6955: z-index: 100;
6956: }
6957:
6958: div.LC_edit_problem_header_title {
6959: font-weight: bold;
6960: font-size: larger;
6961: background: $tabbg;
6962: padding: 3px;
6963: margin: 0 0 5px 0;
6964: }
6965:
6966: table.LC_edit_problem_header_title {
6967: width: 100%;
6968: background: $tabbg;
6969: }
6970:
6971: div.LC_edit_actionbar {
6972: background-color: $sidebg;
6973: margin: 0;
6974: padding: 0;
6975: line-height: 200%;
6976: }
6977:
6978: div.LC_edit_actionbar div{
6979: padding: 0;
6980: margin: 0;
6981: display: inline-block;
6982: }
6983:
6984: .LC_edit_opt {
6985: padding-left: 1em;
6986: white-space: nowrap;
6987: }
6988:
6989: .LC_edit_problem_latexhelper{
6990: text-align: right;
6991: }
6992:
6993: #LC_edit_problem_colorful div{
6994: margin-left: 40px;
6995: }
6996:
6997: #LC_edit_problem_codemirror div{
6998: margin-left: 0px;
6999: }
7000:
7001: img.stift {
7002: border-width: 0;
7003: vertical-align: middle;
7004: }
7005:
7006: table td.LC_mainmenu_col_fieldset {
7007: vertical-align: top;
7008: }
7009:
7010: div.LC_createcourse {
7011: margin: 10px 10px 10px 10px;
7012: }
7013:
7014: .LC_dccid {
7015: float: right;
7016: margin: 0.2em 0 0 0;
7017: padding: 0;
7018: font-size: 90%;
7019: display:none;
7020: }
7021:
7022: ol.LC_primary_menu a:hover,
7023: ol#LC_MenuBreadcrumbs a:hover,
7024: ol#LC_PathBreadcrumbs a:hover,
7025: ul#LC_secondary_menu a:hover,
7026: .LC_FormSectionClearButton input:hover
7027: ul.LC_TabContent li:hover a {
7028: color:$button_hover;
7029: text-decoration:none;
7030: }
7031:
7032: h1 {
7033: padding: 0;
7034: line-height:130%;
7035: }
7036:
7037: h2,
7038: h3,
7039: h4,
7040: h5,
7041: h6 {
7042: margin: 5px 0 5px 0;
7043: padding: 0;
7044: line-height:130%;
7045: }
7046:
7047: .LC_hcell {
7048: padding:3px 15px 3px 15px;
7049: margin: 0;
7050: background-color:$tabbg;
7051: color:$fontmenu;
7052: border-bottom:solid 1px $lg_border_color;
7053: }
7054:
7055: .LC_Box > .LC_hcell {
7056: margin: 0 -10px 10px -10px;
7057: }
7058:
7059: .LC_noBorder {
7060: border: 0;
7061: }
7062:
7063: .LC_FormSectionClearButton input {
7064: background-color:transparent;
7065: border: none;
7066: cursor:pointer;
7067: text-decoration:underline;
7068: }
7069:
7070: .LC_help_open_topic {
7071: color: #FFFFFF;
7072: background-color: #EEEEFF;
7073: margin: 1px;
7074: padding: 4px;
7075: border: 1px solid #000033;
7076: white-space: nowrap;
7077: /* vertical-align: middle; */
7078: }
7079:
7080: dl,
7081: ul,
7082: div,
7083: fieldset {
7084: margin: 10px 10px 10px 0;
7085: /* overflow: hidden; */
7086: }
7087:
7088: article.geogebraweb div {
7089: margin: 0;
7090: }
7091:
7092: fieldset > legend {
7093: font-weight: bold;
7094: padding: 0 5px 0 5px;
7095: }
7096:
7097: #LC_nav_bar {
7098: float: left;
7099: background-color: $pgbg_or_bgcolor;
7100: margin: 0 0 2px 0;
7101: }
7102:
7103: #LC_realm {
7104: margin: 0.2em 0 0 0;
7105: padding: 0;
7106: font-weight: bold;
7107: text-align: center;
7108: background-color: $pgbg_or_bgcolor;
7109: }
7110:
7111: #LC_nav_bar em {
7112: font-weight: bold;
7113: font-style: normal;
7114: }
7115:
7116: ol.LC_primary_menu {
7117: margin: 0;
7118: padding: 0;
7119: }
7120:
7121: ol#LC_PathBreadcrumbs {
7122: margin: 0;
7123: }
7124:
7125: ol.LC_primary_menu li {
7126: color: RGB(80, 80, 80);
7127: vertical-align: middle;
7128: text-align: left;
7129: list-style: none;
7130: position: relative;
7131: float: left;
7132: z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
7133: line-height: 1.5em;
7134: }
7135:
7136: ol.LC_primary_menu li a,
7137: ol.LC_primary_menu li p {
7138: display: block;
7139: margin: 0;
7140: padding: 0 5px 0 10px;
7141: text-decoration: none;
7142: }
7143:
7144: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
7145: display: inline-block;
7146: width: 95%;
7147: text-align: left;
7148: }
7149:
7150: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
7151: display: inline-block;
7152: width: 5%;
7153: float: right;
7154: text-align: right;
7155: font-size: 70%;
7156: }
7157:
7158: ol.LC_primary_menu ul {
7159: display: none;
7160: width: 15em;
7161: background-color: $data_table_light;
7162: position: absolute;
7163: top: 100%;
7164: }
7165:
7166: ol.LC_primary_menu ul ul {
7167: left: 100%;
7168: top: 0;
7169: }
7170:
7171: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
7172: display: block;
7173: position: absolute;
7174: margin: 0;
7175: padding: 0;
7176: z-index: 2;
7177: }
7178:
7179: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
7180: /* First Submenu -> size should be smaller than the menu title of the whole menu */
7181: font-size: 90%;
7182: vertical-align: top;
7183: float: none;
7184: border-left: 1px solid black;
7185: border-right: 1px solid black;
7186: /* A dark bottom border to visualize different menu options;
7187: overwritten in the create_submenu routine for the last border-bottom of the menu */
7188: border-bottom: 1px solid $data_table_dark;
7189: }
7190:
7191: ol.LC_primary_menu li li p:hover {
7192: color:$button_hover;
7193: text-decoration:none;
7194: background-color:$data_table_dark;
7195: }
7196:
7197: ol.LC_primary_menu li li a:hover {
7198: color:$button_hover;
7199: background-color:$data_table_dark;
7200: }
7201:
7202: /* Font-size equal to the size of the predecessors*/
7203: ol.LC_primary_menu li:hover li li {
7204: font-size: 100%;
7205: }
7206:
7207: ol.LC_primary_menu li img {
7208: vertical-align: bottom;
7209: height: 1.1em;
7210: margin: 0.2em 0 0 0;
7211: }
7212:
7213: ol.LC_primary_menu a {
7214: color: RGB(80, 80, 80);
7215: text-decoration: none;
7216: }
7217:
7218: ol.LC_primary_menu a.LC_new_message {
7219: font-weight:bold;
7220: color: darkred;
7221: }
7222:
7223: ol.LC_docs_parameters {
7224: margin-left: 0;
7225: padding: 0;
7226: list-style: none;
7227: }
7228:
7229: ol.LC_docs_parameters li {
7230: margin: 0;
7231: padding-right: 20px;
7232: display: inline;
7233: }
7234:
7235: ol.LC_docs_parameters li:before {
7236: content: "\\002022 \\0020";
7237: }
7238:
7239: li.LC_docs_parameters_title {
7240: font-weight: bold;
7241: }
7242:
7243: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
7244: content: "";
7245: }
7246:
7247: ul#LC_secondary_menu {
7248: clear: right;
7249: color: $fontmenu;
7250: background: $tabbg;
7251: list-style: none;
7252: padding: 0;
7253: margin: 0;
7254: width: 100%;
7255: text-align: left;
7256: float: left;
7257: }
7258:
7259: ul#LC_secondary_menu li {
7260: font-weight: bold;
7261: line-height: 1.8em;
7262: border-right: 1px solid black;
7263: float: left;
7264: }
7265:
7266: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
7267: background-color: $data_table_light;
7268: }
7269:
7270: ul#LC_secondary_menu li a {
7271: padding: 0 0.8em;
7272: }
7273:
7274: ul#LC_secondary_menu li ul {
7275: display: none;
7276: }
7277:
7278: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
7279: display: block;
7280: position: absolute;
7281: margin: 0;
7282: padding: 0;
7283: list-style:none;
7284: float: none;
7285: background-color: $data_table_light;
7286: z-index: 2;
7287: margin-left: -1px;
7288: }
7289:
7290: ul#LC_secondary_menu li ul li {
7291: font-size: 90%;
7292: vertical-align: top;
7293: border-left: 1px solid black;
7294: border-right: 1px solid black;
7295: background-color: $data_table_light;
7296: list-style:none;
7297: float: none;
7298: }
7299:
7300: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
7301: background-color: $data_table_dark;
7302: }
7303:
7304: ul.LC_TabContent {
7305: display:block;
7306: background: $sidebg;
7307: border-bottom: solid 1px $lg_border_color;
7308: list-style:none;
7309: margin: -1px -10px 0 -10px;
7310: padding: 0;
7311: }
7312:
7313: ul.LC_TabContent li,
7314: ul.LC_TabContentBigger li {
7315: float:left;
7316: }
7317:
7318: ul#LC_secondary_menu li a {
7319: color: $fontmenu;
7320: text-decoration: none;
7321: }
7322:
7323: ul.LC_TabContent {
7324: min-height:20px;
7325: }
7326:
7327: ul.LC_TabContent li {
7328: vertical-align:middle;
7329: padding: 0 16px 0 10px;
7330: background-color:$tabbg;
7331: border-bottom:solid 1px $lg_border_color;
7332: border-left: solid 1px $font;
7333: }
7334:
7335: ul.LC_TabContent .right {
7336: float:right;
7337: }
7338:
7339: ul.LC_TabContent li a,
7340: ul.LC_TabContent li {
7341: color:rgb(47,47,47);
7342: text-decoration:none;
7343: font-size:95%;
7344: font-weight:bold;
7345: min-height:20px;
7346: }
7347:
7348: ul.LC_TabContent li a:hover,
7349: ul.LC_TabContent li a:focus {
7350: color: $button_hover;
7351: background:none;
7352: outline:none;
7353: }
7354:
7355: ul.LC_TabContent li:hover {
7356: color: $button_hover;
7357: cursor:pointer;
7358: }
7359:
7360: ul.LC_TabContent li.active {
7361: color: $font;
7362: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
7363: border-bottom:solid 1px #FFFFFF;
7364: cursor: default;
7365: }
7366:
7367: ul.LC_TabContent li.active a {
7368: color:$font;
7369: background:#FFFFFF;
7370: outline: none;
7371: }
7372:
7373: ul.LC_TabContent li.goback {
7374: float: left;
7375: border-left: none;
7376: }
7377:
7378: #maincoursedoc {
7379: clear:both;
7380: }
7381:
7382: ul.LC_TabContentBigger {
7383: display:block;
7384: list-style:none;
7385: padding: 0;
7386: }
7387:
7388: ul.LC_TabContentBigger li {
7389: vertical-align:bottom;
7390: height: 30px;
7391: font-size:110%;
7392: font-weight:bold;
7393: color: #737373;
7394: }
7395:
7396: ul.LC_TabContentBigger li.active {
7397: position: relative;
7398: top: 1px;
7399: }
7400:
7401: ul.LC_TabContentBigger li a {
7402: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
7403: height: 30px;
7404: line-height: 30px;
7405: text-align: center;
7406: display: block;
7407: text-decoration: none;
7408: outline: none;
7409: }
7410:
7411: ul.LC_TabContentBigger li.active a {
7412: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
7413: color:$font;
7414: }
7415:
7416: ul.LC_TabContentBigger li b {
7417: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
7418: display: block;
7419: float: left;
7420: padding: 0 30px;
7421: border-bottom: 1px solid $lg_border_color;
7422: }
7423:
7424: ul.LC_TabContentBigger li:hover b {
7425: color:$button_hover;
7426: }
7427:
7428: ul.LC_TabContentBigger li.active b {
7429: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
7430: color:$font;
7431: border: 0;
7432: }
7433:
7434:
7435: ul.LC_CourseBreadcrumbs {
7436: background: $sidebg;
7437: height: 2em;
7438: padding-left: 10px;
7439: margin: 0;
7440: list-style-position: inside;
7441: }
7442:
7443: ol#LC_MenuBreadcrumbs,
7444: ol#LC_PathBreadcrumbs {
7445: padding-left: 10px;
7446: margin: 0;
7447: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
7448: }
7449:
7450: ol#LC_MenuBreadcrumbs li,
7451: ol#LC_PathBreadcrumbs li,
7452: ul.LC_CourseBreadcrumbs li {
7453: display: inline;
7454: white-space: normal;
7455: }
7456:
7457: ol#LC_MenuBreadcrumbs li a,
7458: ul.LC_CourseBreadcrumbs li a {
7459: text-decoration: none;
7460: font-size:90%;
7461: }
7462:
7463: ol#LC_MenuBreadcrumbs h1 {
7464: display: inline;
7465: font-size: 90%;
7466: line-height: 2.5em;
7467: margin: 0;
7468: padding: 0;
7469: }
7470:
7471: ol#LC_PathBreadcrumbs li a {
7472: text-decoration:none;
7473: font-size:100%;
7474: font-weight:bold;
7475: }
7476:
7477: .LC_Box {
7478: border: solid 1px $lg_border_color;
7479: padding: 0 10px 10px 10px;
7480: }
7481:
7482: .LC_DocsBox {
7483: border: solid 1px $lg_border_color;
7484: padding: 0 0 10px 10px;
7485: }
7486:
7487: .LC_AboutMe_Image {
7488: float:left;
7489: margin-right:10px;
7490: }
7491:
7492: .LC_Clear_AboutMe_Image {
7493: clear:left;
7494: }
7495:
7496: dl.LC_ListStyleClean dt {
7497: padding-right: 5px;
7498: display: table-header-group;
7499: }
7500:
7501: dl.LC_ListStyleClean dd {
7502: display: table-row;
7503: }
7504:
7505: .LC_ListStyleClean,
7506: .LC_ListStyleSimple,
7507: .LC_ListStyleNormal,
7508: .LC_ListStyleSpecial {
7509: /* display:block; */
7510: list-style-position: inside;
7511: list-style-type: none;
7512: overflow: hidden;
7513: padding: 0;
7514: }
7515:
7516: .LC_ListStyleSimple li,
7517: .LC_ListStyleSimple dd,
7518: .LC_ListStyleNormal li,
7519: .LC_ListStyleNormal dd,
7520: .LC_ListStyleSpecial li,
7521: .LC_ListStyleSpecial dd {
7522: margin: 0;
7523: padding: 5px 5px 5px 10px;
7524: clear: both;
7525: }
7526:
7527: .LC_ListStyleClean li,
7528: .LC_ListStyleClean dd {
7529: padding-top: 0;
7530: padding-bottom: 0;
7531: }
7532:
7533: .LC_ListStyleSimple dd,
7534: .LC_ListStyleSimple li {
7535: border-bottom: solid 1px $lg_border_color;
7536: }
7537:
7538: .LC_ListStyleSpecial li,
7539: .LC_ListStyleSpecial dd {
7540: list-style-type: none;
7541: background-color: RGB(220, 220, 220);
7542: margin-bottom: 4px;
7543: }
7544:
7545: table.LC_SimpleTable {
7546: margin:5px;
7547: border:solid 1px $lg_border_color;
7548: }
7549:
7550: table.LC_SimpleTable tr {
7551: padding: 0;
7552: border:solid 1px $lg_border_color;
7553: }
7554:
7555: table.LC_SimpleTable thead {
7556: background:rgb(220,220,220);
7557: }
7558:
7559: div.LC_columnSection {
7560: display: block;
7561: clear: both;
7562: overflow: hidden;
7563: margin: 0;
7564: }
7565:
7566: div.LC_columnSection>* {
7567: float: left;
7568: margin: 10px 20px 10px 0;
7569: overflow:hidden;
7570: }
7571:
7572: table em {
7573: font-weight: bold;
7574: font-style: normal;
7575: }
7576:
7577: table.LC_tableBrowseRes,
7578: table.LC_tableOfContent {
7579: border:none;
7580: border-spacing: 1px;
7581: padding: 3px;
7582: background-color: #FFFFFF;
7583: font-size: 90%;
7584: }
7585:
7586: table.LC_tableOfContent {
7587: border-collapse: collapse;
7588: }
7589:
7590: table.LC_tableBrowseRes a,
7591: table.LC_tableOfContent a {
7592: background-color: transparent;
7593: text-decoration: none;
7594: }
7595:
7596: table.LC_tableOfContent img {
7597: border: none;
7598: height: 1.3em;
7599: vertical-align: text-bottom;
7600: margin-right: 0.3em;
7601: }
7602:
7603: a#LC_content_toolbar_firsthomework {
7604: background-image:url(/res/adm/pages/open-first-problem.gif);
7605: }
7606:
7607: a#LC_content_toolbar_everything {
7608: background-image:url(/res/adm/pages/show-all.gif);
7609: }
7610:
7611: a#LC_content_toolbar_uncompleted {
7612: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
7613: }
7614:
7615: #LC_content_toolbar_clearbubbles {
7616: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
7617: }
7618:
7619: a#LC_content_toolbar_changefolder {
7620: background : url(/res/adm/pages/close-all-folders.gif) top center ;
7621: }
7622:
7623: a#LC_content_toolbar_changefolder_toggled {
7624: background-image:url(/res/adm/pages/open-all-folders.gif);
7625: }
7626:
7627: a#LC_content_toolbar_edittoplevel {
7628: background-image:url(/res/adm/pages/edittoplevel.gif);
7629: }
7630:
7631: ul#LC_toolbar li a:hover {
7632: background-position: bottom center;
7633: }
7634:
7635: ul#LC_toolbar {
7636: padding: 0;
7637: margin: 2px;
7638: list-style:none;
7639: position:relative;
7640: background-color:white;
7641: overflow: auto;
7642: }
7643:
7644: ul#LC_toolbar li {
7645: border:1px solid white;
7646: padding: 0;
7647: margin: 0;
7648: float: left;
7649: display:inline;
7650: vertical-align:middle;
7651: white-space: nowrap;
7652: }
7653:
7654:
7655: a.LC_toolbarItem {
7656: display:block;
7657: padding: 0;
7658: margin: 0;
7659: height: 32px;
7660: width: 32px;
7661: color:white;
7662: border: none;
7663: background-repeat:no-repeat;
7664: background-color:transparent;
7665: }
7666:
7667: ul.LC_funclist {
7668: margin: 0;
7669: padding: 0.5em 1em 0.5em 0;
7670: }
7671:
7672: ul.LC_funclist > li:first-child {
7673: font-weight:bold;
7674: margin-left:0.8em;
7675: }
7676:
7677: ul.LC_funclist + ul.LC_funclist {
7678: /*
7679: left border as a seperator if we have more than
7680: one list
7681: */
7682: border-left: 1px solid $sidebg;
7683: /*
7684: this hides the left border behind the border of the
7685: outer box if element is wrapped to the next 'line'
7686: */
7687: margin-left: -1px;
7688: }
7689:
7690: ul.LC_funclist li {
7691: display: inline;
7692: white-space: nowrap;
7693: margin: 0 0 0 25px;
7694: line-height: 150%;
7695: }
7696:
7697: .LC_hidden {
7698: display: none;
7699: }
7700:
7701: .LCmodal-overlay {
7702: position:fixed;
7703: top:0;
7704: right:0;
7705: bottom:0;
7706: left:0;
7707: height:100%;
7708: width:100%;
7709: margin:0;
7710: padding:0;
7711: background:#999;
7712: opacity:.75;
7713: filter: alpha(opacity=75);
7714: -moz-opacity: 0.75;
7715: z-index:101;
7716: }
7717:
7718: * html .LCmodal-overlay {
7719: position: absolute;
7720: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
7721: }
7722:
7723: .LCmodal-window {
7724: position:fixed;
7725: top:50%;
7726: left:50%;
7727: margin:0;
7728: padding:0;
7729: z-index:102;
7730: }
7731:
7732: * html .LCmodal-window {
7733: position:absolute;
7734: }
7735:
7736: .LCclose-window {
7737: position:absolute;
7738: width:32px;
7739: height:32px;
7740: right:8px;
7741: top:8px;
7742: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
7743: text-indent:-99999px;
7744: overflow:hidden;
7745: cursor:pointer;
7746: }
7747:
7748: /*
7749: styles used by TTH when "Default set of options to pass to tth/m
7750: when converting TeX" in course settings has been set
7751:
7752: option passed: -t
7753:
7754: */
7755:
7756: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
7757: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
7758: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
7759: td div.norm {line-height:normal;}
7760:
7761: /*
7762: option passed -y3
7763: */
7764:
7765: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
7766: span.overacc2 {position: relative; left: .8em; top: -1.2ex;}
7767: span.overacc1 {position: relative; left: .6em; top: -1.2ex;}
7768:
7769: #LC_minitab_header {
7770: float:left;
7771: width:100%;
7772: background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
7773: font-size:93%;
7774: line-height:normal;
7775: margin: 0.5em 0 0.5em 0;
7776: }
7777: #LC_minitab_header ul {
7778: margin:0;
7779: padding:10px 10px 0;
7780: list-style:none;
7781: }
7782: #LC_minitab_header li {
7783: float:left;
7784: background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
7785: margin:0;
7786: padding:0 0 0 9px;
7787: }
7788: #LC_minitab_header a {
7789: display:block;
7790: background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
7791: padding:5px 15px 4px 6px;
7792: }
7793: #LC_minitab_header #LC_current_minitab {
7794: background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
7795: }
7796: #LC_minitab_header #LC_current_minitab a {
7797: background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
7798: padding-bottom:5px;
7799: }
7800:
7801:
7802: END
7803: }
7804:
7805: =pod
7806:
7807: =item * &headtag()
7808:
7809: Returns a uniform footer for LON-CAPA web pages.
7810:
7811: Inputs: $title - optional title for the head
7812: $head_extra - optional extra HTML to put inside the <head>
7813: $args - optional arguments
7814: force_register - if is true call registerurl so the remote is
7815: informed
7816: redirect -> array ref of
7817: 1- seconds before redirect occurs
7818: 2- url to redirect to
7819: 3- whether the side effect should occur
7820: (side effect of setting
7821: $env{'internal.head.redirect'} to the url
7822: redirected too)
7823: domain -> force to color decorate a page for a specific
7824: domain
7825: function -> force usage of a specific rolish color scheme
7826: bgcolor -> override the default page bgcolor
7827: no_auto_mt_title
7828: -> prevent &mt()ing the title arg
7829:
7830: =cut
7831:
7832: sub headtag {
7833: my ($title,$head_extra,$args) = @_;
7834:
7835: my $function = $args->{'function'} || &get_users_function();
7836: my $domain = $args->{'domain'} || &determinedomain();
7837: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
7838: my $httphost = $args->{'use_absolute'};
7839: my $url = join(':',$env{'user.name'},$env{'user.domain'},
7840: $Apache::lonnet::perlvar{'lonVersion'},
7841: #time(),
7842: $env{'environment.color.timestamp'},
7843: $function,$domain,$bgcolor);
7844:
7845: $url = '/adm/css/'.&escape($url).'.css';
7846:
7847: my $result =
7848: '<head>'.
7849: &font_settings($args);
7850:
7851: my $inhibitprint;
7852: if ($args->{'print_suppress'}) {
7853: $inhibitprint = &print_suppression();
7854: }
7855:
7856: if (!$args->{'frameset'}) {
7857: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
7858: }
7859: if ($args->{'force_register'}) {
7860: $result .= &Apache::lonmenu::registerurl(1);
7861: }
7862: if (!$args->{'no_nav_bar'}
7863: && !$args->{'only_body'}
7864: && !$args->{'frameset'}) {
7865: $result .= &help_menu_js($httphost);
7866: $result.=&modal_window();
7867: $result.=&togglebox_script();
7868: $result.=&wishlist_window();
7869: $result.=&LCprogressbarUpdate_script();
7870: } else {
7871: if ($args->{'add_modal'}) {
7872: $result.=&modal_window();
7873: }
7874: if ($args->{'add_wishlist'}) {
7875: $result.=&wishlist_window();
7876: }
7877: if ($args->{'add_togglebox'}) {
7878: $result.=&togglebox_script();
7879: }
7880: if ($args->{'add_progressbar'}) {
7881: $result.=&LCprogressbarUpdate_script();
7882: }
7883: }
7884: if (ref($args->{'redirect'})) {
7885: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
7886: $url = &Apache::lonenc::check_encrypt($url);
7887: if (!$inhibit_continue) {
7888: $env{'internal.head.redirect'} = $url;
7889: }
7890: $result.=<<ADDMETA
7891: <meta http-equiv="pragma" content="no-cache" />
7892: <meta http-equiv="Refresh" content="$time; url=$url" />
7893: ADDMETA
7894: } else {
7895: unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
7896: my $requrl = $env{'request.uri'};
7897: if ($requrl eq '') {
7898: $requrl = $ENV{'REQUEST_URI'};
7899: $requrl =~ s/\?.+$//;
7900: }
7901: unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
7902: (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
7903: ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
7904: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
7905: unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
7906: my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
7907: if (ref($domdefs{'offloadnow'}) eq 'HASH') {
7908: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
7909: if ($domdefs{'offloadnow'}{$lonhost}) {
7910: my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
7911: if (($newserver) && ($newserver ne $lonhost)) {
7912: my $numsec = 5;
7913: my $timeout = $numsec * 1000;
7914: my ($newurl,$locknum,%locks,$msg);
7915: if ($env{'request.role.adv'}) {
7916: ($locknum,%locks) = &Apache::lonnet::get_locks();
7917: }
7918: my $disable_submit = 0;
7919: if ($requrl =~ /$LONCAPA::assess_re/) {
7920: $disable_submit = 1;
7921: }
7922: if ($locknum) {
7923: my @lockinfo = sort(values(%locks));
7924: $msg = &mt('Once the following tasks are complete: ')."\\n".
7925: join(", ",sort(values(%locks)))."\\n".
7926: &mt('your session will be transferred to a different server, after you click "Roles".');
7927: } else {
7928: if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
7929: $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
7930: }
7931: $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
7932: $newurl = '/adm/switchserver?otherserver='.$newserver;
7933: if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
7934: $newurl .= '&role='.$env{'request.role'};
7935: }
7936: if ($env{'request.symb'}) {
7937: $newurl .= '&symb='.$env{'request.symb'};
7938: } else {
7939: $newurl .= '&origurl='.$requrl;
7940: }
7941: }
7942: &js_escape(\$msg);
7943: $result.=<<OFFLOAD
7944: <meta http-equiv="pragma" content="no-cache" />
7945: <script type="text/javascript">
7946: // <![CDATA[
7947: function LC_Offload_Now() {
7948: var dest = "$newurl";
7949: if (dest != '') {
7950: window.location.href="$newurl";
7951: }
7952: }
7953: \$(document).ready(function () {
7954: window.alert('$msg');
7955: if ($disable_submit) {
7956: \$(".LC_hwk_submit").prop("disabled", true);
7957: \$( ".LC_textline" ).prop( "readonly", "readonly");
7958: }
7959: setTimeout('LC_Offload_Now()', $timeout);
7960: });
7961: // ]]>
7962: </script>
7963: OFFLOAD
7964: }
7965: }
7966: }
7967: }
7968: }
7969: }
7970: }
7971: if (!defined($title)) {
7972: $title = 'The LearningOnline Network with CAPA';
7973: }
7974: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
7975: $result .= '<title> LON-CAPA '.$title.'</title>'
7976: .'<link rel="stylesheet" type="text/css" href="'.$url.'"';
7977: if (!$args->{'frameset'}) {
7978: $result .= ' /';
7979: }
7980: $result .= '>'
7981: .$inhibitprint
7982: .$head_extra;
7983: my $clientmobile;
7984: if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
7985: (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
7986: } else {
7987: $clientmobile = $env{'browser.mobile'};
7988: }
7989: if ($clientmobile) {
7990: $result .= '
7991: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
7992: <meta name="apple-mobile-web-app-capable" content="yes" />';
7993: }
7994: $result .= '<meta name="google" content="notranslate" />'."\n";
7995: return $result.'</head>';
7996: }
7997:
7998: =pod
7999:
8000: =item * &font_settings()
8001:
8002: Returns neccessary <meta> to set the proper encoding
8003:
8004: Inputs: optional reference to HASH -- $args passed to &headtag()
8005:
8006: =cut
8007:
8008: sub font_settings {
8009: my ($args) = @_;
8010: my $headerstring='';
8011: if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
8012: ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
8013: $headerstring.=
8014: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
8015: if (!$args->{'frameset'}) {
8016: $headerstring.= ' /';
8017: }
8018: $headerstring .= '>'."\n";
8019: }
8020: return $headerstring;
8021: }
8022:
8023: =pod
8024:
8025: =item * &print_suppression()
8026:
8027: In course context returns css which causes the body to be blank when media="print",
8028: if printout generation is unavailable for the current resource.
8029:
8030: This could be because:
8031:
8032: (a) printstartdate is in the future
8033:
8034: (b) printenddate is in the past
8035:
8036: (c) there is an active exam block with "printout"
8037: functionality blocked
8038:
8039: Users with pav, pfo or evb privileges are exempt.
8040:
8041: Inputs: none
8042:
8043: =cut
8044:
8045:
8046: sub print_suppression {
8047: my $noprint;
8048: if ($env{'request.course.id'}) {
8049: my $scope = $env{'request.course.id'};
8050: if ((&Apache::lonnet::allowed('pav',$scope)) ||
8051: (&Apache::lonnet::allowed('pfo',$scope))) {
8052: return;
8053: }
8054: if ($env{'request.course.sec'} ne '') {
8055: $scope .= "/$env{'request.course.sec'}";
8056: if ((&Apache::lonnet::allowed('pav',$scope)) ||
8057: (&Apache::lonnet::allowed('pfo',$scope))) {
8058: return;
8059: }
8060: }
8061: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8062: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8063: my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
8064: if ($blocked) {
8065: my $checkrole = "cm./$cdom/$cnum";
8066: if ($env{'request.course.sec'} ne '') {
8067: $checkrole .= "/$env{'request.course.sec'}";
8068: }
8069: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
8070: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
8071: $noprint = 1;
8072: }
8073: }
8074: unless ($noprint) {
8075: my $symb = &Apache::lonnet::symbread();
8076: if ($symb ne '') {
8077: my $navmap = Apache::lonnavmaps::navmap->new();
8078: if (ref($navmap)) {
8079: my $res = $navmap->getBySymb($symb);
8080: if (ref($res)) {
8081: if (!$res->resprintable()) {
8082: $noprint = 1;
8083: }
8084: }
8085: }
8086: }
8087: }
8088: if ($noprint) {
8089: return <<"ENDSTYLE";
8090: <style type="text/css" media="print">
8091: body { display:none }
8092: </style>
8093: ENDSTYLE
8094: }
8095: }
8096: return;
8097: }
8098:
8099: =pod
8100:
8101: =item * &xml_begin()
8102:
8103: Returns the needed doctype and <html>
8104:
8105: Inputs: none
8106:
8107: =cut
8108:
8109: sub xml_begin {
8110: my ($is_frameset) = @_;
8111: my $output='';
8112:
8113: if ($env{'browser.mathml'}) {
8114: $output='<?xml version="1.0"?>'
8115: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
8116: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
8117:
8118: # .'<!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">] >'
8119: .'<!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">'
8120: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
8121: .'xmlns="http://www.w3.org/1999/xhtml">';
8122: } elsif ($is_frameset) {
8123: $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
8124: '<html>'."\n";
8125: } else {
8126: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
8127: '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
8128: }
8129: return $output;
8130: }
8131:
8132: =pod
8133:
8134: =item * &start_page()
8135:
8136: Returns a complete <html> .. <body> section for LON-CAPA web pages.
8137:
8138: Inputs:
8139:
8140: =over 4
8141:
8142: $title - optional title for the page
8143:
8144: $head_extra - optional extra HTML to incude inside the <head>
8145:
8146: $args - additional optional args supported are:
8147:
8148: =over 8
8149:
8150: only_body -> is true will set &bodytag() onlybodytag
8151: arg on
8152: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
8153: add_entries -> additional attributes to add to the <body>
8154: domain -> force to color decorate a page for a
8155: specific domain
8156: function -> force usage of a specific rolish color
8157: scheme
8158: redirect -> see &headtag()
8159: bgcolor -> override the default page bg color
8160: js_ready -> return a string ready for being used in
8161: a javascript writeln
8162: html_encode -> return a string ready for being used in
8163: a html attribute
8164: force_register -> if is true will turn on the &bodytag()
8165: $forcereg arg
8166: frameset -> if true will start with a <frameset>
8167: rather than <body>
8168: skip_phases -> hash ref of
8169: head -> skip the <html><head> generation
8170: body -> skip all <body> generation
8171: no_inline_link -> if true and in remote mode, don't show the
8172: 'Switch To Inline Menu' link
8173: no_auto_mt_title -> prevent &mt()ing the title arg
8174: bread_crumbs -> Array containing breadcrumbs
8175: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
8176: bread_crumbs_nomenu -> if true will pass false as the value of $menulink
8177: to lonhtmlcommon::breadcrumbs
8178: group -> includes the current group, if page is for a
8179: specific group
8180: use_absolute -> for request for external resource or syllabus, this
8181: will contain https://<hostname> if server uses
8182: https (as per hosts.tab), but request is for http
8183: hostname -> hostname, originally from $r->hostname(), (optional).
8184:
8185: =back
8186:
8187: =back
8188:
8189: =cut
8190:
8191: sub start_page {
8192: my ($title,$head_extra,$args) = @_;
8193: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
8194:
8195: $env{'internal.start_page'}++;
8196: my ($result,@advtools);
8197:
8198: if (! exists($args->{'skip_phases'}{'head'}) ) {
8199: $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
8200: }
8201:
8202: if (! exists($args->{'skip_phases'}{'body'}) ) {
8203: if ($args->{'frameset'}) {
8204: my $attr_string = &make_attr_string($args->{'force_register'},
8205: $args->{'add_entries'});
8206: $result .= "\n<frameset $attr_string>\n";
8207: } else {
8208: $result .=
8209: &bodytag($title,
8210: $args->{'function'}, $args->{'add_entries'},
8211: $args->{'only_body'}, $args->{'domain'},
8212: $args->{'force_register'}, $args->{'no_nav_bar'},
8213: $args->{'bgcolor'}, $args->{'no_inline_link'},
8214: $args, \@advtools);
8215: }
8216: }
8217:
8218: if ($args->{'js_ready'}) {
8219: $result = &js_ready($result);
8220: }
8221: if ($args->{'html_encode'}) {
8222: $result = &html_encode($result);
8223: }
8224:
8225: # Preparation for new and consistent functionlist at top of screen
8226: # if ($args->{'functionlist'}) {
8227: # $result .= &build_functionlist();
8228: #}
8229:
8230: # Don't add anything more if only_body wanted or in const space
8231: return $result if $args->{'only_body'}
8232: || $env{'request.state'} eq 'construct';
8233:
8234: #Breadcrumbs
8235: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
8236: &Apache::lonhtmlcommon::clear_breadcrumbs();
8237: #if any br links exists, add them to the breadcrumbs
8238: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
8239: foreach my $crumb (@{$args->{'bread_crumbs'}}){
8240: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
8241: }
8242: }
8243: # if @advtools array contains items add then to the breadcrumbs
8244: if (@advtools > 0) {
8245: &Apache::lonmenu::advtools_crumbs(@advtools);
8246: }
8247: my $menulink;
8248: # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
8249: if (exists($args->{'bread_crumbs_nomenu'})) {
8250: $menulink = 0;
8251: } else {
8252: undef($menulink);
8253: }
8254: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
8255: if(exists($args->{'bread_crumbs_component'})){
8256: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
8257: }else{
8258: $result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
8259: }
8260: } elsif (($env{'environment.remote'} eq 'on') &&
8261: ($env{'form.inhibitmenu'} ne 'yes') &&
8262: ($env{'request.noversionuri'} =~ m{^/res/}) &&
8263: ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
8264: $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
8265: }
8266: return $result;
8267: }
8268:
8269: sub end_page {
8270: my ($args) = @_;
8271: $env{'internal.end_page'}++;
8272: my $result;
8273: if ($args->{'discussion'}) {
8274: my ($target,$parser);
8275: if (ref($args->{'discussion'})) {
8276: ($target,$parser) =($args->{'discussion'}{'target'},
8277: $args->{'discussion'}{'parser'});
8278: }
8279: $result .= &Apache::lonxml::xmlend($target,$parser);
8280: }
8281: if ($args->{'frameset'}) {
8282: $result .= '</frameset>';
8283: } else {
8284: $result .= &endbodytag($args);
8285: }
8286: unless ($args->{'notbody'}) {
8287: $result .= "\n</html>";
8288: }
8289:
8290: if ($args->{'js_ready'}) {
8291: $result = &js_ready($result);
8292: }
8293:
8294: if ($args->{'html_encode'}) {
8295: $result = &html_encode($result);
8296: }
8297:
8298: return $result;
8299: }
8300:
8301: sub wishlist_window {
8302: return(<<'ENDWISHLIST');
8303: <script type="text/javascript">
8304: // <![CDATA[
8305: // <!-- BEGIN LON-CAPA Internal
8306: function set_wishlistlink(title, path) {
8307: if (!title) {
8308: title = document.title;
8309: title = title.replace(/^LON-CAPA /,'');
8310: }
8311: title = encodeURIComponent(title);
8312: title = title.replace("'","\\\'");
8313: if (!path) {
8314: path = location.pathname;
8315: }
8316: path = encodeURIComponent(path);
8317: path = path.replace("'","\\\'");
8318: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
8319: 'wishlistNewLink','width=560,height=350,scrollbars=0');
8320: }
8321: // END LON-CAPA Internal -->
8322: // ]]>
8323: </script>
8324: ENDWISHLIST
8325: }
8326:
8327: sub modal_window {
8328: return(<<'ENDMODAL');
8329: <script type="text/javascript">
8330: // <![CDATA[
8331: // <!-- BEGIN LON-CAPA Internal
8332: var modalWindow = {
8333: parent:"body",
8334: windowId:null,
8335: content:null,
8336: width:null,
8337: height:null,
8338: close:function()
8339: {
8340: $(".LCmodal-window").remove();
8341: $(".LCmodal-overlay").remove();
8342: },
8343: open:function()
8344: {
8345: var modal = "";
8346: modal += "<div class=\"LCmodal-overlay\"></div>";
8347: 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;\">";
8348: modal += this.content;
8349: modal += "</div>";
8350:
8351: $(this.parent).append(modal);
8352:
8353: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
8354: $(".LCclose-window").click(function(){modalWindow.close();});
8355: $(".LCmodal-overlay").click(function(){modalWindow.close();});
8356: }
8357: };
8358: var openMyModal = function(source,width,height,scrolling,transparency,style)
8359: {
8360: source = source.replace(/'/g,"'");
8361: modalWindow.windowId = "myModal";
8362: modalWindow.width = width;
8363: modalWindow.height = height;
8364: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
8365: modalWindow.open();
8366: };
8367: // END LON-CAPA Internal -->
8368: // ]]>
8369: </script>
8370: ENDMODAL
8371: }
8372:
8373: sub modal_link {
8374: my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
8375: unless ($width) { $width=480; }
8376: unless ($height) { $height=400; }
8377: unless ($scrolling) { $scrolling='yes'; }
8378: unless ($transparency) { $transparency='true'; }
8379:
8380: my $target_attr;
8381: if (defined($target)) {
8382: $target_attr = 'target="'.$target.'"';
8383: }
8384: return <<"ENDLINK";
8385: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
8386: $linktext</a>
8387: ENDLINK
8388: }
8389:
8390: sub modal_adhoc_script {
8391: my ($funcname,$width,$height,$content)=@_;
8392: return (<<ENDADHOC);
8393: <script type="text/javascript">
8394: // <![CDATA[
8395: var $funcname = function()
8396: {
8397: modalWindow.windowId = "myModal";
8398: modalWindow.width = $width;
8399: modalWindow.height = $height;
8400: modalWindow.content = '$content';
8401: modalWindow.open();
8402: };
8403: // ]]>
8404: </script>
8405: ENDADHOC
8406: }
8407:
8408: sub modal_adhoc_inner {
8409: my ($funcname,$width,$height,$content)=@_;
8410: my $innerwidth=$width-20;
8411: $content=&js_ready(
8412: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
8413: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
8414: $content.
8415: &end_scrollbox().
8416: &end_page()
8417: );
8418: return &modal_adhoc_script($funcname,$width,$height,$content);
8419: }
8420:
8421: sub modal_adhoc_window {
8422: my ($funcname,$width,$height,$content,$linktext)=@_;
8423: return &modal_adhoc_inner($funcname,$width,$height,$content).
8424: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
8425: }
8426:
8427: sub modal_adhoc_launch {
8428: my ($funcname,$width,$height,$content)=@_;
8429: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
8430: <script type="text/javascript">
8431: // <![CDATA[
8432: $funcname();
8433: // ]]>
8434: </script>
8435: ENDLAUNCH
8436: }
8437:
8438: sub modal_adhoc_close {
8439: return (<<ENDCLOSE);
8440: <script type="text/javascript">
8441: // <![CDATA[
8442: modalWindow.close();
8443: // ]]>
8444: </script>
8445: ENDCLOSE
8446: }
8447:
8448: sub togglebox_script {
8449: return(<<ENDTOGGLE);
8450: <script type="text/javascript">
8451: // <![CDATA[
8452: function LCtoggleDisplay(id,hidetext,showtext) {
8453: link = document.getElementById(id + "link").childNodes[0];
8454: with (document.getElementById(id).style) {
8455: if (display == "none" ) {
8456: display = "inline";
8457: link.nodeValue = hidetext;
8458: } else {
8459: display = "none";
8460: link.nodeValue = showtext;
8461: }
8462: }
8463: }
8464: // ]]>
8465: </script>
8466: ENDTOGGLE
8467: }
8468:
8469: sub start_togglebox {
8470: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
8471: unless ($heading) { $heading=''; } else { $heading.=' '; }
8472: unless ($showtext) { $showtext=&mt('show'); }
8473: unless ($hidetext) { $hidetext=&mt('hide'); }
8474: unless ($headerbg) { $headerbg='#FFFFFF'; }
8475: return &start_data_table().
8476: &start_data_table_header_row().
8477: '<td bgcolor="'.$headerbg.'">'.$heading.
8478: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
8479: $showtext.'\')">'.$showtext.'</a>]</td>'.
8480: &end_data_table_header_row().
8481: '<tr id="'.$id.'" style="display:none""><td>';
8482: }
8483:
8484: sub end_togglebox {
8485: return '</td></tr>'.&end_data_table();
8486: }
8487:
8488: sub LCprogressbar_script {
8489: my ($id,$number_to_do)=@_;
8490: if ($number_to_do) {
8491: return(<<ENDPROGRESS);
8492: <script type="text/javascript">
8493: // <![CDATA[
8494: \$('#progressbar$id').progressbar({
8495: value: 0,
8496: change: function(event, ui) {
8497: var newVal = \$(this).progressbar('option', 'value');
8498: \$('.pblabel', this).text(LCprogressTxt);
8499: }
8500: });
8501: // ]]>
8502: </script>
8503: ENDPROGRESS
8504: } else {
8505: return(<<ENDPROGRESS);
8506: <script type="text/javascript">
8507: // <![CDATA[
8508: \$('#progressbar$id').progressbar({
8509: value: false,
8510: create: function(event, ui) {
8511: \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
8512: \$('.ui-progressbar-overlay', this).css({'margin':'0'});
8513: }
8514: });
8515: // ]]>
8516: </script>
8517: ENDPROGRESS
8518: }
8519: }
8520:
8521: sub LCprogressbarUpdate_script {
8522: return(<<ENDPROGRESSUPDATE);
8523: <style type="text/css">
8524: .ui-progressbar { position:relative; }
8525: .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%; }
8526: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
8527: </style>
8528: <script type="text/javascript">
8529: // <![CDATA[
8530: var LCprogressTxt='---';
8531:
8532: function LCupdateProgress(percent,progresstext,id,maxnum) {
8533: LCprogressTxt=progresstext;
8534: if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
8535: \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
8536: } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
8537: \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
8538: } else {
8539: \$('#progressbar'+id).progressbar('value',percent);
8540: }
8541: }
8542: // ]]>
8543: </script>
8544: ENDPROGRESSUPDATE
8545: }
8546:
8547: my $LClastpercent;
8548: my $LCidcnt;
8549: my $LCcurrentid;
8550:
8551: sub LCprogressbar {
8552: my ($r,$number_to_do,$preamble)=@_;
8553: $LClastpercent=0;
8554: $LCidcnt++;
8555: $LCcurrentid=$$.'_'.$LCidcnt;
8556: my ($starting,$content);
8557: if ($number_to_do) {
8558: $starting=&mt('Starting');
8559: $content=(<<ENDPROGBAR);
8560: $preamble
8561: <div id="progressbar$LCcurrentid">
8562: <span class="pblabel">$starting</span>
8563: </div>
8564: ENDPROGBAR
8565: } else {
8566: $starting=&mt('Loading...');
8567: $LClastpercent='false';
8568: $content=(<<ENDPROGBAR);
8569: $preamble
8570: <div id="progressbar$LCcurrentid">
8571: <div class="progress-label">$starting</div>
8572: </div>
8573: ENDPROGBAR
8574: }
8575: &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
8576: }
8577:
8578: sub LCprogressbarUpdate {
8579: my ($r,$val,$text,$number_to_do)=@_;
8580: if ($number_to_do) {
8581: unless ($val) {
8582: if ($LClastpercent) {
8583: $val=$LClastpercent;
8584: } else {
8585: $val=0;
8586: }
8587: }
8588: if ($val<0) { $val=0; }
8589: if ($val>100) { $val=0; }
8590: $LClastpercent=$val;
8591: unless ($text) { $text=$val.'%'; }
8592: } else {
8593: $val = 'false';
8594: }
8595: $text=&js_ready($text);
8596: &r_print($r,<<ENDUPDATE);
8597: <script type="text/javascript">
8598: // <![CDATA[
8599: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
8600: // ]]>
8601: </script>
8602: ENDUPDATE
8603: }
8604:
8605: sub LCprogressbarClose {
8606: my ($r)=@_;
8607: $LClastpercent=0;
8608: &r_print($r,<<ENDCLOSE);
8609: <script type="text/javascript">
8610: // <![CDATA[
8611: \$("#progressbar$LCcurrentid").hide('slow');
8612: // ]]>
8613: </script>
8614: ENDCLOSE
8615: }
8616:
8617: sub r_print {
8618: my ($r,$to_print)=@_;
8619: if ($r) {
8620: $r->print($to_print);
8621: $r->rflush();
8622: } else {
8623: print($to_print);
8624: }
8625: }
8626:
8627: sub html_encode {
8628: my ($result) = @_;
8629:
8630: $result = &HTML::Entities::encode($result,'<>&"');
8631:
8632: return $result;
8633: }
8634:
8635: sub js_ready {
8636: my ($result) = @_;
8637:
8638: $result =~ s/[\n\r]/ /xmsg;
8639: $result =~ s/\\/\\\\/xmsg;
8640: $result =~ s/'/\\'/xmsg;
8641: $result =~ s{</}{<\\/}xmsg;
8642:
8643: return $result;
8644: }
8645:
8646: sub validate_page {
8647: if ( exists($env{'internal.start_page'})
8648: && $env{'internal.start_page'} > 1) {
8649: &Apache::lonnet::logthis('start_page called multiple times '.
8650: $env{'internal.start_page'}.' '.
8651: $ENV{'request.filename'});
8652: }
8653: if ( exists($env{'internal.end_page'})
8654: && $env{'internal.end_page'} > 1) {
8655: &Apache::lonnet::logthis('end_page called multiple times '.
8656: $env{'internal.end_page'}.' '.
8657: $env{'request.filename'});
8658: }
8659: if ( exists($env{'internal.start_page'})
8660: && ! exists($env{'internal.end_page'})) {
8661: &Apache::lonnet::logthis('start_page called without end_page '.
8662: $env{'request.filename'});
8663: }
8664: if ( ! exists($env{'internal.start_page'})
8665: && exists($env{'internal.end_page'})) {
8666: &Apache::lonnet::logthis('end_page called without start_page'.
8667: $env{'request.filename'});
8668: }
8669: }
8670:
8671:
8672: sub start_scrollbox {
8673: my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
8674: unless ($outerwidth) { $outerwidth='520px'; }
8675: unless ($width) { $width='500px'; }
8676: unless ($height) { $height='200px'; }
8677: my ($table_id,$div_id,$tdcol);
8678: if ($id ne '') {
8679: $table_id = ' id="table_'.$id.'"';
8680: $div_id = ' id="div_'.$id.'"';
8681: }
8682: if ($bgcolor ne '') {
8683: $tdcol = "background-color: $bgcolor;";
8684: }
8685: my $nicescroll_js;
8686: if ($env{'browser.mobile'}) {
8687: $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
8688: }
8689: return <<"END";
8690: $nicescroll_js
8691:
8692: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
8693: <div style="overflow:auto; width:$width; height:$height;"$div_id>
8694: END
8695: }
8696:
8697: sub end_scrollbox {
8698: return '</div></td></tr></table>';
8699: }
8700:
8701: sub nicescroll_javascript {
8702: my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
8703: my %options;
8704: if (ref($cursor) eq 'HASH') {
8705: %options = %{$cursor};
8706: }
8707: unless ($options{'railalign'} =~ /^left|right$/) {
8708: $options{'railalign'} = 'left';
8709: }
8710: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
8711: my $function = &get_users_function();
8712: $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
8713: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
8714: $options{'cursorcolor'} = '#00F';
8715: }
8716: }
8717: if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
8718: unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
8719: $options{'cursoropacity'}='1.0';
8720: }
8721: } else {
8722: $options{'cursoropacity'}='1.0';
8723: }
8724: if ($options{'cursorfixedheight'} eq 'none') {
8725: delete($options{'cursorfixedheight'});
8726: } else {
8727: unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
8728: }
8729: unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
8730: delete($options{'railoffset'});
8731: }
8732: my @niceoptions;
8733: while (my($key,$value) = each(%options)) {
8734: if ($value =~ /^\{.+\}$/) {
8735: push(@niceoptions,$key.':'.$value);
8736: } else {
8737: push(@niceoptions,$key.':"'.$value.'"');
8738: }
8739: }
8740: my $nicescroll_js = '
8741: $(document).ready(
8742: function() {
8743: $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
8744: }
8745: );
8746: ';
8747: if ($framecheck) {
8748: $nicescroll_js .= '
8749: function expand_div(caller) {
8750: if (top === self) {
8751: document.getElementById("'.$id.'").style.width = "auto";
8752: document.getElementById("'.$id.'").style.height = "auto";
8753: } else {
8754: try {
8755: if (parent.frames) {
8756: if (parent.frames.length > 1) {
8757: var framesrc = parent.frames[1].location.href;
8758: var currsrc = framesrc.replace(/\#.*$/,"");
8759: if ((caller == "search") || (currsrc == "'.$location.'")) {
8760: document.getElementById("'.$id.'").style.width = "auto";
8761: document.getElementById("'.$id.'").style.height = "auto";
8762: }
8763: }
8764: }
8765: } catch (e) {
8766: return;
8767: }
8768: }
8769: return;
8770: }
8771: ';
8772: }
8773: if ($needjsready) {
8774: $nicescroll_js = '
8775: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
8776: } else {
8777: $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
8778: }
8779: return $nicescroll_js;
8780: }
8781:
8782: sub simple_error_page {
8783: my ($r,$title,$msg,$args) = @_;
8784: if (ref($args) eq 'HASH') {
8785: if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
8786: } else {
8787: $msg = &mt($msg);
8788: }
8789:
8790: my $page =
8791: &Apache::loncommon::start_page($title).
8792: '<p class="LC_error">'.$msg.'</p>'.
8793: &Apache::loncommon::end_page();
8794: if (ref($r)) {
8795: $r->print($page);
8796: return;
8797: }
8798: return $page;
8799: }
8800:
8801: {
8802: my @row_count;
8803:
8804: sub start_data_table_count {
8805: unshift(@row_count, 0);
8806: return;
8807: }
8808:
8809: sub end_data_table_count {
8810: shift(@row_count);
8811: return;
8812: }
8813:
8814: sub start_data_table {
8815: my ($add_class,$id) = @_;
8816: my $css_class = (join(' ','LC_data_table',$add_class));
8817: my $table_id;
8818: if (defined($id)) {
8819: $table_id = ' id="'.$id.'"';
8820: }
8821: &start_data_table_count();
8822: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
8823: }
8824:
8825: sub end_data_table {
8826: &end_data_table_count();
8827: return '</table>'."\n";;
8828: }
8829:
8830: sub start_data_table_row {
8831: my ($add_class, $id) = @_;
8832: $row_count[0]++;
8833: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
8834: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
8835: $id = (' id="'.$id.'"') unless ($id eq '');
8836: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
8837: }
8838:
8839: sub continue_data_table_row {
8840: my ($add_class, $id) = @_;
8841: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
8842: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
8843: $id = (' id="'.$id.'"') unless ($id eq '');
8844: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
8845: }
8846:
8847: sub end_data_table_row {
8848: return '</tr>'."\n";;
8849: }
8850:
8851: sub start_data_table_empty_row {
8852: # $row_count[0]++;
8853: return '<tr class="LC_empty_row" >'."\n";;
8854: }
8855:
8856: sub end_data_table_empty_row {
8857: return '</tr>'."\n";;
8858: }
8859:
8860: sub start_data_table_header_row {
8861: return '<tr class="LC_header_row">'."\n";;
8862: }
8863:
8864: sub end_data_table_header_row {
8865: return '</tr>'."\n";;
8866: }
8867:
8868: sub data_table_caption {
8869: my $caption = shift;
8870: return "<caption class=\"LC_caption\">$caption</caption>";
8871: }
8872: }
8873:
8874: =pod
8875:
8876: =item * &inhibit_menu_check($arg)
8877:
8878: Checks for a inhibitmenu state and generates output to preserve it
8879:
8880: Inputs: $arg - can be any of
8881: - undef - in which case the return value is a string
8882: to add into arguments list of a uri
8883: - 'input' - in which case the return value is a HTML
8884: <form> <input> field of type hidden to
8885: preserve the value
8886: - a url - in which case the return value is the url with
8887: the neccesary cgi args added to preserve the
8888: inhibitmenu state
8889: - a ref to a url - no return value, but the string is
8890: updated to include the neccessary cgi
8891: args to preserve the inhibitmenu state
8892:
8893: =cut
8894:
8895: sub inhibit_menu_check {
8896: my ($arg) = @_;
8897: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
8898: if ($arg eq 'input') {
8899: if ($env{'form.inhibitmenu'}) {
8900: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
8901: } else {
8902: return
8903: }
8904: }
8905: if ($env{'form.inhibitmenu'}) {
8906: if (ref($arg)) {
8907: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
8908: } elsif ($arg eq '') {
8909: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
8910: } else {
8911: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
8912: }
8913: }
8914: if (!ref($arg)) {
8915: return $arg;
8916: }
8917: }
8918:
8919: ###############################################
8920:
8921: =pod
8922:
8923: =back
8924:
8925: =head1 User Information Routines
8926:
8927: =over 4
8928:
8929: =item * &get_users_function()
8930:
8931: Used by &bodytag to determine the current users primary role.
8932: Returns either 'student','coordinator','admin', or 'author'.
8933:
8934: =cut
8935:
8936: ###############################################
8937: sub get_users_function {
8938: my $function = 'norole';
8939: if ($env{'request.role'}=~/^(st)/) {
8940: $function='student';
8941: }
8942: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
8943: $function='coordinator';
8944: }
8945: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
8946: $function='admin';
8947: }
8948: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
8949: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
8950: $function='author';
8951: }
8952: return $function;
8953: }
8954:
8955: ###############################################
8956:
8957: =pod
8958:
8959: =item * &show_course()
8960:
8961: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
8962: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
8963:
8964: Inputs:
8965: None
8966:
8967: Outputs:
8968: Scalar: 1 if 'Course' to be used, 0 otherwise.
8969:
8970: =cut
8971:
8972: ###############################################
8973: sub show_course {
8974: my $course = !$env{'user.adv'};
8975: if (!$env{'user.adv'}) {
8976: foreach my $env (keys(%env)) {
8977: next if ($env !~ m/^user\.priv\./);
8978: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
8979: $course = 0;
8980: last;
8981: }
8982: }
8983: }
8984: return $course;
8985: }
8986:
8987: ###############################################
8988:
8989: =pod
8990:
8991: =item * &check_user_status()
8992:
8993: Determines current status of supplied role for a
8994: specific user. Roles can be active, previous or future.
8995:
8996: Inputs:
8997: user's domain, user's username, course's domain,
8998: course's number, optional section ID.
8999:
9000: Outputs:
9001: role status: active, previous or future.
9002:
9003: =cut
9004:
9005: sub check_user_status {
9006: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
9007: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
9008: my @uroles = keys(%userinfo);
9009: my $srchstr;
9010: my $active_chk = 'none';
9011: my $now = time;
9012: if (@uroles > 0) {
9013: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
9014: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
9015: } else {
9016: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
9017: }
9018: if (grep/^\Q$srchstr\E$/,@uroles) {
9019: my $role_end = 0;
9020: my $role_start = 0;
9021: $active_chk = 'active';
9022: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
9023: $role_end = $1;
9024: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
9025: $role_start = $1;
9026: }
9027: }
9028: if ($role_start > 0) {
9029: if ($now < $role_start) {
9030: $active_chk = 'future';
9031: }
9032: }
9033: if ($role_end > 0) {
9034: if ($now > $role_end) {
9035: $active_chk = 'previous';
9036: }
9037: }
9038: }
9039: }
9040: return $active_chk;
9041: }
9042:
9043: ###############################################
9044:
9045: =pod
9046:
9047: =item * &get_sections()
9048:
9049: Determines all the sections for a course including
9050: sections with students and sections containing other roles.
9051: Incoming parameters:
9052:
9053: 1. domain
9054: 2. course number
9055: 3. reference to array containing roles for which sections should
9056: be gathered (optional).
9057: 4. reference to array containing status types for which sections
9058: should be gathered (optional).
9059:
9060: If the third argument is undefined, sections are gathered for any role.
9061: If the fourth argument is undefined, sections are gathered for any status.
9062: Permissible values are 'active' or 'future' or 'previous'.
9063:
9064: Returns section hash (keys are section IDs, values are
9065: number of users in each section), subject to the
9066: optional roles filter, optional status filter
9067:
9068: =cut
9069:
9070: ###############################################
9071: sub get_sections {
9072: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
9073: if (!defined($cdom) || !defined($cnum)) {
9074: my $cid = $env{'request.course.id'};
9075:
9076: return if (!defined($cid));
9077:
9078: $cdom = $env{'course.'.$cid.'.domain'};
9079: $cnum = $env{'course.'.$cid.'.num'};
9080: }
9081:
9082: my %sectioncount;
9083: my $now = time;
9084:
9085: my $check_students = 1;
9086: my $only_students = 0;
9087: if (ref($possible_roles) eq 'ARRAY') {
9088: if (grep(/^st$/,@{$possible_roles})) {
9089: if (@{$possible_roles} == 1) {
9090: $only_students = 1;
9091: }
9092: } else {
9093: $check_students = 0;
9094: }
9095: }
9096:
9097: if ($check_students) {
9098: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
9099: my $sec_index = &Apache::loncoursedata::CL_SECTION();
9100: my $status_index = &Apache::loncoursedata::CL_STATUS();
9101: my $start_index = &Apache::loncoursedata::CL_START();
9102: my $end_index = &Apache::loncoursedata::CL_END();
9103: my $status;
9104: while (my ($student,$data) = each(%$classlist)) {
9105: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
9106: $data->[$status_index],
9107: $data->[$start_index],
9108: $data->[$end_index]);
9109: if ($stu_status eq 'Active') {
9110: $status = 'active';
9111: } elsif ($end < $now) {
9112: $status = 'previous';
9113: } elsif ($start > $now) {
9114: $status = 'future';
9115: }
9116: if ($section ne '-1' && $section !~ /^\s*$/) {
9117: if ((!defined($possible_status)) || (($status ne '') &&
9118: (grep/^\Q$status\E$/,@{$possible_status}))) {
9119: $sectioncount{$section}++;
9120: }
9121: }
9122: }
9123: }
9124: if ($only_students) {
9125: return %sectioncount;
9126: }
9127: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9128: foreach my $user (sort(keys(%courseroles))) {
9129: if ($user !~ /^(\w{2})/) { next; }
9130: my ($role) = ($user =~ /^(\w{2})/);
9131: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
9132: my ($section,$status);
9133: if ($role eq 'cr' &&
9134: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
9135: $section=$1;
9136: }
9137: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
9138: if (!defined($section) || $section eq '-1') { next; }
9139: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
9140: if ($end == -1 && $start == -1) {
9141: next; #deleted role
9142: }
9143: if (!defined($possible_status)) {
9144: $sectioncount{$section}++;
9145: } else {
9146: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
9147: $status = 'active';
9148: } elsif ($end < $now) {
9149: $status = 'future';
9150: } elsif ($start > $now) {
9151: $status = 'previous';
9152: }
9153: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
9154: $sectioncount{$section}++;
9155: }
9156: }
9157: }
9158: return %sectioncount;
9159: }
9160:
9161: ###############################################
9162:
9163: =pod
9164:
9165: =item * &get_course_users()
9166:
9167: Retrieves usernames:domains for users in the specified course
9168: with specific role(s), and access status.
9169:
9170: Incoming parameters:
9171: 1. course domain
9172: 2. course number
9173: 3. access status: users must have - either active,
9174: previous, future, or all.
9175: 4. reference to array of permissible roles
9176: 5. reference to array of section restrictions (optional)
9177: 6. reference to results object (hash of hashes).
9178: 7. reference to optional userdata hash
9179: 8. reference to optional statushash
9180: 9. flag if privileged users (except those set to unhide in
9181: course settings) should be excluded
9182: Keys of top level results hash are roles.
9183: Keys of inner hashes are username:domain, with
9184: values set to access type.
9185: Optional userdata hash returns an array with arguments in the
9186: same order as loncoursedata::get_classlist() for student data.
9187:
9188: Optional statushash returns
9189:
9190: Entries for end, start, section and status are blank because
9191: of the possibility of multiple values for non-student roles.
9192:
9193: =cut
9194:
9195: ###############################################
9196:
9197: sub get_course_users {
9198: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
9199: my %idx = ();
9200: my %seclists;
9201:
9202: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
9203: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
9204: $idx{end} = &Apache::loncoursedata::CL_END();
9205: $idx{start} = &Apache::loncoursedata::CL_START();
9206: $idx{id} = &Apache::loncoursedata::CL_ID();
9207: $idx{section} = &Apache::loncoursedata::CL_SECTION();
9208: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
9209: $idx{status} = &Apache::loncoursedata::CL_STATUS();
9210:
9211: if (grep(/^st$/,@{$roles})) {
9212: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
9213: my $now = time;
9214: foreach my $student (keys(%{$classlist})) {
9215: my $match = 0;
9216: my $secmatch = 0;
9217: my $section = $$classlist{$student}[$idx{section}];
9218: my $status = $$classlist{$student}[$idx{status}];
9219: if ($section eq '') {
9220: $section = 'none';
9221: }
9222: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
9223: if (grep(/^all$/,@{$sections})) {
9224: $secmatch = 1;
9225: } elsif ($$classlist{$student}[$idx{section}] eq '') {
9226: if (grep(/^none$/,@{$sections})) {
9227: $secmatch = 1;
9228: }
9229: } else {
9230: if (grep(/^\Q$section\E$/,@{$sections})) {
9231: $secmatch = 1;
9232: }
9233: }
9234: if (!$secmatch) {
9235: next;
9236: }
9237: }
9238: if (defined($$types{'active'})) {
9239: if ($$classlist{$student}[$idx{status}] eq 'Active') {
9240: push(@{$$users{st}{$student}},'active');
9241: $match = 1;
9242: }
9243: }
9244: if (defined($$types{'previous'})) {
9245: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
9246: push(@{$$users{st}{$student}},'previous');
9247: $match = 1;
9248: }
9249: }
9250: if (defined($$types{'future'})) {
9251: if ($$classlist{$student}[$idx{status}] eq 'Future') {
9252: push(@{$$users{st}{$student}},'future');
9253: $match = 1;
9254: }
9255: }
9256: if ($match) {
9257: push(@{$seclists{$student}},$section);
9258: if (ref($userdata) eq 'HASH') {
9259: $$userdata{$student} = $$classlist{$student};
9260: }
9261: if (ref($statushash) eq 'HASH') {
9262: $statushash->{$student}{'st'}{$section} = $status;
9263: }
9264: }
9265: }
9266: }
9267: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
9268: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9269: my $now = time;
9270: my %displaystatus = ( previous => 'Expired',
9271: active => 'Active',
9272: future => 'Future',
9273: );
9274: my (%nothide,@possdoms);
9275: if ($hidepriv) {
9276: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
9277: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
9278: if ($user !~ /:/) {
9279: $nothide{join(':',split(/[\@]/,$user))}=1;
9280: } else {
9281: $nothide{$user} = 1;
9282: }
9283: }
9284: my @possdoms = ($cdom);
9285: if ($coursehash{'checkforpriv'}) {
9286: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
9287: }
9288: }
9289: foreach my $person (sort(keys(%coursepersonnel))) {
9290: my $match = 0;
9291: my $secmatch = 0;
9292: my $status;
9293: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
9294: $user =~ s/:$//;
9295: my ($end,$start) = split(/:/,$coursepersonnel{$person});
9296: if ($end == -1 || $start == -1) {
9297: next;
9298: }
9299: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
9300: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
9301: my ($uname,$udom) = split(/:/,$user);
9302: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
9303: if (grep(/^all$/,@{$sections})) {
9304: $secmatch = 1;
9305: } elsif ($usec eq '') {
9306: if (grep(/^none$/,@{$sections})) {
9307: $secmatch = 1;
9308: }
9309: } else {
9310: if (grep(/^\Q$usec\E$/,@{$sections})) {
9311: $secmatch = 1;
9312: }
9313: }
9314: if (!$secmatch) {
9315: next;
9316: }
9317: }
9318: if ($usec eq '') {
9319: $usec = 'none';
9320: }
9321: if ($uname ne '' && $udom ne '') {
9322: if ($hidepriv) {
9323: if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
9324: (!$nothide{$uname.':'.$udom})) {
9325: next;
9326: }
9327: }
9328: if ($end > 0 && $end < $now) {
9329: $status = 'previous';
9330: } elsif ($start > $now) {
9331: $status = 'future';
9332: } else {
9333: $status = 'active';
9334: }
9335: foreach my $type (keys(%{$types})) {
9336: if ($status eq $type) {
9337: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
9338: push(@{$$users{$role}{$user}},$type);
9339: }
9340: $match = 1;
9341: }
9342: }
9343: if (($match) && (ref($userdata) eq 'HASH')) {
9344: if (!exists($$userdata{$uname.':'.$udom})) {
9345: &get_user_info($udom,$uname,\%idx,$userdata);
9346: }
9347: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
9348: push(@{$seclists{$uname.':'.$udom}},$usec);
9349: }
9350: if (ref($statushash) eq 'HASH') {
9351: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
9352: }
9353: }
9354: }
9355: }
9356: }
9357: if (grep(/^ow$/,@{$roles})) {
9358: if ((defined($cdom)) && (defined($cnum))) {
9359: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
9360: if ( defined($csettings{'internal.courseowner'}) ) {
9361: my $owner = $csettings{'internal.courseowner'};
9362: next if ($owner eq '');
9363: my ($ownername,$ownerdom);
9364: if ($owner =~ /^([^:]+):([^:]+)$/) {
9365: $ownername = $1;
9366: $ownerdom = $2;
9367: } else {
9368: $ownername = $owner;
9369: $ownerdom = $cdom;
9370: $owner = $ownername.':'.$ownerdom;
9371: }
9372: @{$$users{'ow'}{$owner}} = 'any';
9373: if (defined($userdata) &&
9374: !exists($$userdata{$owner})) {
9375: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
9376: if (!grep(/^none$/,@{$seclists{$owner}})) {
9377: push(@{$seclists{$owner}},'none');
9378: }
9379: if (ref($statushash) eq 'HASH') {
9380: $statushash->{$owner}{'ow'}{'none'} = 'Any';
9381: }
9382: }
9383: }
9384: }
9385: }
9386: foreach my $user (keys(%seclists)) {
9387: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
9388: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
9389: }
9390: }
9391: return;
9392: }
9393:
9394: sub get_user_info {
9395: my ($udom,$uname,$idx,$userdata) = @_;
9396: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
9397: &plainname($uname,$udom,'lastname');
9398: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
9399: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
9400: my %idhash = &Apache::lonnet::idrget($udom,($uname));
9401: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
9402: return;
9403: }
9404:
9405: ###############################################
9406:
9407: =pod
9408:
9409: =item * &get_user_quota()
9410:
9411: Retrieves quota assigned for storage of user files.
9412: Default is to report quota for portfolio files.
9413:
9414: Incoming parameters:
9415: 1. user's username
9416: 2. user's domain
9417: 3. quota name - portfolio, author, or course
9418: (if no quota name provided, defaults to portfolio).
9419: 4. crstype - official, unofficial, textbook or community, if quota name is
9420: course
9421:
9422: Returns:
9423: 1. Disk quota (in MB) assigned to student.
9424: 2. (Optional) Type of setting: custom or default
9425: (individually assigned or default for user's
9426: institutional status).
9427: 3. (Optional) - User's institutional status (e.g., faculty, staff
9428: or student - types as defined in localenroll::inst_usertypes
9429: for user's domain, which determines default quota for user.
9430: 4. (Optional) - Default quota which would apply to the user.
9431:
9432: If a value has been stored in the user's environment,
9433: it will return that, otherwise it returns the maximal default
9434: defined for the user's institutional status(es) in the domain.
9435:
9436: =cut
9437:
9438: ###############################################
9439:
9440:
9441: sub get_user_quota {
9442: my ($uname,$udom,$quotaname,$crstype) = @_;
9443: my ($quota,$quotatype,$settingstatus,$defquota);
9444: if (!defined($udom)) {
9445: $udom = $env{'user.domain'};
9446: }
9447: if (!defined($uname)) {
9448: $uname = $env{'user.name'};
9449: }
9450: if (($udom eq '' || $uname eq '') ||
9451: ($udom eq 'public') && ($uname eq 'public')) {
9452: $quota = 0;
9453: $quotatype = 'default';
9454: $defquota = 0;
9455: } else {
9456: my $inststatus;
9457: if ($quotaname eq 'course') {
9458: if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
9459: ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
9460: $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
9461: } else {
9462: my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
9463: $quota = $cenv{'internal.uploadquota'};
9464: }
9465: } else {
9466: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
9467: if ($quotaname eq 'author') {
9468: $quota = $env{'environment.authorquota'};
9469: } else {
9470: $quota = $env{'environment.portfolioquota'};
9471: }
9472: $inststatus = $env{'environment.inststatus'};
9473: } else {
9474: my %userenv =
9475: &Apache::lonnet::get('environment',['portfolioquota',
9476: 'authorquota','inststatus'],$udom,$uname);
9477: my ($tmp) = keys(%userenv);
9478: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9479: if ($quotaname eq 'author') {
9480: $quota = $userenv{'authorquota'};
9481: } else {
9482: $quota = $userenv{'portfolioquota'};
9483: }
9484: $inststatus = $userenv{'inststatus'};
9485: } else {
9486: undef(%userenv);
9487: }
9488: }
9489: }
9490: if ($quota eq '' || wantarray) {
9491: if ($quotaname eq 'course') {
9492: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
9493: if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
9494: ($crstype eq 'community') || ($crstype eq 'textbook')) {
9495: $defquota = $domdefs{$crstype.'quota'};
9496: }
9497: if ($defquota eq '') {
9498: $defquota = 500;
9499: }
9500: } else {
9501: ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
9502: }
9503: if ($quota eq '') {
9504: $quota = $defquota;
9505: $quotatype = 'default';
9506: } else {
9507: $quotatype = 'custom';
9508: }
9509: }
9510: }
9511: if (wantarray) {
9512: return ($quota,$quotatype,$settingstatus,$defquota);
9513: } else {
9514: return $quota;
9515: }
9516: }
9517:
9518: ###############################################
9519:
9520: =pod
9521:
9522: =item * &default_quota()
9523:
9524: Retrieves default quota assigned for storage of user portfolio files,
9525: given an (optional) user's institutional status.
9526:
9527: Incoming parameters:
9528:
9529: 1. domain
9530: 2. (Optional) institutional status(es). This is a : separated list of
9531: status types (e.g., faculty, staff, student etc.)
9532: which apply to the user for whom the default is being retrieved.
9533: If the institutional status string in undefined, the domain
9534: default quota will be returned.
9535: 3. quota name - portfolio, author, or course
9536: (if no quota name provided, defaults to portfolio).
9537:
9538: Returns:
9539:
9540: 1. Default disk quota (in MB) for user portfolios in the domain.
9541: 2. (Optional) institutional type which determined the value of the
9542: default quota.
9543:
9544: If a value has been stored in the domain's configuration db,
9545: it will return that, otherwise it returns 20 (for backwards
9546: compatibility with domains which have not set up a configuration
9547: db file; the original statically defined portfolio quota was 20 MB).
9548:
9549: If the user's status includes multiple types (e.g., staff and student),
9550: the largest default quota which applies to the user determines the
9551: default quota returned.
9552:
9553: =cut
9554:
9555: ###############################################
9556:
9557:
9558: sub default_quota {
9559: my ($udom,$inststatus,$quotaname) = @_;
9560: my ($defquota,$settingstatus);
9561: my %quotahash = &Apache::lonnet::get_dom('configuration',
9562: ['quotas'],$udom);
9563: my $key = 'defaultquota';
9564: if ($quotaname eq 'author') {
9565: $key = 'authorquota';
9566: }
9567: if (ref($quotahash{'quotas'}) eq 'HASH') {
9568: if ($inststatus ne '') {
9569: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
9570: foreach my $item (@statuses) {
9571: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
9572: if ($quotahash{'quotas'}{$key}{$item} ne '') {
9573: if ($defquota eq '') {
9574: $defquota = $quotahash{'quotas'}{$key}{$item};
9575: $settingstatus = $item;
9576: } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
9577: $defquota = $quotahash{'quotas'}{$key}{$item};
9578: $settingstatus = $item;
9579: }
9580: }
9581: } elsif ($key eq 'defaultquota') {
9582: if ($quotahash{'quotas'}{$item} ne '') {
9583: if ($defquota eq '') {
9584: $defquota = $quotahash{'quotas'}{$item};
9585: $settingstatus = $item;
9586: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
9587: $defquota = $quotahash{'quotas'}{$item};
9588: $settingstatus = $item;
9589: }
9590: }
9591: }
9592: }
9593: }
9594: if ($defquota eq '') {
9595: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
9596: $defquota = $quotahash{'quotas'}{$key}{'default'};
9597: } elsif ($key eq 'defaultquota') {
9598: $defquota = $quotahash{'quotas'}{'default'};
9599: }
9600: $settingstatus = 'default';
9601: if ($defquota eq '') {
9602: if ($quotaname eq 'author') {
9603: $defquota = 500;
9604: }
9605: }
9606: }
9607: } else {
9608: $settingstatus = 'default';
9609: if ($quotaname eq 'author') {
9610: $defquota = 500;
9611: } else {
9612: $defquota = 20;
9613: }
9614: }
9615: if (wantarray) {
9616: return ($defquota,$settingstatus);
9617: } else {
9618: return $defquota;
9619: }
9620: }
9621:
9622: ###############################################
9623:
9624: =pod
9625:
9626: =item * &excess_filesize_warning()
9627:
9628: Returns warning message if upload of file to authoring space, or copying
9629: of existing file within authoring space will cause quota for the authoring
9630: space to be exceeded.
9631:
9632: Same, if upload of a file directly to a course/community via Course Editor
9633: will cause quota for uploaded content for the course to be exceeded.
9634:
9635: Inputs: 7
9636: 1. username or coursenum
9637: 2. domain
9638: 3. context ('author' or 'course')
9639: 4. filename of file for which action is being requested
9640: 5. filesize (kB) of file
9641: 6. action being taken: copy or upload.
9642: 7. quotatype (in course context -- official, unofficial, community or textbook).
9643:
9644: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
9645: otherwise return null.
9646:
9647: =back
9648:
9649: =cut
9650:
9651: sub excess_filesize_warning {
9652: my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
9653: my $current_disk_usage = 0;
9654: my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
9655: if ($context eq 'author') {
9656: my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
9657: $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
9658: } else {
9659: foreach my $subdir ('docs','supplemental') {
9660: $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
9661: }
9662: }
9663: $disk_quota = int($disk_quota * 1000);
9664: if (($current_disk_usage + $filesize) > $disk_quota) {
9665: return '<p class="LC_warning">'.
9666: &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
9667: '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
9668: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
9669: $disk_quota,$current_disk_usage).
9670: '</p>';
9671: }
9672: return;
9673: }
9674:
9675: ###############################################
9676:
9677:
9678: sub get_secgrprole_info {
9679: my ($cdom,$cnum,$needroles,$type) = @_;
9680: my %sections_count = &get_sections($cdom,$cnum);
9681: my @sections = (sort {$a <=> $b} keys(%sections_count));
9682: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
9683: my @groups = sort(keys(%curr_groups));
9684: my $allroles = [];
9685: my $rolehash;
9686: my $accesshash = {
9687: active => 'Currently has access',
9688: future => 'Will have future access',
9689: previous => 'Previously had access',
9690: };
9691: if ($needroles) {
9692: $rolehash = {'all' => 'all'};
9693: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9694: if (&Apache::lonnet::error(%user_roles)) {
9695: undef(%user_roles);
9696: }
9697: foreach my $item (keys(%user_roles)) {
9698: my ($role)=split(/\:/,$item,2);
9699: if ($role eq 'cr') { next; }
9700: if ($role =~ /^cr/) {
9701: $$rolehash{$role} = (split('/',$role))[3];
9702: } else {
9703: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
9704: }
9705: }
9706: foreach my $key (sort(keys(%{$rolehash}))) {
9707: push(@{$allroles},$key);
9708: }
9709: push (@{$allroles},'st');
9710: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
9711: }
9712: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
9713: }
9714:
9715: sub user_picker {
9716: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
9717: my $currdom = $dom;
9718: my @alldoms = &Apache::lonnet::all_domains();
9719: if (@alldoms == 1) {
9720: my %domsrch = &Apache::lonnet::get_dom('configuration',
9721: ['directorysrch'],$alldoms[0]);
9722: my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
9723: my $showdom = $domdesc;
9724: if ($showdom eq '') {
9725: $showdom = $dom;
9726: }
9727: if (ref($domsrch{'directorysrch'}) eq 'HASH') {
9728: if ((!$domsrch{'directorysrch'}{'available'}) &&
9729: ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
9730: return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
9731: }
9732: }
9733: }
9734: my %curr_selected = (
9735: srchin => 'dom',
9736: srchby => 'lastname',
9737: );
9738: my $srchterm;
9739: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
9740: if ($srch->{'srchby'} ne '') {
9741: $curr_selected{'srchby'} = $srch->{'srchby'};
9742: }
9743: if ($srch->{'srchin'} ne '') {
9744: $curr_selected{'srchin'} = $srch->{'srchin'};
9745: }
9746: if ($srch->{'srchtype'} ne '') {
9747: $curr_selected{'srchtype'} = $srch->{'srchtype'};
9748: }
9749: if ($srch->{'srchdomain'} ne '') {
9750: $currdom = $srch->{'srchdomain'};
9751: }
9752: $srchterm = $srch->{'srchterm'};
9753: }
9754: my %html_lt=&Apache::lonlocal::texthash(
9755: 'usr' => 'Search criteria',
9756: 'doma' => 'Domain/institution to search',
9757: 'uname' => 'username',
9758: 'lastname' => 'last name',
9759: 'lastfirst' => 'last name, first name',
9760: 'crs' => 'in this course',
9761: 'dom' => 'in selected LON-CAPA domain',
9762: 'alc' => 'all LON-CAPA',
9763: 'instd' => 'in institutional directory for selected domain',
9764: 'exact' => 'is',
9765: 'contains' => 'contains',
9766: 'begins' => 'begins with',
9767: );
9768: my %js_lt=&Apache::lonlocal::texthash(
9769: 'youm' => "You must include some text to search for.",
9770: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
9771: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
9772: 'yomc' => "You must choose a domain when using an institutional directory search.",
9773: 'ymcd' => "You must choose a domain when using a domain search.",
9774: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
9775: 'whse' => "When searching by last,first you must include at least one character in the first name.",
9776: 'thfo' => "The following need to be corrected before the search can be run:",
9777: );
9778: &html_escape(\%html_lt);
9779: &js_escape(\%js_lt);
9780: my $domform;
9781: my $allow_blank = 1;
9782: if ($fixeddom) {
9783: $allow_blank = 0;
9784: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
9785: } else {
9786: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
9787: }
9788: my $srchinsel = ' <select name="srchin">';
9789:
9790: my @srchins = ('crs','dom','alc','instd');
9791:
9792: foreach my $option (@srchins) {
9793: # FIXME 'alc' option unavailable until
9794: # loncreateuser::print_user_query_page()
9795: # has been completed.
9796: next if ($option eq 'alc');
9797: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
9798: next if ($option eq 'crs' && !$env{'request.course.id'});
9799: next if (($option eq 'instd') && ($noinstd));
9800: if ($curr_selected{'srchin'} eq $option) {
9801: $srchinsel .= '
9802: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
9803: } else {
9804: $srchinsel .= '
9805: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
9806: }
9807: }
9808: $srchinsel .= "\n </select>\n";
9809:
9810: my $srchbysel = ' <select name="srchby">';
9811: foreach my $option ('lastname','lastfirst','uname') {
9812: if ($curr_selected{'srchby'} eq $option) {
9813: $srchbysel .= '
9814: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
9815: } else {
9816: $srchbysel .= '
9817: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
9818: }
9819: }
9820: $srchbysel .= "\n </select>\n";
9821:
9822: my $srchtypesel = ' <select name="srchtype">';
9823: foreach my $option ('begins','contains','exact') {
9824: if ($curr_selected{'srchtype'} eq $option) {
9825: $srchtypesel .= '
9826: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
9827: } else {
9828: $srchtypesel .= '
9829: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
9830: }
9831: }
9832: $srchtypesel .= "\n </select>\n";
9833:
9834: my ($newuserscript,$new_user_create);
9835: my $context_dom = $env{'request.role.domain'};
9836: if ($context eq 'requestcrs') {
9837: if ($env{'form.coursedom'} ne '') {
9838: $context_dom = $env{'form.coursedom'};
9839: }
9840: }
9841: if ($forcenewuser) {
9842: if (ref($srch) eq 'HASH') {
9843: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
9844: if ($cancreate) {
9845: $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>';
9846: } else {
9847: my $helplink = 'javascript:helpMenu('."'display'".')';
9848: my %usertypetext = (
9849: official => 'institutional',
9850: unofficial => 'non-institutional',
9851: );
9852: $new_user_create = '<p class="LC_warning">'
9853: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
9854: .' '
9855: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
9856: ,'<a href="'.$helplink.'">','</a>')
9857: .'</p><br />';
9858: }
9859: }
9860: }
9861:
9862: $newuserscript = <<"ENDSCRIPT";
9863:
9864: function setSearch(createnew,callingForm) {
9865: if (createnew == 1) {
9866: for (var i=0; i<callingForm.srchby.length; i++) {
9867: if (callingForm.srchby.options[i].value == 'uname') {
9868: callingForm.srchby.selectedIndex = i;
9869: }
9870: }
9871: for (var i=0; i<callingForm.srchin.length; i++) {
9872: if ( callingForm.srchin.options[i].value == 'dom') {
9873: callingForm.srchin.selectedIndex = i;
9874: }
9875: }
9876: for (var i=0; i<callingForm.srchtype.length; i++) {
9877: if (callingForm.srchtype.options[i].value == 'exact') {
9878: callingForm.srchtype.selectedIndex = i;
9879: }
9880: }
9881: for (var i=0; i<callingForm.srchdomain.length; i++) {
9882: if (callingForm.srchdomain.options[i].value == '$context_dom') {
9883: callingForm.srchdomain.selectedIndex = i;
9884: }
9885: }
9886: }
9887: }
9888: ENDSCRIPT
9889:
9890: }
9891:
9892: my $output = <<"END_BLOCK";
9893: <script type="text/javascript">
9894: // <![CDATA[
9895: function validateEntry(callingForm) {
9896:
9897: var checkok = 1;
9898: var srchin;
9899: for (var i=0; i<callingForm.srchin.length; i++) {
9900: if ( callingForm.srchin[i].checked ) {
9901: srchin = callingForm.srchin[i].value;
9902: }
9903: }
9904:
9905: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
9906: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
9907: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
9908: var srchterm = callingForm.srchterm.value;
9909: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
9910: var msg = "";
9911:
9912: if (srchterm == "") {
9913: checkok = 0;
9914: msg += "$js_lt{'youm'}\\n";
9915: }
9916:
9917: if (srchtype== 'begins') {
9918: if (srchterm.length < 2) {
9919: checkok = 0;
9920: msg += "$js_lt{'thte'}\\n";
9921: }
9922: }
9923:
9924: if (srchtype== 'contains') {
9925: if (srchterm.length < 3) {
9926: checkok = 0;
9927: msg += "$js_lt{'thet'}\\n";
9928: }
9929: }
9930: if (srchin == 'instd') {
9931: if (srchdomain == '') {
9932: checkok = 0;
9933: msg += "$js_lt{'yomc'}\\n";
9934: }
9935: }
9936: if (srchin == 'dom') {
9937: if (srchdomain == '') {
9938: checkok = 0;
9939: msg += "$js_lt{'ymcd'}\\n";
9940: }
9941: }
9942: if (srchby == 'lastfirst') {
9943: if (srchterm.indexOf(",") == -1) {
9944: checkok = 0;
9945: msg += "$js_lt{'whus'}\\n";
9946: }
9947: if (srchterm.indexOf(",") == srchterm.length -1) {
9948: checkok = 0;
9949: msg += "$js_lt{'whse'}\\n";
9950: }
9951: }
9952: if (checkok == 0) {
9953: alert("$js_lt{'thfo'}\\n"+msg);
9954: return;
9955: }
9956: if (checkok == 1) {
9957: callingForm.submit();
9958: }
9959: }
9960:
9961: $newuserscript
9962:
9963: // ]]>
9964: </script>
9965:
9966: $new_user_create
9967:
9968: END_BLOCK
9969:
9970: $output .= &Apache::lonhtmlcommon::start_pick_box().
9971: &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
9972: $domform.
9973: &Apache::lonhtmlcommon::row_closure().
9974: &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
9975: $srchbysel.
9976: $srchtypesel.
9977: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
9978: $srchinsel.
9979: &Apache::lonhtmlcommon::row_closure(1).
9980: &Apache::lonhtmlcommon::end_pick_box().
9981: '<br />';
9982: return ($output,1);
9983: }
9984:
9985: sub user_rule_check {
9986: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
9987: my ($response,%inst_response);
9988: if (ref($usershash) eq 'HASH') {
9989: if (keys(%{$usershash}) > 1) {
9990: my (%by_username,%by_id,%userdoms);
9991: my $checkid;
9992: if (ref($checks) eq 'HASH') {
9993: if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
9994: $checkid = 1;
9995: }
9996: }
9997: foreach my $user (keys(%{$usershash})) {
9998: my ($uname,$udom) = split(/:/,$user);
9999: if ($checkid) {
10000: if (ref($usershash->{$user}) eq 'HASH') {
10001: if ($usershash->{$user}->{'id'} ne '') {
10002: $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
10003: $userdoms{$udom} = 1;
10004: if (ref($inst_results) eq 'HASH') {
10005: $inst_results->{$uname.':'.$udom} = {};
10006: }
10007: }
10008: }
10009: } else {
10010: $by_username{$udom}{$uname} = 1;
10011: $userdoms{$udom} = 1;
10012: if (ref($inst_results) eq 'HASH') {
10013: $inst_results->{$uname.':'.$udom} = {};
10014: }
10015: }
10016: }
10017: foreach my $udom (keys(%userdoms)) {
10018: if (!$got_rules->{$udom}) {
10019: my %domconfig = &Apache::lonnet::get_dom('configuration',
10020: ['usercreation'],$udom);
10021: if (ref($domconfig{'usercreation'}) eq 'HASH') {
10022: foreach my $item ('username','id') {
10023: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10024: $$curr_rules{$udom}{$item} =
10025: $domconfig{'usercreation'}{$item.'_rule'};
10026: }
10027: }
10028: }
10029: $got_rules->{$udom} = 1;
10030: }
10031: }
10032: if ($checkid) {
10033: foreach my $udom (keys(%by_id)) {
10034: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10035: if ($outcome eq 'ok') {
10036: foreach my $id (keys(%{$by_id{$udom}})) {
10037: my $uname = $by_id{$udom}{$id};
10038: $inst_response{$uname.':'.$udom} = $outcome;
10039: }
10040: if (ref($results) eq 'HASH') {
10041: foreach my $uname (keys(%{$results})) {
10042: if (exists($inst_response{$uname.':'.$udom})) {
10043: $inst_response{$uname.':'.$udom} = $outcome;
10044: $inst_results->{$uname.':'.$udom} = $results->{$uname};
10045: }
10046: }
10047: }
10048: }
10049: }
10050: } else {
10051: foreach my $udom (keys(%by_username)) {
10052: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10053: if ($outcome eq 'ok') {
10054: foreach my $uname (keys(%{$by_username{$udom}})) {
10055: $inst_response{$uname.':'.$udom} = $outcome;
10056: }
10057: if (ref($results) eq 'HASH') {
10058: foreach my $uname (keys(%{$results})) {
10059: $inst_results->{$uname.':'.$udom} = $results->{$uname};
10060: }
10061: }
10062: }
10063: }
10064: }
10065: } elsif (keys(%{$usershash}) == 1) {
10066: my $user = (keys(%{$usershash}))[0];
10067: my ($uname,$udom) = split(/:/,$user);
10068: if (($udom ne '') && ($uname ne '')) {
10069: if (ref($usershash->{$user}) eq 'HASH') {
10070: if (ref($checks) eq 'HASH') {
10071: if (defined($checks->{'username'})) {
10072: ($inst_response{$user},%{$inst_results->{$user}}) =
10073: &Apache::lonnet::get_instuser($udom,$uname);
10074: } elsif (defined($checks->{'id'})) {
10075: if ($usershash->{$user}->{'id'} ne '') {
10076: ($inst_response{$user},%{$inst_results->{$user}}) =
10077: &Apache::lonnet::get_instuser($udom,undef,
10078: $usershash->{$user}->{'id'});
10079: } else {
10080: ($inst_response{$user},%{$inst_results->{$user}}) =
10081: &Apache::lonnet::get_instuser($udom,$uname);
10082: }
10083: }
10084: } else {
10085: ($inst_response{$user},%{$inst_results->{$user}}) =
10086: &Apache::lonnet::get_instuser($udom,$uname);
10087: return;
10088: }
10089: if (!$got_rules->{$udom}) {
10090: my %domconfig = &Apache::lonnet::get_dom('configuration',
10091: ['usercreation'],$udom);
10092: if (ref($domconfig{'usercreation'}) eq 'HASH') {
10093: foreach my $item ('username','id') {
10094: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10095: $$curr_rules{$udom}{$item} =
10096: $domconfig{'usercreation'}{$item.'_rule'};
10097: }
10098: }
10099: }
10100: $got_rules->{$udom} = 1;
10101: }
10102: }
10103: } else {
10104: return;
10105: }
10106: } else {
10107: return;
10108: }
10109: foreach my $user (keys(%{$usershash})) {
10110: my ($uname,$udom) = split(/:/,$user);
10111: next if (($udom eq '') || ($uname eq ''));
10112: my $id;
10113: if (ref($inst_results) eq 'HASH') {
10114: if (ref($inst_results->{$user}) eq 'HASH') {
10115: $id = $inst_results->{$user}->{'id'};
10116: }
10117: }
10118: if ($id eq '') {
10119: if (ref($usershash->{$user})) {
10120: $id = $usershash->{$user}->{'id'};
10121: }
10122: }
10123: foreach my $item (keys(%{$checks})) {
10124: if (ref($$curr_rules{$udom}) eq 'HASH') {
10125: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10126: if (@{$$curr_rules{$udom}{$item}} > 0) {
10127: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10128: $$curr_rules{$udom}{$item});
10129: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10130: if ($rule_check{$rule}) {
10131: $$rulematch{$user}{$item} = $rule;
10132: if ($inst_response{$user} eq 'ok') {
10133: if (ref($inst_results) eq 'HASH') {
10134: if (ref($inst_results->{$user}) eq 'HASH') {
10135: if (keys(%{$inst_results->{$user}}) == 0) {
10136: $$alerts{$item}{$udom}{$uname} = 1;
10137: } elsif ($item eq 'id') {
10138: if ($inst_results->{$user}->{'id'} eq '') {
10139: $$alerts{$item}{$udom}{$uname} = 1;
10140: }
10141: }
10142: }
10143: }
10144: }
10145: last;
10146: }
10147: }
10148: }
10149: }
10150: }
10151: }
10152: }
10153: }
10154: return;
10155: }
10156:
10157: sub user_rule_formats {
10158: my ($domain,$domdesc,$curr_rules,$check) = @_;
10159: my %text = (
10160: 'username' => 'Usernames',
10161: 'id' => 'IDs',
10162: );
10163: my $output;
10164: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10165: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10166: if (@{$ruleorder} > 0) {
10167: $output = '<br />'.
10168: &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10169: '<span class="LC_cusr_emph">','</span>',$domdesc).
10170: ' <ul>';
10171: foreach my $rule (@{$ruleorder}) {
10172: if (ref($curr_rules) eq 'ARRAY') {
10173: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10174: if (ref($rules->{$rule}) eq 'HASH') {
10175: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10176: $rules->{$rule}{'desc'}.'</li>';
10177: }
10178: }
10179: }
10180: }
10181: $output .= '</ul>';
10182: }
10183: }
10184: return $output;
10185: }
10186:
10187: sub instrule_disallow_msg {
10188: my ($checkitem,$domdesc,$count,$mode) = @_;
10189: my $response;
10190: my %text = (
10191: item => 'username',
10192: items => 'usernames',
10193: match => 'matches',
10194: do => 'does',
10195: action => 'a username',
10196: one => 'one',
10197: );
10198: if ($count > 1) {
10199: $text{'item'} = 'usernames';
10200: $text{'match'} ='match';
10201: $text{'do'} = 'do';
10202: $text{'action'} = 'usernames',
10203: $text{'one'} = 'ones';
10204: }
10205: if ($checkitem eq 'id') {
10206: $text{'items'} = 'IDs';
10207: $text{'item'} = 'ID';
10208: $text{'action'} = 'an ID';
10209: if ($count > 1) {
10210: $text{'item'} = 'IDs';
10211: $text{'action'} = 'IDs';
10212: }
10213: }
10214: $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 />';
10215: if ($mode eq 'upload') {
10216: if ($checkitem eq 'username') {
10217: $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'}.");
10218: } elsif ($checkitem eq 'id') {
10219: $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.");
10220: }
10221: } elsif ($mode eq 'selfcreate') {
10222: if ($checkitem eq 'id') {
10223: $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.");
10224: }
10225: } else {
10226: if ($checkitem eq 'username') {
10227: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10228: } elsif ($checkitem eq 'id') {
10229: $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.");
10230: }
10231: }
10232: return $response;
10233: }
10234:
10235: sub personal_data_fieldtitles {
10236: my %fieldtitles = &Apache::lonlocal::texthash (
10237: id => 'Student/Employee ID',
10238: permanentemail => 'E-mail address',
10239: lastname => 'Last Name',
10240: firstname => 'First Name',
10241: middlename => 'Middle Name',
10242: generation => 'Generation',
10243: gen => 'Generation',
10244: inststatus => 'Affiliation',
10245: );
10246: return %fieldtitles;
10247: }
10248:
10249: sub sorted_inst_types {
10250: my ($dom) = @_;
10251: my ($usertypes,$order);
10252: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10253: if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10254: $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10255: $order = $domdefaults{'inststatus'}{'inststatusorder'};
10256: } else {
10257: ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10258: }
10259: my $othertitle = &mt('All users');
10260: if ($env{'request.course.id'}) {
10261: $othertitle = &mt('Any users');
10262: }
10263: my @types;
10264: if (ref($order) eq 'ARRAY') {
10265: @types = @{$order};
10266: }
10267: if (@types == 0) {
10268: if (ref($usertypes) eq 'HASH') {
10269: @types = sort(keys(%{$usertypes}));
10270: }
10271: }
10272: if (keys(%{$usertypes}) > 0) {
10273: $othertitle = &mt('Other users');
10274: }
10275: return ($othertitle,$usertypes,\@types);
10276: }
10277:
10278: sub get_institutional_codes {
10279: my ($settings,$allcourses,$LC_code) = @_;
10280: # Get complete list of course sections to update
10281: my @currsections = ();
10282: my @currxlists = ();
10283: my $coursecode = $$settings{'internal.coursecode'};
10284:
10285: if ($$settings{'internal.sectionnums'} ne '') {
10286: @currsections = split(/,/,$$settings{'internal.sectionnums'});
10287: }
10288:
10289: if ($$settings{'internal.crosslistings'} ne '') {
10290: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10291: }
10292:
10293: if (@currxlists > 0) {
10294: foreach (@currxlists) {
10295: if (m/^([^:]+):(\w*)$/) {
10296: unless (grep/^$1$/,@{$allcourses}) {
10297: push(@{$allcourses},$1);
10298: $$LC_code{$1} = $2;
10299: }
10300: }
10301: }
10302: }
10303:
10304: if (@currsections > 0) {
10305: foreach (@currsections) {
10306: if (m/^(\w+):(\w*)$/) {
10307: my $sec = $coursecode.$1;
10308: my $lc_sec = $2;
10309: unless (grep/^$sec$/,@{$allcourses}) {
10310: push(@{$allcourses},$sec);
10311: $$LC_code{$sec} = $lc_sec;
10312: }
10313: }
10314: }
10315: }
10316: return;
10317: }
10318:
10319: sub get_standard_codeitems {
10320: return ('Year','Semester','Department','Number','Section');
10321: }
10322:
10323: =pod
10324:
10325: =head1 Slot Helpers
10326:
10327: =over 4
10328:
10329: =item * sorted_slots()
10330:
10331: Sorts an array of slot names in order of an optional sort key,
10332: default sort is by slot start time (earliest first).
10333:
10334: Inputs:
10335:
10336: =over 4
10337:
10338: slotsarr - Reference to array of unsorted slot names.
10339:
10340: slots - Reference to hash of hash, where outer hash keys are slot names.
10341:
10342: sortkey - Name of key in inner hash to be sorted on (e.g., starttime).
10343:
10344: =back
10345:
10346: Returns:
10347:
10348: =over 4
10349:
10350: sorted - An array of slot names sorted by a specified sort key
10351: (default sort key is start time of the slot).
10352:
10353: =back
10354:
10355: =cut
10356:
10357:
10358: sub sorted_slots {
10359: my ($slotsarr,$slots,$sortkey) = @_;
10360: if ($sortkey eq '') {
10361: $sortkey = 'starttime';
10362: }
10363: my @sorted;
10364: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10365: @sorted =
10366: sort {
10367: if (ref($slots->{$a}) && ref($slots->{$b})) {
10368: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10369: }
10370: if (ref($slots->{$a})) { return -1;}
10371: if (ref($slots->{$b})) { return 1;}
10372: return 0;
10373: } @{$slotsarr};
10374: }
10375: return @sorted;
10376: }
10377:
10378: =pod
10379:
10380: =item * get_future_slots()
10381:
10382: Inputs:
10383:
10384: =over 4
10385:
10386: cnum - course number
10387:
10388: cdom - course domain
10389:
10390: now - current UNIX time
10391:
10392: symb - optional symb
10393:
10394: =back
10395:
10396: Returns:
10397:
10398: =over 4
10399:
10400: sorted_reservable - ref to array of student_schedulable slots currently
10401: reservable, ordered by end date of reservation period.
10402:
10403: reservable_now - ref to hash of student_schedulable slots currently
10404: reservable.
10405:
10406: Keys in inner hash are:
10407: (a) symb: either blank or symb to which slot use is restricted.
10408: (b) endreserve: end date of reservation period.
10409: (c) uniqueperiod: start,end dates when slot is to be uniquely
10410: selected.
10411:
10412: sorted_future - ref to array of student_schedulable slots reservable in
10413: the future, ordered by start date of reservation period.
10414:
10415: future_reservable - ref to hash of student_schedulable slots reservable
10416: in the future.
10417:
10418: Keys in inner hash are:
10419: (a) symb: either blank or symb to which slot use is restricted.
10420: (b) startreserve: start date of reservation period.
10421: (c) uniqueperiod: start,end dates when slot is to be uniquely
10422: selected.
10423:
10424: =back
10425:
10426: =cut
10427:
10428: sub get_future_slots {
10429: my ($cnum,$cdom,$now,$symb) = @_;
10430: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10431: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10432: foreach my $slot (keys(%slots)) {
10433: next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10434: if ($symb) {
10435: next if (($slots{$slot}->{'symb'} ne '') &&
10436: ($slots{$slot}->{'symb'} ne $symb));
10437: }
10438: if (($slots{$slot}->{'starttime'} > $now) &&
10439: ($slots{$slot}->{'endtime'} > $now)) {
10440: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10441: my $userallowed = 0;
10442: if ($slots{$slot}->{'allowedsections'}) {
10443: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10444: if (!defined($env{'request.role.sec'})
10445: && grep(/^No section assigned$/,@allowed_sec)) {
10446: $userallowed=1;
10447: } else {
10448: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10449: $userallowed=1;
10450: }
10451: }
10452: unless ($userallowed) {
10453: if (defined($env{'request.course.groups'})) {
10454: my @groups = split(/:/,$env{'request.course.groups'});
10455: foreach my $group (@groups) {
10456: if (grep(/^\Q$group\E$/,@allowed_sec)) {
10457: $userallowed=1;
10458: last;
10459: }
10460: }
10461: }
10462: }
10463: }
10464: if ($slots{$slot}->{'allowedusers'}) {
10465: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10466: my $user = $env{'user.name'}.':'.$env{'user.domain'};
10467: if (grep(/^\Q$user\E$/,@allowed_users)) {
10468: $userallowed = 1;
10469: }
10470: }
10471: next unless($userallowed);
10472: }
10473: my $startreserve = $slots{$slot}->{'startreserve'};
10474: my $endreserve = $slots{$slot}->{'endreserve'};
10475: my $symb = $slots{$slot}->{'symb'};
10476: my $uniqueperiod;
10477: if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
10478: $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
10479: }
10480: if (($startreserve < $now) &&
10481: (!$endreserve || $endreserve > $now)) {
10482: my $lastres = $endreserve;
10483: if (!$lastres) {
10484: $lastres = $slots{$slot}->{'starttime'};
10485: }
10486: $reservable_now{$slot} = {
10487: symb => $symb,
10488: endreserve => $lastres,
10489: uniqueperiod => $uniqueperiod,
10490: };
10491: } elsif (($startreserve > $now) &&
10492: (!$endreserve || $endreserve > $startreserve)) {
10493: $future_reservable{$slot} = {
10494: symb => $symb,
10495: startreserve => $startreserve,
10496: uniqueperiod => $uniqueperiod,
10497: };
10498: }
10499: }
10500: }
10501: my @unsorted_reservable = keys(%reservable_now);
10502: if (@unsorted_reservable > 0) {
10503: @sorted_reservable =
10504: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10505: }
10506: my @unsorted_future = keys(%future_reservable);
10507: if (@unsorted_future > 0) {
10508: @sorted_future =
10509: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10510: }
10511: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10512: }
10513:
10514: =pod
10515:
10516: =back
10517:
10518: =head1 HTTP Helpers
10519:
10520: =over 4
10521:
10522: =item * &get_unprocessed_cgi($query,$possible_names)
10523:
10524: Modify the %env hash to contain unprocessed CGI form parameters held in
10525: $query. The parameters listed in $possible_names (an array reference),
10526: will be set in $env{'form.name'} if they do not already exist.
10527:
10528: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
10529: $possible_names is an ref to an array of form element names. As an example:
10530: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10531: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10532:
10533: =cut
10534:
10535: sub get_unprocessed_cgi {
10536: my ($query,$possible_names)= @_;
10537: # $Apache::lonxml::debug=1;
10538: foreach my $pair (split(/&/,$query)) {
10539: my ($name, $value) = split(/=/,$pair);
10540: $name = &unescape($name);
10541: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10542: $value =~ tr/+/ /;
10543: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10544: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10545: }
10546: }
10547: }
10548:
10549: =pod
10550:
10551: =item * &cacheheader()
10552:
10553: returns cache-controlling header code
10554:
10555: =cut
10556:
10557: sub cacheheader {
10558: unless ($env{'request.method'} eq 'GET') { return ''; }
10559: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10560: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10561: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10562: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10563: return $output;
10564: }
10565:
10566: =pod
10567:
10568: =item * &no_cache($r)
10569:
10570: specifies header code to not have cache
10571:
10572: =cut
10573:
10574: sub no_cache {
10575: my ($r) = @_;
10576: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10577: $env{'request.method'} ne 'GET') { return ''; }
10578: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10579: $r->no_cache(1);
10580: $r->header_out("Expires" => $date);
10581: $r->header_out("Pragma" => "no-cache");
10582: }
10583:
10584: sub content_type {
10585: my ($r,$type,$charset) = @_;
10586: if ($r) {
10587: # Note that printout.pl calls this with undef for $r.
10588: &no_cache($r);
10589: }
10590: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10591: unless ($charset) {
10592: $charset=&Apache::lonlocal::current_encoding;
10593: }
10594: if ($charset) { $type.='; charset='.$charset; }
10595: if ($r) {
10596: $r->content_type($type);
10597: } else {
10598: print("Content-type: $type\n\n");
10599: }
10600: }
10601:
10602: =pod
10603:
10604: =item * &add_to_env($name,$value)
10605:
10606: adds $name to the %env hash with value
10607: $value, if $name already exists, the entry is converted to an array
10608: reference and $value is added to the array.
10609:
10610: =cut
10611:
10612: sub add_to_env {
10613: my ($name,$value)=@_;
10614: if (defined($env{$name})) {
10615: if (ref($env{$name})) {
10616: #already have multiple values
10617: push(@{ $env{$name} },$value);
10618: } else {
10619: #first time seeing multiple values, convert hash entry to an arrayref
10620: my $first=$env{$name};
10621: undef($env{$name});
10622: push(@{ $env{$name} },$first,$value);
10623: }
10624: } else {
10625: $env{$name}=$value;
10626: }
10627: }
10628:
10629: =pod
10630:
10631: =item * &get_env_multiple($name)
10632:
10633: gets $name from the %env hash, it seemlessly handles the cases where multiple
10634: values may be defined and end up as an array ref.
10635:
10636: returns an array of values
10637:
10638: =cut
10639:
10640: sub get_env_multiple {
10641: my ($name) = @_;
10642: my @values;
10643: if (defined($env{$name})) {
10644: # exists is it an array
10645: if (ref($env{$name})) {
10646: @values=@{ $env{$name} };
10647: } else {
10648: $values[0]=$env{$name};
10649: }
10650: }
10651: return(@values);
10652: }
10653:
10654: sub ask_for_embedded_content {
10655: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
10656: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
10657: %currsubfile,%unused,$rem);
10658: my $counter = 0;
10659: my $numnew = 0;
10660: my $numremref = 0;
10661: my $numinvalid = 0;
10662: my $numpathchg = 0;
10663: my $numexisting = 0;
10664: my $numunused = 0;
10665: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10666: $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10667: my $heading = &mt('Upload embedded files');
10668: my $buttontext = &mt('Upload');
10669:
10670: if ($env{'request.course.id'}) {
10671: if ($actionurl eq '/adm/dependencies') {
10672: $navmap = Apache::lonnavmaps::navmap->new();
10673: }
10674: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10675: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10676: }
10677: if (($actionurl eq '/adm/portfolio') ||
10678: ($actionurl eq '/adm/coursegrp_portfolio')) {
10679: my $current_path='/';
10680: if ($env{'form.currentpath'}) {
10681: $current_path = $env{'form.currentpath'};
10682: }
10683: if ($actionurl eq '/adm/coursegrp_portfolio') {
10684: $udom = $cdom;
10685: $uname = $cnum;
10686: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10687: } else {
10688: $udom = $env{'user.domain'};
10689: $uname = $env{'user.name'};
10690: $url = '/userfiles/portfolio';
10691: }
10692: $toplevel = $url.'/';
10693: $url .= $current_path;
10694: $getpropath = 1;
10695: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10696: ($actionurl eq '/adm/imsimport')) {
10697: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
10698: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
10699: $toplevel = $url;
10700: if ($rest ne '') {
10701: $url .= $rest;
10702: }
10703: } elsif ($actionurl eq '/adm/coursedocs') {
10704: if (ref($args) eq 'HASH') {
10705: $url = $args->{'docs_url'};
10706: $toplevel = $url;
10707: if ($args->{'context'} eq 'paste') {
10708: ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
10709: ($path) =
10710: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10711: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10712: $fileloc =~ s{^/}{};
10713: }
10714: }
10715: } elsif ($actionurl eq '/adm/dependencies') {
10716: if ($env{'request.course.id'} ne '') {
10717: if (ref($args) eq 'HASH') {
10718: $url = $args->{'docs_url'};
10719: $title = $args->{'docs_title'};
10720: $toplevel = $url;
10721: unless ($toplevel =~ m{^/}) {
10722: $toplevel = "/$url";
10723: }
10724: ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
10725: if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
10726: $path = $1;
10727: } else {
10728: ($path) =
10729: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10730: }
10731: if ($toplevel=~/^\/*(uploaded|editupload)/) {
10732: $fileloc = $toplevel;
10733: $fileloc=~ s/^\s*(\S+)\s*$/$1/;
10734: my ($udom,$uname,$fname) =
10735: ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
10736: $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
10737: } else {
10738: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10739: }
10740: $fileloc =~ s{^/}{};
10741: ($filename) = ($fileloc =~ m{.+/([^/]+)$});
10742: $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
10743: }
10744: }
10745: } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10746: $udom = $cdom;
10747: $uname = $cnum;
10748: $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
10749: $toplevel = $url;
10750: $path = $url;
10751: $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
10752: $fileloc =~ s{^/}{};
10753: }
10754: foreach my $file (keys(%{$allfiles})) {
10755: my $embed_file;
10756: if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
10757: $embed_file = $1;
10758: } else {
10759: $embed_file = $file;
10760: }
10761: my ($absolutepath,$cleaned_file);
10762: if ($embed_file =~ m{^\w+://}) {
10763: $cleaned_file = $embed_file;
10764: $newfiles{$cleaned_file} = 1;
10765: $mapping{$cleaned_file} = $embed_file;
10766: } else {
10767: $cleaned_file = &clean_path($embed_file);
10768: if ($embed_file =~ m{^/}) {
10769: $absolutepath = $embed_file;
10770: }
10771: if ($cleaned_file =~ m{/}) {
10772: my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
10773: $path = &check_for_traversal($path,$url,$toplevel);
10774: my $item = $fname;
10775: if ($path ne '') {
10776: $item = $path.'/'.$fname;
10777: $subdependencies{$path}{$fname} = 1;
10778: } else {
10779: $dependencies{$item} = 1;
10780: }
10781: if ($absolutepath) {
10782: $mapping{$item} = $absolutepath;
10783: } else {
10784: $mapping{$item} = $embed_file;
10785: }
10786: } else {
10787: $dependencies{$embed_file} = 1;
10788: if ($absolutepath) {
10789: $mapping{$cleaned_file} = $absolutepath;
10790: } else {
10791: $mapping{$cleaned_file} = $embed_file;
10792: }
10793: }
10794: }
10795: }
10796: my $dirptr = 16384;
10797: foreach my $path (keys(%subdependencies)) {
10798: $currsubfile{$path} = {};
10799: if (($actionurl eq '/adm/portfolio') ||
10800: ($actionurl eq '/adm/coursegrp_portfolio')) {
10801: my ($sublistref,$listerror) =
10802: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
10803: if (ref($sublistref) eq 'ARRAY') {
10804: foreach my $line (@{$sublistref}) {
10805: my ($file_name,$rest) = split(/\&/,$line,2);
10806: $currsubfile{$path}{$file_name} = 1;
10807: }
10808: }
10809: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10810: if (opendir(my $dir,$url.'/'.$path)) {
10811: my @subdir_list = grep(!/^\./,readdir($dir));
10812: map {$currsubfile{$path}{$_} = 1;} @subdir_list;
10813: }
10814: } elsif (($actionurl eq '/adm/dependencies') ||
10815: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10816: ($args->{'context'} eq 'paste')) ||
10817: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10818: if ($env{'request.course.id'} ne '') {
10819: my $dir;
10820: if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10821: $dir = $fileloc;
10822: } else {
10823: ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10824: }
10825: if ($dir ne '') {
10826: my ($sublistref,$listerror) =
10827: &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
10828: if (ref($sublistref) eq 'ARRAY') {
10829: foreach my $line (@{$sublistref}) {
10830: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
10831: undef,$mtime)=split(/\&/,$line,12);
10832: unless (($testdir&$dirptr) ||
10833: ($file_name =~ /^\.\.?$/)) {
10834: $currsubfile{$path}{$file_name} = [$size,$mtime];
10835: }
10836: }
10837: }
10838: }
10839: }
10840: }
10841: foreach my $file (keys(%{$subdependencies{$path}})) {
10842: if (exists($currsubfile{$path}{$file})) {
10843: my $item = $path.'/'.$file;
10844: unless ($mapping{$item} eq $item) {
10845: $pathchanges{$item} = 1;
10846: }
10847: $existing{$item} = 1;
10848: $numexisting ++;
10849: } else {
10850: $newfiles{$path.'/'.$file} = 1;
10851: }
10852: }
10853: if ($actionurl eq '/adm/dependencies') {
10854: foreach my $path (keys(%currsubfile)) {
10855: if (ref($currsubfile{$path}) eq 'HASH') {
10856: foreach my $file (keys(%{$currsubfile{$path}})) {
10857: unless ($subdependencies{$path}{$file}) {
10858: next if (($rem ne '') &&
10859: (($env{"httpref.$rem"."$path/$file"} ne '') ||
10860: (ref($navmap) &&
10861: (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10862: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10863: ($navmap->getResourceByUrl($rem."$path/$1")))))));
10864: $unused{$path.'/'.$file} = 1;
10865: }
10866: }
10867: }
10868: }
10869: }
10870: }
10871: my %currfile;
10872: if (($actionurl eq '/adm/portfolio') ||
10873: ($actionurl eq '/adm/coursegrp_portfolio')) {
10874: my ($dirlistref,$listerror) =
10875: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10876: if (ref($dirlistref) eq 'ARRAY') {
10877: foreach my $line (@{$dirlistref}) {
10878: my ($file_name,$rest) = split(/\&/,$line,2);
10879: $currfile{$file_name} = 1;
10880: }
10881: }
10882: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10883: if (opendir(my $dir,$url)) {
10884: my @dir_list = grep(!/^\./,readdir($dir));
10885: map {$currfile{$_} = 1;} @dir_list;
10886: }
10887: } elsif (($actionurl eq '/adm/dependencies') ||
10888: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10889: ($args->{'context'} eq 'paste')) ||
10890: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10891: if ($env{'request.course.id'} ne '') {
10892: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10893: if ($dir ne '') {
10894: my ($dirlistref,$listerror) =
10895: &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10896: if (ref($dirlistref) eq 'ARRAY') {
10897: foreach my $line (@{$dirlistref}) {
10898: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10899: $size,undef,$mtime)=split(/\&/,$line,12);
10900: unless (($testdir&$dirptr) ||
10901: ($file_name =~ /^\.\.?$/)) {
10902: $currfile{$file_name} = [$size,$mtime];
10903: }
10904: }
10905: }
10906: }
10907: }
10908: }
10909: foreach my $file (keys(%dependencies)) {
10910: if (exists($currfile{$file})) {
10911: unless ($mapping{$file} eq $file) {
10912: $pathchanges{$file} = 1;
10913: }
10914: $existing{$file} = 1;
10915: $numexisting ++;
10916: } else {
10917: $newfiles{$file} = 1;
10918: }
10919: }
10920: foreach my $file (keys(%currfile)) {
10921: unless (($file eq $filename) ||
10922: ($file eq $filename.'.bak') ||
10923: ($dependencies{$file})) {
10924: if ($actionurl eq '/adm/dependencies') {
10925: unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10926: next if (($rem ne '') &&
10927: (($env{"httpref.$rem".$file} ne '') ||
10928: (ref($navmap) &&
10929: (($navmap->getResourceByUrl($rem.$file) ne '') ||
10930: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10931: ($navmap->getResourceByUrl($rem.$1)))))));
10932: }
10933: }
10934: $unused{$file} = 1;
10935: }
10936: }
10937: if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10938: ($args->{'context'} eq 'paste')) {
10939: $counter = scalar(keys(%existing));
10940: $numpathchg = scalar(keys(%pathchanges));
10941: return ($output,$counter,$numpathchg,\%existing);
10942: } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
10943: (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10944: $counter = scalar(keys(%existing));
10945: $numpathchg = scalar(keys(%pathchanges));
10946: return ($output,$counter,$numpathchg,\%existing,\%mapping);
10947: }
10948: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10949: if ($actionurl eq '/adm/dependencies') {
10950: next if ($embed_file =~ m{^\w+://});
10951: }
10952: $upload_output .= &start_data_table_row().
10953: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
10954: '<span class="LC_filename">'.$embed_file.'</span>';
10955: unless ($mapping{$embed_file} eq $embed_file) {
10956: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10957: &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10958: }
10959: $upload_output .= '</td>';
10960: if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) {
10961: $upload_output.='<td align="right">'.
10962: '<span class="LC_info LC_fontsize_medium">'.
10963: &mt("URL points to web address").'</span>';
10964: $numremref++;
10965: } elsif ($args->{'error_on_invalid_names'}
10966: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10967: $upload_output.='<td align="right"><span class="LC_warning">'.
10968: &mt('Invalid characters').'</span>';
10969: $numinvalid++;
10970: } else {
10971: $upload_output .= '<td>'.
10972: &embedded_file_element('upload_embedded',$counter,
10973: $embed_file,\%mapping,
10974: $allfiles,$codebase,'upload');
10975: $counter ++;
10976: $numnew ++;
10977: }
10978: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10979: }
10980: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10981: if ($actionurl eq '/adm/dependencies') {
10982: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10983: $modify_output .= &start_data_table_row().
10984: '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10985: '<img src="'.&icon($embed_file).'" border="0" />'.
10986: ' <span class="LC_filename">'.$embed_file.'</span></a></td>'.
10987: '<td>'.$size.'</td>'.
10988: '<td>'.$mtime.'</td>'.
10989: '<td><label><input type="checkbox" name="mod_upload_dep" '.
10990: 'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10991: $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10992: '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10993: &embedded_file_element('upload_embedded',$counter,
10994: $embed_file,\%mapping,
10995: $allfiles,$codebase,'modify').
10996: '</div></td>'.
10997: &end_data_table_row()."\n";
10998: $counter ++;
10999: } else {
11000: $upload_output .= &start_data_table_row().
11001: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
11002: '<span class="LC_filename">'.$embed_file.'</span></td>'.
11003: '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11004: &Apache::loncommon::end_data_table_row()."\n";
11005: }
11006: }
11007: my $delidx = $counter;
11008: foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11009: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11010: $delete_output .= &start_data_table_row().
11011: '<td><img src="'.&icon($oldfile).'" />'.
11012: ' <span class="LC_filename">'.$oldfile.'</span></td>'.
11013: '<td>'.$size.'</td>'.
11014: '<td>'.$mtime.'</td>'.
11015: '<td><label><input type="checkbox" name="del_upload_dep" '.
11016: ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11017: &embedded_file_element('upload_embedded',$delidx,
11018: $oldfile,\%mapping,$allfiles,
11019: $codebase,'delete').'</td>'.
11020: &end_data_table_row()."\n";
11021: $numunused ++;
11022: $delidx ++;
11023: }
11024: if ($upload_output) {
11025: $upload_output = &start_data_table().
11026: $upload_output.
11027: &end_data_table()."\n";
11028: }
11029: if ($modify_output) {
11030: $modify_output = &start_data_table().
11031: &start_data_table_header_row().
11032: '<th>'.&mt('File').'</th>'.
11033: '<th>'.&mt('Size (KB)').'</th>'.
11034: '<th>'.&mt('Modified').'</th>'.
11035: '<th>'.&mt('Upload replacement?').'</th>'.
11036: &end_data_table_header_row().
11037: $modify_output.
11038: &end_data_table()."\n";
11039: }
11040: if ($delete_output) {
11041: $delete_output = &start_data_table().
11042: &start_data_table_header_row().
11043: '<th>'.&mt('File').'</th>'.
11044: '<th>'.&mt('Size (KB)').'</th>'.
11045: '<th>'.&mt('Modified').'</th>'.
11046: '<th>'.&mt('Delete?').'</th>'.
11047: &end_data_table_header_row().
11048: $delete_output.
11049: &end_data_table()."\n";
11050: }
11051: my $applies = 0;
11052: if ($numremref) {
11053: $applies ++;
11054: }
11055: if ($numinvalid) {
11056: $applies ++;
11057: }
11058: if ($numexisting) {
11059: $applies ++;
11060: }
11061: if ($counter || $numunused) {
11062: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11063: ' method="post" enctype="multipart/form-data">'."\n".
11064: $state.'<h3>'.$heading.'</h3>';
11065: if ($actionurl eq '/adm/dependencies') {
11066: if ($numnew) {
11067: $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11068: '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11069: $upload_output.'<br />'."\n";
11070: }
11071: if ($numexisting) {
11072: $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11073: '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11074: $modify_output.'<br />'."\n";
11075: $buttontext = &mt('Save changes');
11076: }
11077: if ($numunused) {
11078: $output .= '<h4>'.&mt('Unused files').'</h4>'.
11079: '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11080: $delete_output.'<br />'."\n";
11081: $buttontext = &mt('Save changes');
11082: }
11083: } else {
11084: $output .= $upload_output.'<br />'."\n";
11085: }
11086: $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11087: $counter.'" />'."\n";
11088: if ($actionurl eq '/adm/dependencies') {
11089: $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11090: $numnew.'" />'."\n";
11091: } elsif ($actionurl eq '') {
11092: $output .= '<input type="hidden" name="phase" value="three" />';
11093: }
11094: } elsif ($applies) {
11095: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11096: if ($applies > 1) {
11097: $output .=
11098: &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11099: if ($numremref) {
11100: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11101: }
11102: if ($numinvalid) {
11103: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11104: }
11105: if ($numexisting) {
11106: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11107: }
11108: $output .= '</ul><br />';
11109: } elsif ($numremref) {
11110: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11111: } elsif ($numinvalid) {
11112: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11113: } elsif ($numexisting) {
11114: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11115: }
11116: $output .= $upload_output.'<br />';
11117: }
11118: my ($pathchange_output,$chgcount);
11119: $chgcount = $counter;
11120: if (keys(%pathchanges) > 0) {
11121: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11122: if ($counter) {
11123: $output .= &embedded_file_element('pathchange',$chgcount,
11124: $embed_file,\%mapping,
11125: $allfiles,$codebase,'change');
11126: } else {
11127: $pathchange_output .=
11128: &start_data_table_row().
11129: '<td><input type ="checkbox" name="namechange" value="'.
11130: $chgcount.'" checked="checked" /></td>'.
11131: '<td>'.$mapping{$embed_file}.'</td>'.
11132: '<td>'.$embed_file.
11133: &embedded_file_element('pathchange',$numpathchg,$embed_file,
11134: \%mapping,$allfiles,$codebase,'change').
11135: '</td>'.&end_data_table_row();
11136: }
11137: $numpathchg ++;
11138: $chgcount ++;
11139: }
11140: }
11141: if (($counter) || ($numunused)) {
11142: if ($numpathchg) {
11143: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11144: $numpathchg.'" />'."\n";
11145: }
11146: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11147: ($actionurl eq '/adm/imsimport')) {
11148: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11149: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11150: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11151: } elsif ($actionurl eq '/adm/dependencies') {
11152: $output .= '<input type="hidden" name="action" value="process_changes" />';
11153: }
11154: $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11155: } elsif ($numpathchg) {
11156: my %pathchange = ();
11157: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11158: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11159: $output .= '<p>'.&mt('or').'</p>';
11160: }
11161: }
11162: return ($output,$counter,$numpathchg);
11163: }
11164:
11165: =pod
11166:
11167: =item * clean_path($name)
11168:
11169: Performs clean-up of directories, subdirectories and filename in an
11170: embedded object, referenced in an HTML file which is being uploaded
11171: to a course or portfolio, where
11172: "Upload embedded images/multimedia files if HTML file" checkbox was
11173: checked.
11174:
11175: Clean-up is similar to replacements in lonnet::clean_filename()
11176: except each / between sub-directory and next level is preserved.
11177:
11178: =cut
11179:
11180: sub clean_path {
11181: my ($embed_file) = @_;
11182: $embed_file =~s{^/+}{};
11183: my @contents;
11184: if ($embed_file =~ m{/}) {
11185: @contents = split(/\//,$embed_file);
11186: } else {
11187: @contents = ($embed_file);
11188: }
11189: my $lastidx = scalar(@contents)-1;
11190: for (my $i=0; $i<=$lastidx; $i++) {
11191: $contents[$i]=~s{\\}{/}g;
11192: $contents[$i]=~s/\s+/\_/g;
11193: $contents[$i]=~s{[^/\w\.\-]}{}g;
11194: if ($i == $lastidx) {
11195: $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11196: }
11197: }
11198: if ($lastidx > 0) {
11199: return join('/',@contents);
11200: } else {
11201: return $contents[0];
11202: }
11203: }
11204:
11205: sub embedded_file_element {
11206: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11207: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11208: (ref($codebase) eq 'HASH'));
11209: my $output;
11210: if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11211: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11212: }
11213: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11214: &escape($embed_file).'" />';
11215: unless (($context eq 'upload_embedded') &&
11216: ($mapping->{$embed_file} eq $embed_file)) {
11217: $output .='
11218: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11219: }
11220: my $attrib;
11221: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11222: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11223: }
11224: $output .=
11225: "\n\t\t".
11226: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11227: $attrib.'" />';
11228: if (exists($codebase->{$mapping->{$embed_file}})) {
11229: $output .=
11230: "\n\t\t".
11231: '<input name="codebase_'.$num.'" type="hidden" value="'.
11232: &escape($codebase->{$mapping->{$embed_file}}).'" />';
11233: }
11234: return $output;
11235: }
11236:
11237: sub get_dependency_details {
11238: my ($currfile,$currsubfile,$embed_file) = @_;
11239: my ($size,$mtime,$showsize,$showmtime);
11240: if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11241: if ($embed_file =~ m{/}) {
11242: my ($path,$fname) = split(/\//,$embed_file);
11243: if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11244: ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11245: }
11246: } else {
11247: if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11248: ($size,$mtime) = @{$currfile->{$embed_file}};
11249: }
11250: }
11251: $showsize = $size/1024.0;
11252: $showsize = sprintf("%.1f",$showsize);
11253: if ($mtime > 0) {
11254: $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11255: }
11256: }
11257: return ($showsize,$showmtime);
11258: }
11259:
11260: sub ask_embedded_js {
11261: return <<"END";
11262: <script type="text/javascript"">
11263: // <![CDATA[
11264: function toggleBrowse(counter) {
11265: var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11266: var fileid = document.getElementById('embedded_item_'+counter);
11267: var uploaddivid = document.getElementById('moduploaddep_'+counter);
11268: if (chkboxid.checked == true) {
11269: uploaddivid.style.display='block';
11270: } else {
11271: uploaddivid.style.display='none';
11272: fileid.value = '';
11273: }
11274: }
11275: // ]]>
11276: </script>
11277:
11278: END
11279: }
11280:
11281: sub upload_embedded {
11282: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11283: $current_disk_usage,$hiddenstate,$actionurl) = @_;
11284: my (%pathchange,$output,$modifyform,$footer,$returnflag);
11285: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11286: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11287: my $orig_uploaded_filename =
11288: $env{'form.embedded_item_'.$i.'.filename'};
11289: foreach my $type ('orig','ref','attrib','codebase') {
11290: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11291: $env{'form.embedded_'.$type.'_'.$i} =
11292: &unescape($env{'form.embedded_'.$type.'_'.$i});
11293: }
11294: }
11295: my ($path,$fname) =
11296: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11297: # no path, whole string is fname
11298: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11299: $fname = &Apache::lonnet::clean_filename($fname);
11300: # See if there is anything left
11301: next if ($fname eq '');
11302:
11303: # Check if file already exists as a file or directory.
11304: my ($state,$msg);
11305: if ($context eq 'portfolio') {
11306: my $port_path = $dirpath;
11307: if ($group ne '') {
11308: $port_path = "groups/$group/$port_path";
11309: }
11310: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11311: $fname,$group,'embedded_item_'.$i,
11312: $dir_root,$port_path,$disk_quota,
11313: $current_disk_usage,$uname,$udom);
11314: if ($state eq 'will_exceed_quota'
11315: || $state eq 'file_locked') {
11316: $output .= $msg;
11317: next;
11318: }
11319: } elsif (($context eq 'author') || ($context eq 'testbank')) {
11320: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11321: if ($state eq 'exists') {
11322: $output .= $msg;
11323: next;
11324: }
11325: }
11326: # Check if extension is valid
11327: if (($fname =~ /\.(\w+)$/) &&
11328: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11329: $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11330: .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11331: next;
11332: } elsif (($fname =~ /\.(\w+)$/) &&
11333: (!defined(&Apache::loncommon::fileembstyle($1)))) {
11334: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11335: next;
11336: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11337: $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11338: next;
11339: }
11340: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11341: my $subdir = $path;
11342: $subdir =~ s{/+$}{};
11343: if ($context eq 'portfolio') {
11344: my $result;
11345: if ($state eq 'existingfile') {
11346: $result=
11347: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11348: $dirpath.$env{'form.currentpath'}.$subdir);
11349: } else {
11350: $result=
11351: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11352: $dirpath.
11353: $env{'form.currentpath'}.$subdir);
11354: if ($result !~ m|^/uploaded/|) {
11355: $output .= '<span class="LC_error">'
11356: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11357: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11358: .'</span><br />';
11359: next;
11360: } else {
11361: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11362: $path.$fname.'</span>').'<br />';
11363: }
11364: }
11365: } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11366: my $extendedsubdir = $dirpath.'/'.$subdir;
11367: $extendedsubdir =~ s{/+$}{};
11368: my $result =
11369: &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11370: if ($result !~ m|^/uploaded/|) {
11371: $output .= '<span class="LC_error">'
11372: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11373: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11374: .'</span><br />';
11375: next;
11376: } else {
11377: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11378: $path.$fname.'</span>').'<br />';
11379: if ($context eq 'syllabus') {
11380: &Apache::lonnet::make_public_indefinitely($result);
11381: }
11382: }
11383: } else {
11384: # Save the file
11385: my $target = $env{'form.embedded_item_'.$i};
11386: my $fullpath = $dir_root.$dirpath.'/'.$path;
11387: my $dest = $fullpath.$fname;
11388: my $url = $url_root.$dirpath.'/'.$path.$fname;
11389: my @parts=split(/\//,"$dirpath/$path");
11390: my $count;
11391: my $filepath = $dir_root;
11392: foreach my $subdir (@parts) {
11393: $filepath .= "/$subdir";
11394: if (!-e $filepath) {
11395: mkdir($filepath,0770);
11396: }
11397: }
11398: my $fh;
11399: if (!open($fh,'>'.$dest)) {
11400: &Apache::lonnet::logthis('Failed to create '.$dest);
11401: $output .= '<span class="LC_error">'.
11402: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11403: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11404: '</span><br />';
11405: } else {
11406: if (!print $fh $env{'form.embedded_item_'.$i}) {
11407: &Apache::lonnet::logthis('Failed to write to '.$dest);
11408: $output .= '<span class="LC_error">'.
11409: &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11410: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11411: '</span><br />';
11412: } else {
11413: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11414: $url.'</span>').'<br />';
11415: unless ($context eq 'testbank') {
11416: $footer .= &mt('View embedded file: [_1]',
11417: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11418: }
11419: }
11420: close($fh);
11421: }
11422: }
11423: if ($env{'form.embedded_ref_'.$i}) {
11424: $pathchange{$i} = 1;
11425: }
11426: }
11427: if ($output) {
11428: $output = '<p>'.$output.'</p>';
11429: }
11430: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11431: $returnflag = 'ok';
11432: my $numpathchgs = scalar(keys(%pathchange));
11433: if ($numpathchgs > 0) {
11434: if ($context eq 'portfolio') {
11435: $output .= '<p>'.&mt('or').'</p>';
11436: } elsif ($context eq 'testbank') {
11437: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11438: '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11439: $returnflag = 'modify_orightml';
11440: }
11441: }
11442: return ($output.$footer,$returnflag,$numpathchgs);
11443: }
11444:
11445: sub modify_html_form {
11446: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11447: my $end = 0;
11448: my $modifyform;
11449: if ($context eq 'upload_embedded') {
11450: return unless (ref($pathchange) eq 'HASH');
11451: if ($env{'form.number_embedded_items'}) {
11452: $end += $env{'form.number_embedded_items'};
11453: }
11454: if ($env{'form.number_pathchange_items'}) {
11455: $end += $env{'form.number_pathchange_items'};
11456: }
11457: if ($end) {
11458: for (my $i=0; $i<$end; $i++) {
11459: if ($i < $env{'form.number_embedded_items'}) {
11460: next unless($pathchange->{$i});
11461: }
11462: $modifyform .=
11463: &start_data_table_row().
11464: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11465: 'checked="checked" /></td>'.
11466: '<td>'.$env{'form.embedded_ref_'.$i}.
11467: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11468: &escape($env{'form.embedded_ref_'.$i}).'" />'.
11469: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11470: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11471: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11472: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11473: '<td>'.$env{'form.embedded_orig_'.$i}.
11474: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11475: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11476: &end_data_table_row();
11477: }
11478: }
11479: } else {
11480: $modifyform = $pathchgtable;
11481: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11482: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11483: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11484: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11485: }
11486: }
11487: if ($modifyform) {
11488: if ($actionurl eq '/adm/dependencies') {
11489: $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11490: }
11491: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11492: '<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".
11493: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11494: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11495: '</ol></p>'."\n".'<p>'.
11496: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11497: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11498: &start_data_table()."\n".
11499: &start_data_table_header_row().
11500: '<th>'.&mt('Change?').'</th>'.
11501: '<th>'.&mt('Current reference').'</th>'.
11502: '<th>'.&mt('Required reference').'</th>'.
11503: &end_data_table_header_row()."\n".
11504: $modifyform.
11505: &end_data_table().'<br />'."\n".$hiddenstate.
11506: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11507: '</form>'."\n";
11508: }
11509: return;
11510: }
11511:
11512: sub modify_html_refs {
11513: my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11514: my $container;
11515: if ($context eq 'portfolio') {
11516: $container = $env{'form.container'};
11517: } elsif ($context eq 'coursedoc') {
11518: $container = $env{'form.primaryurl'};
11519: } elsif ($context eq 'manage_dependencies') {
11520: (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11521: $container = "/$container";
11522: } elsif ($context eq 'syllabus') {
11523: $container = $url;
11524: } else {
11525: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11526: }
11527: my (%allfiles,%codebase,$output,$content);
11528: my @changes = &get_env_multiple('form.namechange');
11529: unless ((@changes > 0) || ($context eq 'syllabus')) {
11530: if (wantarray) {
11531: return ('',0,0);
11532: } else {
11533: return;
11534: }
11535: }
11536: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
11537: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11538: unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11539: if (wantarray) {
11540: return ('',0,0);
11541: } else {
11542: return;
11543: }
11544: }
11545: $content = &Apache::lonnet::getfile($container);
11546: if ($content eq '-1') {
11547: if (wantarray) {
11548: return ('',0,0);
11549: } else {
11550: return;
11551: }
11552: }
11553: } else {
11554: unless ($container =~ /^\Q$dir_root\E/) {
11555: if (wantarray) {
11556: return ('',0,0);
11557: } else {
11558: return;
11559: }
11560: }
11561: if (open(my $fh,'<',$container)) {
11562: $content = join('', <$fh>);
11563: close($fh);
11564: } else {
11565: if (wantarray) {
11566: return ('',0,0);
11567: } else {
11568: return;
11569: }
11570: }
11571: }
11572: my ($count,$codebasecount) = (0,0);
11573: my $mm = new File::MMagic;
11574: my $mime_type = $mm->checktype_contents($content);
11575: if ($mime_type eq 'text/html') {
11576: my $parse_result =
11577: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11578: \%codebase,\$content);
11579: if ($parse_result eq 'ok') {
11580: foreach my $i (@changes) {
11581: my $orig = &unescape($env{'form.embedded_orig_'.$i});
11582: my $ref = &unescape($env{'form.embedded_ref_'.$i});
11583: if ($allfiles{$ref}) {
11584: my $newname = $orig;
11585: my ($attrib_regexp,$codebase);
11586: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11587: if ($attrib_regexp =~ /:/) {
11588: $attrib_regexp =~ s/\:/|/g;
11589: }
11590: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11591: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11592: $count += $numchg;
11593: $allfiles{$newname} = $allfiles{$ref};
11594: delete($allfiles{$ref});
11595: }
11596: if ($env{'form.embedded_codebase_'.$i} ne '') {
11597: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11598: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
11599: $codebasecount ++;
11600: }
11601: }
11602: }
11603: my $skiprewrites;
11604: if ($count || $codebasecount) {
11605: my $saveresult;
11606: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
11607: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11608: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11609: if ($url eq $container) {
11610: my ($fname) = ($container =~ m{/([^/]+)$});
11611: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11612: $count,'<span class="LC_filename">'.
11613: $fname.'</span>').'</p>';
11614: } else {
11615: $output = '<p class="LC_error">'.
11616: &mt('Error: update failed for: [_1].',
11617: '<span class="LC_filename">'.
11618: $container.'</span>').'</p>';
11619: }
11620: if ($context eq 'syllabus') {
11621: unless ($saveresult eq 'ok') {
11622: $skiprewrites = 1;
11623: }
11624: }
11625: } else {
11626: if (open(my $fh,'>',$container)) {
11627: print $fh $content;
11628: close($fh);
11629: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11630: $count,'<span class="LC_filename">'.
11631: $container.'</span>').'</p>';
11632: } else {
11633: $output = '<p class="LC_error">'.
11634: &mt('Error: could not update [_1].',
11635: '<span class="LC_filename">'.
11636: $container.'</span>').'</p>';
11637: }
11638: }
11639: }
11640: if (($context eq 'syllabus') && (!$skiprewrites)) {
11641: my ($actionurl,$state);
11642: $actionurl = "/public/$udom/$uname/syllabus";
11643: my ($ignore,$num,$numpathchanges,$existing,$mapping) =
11644: &ask_for_embedded_content($actionurl,$state,\%allfiles,
11645: \%codebase,
11646: {'context' => 'rewrites',
11647: 'ignore_remote_references' => 1,});
11648: if (ref($mapping) eq 'HASH') {
11649: my $rewrites = 0;
11650: foreach my $key (keys(%{$mapping})) {
11651: next if ($key =~ m{^https?://});
11652: my $ref = $mapping->{$key};
11653: my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
11654: my $attrib;
11655: if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
11656: $attrib = join('|',@{$allfiles{$mapping->{$key}}});
11657: }
11658: if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11659: my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11660: $rewrites += $numchg;
11661: }
11662: }
11663: if ($rewrites) {
11664: my $saveresult;
11665: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11666: if ($url eq $container) {
11667: my ($fname) = ($container =~ m{/([^/]+)$});
11668: $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11669: $count,'<span class="LC_filename">'.
11670: $fname.'</span>').'</p>';
11671: } else {
11672: $output .= '<p class="LC_error">'.
11673: &mt('Error: could not update links in [_1].',
11674: '<span class="LC_filename">'.
11675: $container.'</span>').'</p>';
11676:
11677: }
11678: }
11679: }
11680: }
11681: } else {
11682: &logthis('Failed to parse '.$container.
11683: ' to modify references: '.$parse_result);
11684: }
11685: }
11686: if (wantarray) {
11687: return ($output,$count,$codebasecount);
11688: } else {
11689: return $output;
11690: }
11691: }
11692:
11693: sub check_for_existing {
11694: my ($path,$fname,$element) = @_;
11695: my ($state,$msg);
11696: if (-d $path.'/'.$fname) {
11697: $state = 'exists';
11698: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11699: } elsif (-e $path.'/'.$fname) {
11700: $state = 'exists';
11701: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11702: }
11703: if ($state eq 'exists') {
11704: $msg = '<span class="LC_error">'.$msg.'</span><br />';
11705: }
11706: return ($state,$msg);
11707: }
11708:
11709: sub check_for_upload {
11710: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
11711: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
11712: my $filesize = length($env{'form.'.$element});
11713: if (!$filesize) {
11714: my $msg = '<span class="LC_error">'.
11715: &mt('Unable to upload [_1]. (size = [_2] bytes)',
11716: '<span class="LC_filename">'.$fname.'</span>',
11717: $filesize).'<br />'.
11718: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
11719: '</span>';
11720: return ('zero_bytes',$msg);
11721: }
11722: $filesize = $filesize/1000; #express in k (1024?)
11723: my $getpropath = 1;
11724: my ($dirlistref,$listerror) =
11725: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
11726: my $found_file = 0;
11727: my $locked_file = 0;
11728: my @lockers;
11729: my $navmap;
11730: if ($env{'request.course.id'}) {
11731: $navmap = Apache::lonnavmaps::navmap->new();
11732: }
11733: if (ref($dirlistref) eq 'ARRAY') {
11734: foreach my $line (@{$dirlistref}) {
11735: my ($file_name,$rest)=split(/\&/,$line,2);
11736: if ($file_name eq $fname){
11737: $file_name = $path.$file_name;
11738: if ($group ne '') {
11739: $file_name = $group.$file_name;
11740: }
11741: $found_file = 1;
11742: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
11743: foreach my $lock (@lockers) {
11744: if (ref($lock) eq 'ARRAY') {
11745: my ($symb,$crsid) = @{$lock};
11746: if ($crsid eq $env{'request.course.id'}) {
11747: if (ref($navmap)) {
11748: my $res = $navmap->getBySymb($symb);
11749: foreach my $part (@{$res->parts()}) {
11750: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
11751: unless (($slot_status == $res->RESERVED) ||
11752: ($slot_status == $res->RESERVED_LOCATION)) {
11753: $locked_file = 1;
11754: }
11755: }
11756: } else {
11757: $locked_file = 1;
11758: }
11759: } else {
11760: $locked_file = 1;
11761: }
11762: }
11763: }
11764: } else {
11765: my @info = split(/\&/,$rest);
11766: my $currsize = $info[6]/1000;
11767: if ($currsize < $filesize) {
11768: my $extra = $filesize - $currsize;
11769: if (($current_disk_usage + $extra) > $disk_quota) {
11770: my $msg = '<p class="LC_warning">'.
11771: &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.',
11772: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
11773: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11774: $disk_quota,$current_disk_usage).'</p>';
11775: return ('will_exceed_quota',$msg);
11776: }
11777: }
11778: }
11779: }
11780: }
11781: }
11782: if (($current_disk_usage + $filesize) > $disk_quota){
11783: my $msg = '<p class="LC_warning">'.
11784: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
11785: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
11786: return ('will_exceed_quota',$msg);
11787: } elsif ($found_file) {
11788: if ($locked_file) {
11789: my $msg = '<p class="LC_warning">';
11790: $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>');
11791: $msg .= '</p>';
11792: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
11793: return ('file_locked',$msg);
11794: } else {
11795: my $msg = '<p class="LC_error">';
11796: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
11797: $msg .= '</p>';
11798: return ('existingfile',$msg);
11799: }
11800: }
11801: }
11802:
11803: sub check_for_traversal {
11804: my ($path,$url,$toplevel) = @_;
11805: my @parts=split(/\//,$path);
11806: my $cleanpath;
11807: my $fullpath = $url;
11808: for (my $i=0;$i<@parts;$i++) {
11809: next if ($parts[$i] eq '.');
11810: if ($parts[$i] eq '..') {
11811: $fullpath =~ s{([^/]+/)$}{};
11812: } else {
11813: $fullpath .= $parts[$i].'/';
11814: }
11815: }
11816: if ($fullpath =~ /^\Q$url\E(.*)$/) {
11817: $cleanpath = $1;
11818: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
11819: my $curr_toprel = $1;
11820: my @parts = split(/\//,$curr_toprel);
11821: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
11822: my @urlparts = split(/\//,$url_toprel);
11823: my $doubledots;
11824: my $startdiff = -1;
11825: for (my $i=0; $i<@urlparts; $i++) {
11826: if ($startdiff == -1) {
11827: unless ($urlparts[$i] eq $parts[$i]) {
11828: $startdiff = $i;
11829: $doubledots .= '../';
11830: }
11831: } else {
11832: $doubledots .= '../';
11833: }
11834: }
11835: if ($startdiff > -1) {
11836: $cleanpath = $doubledots;
11837: for (my $i=$startdiff; $i<@parts; $i++) {
11838: $cleanpath .= $parts[$i].'/';
11839: }
11840: }
11841: }
11842: $cleanpath =~ s{(/)$}{};
11843: return $cleanpath;
11844: }
11845:
11846: sub is_archive_file {
11847: my ($mimetype) = @_;
11848: if (($mimetype eq 'application/octet-stream') ||
11849: ($mimetype eq 'application/x-stuffit') ||
11850: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
11851: return 1;
11852: }
11853: return;
11854: }
11855:
11856: sub decompress_form {
11857: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11858: my %lt = &Apache::lonlocal::texthash (
11859: this => 'This file is an archive file.',
11860: camt => 'This file is a Camtasia archive file.',
11861: itsc => 'Its contents are as follows:',
11862: youm => 'You may wish to extract its contents.',
11863: extr => 'Extract contents',
11864: auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11865: proa => 'Process automatically?',
11866: yes => 'Yes',
11867: no => 'No',
11868: fold => 'Title for folder containing movie',
11869: movi => 'Title for page containing embedded movie',
11870: );
11871: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11872: my ($is_camtasia,$topdir,%toplevel,@paths);
11873: my $info = &list_archive_contents($fileloc,\@paths);
11874: if (@paths) {
11875: foreach my $path (@paths) {
11876: $path =~ s{^/}{};
11877: if ($path =~ m{^([^/]+)/$}) {
11878: $topdir = $1;
11879: }
11880: if ($path =~ m{^([^/]+)/}) {
11881: $toplevel{$1} = $path;
11882: } else {
11883: $toplevel{$path} = $path;
11884: }
11885: }
11886: }
11887: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11888: my @camtasia6 = ("$topdir/","$topdir/index.html",
11889: "$topdir/media/",
11890: "$topdir/media/$topdir.mp4",
11891: "$topdir/media/FirstFrame.png",
11892: "$topdir/media/player.swf",
11893: "$topdir/media/swfobject.js",
11894: "$topdir/media/expressInstall.swf");
11895: my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
11896: "$topdir/$topdir.mp4",
11897: "$topdir/$topdir\_config.xml",
11898: "$topdir/$topdir\_controller.swf",
11899: "$topdir/$topdir\_embed.css",
11900: "$topdir/$topdir\_First_Frame.png",
11901: "$topdir/$topdir\_player.html",
11902: "$topdir/$topdir\_Thumbnails.png",
11903: "$topdir/playerProductInstall.swf",
11904: "$topdir/scripts/",
11905: "$topdir/scripts/config_xml.js",
11906: "$topdir/scripts/handlebars.js",
11907: "$topdir/scripts/jquery-1.7.1.min.js",
11908: "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11909: "$topdir/scripts/modernizr.js",
11910: "$topdir/scripts/player-min.js",
11911: "$topdir/scripts/swfobject.js",
11912: "$topdir/skins/",
11913: "$topdir/skins/configuration_express.xml",
11914: "$topdir/skins/express_show/",
11915: "$topdir/skins/express_show/player-min.css",
11916: "$topdir/skins/express_show/spritesheet.png");
11917: my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
11918: "$topdir/$topdir.mp4",
11919: "$topdir/$topdir\_config.xml",
11920: "$topdir/$topdir\_controller.swf",
11921: "$topdir/$topdir\_embed.css",
11922: "$topdir/$topdir\_First_Frame.png",
11923: "$topdir/$topdir\_player.html",
11924: "$topdir/$topdir\_Thumbnails.png",
11925: "$topdir/playerProductInstall.swf",
11926: "$topdir/scripts/",
11927: "$topdir/scripts/config_xml.js",
11928: "$topdir/scripts/techsmith-smart-player.min.js",
11929: "$topdir/skins/",
11930: "$topdir/skins/configuration_express.xml",
11931: "$topdir/skins/express_show/",
11932: "$topdir/skins/express_show/spritesheet.min.css",
11933: "$topdir/skins/express_show/spritesheet.png",
11934: "$topdir/skins/express_show/techsmith-smart-player.min.css");
11935: my @diffs = &compare_arrays(\@paths,\@camtasia6);
11936: if (@diffs == 0) {
11937: $is_camtasia = 6;
11938: } else {
11939: @diffs = &compare_arrays(\@paths,\@camtasia8_1);
11940: if (@diffs == 0) {
11941: $is_camtasia = 8;
11942: } else {
11943: @diffs = &compare_arrays(\@paths,\@camtasia8_4);
11944: if (@diffs == 0) {
11945: $is_camtasia = 8;
11946: }
11947: }
11948: }
11949: }
11950: my $output;
11951: if ($is_camtasia) {
11952: $output = <<"ENDCAM";
11953: <script type="text/javascript" language="Javascript">
11954: // <![CDATA[
11955:
11956: function camtasiaToggle() {
11957: for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11958: if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11959: if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11960: document.getElementById('camtasia_titles').style.display='block';
11961: } else {
11962: document.getElementById('camtasia_titles').style.display='none';
11963: }
11964: }
11965: }
11966: return;
11967: }
11968:
11969: // ]]>
11970: </script>
11971: <p>$lt{'camt'}</p>
11972: ENDCAM
11973: } else {
11974: $output = '<p>'.$lt{'this'};
11975: if ($info eq '') {
11976: $output .= ' '.$lt{'youm'}.'</p>'."\n";
11977: } else {
11978: $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11979: '<div><pre>'.$info.'</pre></div>';
11980: }
11981: }
11982: $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11983: my $duplicates;
11984: my $num = 0;
11985: if (ref($dirlist) eq 'ARRAY') {
11986: foreach my $item (@{$dirlist}) {
11987: if (ref($item) eq 'ARRAY') {
11988: if (exists($toplevel{$item->[0]})) {
11989: $duplicates .=
11990: &start_data_table_row().
11991: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11992: 'value="0" checked="checked" />'.&mt('No').'</label>'.
11993: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '.
11994: 'value="1" />'.&mt('Yes').'</label>'.
11995: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11996: '<td>'.$item->[0].'</td>';
11997: if ($item->[2]) {
11998: $duplicates .= '<td>'.&mt('Directory').'</td>';
11999: } else {
12000: $duplicates .= '<td>'.&mt('File').'</td>';
12001: }
12002: $duplicates .= '<td>'.$item->[3].'</td>'.
12003: '<td>'.
12004: &Apache::lonlocal::locallocaltime($item->[4]).
12005: '</td>'.
12006: &end_data_table_row();
12007: $num ++;
12008: }
12009: }
12010: }
12011: }
12012: my $itemcount;
12013: if (@paths > 0) {
12014: $itemcount = scalar(@paths);
12015: } else {
12016: $itemcount = 1;
12017: }
12018: if ($is_camtasia) {
12019: $output .= $lt{'auto'}.'<br />'.
12020: '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12021: '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12022: $lt{'yes'}.'</label> <label>'.
12023: '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12024: $lt{'no'}.'</label></span><br />'.
12025: '<div id="camtasia_titles" style="display:block">'.
12026: &Apache::lonhtmlcommon::start_pick_box().
12027: &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12028: '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12029: &Apache::lonhtmlcommon::row_closure().
12030: &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12031: '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12032: &Apache::lonhtmlcommon::row_closure(1).
12033: &Apache::lonhtmlcommon::end_pick_box().
12034: '</div>';
12035: }
12036: $output .=
12037: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12038: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12039: "\n";
12040: if ($duplicates ne '') {
12041: $output .= '<p><span class="LC_warning">'.
12042: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.
12043: &start_data_table().
12044: &start_data_table_header_row().
12045: '<th>'.&mt('Overwrite?').'</th>'.
12046: '<th>'.&mt('Name').'</th>'.
12047: '<th>'.&mt('Type').'</th>'.
12048: '<th>'.&mt('Size').'</th>'.
12049: '<th>'.&mt('Last modified').'</th>'.
12050: &end_data_table_header_row().
12051: $duplicates.
12052: &end_data_table().
12053: '</p>';
12054: }
12055: $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12056: if (ref($hiddenelements) eq 'HASH') {
12057: foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12058: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12059: }
12060: }
12061: $output .= <<"END";
12062: <br />
12063: <input type="submit" name="decompress" value="$lt{'extr'}" />
12064: </form>
12065: $noextract
12066: END
12067: return $output;
12068: }
12069:
12070: sub decompression_utility {
12071: my ($program) = @_;
12072: my @utilities = ('tar','gunzip','bunzip2','unzip');
12073: my $location;
12074: if (grep(/^\Q$program\E$/,@utilities)) {
12075: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12076: '/usr/sbin/') {
12077: if (-x $dir.$program) {
12078: $location = $dir.$program;
12079: last;
12080: }
12081: }
12082: }
12083: return $location;
12084: }
12085:
12086: sub list_archive_contents {
12087: my ($file,$pathsref) = @_;
12088: my (@cmd,$output);
12089: my $needsregexp;
12090: if ($file =~ /\.zip$/) {
12091: @cmd = (&decompression_utility('unzip'),"-l");
12092: $needsregexp = 1;
12093: } elsif (($file =~ m/\.tar\.gz$/) ||
12094: ($file =~ /\.tgz$/)) {
12095: @cmd = (&decompression_utility('tar'),"-ztf");
12096: } elsif ($file =~ /\.tar\.bz2$/) {
12097: @cmd = (&decompression_utility('tar'),"-jtf");
12098: } elsif ($file =~ m|\.tar$|) {
12099: @cmd = (&decompression_utility('tar'),"-tf");
12100: }
12101: if (@cmd) {
12102: undef($!);
12103: undef($@);
12104: if (open(my $fh,"-|", @cmd, $file)) {
12105: while (my $line = <$fh>) {
12106: $output .= $line;
12107: chomp($line);
12108: my $item;
12109: if ($needsregexp) {
12110: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/);
12111: } else {
12112: $item = $line;
12113: }
12114: if ($item ne '') {
12115: unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12116: push(@{$pathsref},$item);
12117: }
12118: }
12119: }
12120: close($fh);
12121: }
12122: }
12123: return $output;
12124: }
12125:
12126: sub decompress_uploaded_file {
12127: my ($file,$dir) = @_;
12128: &Apache::lonnet::appenv({'cgi.file' => $file});
12129: &Apache::lonnet::appenv({'cgi.dir' => $dir});
12130: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12131: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12132: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12133: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12134: my $decompressed = $env{'cgi.decompressed'};
12135: &Apache::lonnet::delenv('cgi.file');
12136: &Apache::lonnet::delenv('cgi.dir');
12137: &Apache::lonnet::delenv('cgi.decompressed');
12138: return ($decompressed,$result);
12139: }
12140:
12141: sub process_decompression {
12142: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12143: unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
12144: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12145: &mt('Unexpected file path.').'</p>'."\n";
12146: }
12147: unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
12148: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12149: &mt('Unexpected course context.').'</p>'."\n";
12150: }
12151: unless ($file eq &Apache::lonnet::clean_filename($file)) {
12152: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12153: &mt('Filename contained unexpected characters.').'</p>'."\n";
12154: }
12155: my ($dir,$error,$warning,$output);
12156: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12157: $error = &mt('Filename not a supported archive file type.').
12158: '<br />'.&mt('Filename should end with one of: [_1].',
12159: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12160: } else {
12161: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12162: if ($docuhome eq 'no_host') {
12163: $error = &mt('Could not determine home server for course.');
12164: } else {
12165: my @ids=&Apache::lonnet::current_machine_ids();
12166: my $currdir = "$dir_root/$destination";
12167: if (grep(/^\Q$docuhome\E$/,@ids)) {
12168: $dir = &LONCAPA::propath($docudom,$docuname).
12169: "$dir_root/$destination";
12170: } else {
12171: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12172: "$dir_root/$docudom/$docuname/$destination";
12173: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12174: $error = &mt('Archive file not found.');
12175: }
12176: }
12177: my (@to_overwrite,@to_skip);
12178: if ($env{'form.archive_overwrite_total'} > 0) {
12179: my $total = $env{'form.archive_overwrite_total'};
12180: for (my $i=0; $i<$total; $i++) {
12181: if ($env{'form.archive_overwrite_'.$i} == 1) {
12182: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12183: } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12184: push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12185: }
12186: }
12187: }
12188: my $numskip = scalar(@to_skip);
12189: my $numoverwrite = scalar(@to_overwrite);
12190: if (($numskip) && (!$numoverwrite)) {
12191: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');
12192: } elsif ($dir eq '') {
12193: $error = &mt('Directory containing archive file unavailable.');
12194: } elsif (!$error) {
12195: my ($decompressed,$display);
12196: if (($numskip) || ($numoverwrite)) {
12197: my $tempdir = time.'_'.$$.int(rand(10000));
12198: mkdir("$dir/$tempdir",0755);
12199: if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
12200: ($decompressed,$display) =
12201: &decompress_uploaded_file($file,"$dir/$tempdir");
12202: foreach my $item (@to_skip) {
12203: if (($item ne '') && ($item !~ /\.\./)) {
12204: if (-f "$dir/$tempdir/$item") {
12205: unlink("$dir/$tempdir/$item");
12206: } elsif (-d "$dir/$tempdir/$item") {
12207: &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
12208: }
12209: }
12210: }
12211: foreach my $item (@to_overwrite) {
12212: if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
12213: if (($item ne '') && ($item !~ /\.\./)) {
12214: if (-f "$dir/$item") {
12215: unlink("$dir/$item");
12216: } elsif (-d "$dir/$item") {
12217: &File::Path::remove_tree("$dir/$item",{ safe => 1 });
12218: }
12219: &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
12220: }
12221: }
12222: }
12223: if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
12224: &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
12225: }
12226: }
12227: } else {
12228: ($decompressed,$display) =
12229: &decompress_uploaded_file($file,$dir);
12230: }
12231: if ($decompressed eq 'ok') {
12232: $output = '<p class="LC_info">'.
12233: &mt('Files extracted successfully from archive.').
12234: '</p>'."\n";
12235: my ($warning,$result,@contents);
12236: my ($newdirlistref,$newlisterror) =
12237: &Apache::lonnet::dirlist($currdir,$docudom,
12238: $docuname,1);
12239: my (%is_dir,%changes,@newitems);
12240: my $dirptr = 16384;
12241: if (ref($newdirlistref) eq 'ARRAY') {
12242: foreach my $dir_line (@{$newdirlistref}) {
12243: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12244: unless (($item =~ /^\.+$/) || ($item eq $file)) {
12245: push(@newitems,$item);
12246: if ($dirptr&$testdir) {
12247: $is_dir{$item} = 1;
12248: }
12249: $changes{$item} = 1;
12250: }
12251: }
12252: }
12253: if (keys(%changes) > 0) {
12254: foreach my $item (sort(@newitems)) {
12255: if ($changes{$item}) {
12256: push(@contents,$item);
12257: }
12258: }
12259: }
12260: if (@contents > 0) {
12261: my $wantform;
12262: unless ($env{'form.autoextract_camtasia'}) {
12263: $wantform = 1;
12264: }
12265: my (%children,%parent,%dirorder,%titles);
12266: my ($count,$datatable) = &get_extracted($docudom,$docuname,
12267: $currdir,\%is_dir,
12268: \%children,\%parent,
12269: \@contents,\%dirorder,
12270: \%titles,$wantform);
12271: if ($datatable ne '') {
12272: $output .= &archive_options_form('decompressed',$datatable,
12273: $count,$hiddenelem);
12274: my $startcount = 6;
12275: $output .= &archive_javascript($startcount,$count,
12276: \%titles,\%children);
12277: }
12278: if ($env{'form.autoextract_camtasia'}) {
12279: my $version = $env{'form.autoextract_camtasia'};
12280: my %displayed;
12281: my $total = 1;
12282: $env{'form.archive_directory'} = [];
12283: foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12284: my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12285: $path =~ s{/$}{};
12286: my $item;
12287: if ($path ne '') {
12288: $item = "$path/$titles{$i}";
12289: } else {
12290: $item = $titles{$i};
12291: }
12292: $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12293: if ($item eq $contents[0]) {
12294: push(@{$env{'form.archive_directory'}},$i);
12295: $env{'form.archive_'.$i} = 'display';
12296: $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12297: $displayed{'folder'} = $i;
12298: } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12299: (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
12300: $env{'form.archive_'.$i} = 'display';
12301: $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12302: $displayed{'web'} = $i;
12303: } else {
12304: if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12305: ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12306: ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12307: push(@{$env{'form.archive_directory'}},$i);
12308: }
12309: $env{'form.archive_'.$i} = 'dependency';
12310: }
12311: $total ++;
12312: }
12313: for (my $i=1; $i<$total; $i++) {
12314: next if ($i == $displayed{'web'});
12315: next if ($i == $displayed{'folder'});
12316: $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12317: }
12318: $env{'form.phase'} = 'decompress_cleanup';
12319: $env{'form.archivedelete'} = 1;
12320: $env{'form.archive_count'} = $total-1;
12321: $output .=
12322: &process_extracted_files('coursedocs',$docudom,
12323: $docuname,$destination,
12324: $dir_root,$hiddenelem);
12325: }
12326: } else {
12327: $warning = &mt('No new items extracted from archive file.');
12328: }
12329: } else {
12330: $output = $display;
12331: $error = &mt('An error occurred during extraction from the archive file.');
12332: }
12333: }
12334: }
12335: }
12336: if ($error) {
12337: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12338: $error.'</p>'."\n";
12339: }
12340: if ($warning) {
12341: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12342: }
12343: return $output;
12344: }
12345:
12346: sub get_extracted {
12347: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12348: $titles,$wantform) = @_;
12349: my $count = 0;
12350: my $depth = 0;
12351: my $datatable;
12352: my @hierarchy;
12353: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12354: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12355: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12356: foreach my $item (@{$contents}) {
12357: $count ++;
12358: @{$dirorder->{$count}} = @hierarchy;
12359: $titles->{$count} = $item;
12360: &archive_hierarchy($depth,$count,$parent,$children);
12361: if ($wantform) {
12362: $datatable .= &archive_row($is_dir->{$item},$item,
12363: $currdir,$depth,$count);
12364: }
12365: if ($is_dir->{$item}) {
12366: $depth ++;
12367: push(@hierarchy,$count);
12368: $parent->{$depth} = $count;
12369: $datatable .=
12370: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12371: \$depth,\$count,\@hierarchy,$dirorder,
12372: $children,$parent,$titles,$wantform);
12373: $depth --;
12374: pop(@hierarchy);
12375: }
12376: }
12377: return ($count,$datatable);
12378: }
12379:
12380: sub recurse_extracted_archive {
12381: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12382: $children,$parent,$titles,$wantform) = @_;
12383: my $result='';
12384: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12385: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12386: (ref($dirorder) eq 'HASH')) {
12387: return $result;
12388: }
12389: my $dirptr = 16384;
12390: my ($newdirlistref,$newlisterror) =
12391: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12392: if (ref($newdirlistref) eq 'ARRAY') {
12393: foreach my $dir_line (@{$newdirlistref}) {
12394: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12395: unless ($item =~ /^\.+$/) {
12396: $$count ++;
12397: @{$dirorder->{$$count}} = @{$hierarchy};
12398: $titles->{$$count} = $item;
12399: &archive_hierarchy($$depth,$$count,$parent,$children);
12400:
12401: my $is_dir;
12402: if ($dirptr&$testdir) {
12403: $is_dir = 1;
12404: }
12405: if ($wantform) {
12406: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12407: }
12408: if ($is_dir) {
12409: $$depth ++;
12410: push(@{$hierarchy},$$count);
12411: $parent->{$$depth} = $$count;
12412: $result .=
12413: &recurse_extracted_archive("$currdir/$item",$docudom,
12414: $docuname,$depth,$count,
12415: $hierarchy,$dirorder,$children,
12416: $parent,$titles,$wantform);
12417: $$depth --;
12418: pop(@{$hierarchy});
12419: }
12420: }
12421: }
12422: }
12423: return $result;
12424: }
12425:
12426: sub archive_hierarchy {
12427: my ($depth,$count,$parent,$children) =@_;
12428: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12429: if (exists($parent->{$depth})) {
12430: $children->{$parent->{$depth}} .= $count.':';
12431: }
12432: }
12433: return;
12434: }
12435:
12436: sub archive_row {
12437: my ($is_dir,$item,$currdir,$depth,$count) = @_;
12438: my ($name) = ($item =~ m{([^/]+)$});
12439: my %choices = &Apache::lonlocal::texthash (
12440: 'display' => 'Add as file',
12441: 'dependency' => 'Include as dependency',
12442: 'discard' => 'Discard',
12443: );
12444: if ($is_dir) {
12445: $choices{'display'} = &mt('Add as folder');
12446: }
12447: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12448: my $offset = 0;
12449: foreach my $action ('display','dependency','discard') {
12450: $offset ++;
12451: if ($action ne 'display') {
12452: $offset ++;
12453: }
12454: $output .= '<td><span class="LC_nobreak">'.
12455: '<label><input type="radio" name="archive_'.$count.
12456: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12457: my $text = $choices{$action};
12458: if ($is_dir) {
12459: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12460: if ($action eq 'display') {
12461: $text = &mt('Add as folder');
12462: }
12463: } else {
12464: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12465:
12466: }
12467: $output .= ' /> '.$choices{$action}.'</label></span>';
12468: if ($action eq 'dependency') {
12469: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12470: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '.
12471: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12472: '<option value=""></option>'."\n".
12473: '</select>'."\n".
12474: '</div>';
12475: } elsif ($action eq 'display') {
12476: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12477: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12478: '</div>';
12479: }
12480: $output .= '</td>';
12481: }
12482: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12483: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2);
12484: for (my $i=0; $i<$depth; $i++) {
12485: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12486: }
12487: if ($is_dir) {
12488: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n".
12489: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12490: } else {
12491: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12492: }
12493: $output .= ' '.$name.'</td>'."\n".
12494: &end_data_table_row();
12495: return $output;
12496: }
12497:
12498: sub archive_options_form {
12499: my ($form,$display,$count,$hiddenelem) = @_;
12500: my %lt = &Apache::lonlocal::texthash(
12501: perm => 'Permanently remove archive file?',
12502: hows => 'How should each extracted item be incorporated in the course?',
12503: cont => 'Content actions for all',
12504: addf => 'Add as folder/file',
12505: incd => 'Include as dependency for a displayed file',
12506: disc => 'Discard',
12507: no => 'No',
12508: yes => 'Yes',
12509: save => 'Save',
12510: );
12511: my $output = <<"END";
12512: <form name="$form" method="post" action="">
12513: <p><span class="LC_nobreak">$lt{'perm'}
12514: <label>
12515: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12516: </label>
12517:
12518: <label>
12519: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12520: </span>
12521: </p>
12522: <input type="hidden" name="phase" value="decompress_cleanup" />
12523: <br />$lt{'hows'}
12524: <div class="LC_columnSection">
12525: <fieldset>
12526: <legend>$lt{'cont'}</legend>
12527: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" />
12528: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12529: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12530: </fieldset>
12531: </div>
12532: END
12533: return $output.
12534: &start_data_table()."\n".
12535: $display."\n".
12536: &end_data_table()."\n".
12537: '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12538: $hiddenelem.
12539: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12540: '</form>';
12541: }
12542:
12543: sub archive_javascript {
12544: my ($startcount,$numitems,$titles,$children) = @_;
12545: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12546: my $maintitle = $env{'form.comment'};
12547: my $scripttag = <<START;
12548: <script type="text/javascript">
12549: // <![CDATA[
12550:
12551: function checkAll(form,prefix) {
12552: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$");
12553: for (var i=0; i < form.elements.length; i++) {
12554: var id = form.elements[i].id;
12555: if ((id != '') && (id != undefined)) {
12556: if (idstr.test(id)) {
12557: if (form.elements[i].type == 'radio') {
12558: form.elements[i].checked = true;
12559: var nostart = i-$startcount;
12560: var offset = nostart%7;
12561: var count = (nostart-offset)/7;
12562: dependencyCheck(form,count,offset);
12563: }
12564: }
12565: }
12566: }
12567: }
12568:
12569: function propagateCheck(form,count) {
12570: if (count > 0) {
12571: var startelement = $startcount + ((count-1) * 7);
12572: for (var j=1; j<6; j++) {
12573: if ((j != 2) && (j != 4)) {
12574: var item = startelement + j;
12575: if (form.elements[item].type == 'radio') {
12576: if (form.elements[item].checked) {
12577: containerCheck(form,count,j);
12578: break;
12579: }
12580: }
12581: }
12582: }
12583: }
12584: }
12585:
12586: numitems = $numitems
12587: var titles = new Array(numitems);
12588: var parents = new Array(numitems);
12589: for (var i=0; i<numitems; i++) {
12590: parents[i] = new Array;
12591: }
12592: var maintitle = '$maintitle';
12593:
12594: START
12595:
12596: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12597: my @contents = split(/:/,$children->{$container});
12598: for (my $i=0; $i<@contents; $i ++) {
12599: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12600: }
12601: }
12602:
12603: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12604: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12605: }
12606:
12607: $scripttag .= <<END;
12608:
12609: function containerCheck(form,count,offset) {
12610: if (count > 0) {
12611: dependencyCheck(form,count,offset);
12612: var item = (offset+$startcount)+7*(count-1);
12613: form.elements[item].checked = true;
12614: if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12615: if (parents[count].length > 0) {
12616: for (var j=0; j<parents[count].length; j++) {
12617: containerCheck(form,parents[count][j],offset);
12618: }
12619: }
12620: }
12621: }
12622: }
12623:
12624: function dependencyCheck(form,count,offset) {
12625: if (count > 0) {
12626: var chosen = (offset+$startcount)+7*(count-1);
12627: var depitem = $startcount + ((count-1) * 7) + 4;
12628: var currtype = form.elements[depitem].type;
12629: if (form.elements[chosen].value == 'dependency') {
12630: document.getElementById('arc_depon_'+count).style.display='block';
12631: form.elements[depitem].options.length = 0;
12632: form.elements[depitem].options[0] = new Option('Select','',true,true);
12633: for (var i=1; i<=numitems; i++) {
12634: if (i == count) {
12635: continue;
12636: }
12637: var startelement = $startcount + (i-1) * 7;
12638: for (var j=1; j<6; j++) {
12639: if ((j != 2) && (j!= 4)) {
12640: var item = startelement + j;
12641: if (form.elements[item].type == 'radio') {
12642: if (form.elements[item].checked) {
12643: if (form.elements[item].value == 'display') {
12644: var n = form.elements[depitem].options.length;
12645: form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
12646: }
12647: }
12648: }
12649: }
12650: }
12651: }
12652: } else {
12653: document.getElementById('arc_depon_'+count).style.display='none';
12654: form.elements[depitem].options.length = 0;
12655: form.elements[depitem].options[0] = new Option('Select','',true,true);
12656: }
12657: titleCheck(form,count,offset);
12658: }
12659: }
12660:
12661: function propagateSelect(form,count,offset) {
12662: if (count > 0) {
12663: var item = (1+offset+$startcount)+7*(count-1);
12664: var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
12665: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12666: if (parents[count].length > 0) {
12667: for (var j=0; j<parents[count].length; j++) {
12668: containerSelect(form,parents[count][j],offset,picked);
12669: }
12670: }
12671: }
12672: }
12673: }
12674:
12675: function containerSelect(form,count,offset,picked) {
12676: if (count > 0) {
12677: var item = (offset+$startcount)+7*(count-1);
12678: if (form.elements[item].type == 'radio') {
12679: if (form.elements[item].value == 'dependency') {
12680: if (form.elements[item+1].type == 'select-one') {
12681: for (var i=0; i<form.elements[item+1].options.length; i++) {
12682: if (form.elements[item+1].options[i].value == picked) {
12683: form.elements[item+1].selectedIndex = i;
12684: break;
12685: }
12686: }
12687: }
12688: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12689: if (parents[count].length > 0) {
12690: for (var j=0; j<parents[count].length; j++) {
12691: containerSelect(form,parents[count][j],offset,picked);
12692: }
12693: }
12694: }
12695: }
12696: }
12697: }
12698: }
12699:
12700: function titleCheck(form,count,offset) {
12701: if (count > 0) {
12702: var chosen = (offset+$startcount)+7*(count-1);
12703: var depitem = $startcount + ((count-1) * 7) + 2;
12704: var currtype = form.elements[depitem].type;
12705: if (form.elements[chosen].value == 'display') {
12706: document.getElementById('arc_title_'+count).style.display='block';
12707: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
12708: document.getElementById('archive_title_'+count).value=maintitle;
12709: }
12710: } else {
12711: document.getElementById('arc_title_'+count).style.display='none';
12712: if (currtype == 'text') {
12713: document.getElementById('archive_title_'+count).value='';
12714: }
12715: }
12716: }
12717: return;
12718: }
12719:
12720: // ]]>
12721: </script>
12722: END
12723: return $scripttag;
12724: }
12725:
12726: sub process_extracted_files {
12727: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
12728: my $numitems = $env{'form.archive_count'};
12729: return if ((!$numitems) || ($numitems =~ /\D/));
12730: my @ids=&Apache::lonnet::current_machine_ids();
12731: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
12732: %folders,%containers,%mapinner,%prompttofetch);
12733: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12734: if (grep(/^\Q$docuhome\E$/,@ids)) {
12735: $prefix = &LONCAPA::propath($docudom,$docuname);
12736: $pathtocheck = "$dir_root/$destination";
12737: $dir = $dir_root;
12738: $ishome = 1;
12739: } else {
12740: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
12741: $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
12742: $dir = "$dir_root/$docudom/$docuname";
12743: }
12744: my $currdir = "$dir_root/$destination";
12745: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
12746: if ($env{'form.folderpath'}) {
12747: my @items = split('&',$env{'form.folderpath'});
12748: $folders{'0'} = $items[-2];
12749: if ($env{'form.folderpath'} =~ /\:1$/) {
12750: $containers{'0'}='page';
12751: } else {
12752: $containers{'0'}='sequence';
12753: }
12754: }
12755: my @archdirs = &get_env_multiple('form.archive_directory');
12756: if ($numitems) {
12757: for (my $i=1; $i<=$numitems; $i++) {
12758: my $path = $env{'form.archive_content_'.$i};
12759: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
12760: my $item = $1;
12761: $toplevelitems{$item} = $i;
12762: if (grep(/^\Q$i\E$/,@archdirs)) {
12763: $is_dir{$item} = 1;
12764: }
12765: }
12766: }
12767: }
12768: my ($output,%children,%parent,%titles,%dirorder,$result);
12769: if (keys(%toplevelitems) > 0) {
12770: my @contents = sort(keys(%toplevelitems));
12771: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
12772: \%parent,\@contents,\%dirorder,\%titles);
12773: }
12774: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
12775: if ($numitems) {
12776: for (my $i=1; $i<=$numitems; $i++) {
12777: next if ($env{'form.archive_'.$i} eq 'dependency');
12778: my $path = $env{'form.archive_content_'.$i};
12779: if ($path =~ /^\Q$pathtocheck\E/) {
12780: if ($env{'form.archive_'.$i} eq 'discard') {
12781: if ($prefix ne '' && $path ne '') {
12782: if (-e $prefix.$path) {
12783: if ((@archdirs > 0) &&
12784: (grep(/^\Q$i\E$/,@archdirs))) {
12785: $todeletedir{$prefix.$path} = 1;
12786: } else {
12787: $todelete{$prefix.$path} = 1;
12788: }
12789: }
12790: }
12791: } elsif ($env{'form.archive_'.$i} eq 'display') {
12792: my ($docstitle,$title,$url,$outer);
12793: ($title) = ($path =~ m{/([^/]+)$});
12794: $docstitle = $env{'form.archive_title_'.$i};
12795: if ($docstitle eq '') {
12796: $docstitle = $title;
12797: }
12798: $outer = 0;
12799: if (ref($dirorder{$i}) eq 'ARRAY') {
12800: if (@{$dirorder{$i}} > 0) {
12801: foreach my $item (reverse(@{$dirorder{$i}})) {
12802: if ($env{'form.archive_'.$item} eq 'display') {
12803: $outer = $item;
12804: last;
12805: }
12806: }
12807: }
12808: }
12809: my ($errtext,$fatal) =
12810: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
12811: '/'.$folders{$outer}.'.'.
12812: $containers{$outer});
12813: next if ($fatal);
12814: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
12815: if ($context eq 'coursedocs') {
12816: $mapinner{$i} = time;
12817: $folders{$i} = 'default_'.$mapinner{$i};
12818: $containers{$i} = 'sequence';
12819: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12820: $folders{$i}.'.'.$containers{$i};
12821: my $newidx = &LONCAPA::map::getresidx();
12822: $LONCAPA::map::resources[$newidx]=
12823: $docstitle.':'.$url.':false:normal:res';
12824: push(@LONCAPA::map::order,$newidx);
12825: my ($outtext,$errtext) =
12826: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12827: $docuname.'/'.$folders{$outer}.
12828: '.'.$containers{$outer},1,1);
12829: $newseqid{$i} = $newidx;
12830: unless ($errtext) {
12831: $result .= '<li>'.&mt('Folder: [_1] added to course',
12832: &HTML::Entities::encode($docstitle,'<>&"'))..
12833: '</li>'."\n";
12834: }
12835: }
12836: } else {
12837: if ($context eq 'coursedocs') {
12838: my $newidx=&LONCAPA::map::getresidx();
12839: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12840: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
12841: $title;
12842: if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
12843: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
12844: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
12845: }
12846: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12847: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
12848: }
12849: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12850: if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
12851: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
12852: unless ($ishome) {
12853: my $fetch = "$newdest{$i}/$title";
12854: $fetch =~ s/^\Q$prefix$dir\E//;
12855: $prompttofetch{$fetch} = 1;
12856: }
12857: }
12858: }
12859: $LONCAPA::map::resources[$newidx]=
12860: $docstitle.':'.$url.':false:normal:res';
12861: push(@LONCAPA::map::order, $newidx);
12862: my ($outtext,$errtext)=
12863: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12864: $docuname.'/'.$folders{$outer}.
12865: '.'.$containers{$outer},1,1);
12866: unless ($errtext) {
12867: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
12868: $result .= '<li>'.&mt('File: [_1] added to course',
12869: &HTML::Entities::encode($docstitle,'<>&"')).
12870: '</li>'."\n";
12871: }
12872: }
12873: } else {
12874: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12875: &HTML::Entities::encode($path,'<>&"')).'<br />';
12876: }
12877: }
12878: }
12879: }
12880: } else {
12881: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12882: &HTML::Entities::encode($path,'<>&"')).'<br />';
12883: }
12884: }
12885: for (my $i=1; $i<=$numitems; $i++) {
12886: next unless ($env{'form.archive_'.$i} eq 'dependency');
12887: my $path = $env{'form.archive_content_'.$i};
12888: if ($path =~ /^\Q$pathtocheck\E/) {
12889: my ($title) = ($path =~ m{/([^/]+)$});
12890: $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
12891: if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
12892: if (ref($dirorder{$i}) eq 'ARRAY') {
12893: my ($itemidx,$fullpath,$relpath);
12894: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
12895: my $container = $dirorder{$referrer{$i}}->[-1];
12896: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
12897: if ($dirorder{$i}->[$j] eq $container) {
12898: $itemidx = $j;
12899: }
12900: }
12901: }
12902: if ($itemidx eq '') {
12903: $itemidx = 0;
12904: }
12905: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
12906: if ($mapinner{$referrer{$i}}) {
12907: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
12908: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12909: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12910: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12911: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12912: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12913: if (!-e $fullpath) {
12914: mkdir($fullpath,0755);
12915: }
12916: }
12917: } else {
12918: last;
12919: }
12920: }
12921: }
12922: } elsif ($newdest{$referrer{$i}}) {
12923: $fullpath = $newdest{$referrer{$i}};
12924: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12925: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12926: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12927: last;
12928: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12929: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12930: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12931: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12932: if (!-e $fullpath) {
12933: mkdir($fullpath,0755);
12934: }
12935: }
12936: } else {
12937: last;
12938: }
12939: }
12940: }
12941: if ($fullpath ne '') {
12942: if (-e "$prefix$path") {
12943: unless (rename("$prefix$path","$fullpath/$title")) {
12944: $warning .= &mt('Failed to rename dependency').'<br />';
12945: }
12946: }
12947: if (-e "$fullpath/$title") {
12948: my $showpath;
12949: if ($relpath ne '') {
12950: $showpath = "$relpath/$title";
12951: } else {
12952: $showpath = "/$title";
12953: }
12954: $result .= '<li>'.&mt('[_1] included as a dependency',
12955: &HTML::Entities::encode($showpath,'<>&"')).
12956: '</li>'."\n";
12957: unless ($ishome) {
12958: my $fetch = "$fullpath/$title";
12959: $fetch =~ s/^\Q$prefix$dir\E//;
12960: $prompttofetch{$fetch} = 1;
12961: }
12962: }
12963: }
12964: }
12965: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12966: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12967: &HTML::Entities::encode($path,'<>&"'),
12968: &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
12969: '<br />';
12970: }
12971: } else {
12972: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12973: &HTML::Entities::encode($path)).'<br />';
12974: }
12975: }
12976: if (keys(%todelete)) {
12977: foreach my $key (keys(%todelete)) {
12978: unlink($key);
12979: }
12980: }
12981: if (keys(%todeletedir)) {
12982: foreach my $key (keys(%todeletedir)) {
12983: rmdir($key);
12984: }
12985: }
12986: foreach my $dir (sort(keys(%is_dir))) {
12987: if (($pathtocheck ne '') && ($dir ne '')) {
12988: &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12989: }
12990: }
12991: if ($result ne '') {
12992: $output .= '<ul>'."\n".
12993: $result."\n".
12994: '</ul>';
12995: }
12996: unless ($ishome) {
12997: my $replicationfail;
12998: foreach my $item (keys(%prompttofetch)) {
12999: my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13000: unless ($fetchresult eq 'ok') {
13001: $replicationfail .= '<li>'.$item.'</li>'."\n";
13002: }
13003: }
13004: if ($replicationfail) {
13005: $output .= '<p class="LC_error">'.
13006: &mt('Course home server failed to retrieve:').'<ul>'.
13007: $replicationfail.
13008: '</ul></p>';
13009: }
13010: }
13011: } else {
13012: $warning = &mt('No items found in archive.');
13013: }
13014: if ($error) {
13015: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13016: $error.'</p>'."\n";
13017: }
13018: if ($warning) {
13019: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13020: }
13021: return $output;
13022: }
13023:
13024: sub cleanup_empty_dirs {
13025: my ($path) = @_;
13026: if (($path ne '') && (-d $path)) {
13027: if (opendir(my $dirh,$path)) {
13028: my @dircontents = grep(!/^\./,readdir($dirh));
13029: my $numitems = 0;
13030: foreach my $item (@dircontents) {
13031: if (-d "$path/$item") {
13032: &cleanup_empty_dirs("$path/$item");
13033: if (-e "$path/$item") {
13034: $numitems ++;
13035: }
13036: } else {
13037: $numitems ++;
13038: }
13039: }
13040: if ($numitems == 0) {
13041: rmdir($path);
13042: }
13043: closedir($dirh);
13044: }
13045: }
13046: return;
13047: }
13048:
13049: =pod
13050:
13051: =item * &get_folder_hierarchy()
13052:
13053: Provides hierarchy of names of folders/sub-folders containing the current
13054: item,
13055:
13056: Inputs: 3
13057: - $navmap - navmaps object
13058:
13059: - $map - url for map (either the trigger itself, or map containing
13060: the resource, which is the trigger).
13061:
13062: - $showitem - 1 => show title for map itself; 0 => do not show.
13063:
13064: Outputs: 1 @pathitems - array of folder/subfolder names.
13065:
13066: =cut
13067:
13068: sub get_folder_hierarchy {
13069: my ($navmap,$map,$showitem) = @_;
13070: my @pathitems;
13071: if (ref($navmap)) {
13072: my $mapres = $navmap->getResourceByUrl($map);
13073: if (ref($mapres)) {
13074: my $pcslist = $mapres->map_hierarchy();
13075: if ($pcslist ne '') {
13076: my @pcs = split(/,/,$pcslist);
13077: foreach my $pc (@pcs) {
13078: if ($pc == 1) {
13079: push(@pathitems,&mt('Main Content'));
13080: } else {
13081: my $res = $navmap->getByMapPc($pc);
13082: if (ref($res)) {
13083: my $title = $res->compTitle();
13084: $title =~ s/\W+/_/g;
13085: if ($title ne '') {
13086: push(@pathitems,$title);
13087: }
13088: }
13089: }
13090: }
13091: }
13092: if ($showitem) {
13093: if ($mapres->{ID} eq '0.0') {
13094: push(@pathitems,&mt('Main Content'));
13095: } else {
13096: my $maptitle = $mapres->compTitle();
13097: $maptitle =~ s/\W+/_/g;
13098: if ($maptitle ne '') {
13099: push(@pathitems,$maptitle);
13100: }
13101: }
13102: }
13103: }
13104: }
13105: return @pathitems;
13106: }
13107:
13108: =pod
13109:
13110: =item * &get_turnedin_filepath()
13111:
13112: Determines path in a user's portfolio file for storage of files uploaded
13113: to a specific essayresponse or dropbox item.
13114:
13115: Inputs: 3 required + 1 optional.
13116: $symb is symb for resource, $uname and $udom are for current user (required).
13117: $caller is optional (can be "submission", if routine is called when storing
13118: an upoaded file when "Submit Answer" button was pressed).
13119:
13120: Returns array containing $path and $multiresp.
13121: $path is path in portfolio. $multiresp is 1 if this resource contains more
13122: than one file upload item. Callers of routine should append partid as a
13123: subdirectory to $path in cases where $multiresp is 1.
13124:
13125: Called by: homework/essayresponse.pm and homework/structuretags.pm
13126:
13127: =cut
13128:
13129: sub get_turnedin_filepath {
13130: my ($symb,$uname,$udom,$caller) = @_;
13131: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13132: my $turnindir;
13133: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13134: $turnindir = $userhash{'turnindir'};
13135: my ($path,$multiresp);
13136: if ($turnindir eq '') {
13137: if ($caller eq 'submission') {
13138: $turnindir = &mt('turned in');
13139: $turnindir =~ s/\W+/_/g;
13140: my %newhash = (
13141: 'turnindir' => $turnindir,
13142: );
13143: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13144: }
13145: }
13146: if ($turnindir ne '') {
13147: $path = '/'.$turnindir.'/';
13148: my ($multipart,$turnin,@pathitems);
13149: my $navmap = Apache::lonnavmaps::navmap->new();
13150: if (defined($navmap)) {
13151: my $mapres = $navmap->getResourceByUrl($map);
13152: if (ref($mapres)) {
13153: my $pcslist = $mapres->map_hierarchy();
13154: if ($pcslist ne '') {
13155: foreach my $pc (split(/,/,$pcslist)) {
13156: my $res = $navmap->getByMapPc($pc);
13157: if (ref($res)) {
13158: my $title = $res->compTitle();
13159: $title =~ s/\W+/_/g;
13160: if ($title ne '') {
13161: if (($pc > 1) && (length($title) > 12)) {
13162: $title = substr($title,0,12);
13163: }
13164: push(@pathitems,$title);
13165: }
13166: }
13167: }
13168: }
13169: my $maptitle = $mapres->compTitle();
13170: $maptitle =~ s/\W+/_/g;
13171: if ($maptitle ne '') {
13172: if (length($maptitle) > 12) {
13173: $maptitle = substr($maptitle,0,12);
13174: }
13175: push(@pathitems,$maptitle);
13176: }
13177: unless ($env{'request.state'} eq 'construct') {
13178: my $res = $navmap->getBySymb($symb);
13179: if (ref($res)) {
13180: my $partlist = $res->parts();
13181: my $totaluploads = 0;
13182: if (ref($partlist) eq 'ARRAY') {
13183: foreach my $part (@{$partlist}) {
13184: my @types = $res->responseType($part);
13185: my @ids = $res->responseIds($part);
13186: for (my $i=0; $i < scalar(@ids); $i++) {
13187: if ($types[$i] eq 'essay') {
13188: my $partid = $part.'_'.$ids[$i];
13189: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13190: $totaluploads ++;
13191: }
13192: }
13193: }
13194: }
13195: if ($totaluploads > 1) {
13196: $multiresp = 1;
13197: }
13198: }
13199: }
13200: }
13201: } else {
13202: return;
13203: }
13204: } else {
13205: return;
13206: }
13207: my $restitle=&Apache::lonnet::gettitle($symb);
13208: $restitle =~ s/\W+/_/g;
13209: if ($restitle eq '') {
13210: $restitle = ($resurl =~ m{/[^/]+$});
13211: if ($restitle eq '') {
13212: $restitle = time;
13213: }
13214: }
13215: if (length($restitle) > 12) {
13216: $restitle = substr($restitle,0,12);
13217: }
13218: push(@pathitems,$restitle);
13219: $path .= join('/',@pathitems);
13220: }
13221: return ($path,$multiresp);
13222: }
13223:
13224: =pod
13225:
13226: =back
13227:
13228: =head1 CSV Upload/Handling functions
13229:
13230: =over 4
13231:
13232: =item * &upfile_store($r)
13233:
13234: Store uploaded file, $r should be the HTTP Request object,
13235: needs $env{'form.upfile'}
13236: returns $datatoken to be put into hidden field
13237:
13238: =cut
13239:
13240: sub upfile_store {
13241: my $r=shift;
13242: $env{'form.upfile'}=~s/\r/\n/gs;
13243: $env{'form.upfile'}=~s/\f/\n/gs;
13244: $env{'form.upfile'}=~s/\n+/\n/gs;
13245: $env{'form.upfile'}=~s/\n+$//gs;
13246:
13247: my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
13248: '_enroll_'.$env{'request.course.id'}.'_'.
13249: time.'_'.$$);
13250: return if ($datatoken eq '');
13251:
13252: {
13253: my $datafile = $r->dir_config('lonDaemons').
13254: '/tmp/'.$datatoken.'.tmp';
13255: if ( open(my $fh,'>',$datafile) ) {
13256: print $fh $env{'form.upfile'};
13257: close($fh);
13258: }
13259: }
13260: return $datatoken;
13261: }
13262:
13263: =pod
13264:
13265: =item * &load_tmp_file($r,$datatoken)
13266:
13267: Load uploaded file from tmp, $r should be the HTTP Request object,
13268: $datatoken is the name to assign to the temporary file.
13269: sets $env{'form.upfile'} to the contents of the file
13270:
13271: =cut
13272:
13273: sub load_tmp_file {
13274: my ($r,$datatoken) = @_;
13275: return if ($datatoken eq '');
13276: my @studentdata=();
13277: {
13278: my $studentfile = $r->dir_config('lonDaemons').
13279: '/tmp/'.$datatoken.'.tmp';
13280: if ( open(my $fh,'<',$studentfile) ) {
13281: @studentdata=<$fh>;
13282: close($fh);
13283: }
13284: }
13285: $env{'form.upfile'}=join('',@studentdata);
13286: }
13287:
13288: sub valid_datatoken {
13289: my ($datatoken) = @_;
13290: if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
13291: return $datatoken;
13292: }
13293: return;
13294: }
13295:
13296: =pod
13297:
13298: =item * &upfile_record_sep()
13299:
13300: Separate uploaded file into records
13301: returns array of records,
13302: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13303:
13304: =cut
13305:
13306: sub upfile_record_sep {
13307: if ($env{'form.upfiletype'} eq 'xml') {
13308: } else {
13309: my @records;
13310: foreach my $line (split(/\n/,$env{'form.upfile'})) {
13311: if ($line=~/^\s*$/) { next; }
13312: push(@records,$line);
13313: }
13314: return @records;
13315: }
13316: }
13317:
13318: =pod
13319:
13320: =item * &record_sep($record)
13321:
13322: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13323:
13324: =cut
13325:
13326: sub takeleft {
13327: my $index=shift;
13328: return substr('0000'.$index,-4,4);
13329: }
13330:
13331: sub record_sep {
13332: my $record=shift;
13333: my %components=();
13334: if ($env{'form.upfiletype'} eq 'xml') {
13335: } elsif ($env{'form.upfiletype'} eq 'space') {
13336: my $i=0;
13337: foreach my $field (split(/\s+/,$record)) {
13338: $field=~s/^(\"|\')//;
13339: $field=~s/(\"|\')$//;
13340: $components{&takeleft($i)}=$field;
13341: $i++;
13342: }
13343: } elsif ($env{'form.upfiletype'} eq 'tab') {
13344: my $i=0;
13345: foreach my $field (split(/\t/,$record)) {
13346: $field=~s/^(\"|\')//;
13347: $field=~s/(\"|\')$//;
13348: $components{&takeleft($i)}=$field;
13349: $i++;
13350: }
13351: } else {
13352: my $separator=',';
13353: if ($env{'form.upfiletype'} eq 'semisv') {
13354: $separator=';';
13355: }
13356: my $i=0;
13357: # the character we are looking for to indicate the end of a quote or a record
13358: my $looking_for=$separator;
13359: # do not add the characters to the fields
13360: my $ignore=0;
13361: # we just encountered a separator (or the beginning of the record)
13362: my $just_found_separator=1;
13363: # store the field we are working on here
13364: my $field='';
13365: # work our way through all characters in record
13366: foreach my $character ($record=~/(.)/g) {
13367: if ($character eq $looking_for) {
13368: if ($character ne $separator) {
13369: # Found the end of a quote, again looking for separator
13370: $looking_for=$separator;
13371: $ignore=1;
13372: } else {
13373: # Found a separator, store away what we got
13374: $components{&takeleft($i)}=$field;
13375: $i++;
13376: $just_found_separator=1;
13377: $ignore=0;
13378: $field='';
13379: }
13380: next;
13381: }
13382: # single or double quotation marks after a separator indicate beginning of a quote
13383: # we are now looking for the end of the quote and need to ignore separators
13384: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
13385: $looking_for=$character;
13386: next;
13387: }
13388: # ignore would be true after we reached the end of a quote
13389: if ($ignore) { next; }
13390: if (($just_found_separator) && ($character=~/\s/)) { next; }
13391: $field.=$character;
13392: $just_found_separator=0;
13393: }
13394: # catch the very last entry, since we never encountered the separator
13395: $components{&takeleft($i)}=$field;
13396: }
13397: return %components;
13398: }
13399:
13400: ######################################################
13401: ######################################################
13402:
13403: =pod
13404:
13405: =item * &upfile_select_html()
13406:
13407: Return HTML code to select a file from the users machine and specify
13408: the file type.
13409:
13410: =cut
13411:
13412: ######################################################
13413: ######################################################
13414: sub upfile_select_html {
13415: my %Types = (
13416: csv => &mt('CSV (comma separated values, spreadsheet)'),
13417: semisv => &mt('Semicolon separated values'),
13418: space => &mt('Space separated'),
13419: tab => &mt('Tabulator separated'),
13420: # xml => &mt('HTML/XML'),
13421: );
13422: my $Str = '<input type="file" name="upfile" size="50" />'.
13423: '<br />'.&mt('Type').': <select name="upfiletype">';
13424: foreach my $type (sort(keys(%Types))) {
13425: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13426: }
13427: $Str .= "</select>\n";
13428: return $Str;
13429: }
13430:
13431: sub get_samples {
13432: my ($records,$toget) = @_;
13433: my @samples=({});
13434: my $got=0;
13435: foreach my $rec (@$records) {
13436: my %temp = &record_sep($rec);
13437: if (! grep(/\S/, values(%temp))) { next; }
13438: if (%temp) {
13439: $samples[$got]=\%temp;
13440: $got++;
13441: if ($got == $toget) { last; }
13442: }
13443: }
13444: return \@samples;
13445: }
13446:
13447: ######################################################
13448: ######################################################
13449:
13450: =pod
13451:
13452: =item * &csv_print_samples($r,$records)
13453:
13454: Prints a table of sample values from each column uploaded $r is an
13455: Apache Request ref, $records is an arrayref from
13456: &Apache::loncommon::upfile_record_sep
13457:
13458: =cut
13459:
13460: ######################################################
13461: ######################################################
13462: sub csv_print_samples {
13463: my ($r,$records) = @_;
13464: my $samples = &get_samples($records,5);
13465:
13466: $r->print(&mt('Samples').'<br />'.&start_data_table().
13467: &start_data_table_header_row());
13468: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13469: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13470: $r->print(&end_data_table_header_row());
13471: foreach my $hash (@$samples) {
13472: $r->print(&start_data_table_row());
13473: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13474: $r->print('<td>');
13475: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13476: $r->print('</td>');
13477: }
13478: $r->print(&end_data_table_row());
13479: }
13480: $r->print(&end_data_table().'<br />'."\n");
13481: }
13482:
13483: ######################################################
13484: ######################################################
13485:
13486: =pod
13487:
13488: =item * &csv_print_select_table($r,$records,$d)
13489:
13490: Prints a table to create associations between values and table columns.
13491:
13492: $r is an Apache Request ref,
13493: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13494: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13495:
13496: =cut
13497:
13498: ######################################################
13499: ######################################################
13500: sub csv_print_select_table {
13501: my ($r,$records,$d) = @_;
13502: my $i=0;
13503: my $samples = &get_samples($records,1);
13504: $r->print(&mt('Associate columns with student attributes.')."\n".
13505: &start_data_table().&start_data_table_header_row().
13506: '<th>'.&mt('Attribute').'</th>'.
13507: '<th>'.&mt('Column').'</th>'.
13508: &end_data_table_header_row()."\n");
13509: foreach my $array_ref (@$d) {
13510: my ($value,$display,$defaultcol)=@{ $array_ref };
13511: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
13512:
13513: $r->print('<td><select name="f'.$i.'"'.
13514: ' onchange="javascript:flip(this.form,'.$i.');">');
13515: $r->print('<option value="none"></option>');
13516: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13517: $r->print('<option value="'.$sample.'"'.
13518: ($sample eq $defaultcol ? ' selected="selected" ' : '').
13519: '>'.&mt('Column [_1]',($sample+1)).'</option>');
13520: }
13521: $r->print('</select></td>'.&end_data_table_row()."\n");
13522: $i++;
13523: }
13524: $r->print(&end_data_table());
13525: $i--;
13526: return $i;
13527: }
13528:
13529: ######################################################
13530: ######################################################
13531:
13532: =pod
13533:
13534: =item * &csv_samples_select_table($r,$records,$d)
13535:
13536: Prints a table of sample values from the upload and can make associate samples to internal names.
13537:
13538: $r is an Apache Request ref,
13539: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13540: $d is an array of 2 element arrays (internal name, displayed name)
13541:
13542: =cut
13543:
13544: ######################################################
13545: ######################################################
13546: sub csv_samples_select_table {
13547: my ($r,$records,$d) = @_;
13548: my $i=0;
13549: #
13550: my $max_samples = 5;
13551: my $samples = &get_samples($records,$max_samples);
13552: $r->print(&start_data_table().
13553: &start_data_table_header_row().'<th>'.
13554: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13555: &end_data_table_header_row());
13556:
13557: foreach my $key (sort(keys(%{ $samples->[0] }))) {
13558: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13559: ' onchange="javascript:flip(this.form,'.$i.');">');
13560: foreach my $option (@$d) {
13561: my ($value,$display,$defaultcol)=@{ $option };
13562: $r->print('<option value="'.$value.'"'.
13563: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13564: $display.'</option>');
13565: }
13566: $r->print('</select></td><td>');
13567: foreach my $line (0..($max_samples-1)) {
13568: if (defined($samples->[$line]{$key})) {
13569: $r->print($samples->[$line]{$key}."<br />\n");
13570: }
13571: }
13572: $r->print('</td>'.&end_data_table_row());
13573: $i++;
13574: }
13575: $r->print(&end_data_table());
13576: $i--;
13577: return($i);
13578: }
13579:
13580: ######################################################
13581: ######################################################
13582:
13583: =pod
13584:
13585: =item * &clean_excel_name($name)
13586:
13587: Returns a replacement for $name which does not contain any illegal characters.
13588:
13589: =cut
13590:
13591: ######################################################
13592: ######################################################
13593: sub clean_excel_name {
13594: my ($name) = @_;
13595: $name =~ s/[:\*\?\/\\]//g;
13596: if (length($name) > 31) {
13597: $name = substr($name,0,31);
13598: }
13599: return $name;
13600: }
13601:
13602: =pod
13603:
13604: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13605:
13606: Returns either 1 or undef
13607:
13608: 1 if the part is to be hidden, undef if it is to be shown
13609:
13610: Arguments are:
13611:
13612: $id the id of the part to be checked
13613: $symb, optional the symb of the resource to check
13614: $udom, optional the domain of the user to check for
13615: $uname, optional the username of the user to check for
13616:
13617: =cut
13618:
13619: sub check_if_partid_hidden {
13620: my ($id,$symb,$udom,$uname) = @_;
13621: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13622: $symb,$udom,$uname);
13623: my $truth=1;
13624: #if the string starts with !, then the list is the list to show not hide
13625: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13626: my @hiddenlist=split(/,/,$hiddenparts);
13627: foreach my $checkid (@hiddenlist) {
13628: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13629: }
13630: return !$truth;
13631: }
13632:
13633:
13634: ############################################################
13635: ############################################################
13636:
13637: =pod
13638:
13639: =back
13640:
13641: =head1 cgi-bin script and graphing routines
13642:
13643: =over 4
13644:
13645: =item * &get_cgi_id()
13646:
13647: Inputs: none
13648:
13649: Returns an id which can be used to pass environment variables
13650: to various cgi-bin scripts. These environment variables will
13651: be removed from the users environment after a given time by
13652: the routine &Apache::lonnet::transfer_profile_to_env.
13653:
13654: =cut
13655:
13656: ############################################################
13657: ############################################################
13658: my $uniq=0;
13659: sub get_cgi_id {
13660: $uniq=($uniq+1)%100000;
13661: return (time.'_'.$$.'_'.$uniq);
13662: }
13663:
13664: ############################################################
13665: ############################################################
13666:
13667: =pod
13668:
13669: =item * &DrawBarGraph()
13670:
13671: Facilitates the plotting of data in a (stacked) bar graph.
13672: Puts plot definition data into the users environment in order for
13673: graph.png to plot it. Returns an <img> tag for the plot.
13674: The bars on the plot are labeled '1','2',...,'n'.
13675:
13676: Inputs:
13677:
13678: =over 4
13679:
13680: =item $Title: string, the title of the plot
13681:
13682: =item $xlabel: string, text describing the X-axis of the plot
13683:
13684: =item $ylabel: string, text describing the Y-axis of the plot
13685:
13686: =item $Max: scalar, the maximum Y value to use in the plot
13687: If $Max is < any data point, the graph will not be rendered.
13688:
13689: =item $colors: array ref holding the colors to be used for the data sets when
13690: they are plotted. If undefined, default values will be used.
13691:
13692: =item $labels: array ref holding the labels to use on the x-axis for the bars.
13693:
13694: =item @Values: An array of array references. Each array reference holds data
13695: to be plotted in a stacked bar chart.
13696:
13697: =item If the final element of @Values is a hash reference the key/value
13698: pairs will be added to the graph definition.
13699:
13700: =back
13701:
13702: Returns:
13703:
13704: An <img> tag which references graph.png and the appropriate identifying
13705: information for the plot.
13706:
13707: =cut
13708:
13709: ############################################################
13710: ############################################################
13711: sub DrawBarGraph {
13712: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
13713: #
13714: if (! defined($colors)) {
13715: $colors = ['#33ff00',
13716: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
13717: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
13718: ];
13719: }
13720: my $extra_settings = {};
13721: if (ref($Values[-1]) eq 'HASH') {
13722: $extra_settings = pop(@Values);
13723: }
13724: #
13725: my $identifier = &get_cgi_id();
13726: my $id = 'cgi.'.$identifier;
13727: if (! @Values || ref($Values[0]) ne 'ARRAY') {
13728: return '';
13729: }
13730: #
13731: my @Labels;
13732: if (defined($labels)) {
13733: @Labels = @$labels;
13734: } else {
13735: for (my $i=0;$i<@{$Values[0]};$i++) {
13736: push(@Labels,$i+1);
13737: }
13738: }
13739: #
13740: my $NumBars = scalar(@{$Values[0]});
13741: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
13742: my %ValuesHash;
13743: my $NumSets=1;
13744: foreach my $array (@Values) {
13745: next if (! ref($array));
13746: $ValuesHash{$id.'.data.'.$NumSets++} =
13747: join(',',@$array);
13748: }
13749: #
13750: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
13751: if ($NumBars < 3) {
13752: $width = 120+$NumBars*32;
13753: $xskip = 1;
13754: $bar_width = 30;
13755: } elsif ($NumBars < 5) {
13756: $width = 120+$NumBars*20;
13757: $xskip = 1;
13758: $bar_width = 20;
13759: } elsif ($NumBars < 10) {
13760: $width = 120+$NumBars*15;
13761: $xskip = 1;
13762: $bar_width = 15;
13763: } elsif ($NumBars <= 25) {
13764: $width = 120+$NumBars*11;
13765: $xskip = 5;
13766: $bar_width = 8;
13767: } elsif ($NumBars <= 50) {
13768: $width = 120+$NumBars*8;
13769: $xskip = 5;
13770: $bar_width = 4;
13771: } else {
13772: $width = 120+$NumBars*8;
13773: $xskip = 5;
13774: $bar_width = 4;
13775: }
13776: #
13777: $Max = 1 if ($Max < 1);
13778: if ( int($Max) < $Max ) {
13779: $Max++;
13780: $Max = int($Max);
13781: }
13782: $Title = '' if (! defined($Title));
13783: $xlabel = '' if (! defined($xlabel));
13784: $ylabel = '' if (! defined($ylabel));
13785: $ValuesHash{$id.'.title'} = &escape($Title);
13786: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
13787: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
13788: $ValuesHash{$id.'.y_max_value'} = $Max;
13789: $ValuesHash{$id.'.NumBars'} = $NumBars;
13790: $ValuesHash{$id.'.NumSets'} = $NumSets;
13791: $ValuesHash{$id.'.PlotType'} = 'bar';
13792: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
13793: $ValuesHash{$id.'.height'} = $height;
13794: $ValuesHash{$id.'.width'} = $width;
13795: $ValuesHash{$id.'.xskip'} = $xskip;
13796: $ValuesHash{$id.'.bar_width'} = $bar_width;
13797: $ValuesHash{$id.'.labels'} = join(',',@Labels);
13798: #
13799: # Deal with other parameters
13800: while (my ($key,$value) = each(%$extra_settings)) {
13801: $ValuesHash{$id.'.'.$key} = $value;
13802: }
13803: #
13804: &Apache::lonnet::appenv(\%ValuesHash);
13805: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13806: }
13807:
13808: ############################################################
13809: ############################################################
13810:
13811: =pod
13812:
13813: =item * &DrawXYGraph()
13814:
13815: Facilitates the plotting of data in an XY graph.
13816: Puts plot definition data into the users environment in order for
13817: graph.png to plot it. Returns an <img> tag for the plot.
13818:
13819: Inputs:
13820:
13821: =over 4
13822:
13823: =item $Title: string, the title of the plot
13824:
13825: =item $xlabel: string, text describing the X-axis of the plot
13826:
13827: =item $ylabel: string, text describing the Y-axis of the plot
13828:
13829: =item $Max: scalar, the maximum Y value to use in the plot
13830: If $Max is < any data point, the graph will not be rendered.
13831:
13832: =item $colors: Array ref containing the hex color codes for the data to be
13833: plotted in. If undefined, default values will be used.
13834:
13835: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13836:
13837: =item $Ydata: Array ref containing Array refs.
13838: Each of the contained arrays will be plotted as a separate curve.
13839:
13840: =item %Values: hash indicating or overriding any default values which are
13841: passed to graph.png.
13842: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13843:
13844: =back
13845:
13846: Returns:
13847:
13848: An <img> tag which references graph.png and the appropriate identifying
13849: information for the plot.
13850:
13851: =cut
13852:
13853: ############################################################
13854: ############################################################
13855: sub DrawXYGraph {
13856: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
13857: #
13858: # Create the identifier for the graph
13859: my $identifier = &get_cgi_id();
13860: my $id = 'cgi.'.$identifier;
13861: #
13862: $Title = '' if (! defined($Title));
13863: $xlabel = '' if (! defined($xlabel));
13864: $ylabel = '' if (! defined($ylabel));
13865: my %ValuesHash =
13866: (
13867: $id.'.title' => &escape($Title),
13868: $id.'.xlabel' => &escape($xlabel),
13869: $id.'.ylabel' => &escape($ylabel),
13870: $id.'.y_max_value'=> $Max,
13871: $id.'.labels' => join(',',@$Xlabels),
13872: $id.'.PlotType' => 'XY',
13873: );
13874: #
13875: if (defined($colors) && ref($colors) eq 'ARRAY') {
13876: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
13877: }
13878: #
13879: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
13880: return '';
13881: }
13882: my $NumSets=1;
13883: foreach my $array (@{$Ydata}){
13884: next if (! ref($array));
13885: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13886: }
13887: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
13888: #
13889: # Deal with other parameters
13890: while (my ($key,$value) = each(%Values)) {
13891: $ValuesHash{$id.'.'.$key} = $value;
13892: }
13893: #
13894: &Apache::lonnet::appenv(\%ValuesHash);
13895: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13896: }
13897:
13898: ############################################################
13899: ############################################################
13900:
13901: =pod
13902:
13903: =item * &DrawXYYGraph()
13904:
13905: Facilitates the plotting of data in an XY graph with two Y axes.
13906: Puts plot definition data into the users environment in order for
13907: graph.png to plot it. Returns an <img> tag for the plot.
13908:
13909: Inputs:
13910:
13911: =over 4
13912:
13913: =item $Title: string, the title of the plot
13914:
13915: =item $xlabel: string, text describing the X-axis of the plot
13916:
13917: =item $ylabel: string, text describing the Y-axis of the plot
13918:
13919: =item $colors: Array ref containing the hex color codes for the data to be
13920: plotted in. If undefined, default values will be used.
13921:
13922: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13923:
13924: =item $Ydata1: The first data set
13925:
13926: =item $Min1: The minimum value of the left Y-axis
13927:
13928: =item $Max1: The maximum value of the left Y-axis
13929:
13930: =item $Ydata2: The second data set
13931:
13932: =item $Min2: The minimum value of the right Y-axis
13933:
13934: =item $Max2: The maximum value of the left Y-axis
13935:
13936: =item %Values: hash indicating or overriding any default values which are
13937: passed to graph.png.
13938: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13939:
13940: =back
13941:
13942: Returns:
13943:
13944: An <img> tag which references graph.png and the appropriate identifying
13945: information for the plot.
13946:
13947: =cut
13948:
13949: ############################################################
13950: ############################################################
13951: sub DrawXYYGraph {
13952: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13953: $Ydata2,$Min2,$Max2,%Values)=@_;
13954: #
13955: # Create the identifier for the graph
13956: my $identifier = &get_cgi_id();
13957: my $id = 'cgi.'.$identifier;
13958: #
13959: $Title = '' if (! defined($Title));
13960: $xlabel = '' if (! defined($xlabel));
13961: $ylabel = '' if (! defined($ylabel));
13962: my %ValuesHash =
13963: (
13964: $id.'.title' => &escape($Title),
13965: $id.'.xlabel' => &escape($xlabel),
13966: $id.'.ylabel' => &escape($ylabel),
13967: $id.'.labels' => join(',',@$Xlabels),
13968: $id.'.PlotType' => 'XY',
13969: $id.'.NumSets' => 2,
13970: $id.'.two_axes' => 1,
13971: $id.'.y1_max_value' => $Max1,
13972: $id.'.y1_min_value' => $Min1,
13973: $id.'.y2_max_value' => $Max2,
13974: $id.'.y2_min_value' => $Min2,
13975: );
13976: #
13977: if (defined($colors) && ref($colors) eq 'ARRAY') {
13978: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
13979: }
13980: #
13981: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13982: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13983: return '';
13984: }
13985: my $NumSets=1;
13986: foreach my $array ($Ydata1,$Ydata2){
13987: next if (! ref($array));
13988: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13989: }
13990: #
13991: # Deal with other parameters
13992: while (my ($key,$value) = each(%Values)) {
13993: $ValuesHash{$id.'.'.$key} = $value;
13994: }
13995: #
13996: &Apache::lonnet::appenv(\%ValuesHash);
13997: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13998: }
13999:
14000: ############################################################
14001: ############################################################
14002:
14003: =pod
14004:
14005: =back
14006:
14007: =head1 Statistics helper routines?
14008:
14009: Bad place for them but what the hell.
14010:
14011: =over 4
14012:
14013: =item * &chartlink()
14014:
14015: Returns a link to the chart for a specific student.
14016:
14017: Inputs:
14018:
14019: =over 4
14020:
14021: =item $linktext: The text of the link
14022:
14023: =item $sname: The students username
14024:
14025: =item $sdomain: The students domain
14026:
14027: =back
14028:
14029: =back
14030:
14031: =cut
14032:
14033: ############################################################
14034: ############################################################
14035: sub chartlink {
14036: my ($linktext, $sname, $sdomain) = @_;
14037: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14038: '&SelectedStudent='.&escape($sname.':'.$sdomain).
14039: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
14040: '">'.$linktext.'</a>';
14041: }
14042:
14043: #######################################################
14044: #######################################################
14045:
14046: =pod
14047:
14048: =head1 Course Environment Routines
14049:
14050: =over 4
14051:
14052: =item * &restore_course_settings()
14053:
14054: =item * &store_course_settings()
14055:
14056: Restores/Store indicated form parameters from the course environment.
14057: Will not overwrite existing values of the form parameters.
14058:
14059: Inputs:
14060: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14061:
14062: a hash ref describing the data to be stored. For example:
14063:
14064: %Save_Parameters = ('Status' => 'scalar',
14065: 'chartoutputmode' => 'scalar',
14066: 'chartoutputdata' => 'scalar',
14067: 'Section' => 'array',
14068: 'Group' => 'array',
14069: 'StudentData' => 'array',
14070: 'Maps' => 'array');
14071:
14072: Returns: both routines return nothing
14073:
14074: =back
14075:
14076: =cut
14077:
14078: #######################################################
14079: #######################################################
14080: sub store_course_settings {
14081: return &store_settings($env{'request.course.id'},@_);
14082: }
14083:
14084: sub store_settings {
14085: # save to the environment
14086: # appenv the same items, just to be safe
14087: my $udom = $env{'user.domain'};
14088: my $uname = $env{'user.name'};
14089: my ($context,$prefix,$Settings) = @_;
14090: my %SaveHash;
14091: my %AppHash;
14092: while (my ($setting,$type) = each(%$Settings)) {
14093: my $basename = join('.','internal',$context,$prefix,$setting);
14094: my $envname = 'environment.'.$basename;
14095: if (exists($env{'form.'.$setting})) {
14096: # Save this value away
14097: if ($type eq 'scalar' &&
14098: (! exists($env{$envname}) ||
14099: $env{$envname} ne $env{'form.'.$setting})) {
14100: $SaveHash{$basename} = $env{'form.'.$setting};
14101: $AppHash{$envname} = $env{'form.'.$setting};
14102: } elsif ($type eq 'array') {
14103: my $stored_form;
14104: if (ref($env{'form.'.$setting})) {
14105: $stored_form = join(',',
14106: map {
14107: &escape($_);
14108: } sort(@{$env{'form.'.$setting}}));
14109: } else {
14110: $stored_form =
14111: &escape($env{'form.'.$setting});
14112: }
14113: # Determine if the array contents are the same.
14114: if ($stored_form ne $env{$envname}) {
14115: $SaveHash{$basename} = $stored_form;
14116: $AppHash{$envname} = $stored_form;
14117: }
14118: }
14119: }
14120: }
14121: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14122: $udom,$uname);
14123: if ($put_result !~ /^(ok|delayed)/) {
14124: &Apache::lonnet::logthis('unable to save form parameters, '.
14125: 'got error:'.$put_result);
14126: }
14127: # Make sure these settings stick around in this session, too
14128: &Apache::lonnet::appenv(\%AppHash);
14129: return;
14130: }
14131:
14132: sub restore_course_settings {
14133: return &restore_settings($env{'request.course.id'},@_);
14134: }
14135:
14136: sub restore_settings {
14137: my ($context,$prefix,$Settings) = @_;
14138: while (my ($setting,$type) = each(%$Settings)) {
14139: next if (exists($env{'form.'.$setting}));
14140: my $envname = 'environment.internal.'.$context.'.'.$prefix.
14141: '.'.$setting;
14142: if (exists($env{$envname})) {
14143: if ($type eq 'scalar') {
14144: $env{'form.'.$setting} = $env{$envname};
14145: } elsif ($type eq 'array') {
14146: $env{'form.'.$setting} = [
14147: map {
14148: &unescape($_);
14149: } split(',',$env{$envname})
14150: ];
14151: }
14152: }
14153: }
14154: }
14155:
14156: #######################################################
14157: #######################################################
14158:
14159: =pod
14160:
14161: =head1 Domain E-mail Routines
14162:
14163: =over 4
14164:
14165: =item * &build_recipient_list()
14166:
14167: Build recipient lists for following types of e-mail:
14168: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14169: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14170: module change checking, student/employee ID conflict checks, as
14171: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14172: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14173:
14174: Inputs:
14175: defmail (scalar - email address of default recipient),
14176: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14177: requestsmail, updatesmail, or idconflictsmail).
14178:
14179: defdom (domain for which to retrieve configuration settings),
14180:
14181: origmail (scalar - email address of recipient from loncapa.conf,
14182: i.e., predates configuration by DC via domainprefs.pm
14183:
14184: $requname username of requester (if mailing type is helpdeskmail)
14185:
14186: $requdom domain of requester (if mailing type is helpdeskmail)
14187:
14188: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
14189:
14190: Returns: comma separated list of addresses to which to send e-mail.
14191:
14192: =back
14193:
14194: =cut
14195:
14196: ############################################################
14197: ############################################################
14198: sub build_recipient_list {
14199: my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
14200: my @recipients;
14201: my ($otheremails,$lastresort,$allbcc,$addtext);
14202: my %domconfig =
14203: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14204: if (ref($domconfig{'contacts'}) eq 'HASH') {
14205: if (exists($domconfig{'contacts'}{$mailing})) {
14206: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14207: my @contacts = ('adminemail','supportemail');
14208: foreach my $item (@contacts) {
14209: if ($domconfig{'contacts'}{$mailing}{$item}) {
14210: my $addr = $domconfig{'contacts'}{$item};
14211: if (!grep(/^\Q$addr\E$/,@recipients)) {
14212: push(@recipients,$addr);
14213: }
14214: }
14215: }
14216: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14217: if ($mailing eq 'helpdeskmail') {
14218: if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
14219: my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
14220: my @ok_bccs;
14221: foreach my $bcc (@bccs) {
14222: $bcc =~ s/^\s+//g;
14223: $bcc =~ s/\s+$//g;
14224: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14225: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14226: push(@ok_bccs,$bcc);
14227: }
14228: }
14229: }
14230: if (@ok_bccs > 0) {
14231: $allbcc = join(', ',@ok_bccs);
14232: }
14233: }
14234: $addtext = $domconfig{'contacts'}{$mailing}{'include'};
14235: }
14236: }
14237: } elsif ($origmail ne '') {
14238: $lastresort = $origmail;
14239: }
14240: if ($mailing eq 'helpdeskmail') {
14241: if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
14242: (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
14243: my ($inststatus,$inststatus_checked);
14244: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
14245: ($env{'user.domain'} ne 'public')) {
14246: $inststatus_checked = 1;
14247: $inststatus = $env{'environment.inststatus'};
14248: }
14249: unless ($inststatus_checked) {
14250: if (($requname ne '') && ($requdom ne '')) {
14251: if (($requname =~ /^$match_username$/) &&
14252: ($requdom =~ /^$match_domain$/) &&
14253: (&Apache::lonnet::domain($requdom))) {
14254: my $requhome = &Apache::lonnet::homeserver($requname,
14255: $requdom);
14256: unless ($requhome eq 'no_host') {
14257: my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
14258: $inststatus = $userenv{'inststatus'};
14259: $inststatus_checked = 1;
14260: }
14261: }
14262: }
14263: }
14264: unless ($inststatus_checked) {
14265: if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
14266: my %srch = (srchby => 'email',
14267: srchdomain => $defdom,
14268: srchterm => $reqemail,
14269: srchtype => 'exact');
14270: my %srch_results = &Apache::lonnet::usersearch(\%srch);
14271: foreach my $uname (keys(%srch_results)) {
14272: if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14273: $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14274: $inststatus_checked = 1;
14275: last;
14276: }
14277: }
14278: unless ($inststatus_checked) {
14279: my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
14280: if ($dirsrchres eq 'ok') {
14281: foreach my $uname (keys(%srch_results)) {
14282: if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14283: $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14284: $inststatus_checked = 1;
14285: last;
14286: }
14287: }
14288: }
14289: }
14290: }
14291: }
14292: if ($inststatus ne '') {
14293: foreach my $status (split(/\:/,$inststatus)) {
14294: if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
14295: my @contacts = ('adminemail','supportemail');
14296: foreach my $item (@contacts) {
14297: if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
14298: my $addr = $domconfig{'contacts'}{'overrides'}{$status};
14299: if (!grep(/^\Q$addr\E$/,@recipients)) {
14300: push(@recipients,$addr);
14301: }
14302: }
14303: }
14304: $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
14305: if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
14306: my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
14307: my @ok_bccs;
14308: foreach my $bcc (@bccs) {
14309: $bcc =~ s/^\s+//g;
14310: $bcc =~ s/\s+$//g;
14311: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14312: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14313: push(@ok_bccs,$bcc);
14314: }
14315: }
14316: }
14317: if (@ok_bccs > 0) {
14318: $allbcc = join(', ',@ok_bccs);
14319: }
14320: }
14321: $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
14322: last;
14323: }
14324: }
14325: }
14326: }
14327: }
14328: } elsif ($origmail ne '') {
14329: $lastresort = $origmail;
14330: }
14331: if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
14332: unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
14333: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
14334: my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
14335: my %what = (
14336: perlvar => 1,
14337: );
14338: my $primary = &Apache::lonnet::domain($defdom,'primary');
14339: if ($primary) {
14340: my $gotaddr;
14341: my ($result,$returnhash) =
14342: &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
14343: if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
14344: if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
14345: $lastresort = $returnhash->{'lonSupportEMail'};
14346: $gotaddr = 1;
14347: }
14348: }
14349: unless ($gotaddr) {
14350: my $uintdom = &Apache::lonnet::internet_dom($primary);
14351: my $intdom = &Apache::lonnet::internet_dom($lonhost);
14352: unless ($uintdom eq $intdom) {
14353: my %domconfig =
14354: &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
14355: if (ref($domconfig{'contacts'}) eq 'HASH') {
14356: if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
14357: my @contacts = ('adminemail','supportemail');
14358: foreach my $item (@contacts) {
14359: if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
14360: my $addr = $domconfig{'contacts'}{$item};
14361: if (!grep(/^\Q$addr\E$/,@recipients)) {
14362: push(@recipients,$addr);
14363: }
14364: }
14365: }
14366: if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
14367: $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
14368: }
14369: if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
14370: my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
14371: my @ok_bccs;
14372: foreach my $bcc (@bccs) {
14373: $bcc =~ s/^\s+//g;
14374: $bcc =~ s/\s+$//g;
14375: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14376: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14377: push(@ok_bccs,$bcc);
14378: }
14379: }
14380: }
14381: if (@ok_bccs > 0) {
14382: $allbcc = join(', ',@ok_bccs);
14383: }
14384: }
14385: $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
14386: }
14387: }
14388: }
14389: }
14390: }
14391: }
14392: }
14393: if (defined($defmail)) {
14394: if ($defmail ne '') {
14395: push(@recipients,$defmail);
14396: }
14397: }
14398: if ($otheremails) {
14399: my @others;
14400: if ($otheremails =~ /,/) {
14401: @others = split(/,/,$otheremails);
14402: } else {
14403: push(@others,$otheremails);
14404: }
14405: foreach my $addr (@others) {
14406: if (!grep(/^\Q$addr\E$/,@recipients)) {
14407: push(@recipients,$addr);
14408: }
14409: }
14410: }
14411: if ($mailing eq 'helpdeskmail') {
14412: if ((!@recipients) && ($lastresort ne '')) {
14413: push(@recipients,$lastresort);
14414: }
14415: } elsif ($lastresort ne '') {
14416: if (!grep(/^\Q$lastresort\E$/,@recipients)) {
14417: push(@recipients,$lastresort);
14418: }
14419: }
14420: my $recipientlist = join(',',@recipients);
14421: if (wantarray) {
14422: return ($recipientlist,$allbcc,$addtext);
14423: } else {
14424: return $recipientlist;
14425: }
14426: }
14427:
14428: ############################################################
14429: ############################################################
14430:
14431: =pod
14432:
14433: =head1 Course Catalog Routines
14434:
14435: =over 4
14436:
14437: =item * &gather_categories()
14438:
14439: Converts category definitions - keys of categories hash stored in
14440: coursecategories in configuration.db on the primary library server in a
14441: domain - to an array. Also generates javascript and idx hash used to
14442: generate Domain Coordinator interface for editing Course Categories.
14443:
14444: Inputs:
14445:
14446: categories (reference to hash of category definitions).
14447:
14448: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14449: categories and subcategories).
14450:
14451: idx (reference to hash of counters used in Domain Coordinator interface for
14452: editing Course Categories).
14453:
14454: jsarray (reference to array of categories used to create Javascript arrays for
14455: Domain Coordinator interface for editing Course Categories).
14456:
14457: Returns: nothing
14458:
14459: Side effects: populates cats, idx and jsarray.
14460:
14461: =cut
14462:
14463: sub gather_categories {
14464: my ($categories,$cats,$idx,$jsarray) = @_;
14465: my %counters;
14466: my $num = 0;
14467: foreach my $item (keys(%{$categories})) {
14468: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
14469: if ($container eq '' && $depth == 0) {
14470: $cats->[$depth][$categories->{$item}] = $cat;
14471: } else {
14472: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
14473: }
14474: my ($escitem,$tail) = split(/:/,$item,2);
14475: if ($counters{$tail} eq '') {
14476: $counters{$tail} = $num;
14477: $num ++;
14478: }
14479: if (ref($idx) eq 'HASH') {
14480: $idx->{$item} = $counters{$tail};
14481: }
14482: if (ref($jsarray) eq 'ARRAY') {
14483: push(@{$jsarray->[$counters{$tail}]},$item);
14484: }
14485: }
14486: return;
14487: }
14488:
14489: =pod
14490:
14491: =item * &extract_categories()
14492:
14493: Used to generate breadcrumb trails for course categories.
14494:
14495: Inputs:
14496:
14497: categories (reference to hash of category definitions).
14498:
14499: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14500: categories and subcategories).
14501:
14502: trails (reference to array of breacrumb trails for each category).
14503:
14504: allitems (reference to hash - key is category key
14505: (format: escaped(name):escaped(parent category):depth in hierarchy).
14506:
14507: idx (reference to hash of counters used in Domain Coordinator interface for
14508: editing Course Categories).
14509:
14510: jsarray (reference to array of categories used to create Javascript arrays for
14511: Domain Coordinator interface for editing Course Categories).
14512:
14513: subcats (reference to hash of arrays containing all subcategories within each
14514: category, -recursive)
14515:
14516: maxd (reference to hash used to hold max depth for all top-level categories).
14517:
14518: Returns: nothing
14519:
14520: Side effects: populates trails and allitems hash references.
14521:
14522: =cut
14523:
14524: sub extract_categories {
14525: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
14526: if (ref($categories) eq 'HASH') {
14527: &gather_categories($categories,$cats,$idx,$jsarray);
14528: if (ref($cats->[0]) eq 'ARRAY') {
14529: for (my $i=0; $i<@{$cats->[0]}; $i++) {
14530: my $name = $cats->[0][$i];
14531: my $item = &escape($name).'::0';
14532: my $trailstr;
14533: if ($name eq 'instcode') {
14534: $trailstr = &mt('Official courses (with institutional codes)');
14535: } elsif ($name eq 'communities') {
14536: $trailstr = &mt('Communities');
14537: } else {
14538: $trailstr = $name;
14539: }
14540: if ($allitems->{$item} eq '') {
14541: push(@{$trails},$trailstr);
14542: $allitems->{$item} = scalar(@{$trails})-1;
14543: }
14544: my @parents = ($name);
14545: if (ref($cats->[1]{$name}) eq 'ARRAY') {
14546: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
14547: my $category = $cats->[1]{$name}[$j];
14548: if (ref($subcats) eq 'HASH') {
14549: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
14550: }
14551: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
14552: }
14553: } else {
14554: if (ref($subcats) eq 'HASH') {
14555: $subcats->{$item} = [];
14556: }
14557: if (ref($maxd) eq 'HASH') {
14558: $maxd->{$name} = 1;
14559: }
14560: }
14561: }
14562: }
14563: }
14564: return;
14565: }
14566:
14567: =pod
14568:
14569: =item * &recurse_categories()
14570:
14571: Recursively used to generate breadcrumb trails for course categories.
14572:
14573: Inputs:
14574:
14575: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14576: categories and subcategories).
14577:
14578: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
14579:
14580: category (current course category, for which breadcrumb trail is being generated).
14581:
14582: trails (reference to array of breadcrumb trails for each category).
14583:
14584: allitems (reference to hash - key is category key
14585: (format: escaped(name):escaped(parent category):depth in hierarchy).
14586:
14587: parents (array containing containers directories for current category,
14588: back to top level).
14589:
14590: Returns: nothing
14591:
14592: Side effects: populates trails and allitems hash references
14593:
14594: =cut
14595:
14596: sub recurse_categories {
14597: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
14598: my $shallower = $depth - 1;
14599: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
14600: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
14601: my $name = $cats->[$depth]{$category}[$k];
14602: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14603: my $trailstr = join(' -> ',(@{$parents},$category));
14604: if ($allitems->{$item} eq '') {
14605: push(@{$trails},$trailstr);
14606: $allitems->{$item} = scalar(@{$trails})-1;
14607: }
14608: my $deeper = $depth+1;
14609: push(@{$parents},$category);
14610: if (ref($subcats) eq 'HASH') {
14611: my $subcat = &escape($name).':'.$category.':'.$depth;
14612: for (my $j=@{$parents}; $j>=0; $j--) {
14613: my $higher;
14614: if ($j > 0) {
14615: $higher = &escape($parents->[$j]).':'.
14616: &escape($parents->[$j-1]).':'.$j;
14617: } else {
14618: $higher = &escape($parents->[$j]).'::'.$j;
14619: }
14620: push(@{$subcats->{$higher}},$subcat);
14621: }
14622: }
14623: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14624: $subcats,$maxd);
14625: pop(@{$parents});
14626: }
14627: } else {
14628: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14629: my $trailstr = join(' » ',(@{$parents},$category));
14630: if ($allitems->{$item} eq '') {
14631: push(@{$trails},$trailstr);
14632: $allitems->{$item} = scalar(@{$trails})-1;
14633: }
14634: if (ref($maxd) eq 'HASH') {
14635: if ($depth > $maxd->{$parents->[0]}) {
14636: $maxd->{$parents->[0]} = $depth;
14637: }
14638: }
14639: }
14640: return;
14641: }
14642:
14643: =pod
14644:
14645: =item * &assign_categories_table()
14646:
14647: Create a datatable for display of hierarchical categories in a domain,
14648: with checkboxes to allow a course to be categorized.
14649:
14650: Inputs:
14651:
14652: cathash - reference to hash of categories defined for the domain (from
14653: configuration.db)
14654:
14655: currcat - scalar with an & separated list of categories assigned to a course.
14656:
14657: type - scalar contains course type (Course or Community).
14658:
14659: disabled - scalar (optional) contains disabled="disabled" if input elements are
14660: to be readonly (e.g., Domain Helpdesk role viewing course settings).
14661:
14662: Returns: $output (markup to be displayed)
14663:
14664: =cut
14665:
14666: sub assign_categories_table {
14667: my ($cathash,$currcat,$type,$disabled) = @_;
14668: my $output;
14669: if (ref($cathash) eq 'HASH') {
14670: my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
14671: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
14672: $maxdepth = scalar(@cats);
14673: if (@cats > 0) {
14674: my $itemcount = 0;
14675: if (ref($cats[0]) eq 'ARRAY') {
14676: my @currcategories;
14677: if ($currcat ne '') {
14678: @currcategories = split('&',$currcat);
14679: }
14680: my $table;
14681: for (my $i=0; $i<@{$cats[0]}; $i++) {
14682: my $parent = $cats[0][$i];
14683: next if ($parent eq 'instcode');
14684: if ($type eq 'Community') {
14685: next unless ($parent eq 'communities');
14686: } else {
14687: next if ($parent eq 'communities');
14688: }
14689: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14690: my $item = &escape($parent).'::0';
14691: my $checked = '';
14692: if (@currcategories > 0) {
14693: if (grep(/^\Q$item\E$/,@currcategories)) {
14694: $checked = ' checked="checked"';
14695: }
14696: }
14697: my $parent_title = $parent;
14698: if ($parent eq 'communities') {
14699: $parent_title = &mt('Communities');
14700: }
14701: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
14702: '<input type="checkbox" name="usecategory" value="'.
14703: $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
14704: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
14705: my $depth = 1;
14706: push(@path,$parent);
14707: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
14708: pop(@path);
14709: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
14710: $itemcount ++;
14711: }
14712: if ($itemcount) {
14713: $output = &Apache::loncommon::start_data_table().
14714: $table.
14715: &Apache::loncommon::end_data_table();
14716: }
14717: }
14718: }
14719: }
14720: return $output;
14721: }
14722:
14723: =pod
14724:
14725: =item * &assign_category_rows()
14726:
14727: Create a datatable row for display of nested categories in a domain,
14728: with checkboxes to allow a course to be categorized,called recursively.
14729:
14730: Inputs:
14731:
14732: itemcount - track row number for alternating colors
14733:
14734: cats - reference to array of arrays/hashes which encapsulates hierarchy of
14735: categories and subcategories.
14736:
14737: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
14738:
14739: parent - parent of current category item
14740:
14741: path - Array containing all categories back up through the hierarchy from the
14742: current category to the top level.
14743:
14744: currcategories - reference to array of current categories assigned to the course
14745:
14746: disabled - scalar (optional) contains disabled="disabled" if input elements are
14747: to be readonly (e.g., Domain Helpdesk role viewing course settings).
14748:
14749: Returns: $output (markup to be displayed).
14750:
14751: =cut
14752:
14753: sub assign_category_rows {
14754: my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
14755: my ($text,$name,$item,$chgstr);
14756: if (ref($cats) eq 'ARRAY') {
14757: my $maxdepth = scalar(@{$cats});
14758: if (ref($cats->[$depth]) eq 'HASH') {
14759: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
14760: my $numchildren = @{$cats->[$depth]{$parent}};
14761: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14762: $text .= '<td><table class="LC_data_table">';
14763: for (my $j=0; $j<$numchildren; $j++) {
14764: $name = $cats->[$depth]{$parent}[$j];
14765: $item = &escape($name).':'.&escape($parent).':'.$depth;
14766: my $deeper = $depth+1;
14767: my $checked = '';
14768: if (ref($currcategories) eq 'ARRAY') {
14769: if (@{$currcategories} > 0) {
14770: if (grep(/^\Q$item\E$/,@{$currcategories})) {
14771: $checked = ' checked="checked"';
14772: }
14773: }
14774: }
14775: $text .= '<tr><td><span class="LC_nobreak"><label>'.
14776: '<input type="checkbox" name="usecategory" value="'.
14777: $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
14778: '<input type="hidden" name="catname" value="'.$name.'" />'.
14779: '</td><td>';
14780: if (ref($path) eq 'ARRAY') {
14781: push(@{$path},$name);
14782: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
14783: pop(@{$path});
14784: }
14785: $text .= '</td></tr>';
14786: }
14787: $text .= '</table></td>';
14788: }
14789: }
14790: }
14791: return $text;
14792: }
14793:
14794: =pod
14795:
14796: =back
14797:
14798: =cut
14799:
14800: ############################################################
14801: ############################################################
14802:
14803:
14804: sub commit_customrole {
14805: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
14806: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
14807: ($start?', '.&mt('starting').' '.localtime($start):'').
14808: ($end?', ending '.localtime($end):'').': <b>'.
14809: &Apache::lonnet::assigncustomrole(
14810: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
14811: '</b><br />';
14812: return $output;
14813: }
14814:
14815: sub commit_standardrole {
14816: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
14817: my ($output,$logmsg,$linefeed);
14818: if ($context eq 'auto') {
14819: $linefeed = "\n";
14820: } else {
14821: $linefeed = "<br />\n";
14822: }
14823: if ($three eq 'st') {
14824: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
14825: $one,$two,$sec,$context,$credits);
14826: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
14827: ($result eq 'unknown_course') || ($result eq 'refused')) {
14828: $output = $logmsg.' '.&mt('Error: ').$result."\n";
14829: } else {
14830: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
14831: ($start?', '.&mt('starting').' '.localtime($start):'').
14832: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14833: if ($context eq 'auto') {
14834: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
14835: } else {
14836: $output .= '<b>'.$result.'</b>'.$linefeed.
14837: &mt('Add to classlist').': <b>ok</b>';
14838: }
14839: $output .= $linefeed;
14840: }
14841: } else {
14842: $output = &mt('Assigning').' '.$three.' in '.$url.
14843: ($start?', '.&mt('starting').' '.localtime($start):'').
14844: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14845: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
14846: if ($context eq 'auto') {
14847: $output .= $result.$linefeed;
14848: } else {
14849: $output .= '<b>'.$result.'</b>'.$linefeed;
14850: }
14851: }
14852: return $output;
14853: }
14854:
14855: sub commit_studentrole {
14856: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
14857: $credits) = @_;
14858: my ($result,$linefeed,$oldsecurl,$newsecurl);
14859: if ($context eq 'auto') {
14860: $linefeed = "\n";
14861: } else {
14862: $linefeed = '<br />'."\n";
14863: }
14864: if (defined($one) && defined($two)) {
14865: my $cid=$one.'_'.$two;
14866: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
14867: my $secchange = 0;
14868: my $expire_role_result;
14869: my $modify_section_result;
14870: if ($oldsec ne '-1') {
14871: if ($oldsec ne $sec) {
14872: $secchange = 1;
14873: my $now = time;
14874: my $uurl='/'.$cid;
14875: $uurl=~s/\_/\//g;
14876: if ($oldsec) {
14877: $uurl.='/'.$oldsec;
14878: }
14879: $oldsecurl = $uurl;
14880: $expire_role_result =
14881: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
14882: if ($env{'request.course.sec'} ne '') {
14883: if ($expire_role_result eq 'refused') {
14884: my @roles = ('st');
14885: my @statuses = ('previous');
14886: my @roledoms = ($one);
14887: my $withsec = 1;
14888: my %roleshash =
14889: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
14890: \@statuses,\@roles,\@roledoms,$withsec);
14891: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
14892: my ($oldstart,$oldend) =
14893: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
14894: if ($oldend > 0 && $oldend <= $now) {
14895: $expire_role_result = 'ok';
14896: }
14897: }
14898: }
14899: }
14900: $result = $expire_role_result;
14901: }
14902: }
14903: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
14904: $modify_section_result =
14905: &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
14906: undef,undef,undef,$sec,
14907: $end,$start,'','',$cid,
14908: '',$context,$credits);
14909: if ($modify_section_result =~ /^ok/) {
14910: if ($secchange == 1) {
14911: if ($sec eq '') {
14912: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
14913: } else {
14914: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
14915: }
14916: } elsif ($oldsec eq '-1') {
14917: if ($sec eq '') {
14918: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
14919: } else {
14920: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14921: }
14922: } else {
14923: if ($sec eq '') {
14924: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
14925: } else {
14926: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14927: }
14928: }
14929: } else {
14930: if ($secchange) {
14931: $$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;
14932: } else {
14933: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
14934: }
14935: }
14936: $result = $modify_section_result;
14937: } elsif ($secchange == 1) {
14938: if ($oldsec eq '') {
14939: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
14940: } else {
14941: $$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;
14942: }
14943: if ($expire_role_result eq 'refused') {
14944: my $newsecurl = '/'.$cid;
14945: $newsecurl =~ s/\_/\//g;
14946: if ($sec ne '') {
14947: $newsecurl.='/'.$sec;
14948: }
14949: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
14950: if ($sec eq '') {
14951: $$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;
14952: } else {
14953: $$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;
14954: }
14955: }
14956: }
14957: }
14958: } else {
14959: $$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;
14960: $result = "error: incomplete course id\n";
14961: }
14962: return $result;
14963: }
14964:
14965: sub show_role_extent {
14966: my ($scope,$context,$role) = @_;
14967: $scope =~ s{^/}{};
14968: my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
14969: push(@courseroles,'co');
14970: my @authorroles = &Apache::lonuserutils::roles_by_context('author');
14971: if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
14972: $scope =~ s{/}{_};
14973: return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
14974: } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
14975: my ($audom,$auname) = split(/\//,$scope);
14976: return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
14977: &Apache::loncommon::plainname($auname,$audom).'</span>');
14978: } else {
14979: $scope =~ s{/$}{};
14980: return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
14981: &Apache::lonnet::domain($scope,'description').'</span>');
14982: }
14983: }
14984:
14985: ############################################################
14986: ############################################################
14987:
14988: sub check_clone {
14989: my ($args,$linefeed) = @_;
14990: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
14991: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
14992: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
14993: my $clonemsg;
14994: my $can_clone = 0;
14995: my $lctype = lc($args->{'crstype'});
14996: if ($lctype ne 'community') {
14997: $lctype = 'course';
14998: }
14999: if ($clonehome eq 'no_host') {
15000: if ($args->{'crstype'} eq 'Community') {
15001: $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
15002: } else {
15003: $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
15004: }
15005: } else {
15006: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15007: if ($args->{'crstype'} eq 'Community') {
15008: if ($clonedesc{'type'} ne 'Community') {
15009: $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
15010: return ($can_clone, $clonemsg, $cloneid, $clonehome);
15011: }
15012: }
15013: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
15014: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15015: $can_clone = 1;
15016: } else {
15017: my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15018: $args->{'clonedomain'},$args->{'clonecourse'});
15019: if ($clonehash{'cloners'} eq '') {
15020: my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15021: if ($domdefs{'canclone'}) {
15022: unless ($domdefs{'canclone'} eq 'none') {
15023: if ($domdefs{'canclone'} eq 'domain') {
15024: if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15025: $can_clone = 1;
15026: }
15027: } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15028: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
15029: if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
15030: $clonehash{'internal.coursecode'},$args->{'crscode'})) {
15031: $can_clone = 1;
15032: }
15033: }
15034: }
15035: }
15036: } else {
15037: my @cloners = split(/,/,$clonehash{'cloners'});
15038: if (grep(/^\*$/,@cloners)) {
15039: $can_clone = 1;
15040: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15041: $can_clone = 1;
15042: } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15043: $can_clone = 1;
15044: }
15045: unless ($can_clone) {
15046: if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15047: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
15048: my (%gotdomdefaults,%gotcodedefaults);
15049: foreach my $cloner (@cloners) {
15050: if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
15051: ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
15052: my (%codedefaults,@code_order);
15053: if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
15054: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
15055: %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15056: }
15057: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15058: @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15059: }
15060: } else {
15061: &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15062: \%codedefaults,
15063: \@code_order);
15064: $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15065: $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15066: }
15067: if (@code_order > 0) {
15068: if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15069: $cloner,$clonehash{'internal.coursecode'},
15070: $args->{'crscode'})) {
15071: $can_clone = 1;
15072: last;
15073: }
15074: }
15075: }
15076: }
15077: }
15078: }
15079: }
15080: unless ($can_clone) {
15081: my $ccrole = 'cc';
15082: if ($args->{'crstype'} eq 'Community') {
15083: $ccrole = 'co';
15084: }
15085: my %roleshash =
15086: &Apache::lonnet::get_my_roles($args->{'ccuname'},
15087: $args->{'ccdomain'},
15088: 'userroles',['active'],[$ccrole],
15089: [$args->{'clonedomain'}]);
15090: if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15091: $can_clone = 1;
15092: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15093: $args->{'ccuname'},$args->{'ccdomain'})) {
15094: $can_clone = 1;
15095: }
15096: }
15097: unless ($can_clone) {
15098: if ($args->{'crstype'} eq 'Community') {
15099: $clonemsg = &mt('No new community created.').$linefeed.&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]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
15100: } else {
15101: $clonemsg = &mt('No new course created.').$linefeed.&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]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
15102: }
15103: }
15104: }
15105: }
15106: return ($can_clone, $clonemsg, $cloneid, $clonehome);
15107: }
15108:
15109: sub construct_course {
15110: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
15111: $cnum,$category,$coderef) = @_;
15112: my $outcome;
15113: my $linefeed = '<br />'."\n";
15114: if ($context eq 'auto') {
15115: $linefeed = "\n";
15116: }
15117:
15118: #
15119: # Are we cloning?
15120: #
15121: my ($can_clone, $clonemsg, $cloneid, $clonehome);
15122: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
15123: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
15124: if ($context ne 'auto') {
15125: if ($clonemsg ne '') {
15126: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
15127: }
15128: }
15129: $outcome .= $clonemsg.$linefeed;
15130:
15131: if (!$can_clone) {
15132: return (0,$outcome);
15133: }
15134: }
15135:
15136: #
15137: # Open course
15138: #
15139: my $crstype = lc($args->{'crstype'});
15140: my %cenv=();
15141: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
15142: $args->{'cdescr'},
15143: $args->{'curl'},
15144: $args->{'course_home'},
15145: $args->{'nonstandard'},
15146: $args->{'crscode'},
15147: $args->{'ccuname'}.':'.
15148: $args->{'ccdomain'},
15149: $args->{'crstype'},
15150: $cnum,$context,$category);
15151:
15152: # Note: The testing routines depend on this being output; see
15153: # Utils::Course. This needs to at least be output as a comment
15154: # if anyone ever decides to not show this, and Utils::Course::new
15155: # will need to be suitably modified.
15156: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
15157: if ($$courseid =~ /^error:/) {
15158: return (0,$outcome);
15159: }
15160:
15161: #
15162: # Check if created correctly
15163: #
15164: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
15165: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
15166: if ($crsuhome eq 'no_host') {
15167: $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
15168: return (0,$outcome);
15169: }
15170: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
15171:
15172: #
15173: # Do the cloning
15174: #
15175: if ($can_clone && $cloneid) {
15176: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
15177: if ($context ne 'auto') {
15178: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
15179: }
15180: $outcome .= $clonemsg.$linefeed;
15181: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
15182: # Copy all files
15183: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
15184: # Restore URL
15185: $cenv{'url'}=$oldcenv{'url'};
15186: # Restore title
15187: $cenv{'description'}=$oldcenv{'description'};
15188: # Restore creation date, creator and creation context.
15189: $cenv{'internal.created'}=$oldcenv{'internal.created'};
15190: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
15191: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
15192: # Mark as cloned
15193: $cenv{'clonedfrom'}=$cloneid;
15194: # Need to clone grading mode
15195: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
15196: $cenv{'grading'}=$newenv{'grading'};
15197: # Do not clone these environment entries
15198: &Apache::lonnet::del('environment',
15199: ['default_enrollment_start_date',
15200: 'default_enrollment_end_date',
15201: 'question.email',
15202: 'policy.email',
15203: 'comment.email',
15204: 'pch.users.denied',
15205: 'plc.users.denied',
15206: 'hidefromcat',
15207: 'checkforpriv',
15208: 'categories',
15209: 'internal.uniquecode'],
15210: $$crsudom,$$crsunum);
15211: if ($args->{'textbook'}) {
15212: $cenv{'internal.textbook'} = $args->{'textbook'};
15213: }
15214: }
15215:
15216: #
15217: # Set environment (will override cloned, if existing)
15218: #
15219: my @sections = ();
15220: my @xlists = ();
15221: if ($args->{'crstype'}) {
15222: $cenv{'type'}=$args->{'crstype'};
15223: }
15224: if ($args->{'crsid'}) {
15225: $cenv{'courseid'}=$args->{'crsid'};
15226: }
15227: if ($args->{'crscode'}) {
15228: $cenv{'internal.coursecode'}=$args->{'crscode'};
15229: }
15230: if ($args->{'crsquota'} ne '') {
15231: $cenv{'internal.coursequota'}=$args->{'crsquota'};
15232: } else {
15233: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
15234: }
15235: if ($args->{'ccuname'}) {
15236: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
15237: ':'.$args->{'ccdomain'};
15238: } else {
15239: $cenv{'internal.courseowner'} = $args->{'curruser'};
15240: }
15241: if ($args->{'defaultcredits'}) {
15242: $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
15243: }
15244: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
15245: if ($args->{'crssections'}) {
15246: $cenv{'internal.sectionnums'} = '';
15247: if ($args->{'crssections'} =~ m/,/) {
15248: @sections = split/,/,$args->{'crssections'};
15249: } else {
15250: $sections[0] = $args->{'crssections'};
15251: }
15252: if (@sections > 0) {
15253: foreach my $item (@sections) {
15254: my ($sec,$gp) = split/:/,$item;
15255: my $class = $args->{'crscode'}.$sec;
15256: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
15257: $cenv{'internal.sectionnums'} .= $item.',';
15258: unless ($addcheck eq 'ok') {
15259: push(@badclasses,$class);
15260: }
15261: }
15262: $cenv{'internal.sectionnums'} =~ s/,$//;
15263: }
15264: }
15265: # do not hide course coordinator from staff listing,
15266: # even if privileged
15267: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15268: # add course coordinator's domain to domains to check for privileged users
15269: # if different to course domain
15270: if ($$crsudom ne $args->{'ccdomain'}) {
15271: $cenv{'checkforpriv'} = $args->{'ccdomain'};
15272: }
15273: # add crosslistings
15274: if ($args->{'crsxlist'}) {
15275: $cenv{'internal.crosslistings'}='';
15276: if ($args->{'crsxlist'} =~ m/,/) {
15277: @xlists = split/,/,$args->{'crsxlist'};
15278: } else {
15279: $xlists[0] = $args->{'crsxlist'};
15280: }
15281: if (@xlists > 0) {
15282: foreach my $item (@xlists) {
15283: my ($xl,$gp) = split/:/,$item;
15284: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15285: $cenv{'internal.crosslistings'} .= $item.',';
15286: unless ($addcheck eq 'ok') {
15287: push(@badclasses,$xl);
15288: }
15289: }
15290: $cenv{'internal.crosslistings'} =~ s/,$//;
15291: }
15292: }
15293: if ($args->{'autoadds'}) {
15294: $cenv{'internal.autoadds'}=$args->{'autoadds'};
15295: }
15296: if ($args->{'autodrops'}) {
15297: $cenv{'internal.autodrops'}=$args->{'autodrops'};
15298: }
15299: # check for notification of enrollment changes
15300: my @notified = ();
15301: if ($args->{'notify_owner'}) {
15302: if ($args->{'ccuname'} ne '') {
15303: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15304: }
15305: }
15306: if ($args->{'notify_dc'}) {
15307: if ($uname ne '') {
15308: push(@notified,$uname.':'.$udom);
15309: }
15310: }
15311: if (@notified > 0) {
15312: my $notifylist;
15313: if (@notified > 1) {
15314: $notifylist = join(',',@notified);
15315: } else {
15316: $notifylist = $notified[0];
15317: }
15318: $cenv{'internal.notifylist'} = $notifylist;
15319: }
15320: if (@badclasses > 0) {
15321: my %lt=&Apache::lonlocal::texthash(
15322: 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
15323: 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
15324: 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
15325: );
15326: my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
15327: &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'};
15328: if ($context eq 'auto') {
15329: $outcome .= $badclass_msg.$linefeed;
15330: } else {
15331: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15332: }
15333: foreach my $item (@badclasses) {
15334: if ($context eq 'auto') {
15335: $outcome .= " - $item\n";
15336: } else {
15337: $outcome .= "<li>$item</li>\n";
15338: }
15339: }
15340: if ($context eq 'auto') {
15341: $outcome .= $linefeed;
15342: } else {
15343: $outcome .= "</ul><br /><br /></div>\n";
15344: }
15345: }
15346: if ($args->{'no_end_date'}) {
15347: $args->{'endaccess'} = 0;
15348: }
15349: $cenv{'internal.autostart'}=$args->{'enrollstart'};
15350: $cenv{'internal.autoend'}=$args->{'enrollend'};
15351: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15352: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15353: if ($args->{'showphotos'}) {
15354: $cenv{'internal.showphotos'}=$args->{'showphotos'};
15355: }
15356: $cenv{'internal.authtype'} = $args->{'authtype'};
15357: $cenv{'internal.autharg'} = $args->{'autharg'};
15358: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15359: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
15360: 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');
15361: if ($context eq 'auto') {
15362: $outcome .= $krb_msg;
15363: } else {
15364: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15365: }
15366: $outcome .= $linefeed;
15367: }
15368: }
15369: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15370: if ($args->{'setpolicy'}) {
15371: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15372: }
15373: if ($args->{'setcontent'}) {
15374: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15375: }
15376: if ($args->{'setcomment'}) {
15377: $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15378: }
15379: }
15380: if ($args->{'reshome'}) {
15381: $cenv{'reshome'}=$args->{'reshome'}.'/';
15382: $cenv{'reshome'}=~s/\/+$/\//;
15383: }
15384: #
15385: # course has keyed access
15386: #
15387: if ($args->{'setkeys'}) {
15388: $cenv{'keyaccess'}='yes';
15389: }
15390: # if specified, key authority is not course, but user
15391: # only active if keyaccess is yes
15392: if ($args->{'keyauth'}) {
15393: my ($user,$domain) = split(':',$args->{'keyauth'});
15394: $user = &LONCAPA::clean_username($user);
15395: $domain = &LONCAPA::clean_username($domain);
15396: if ($user ne '' && $domain ne '') {
15397: $cenv{'keyauth'}=$user.':'.$domain;
15398: }
15399: }
15400:
15401: #
15402: # generate and store uniquecode (available to course requester), if course should have one.
15403: #
15404: if ($args->{'uniquecode'}) {
15405: my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
15406: if ($code) {
15407: $cenv{'internal.uniquecode'} = $code;
15408: my %crsinfo =
15409: &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
15410: if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
15411: $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
15412: my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
15413: }
15414: if (ref($coderef)) {
15415: $$coderef = $code;
15416: }
15417: }
15418: }
15419:
15420: if ($args->{'disresdis'}) {
15421: $cenv{'pch.roles.denied'}='st';
15422: }
15423: if ($args->{'disablechat'}) {
15424: $cenv{'plc.roles.denied'}='st';
15425: }
15426:
15427: # Record we've not yet viewed the Course Initialization Helper for this
15428: # course
15429: $cenv{'course.helper.not.run'} = 1;
15430: #
15431: # Use new Randomseed
15432: #
15433: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
15434: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
15435: #
15436: # The encryption code and receipt prefix for this course
15437: #
15438: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
15439: $cenv{'internal.encpref'}=100+int(9*rand(99));
15440: #
15441: # By default, use standard grading
15442: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
15443:
15444: $outcome .= $linefeed.&mt('Setting environment').': '.
15445: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
15446: #
15447: # Open all assignments
15448: #
15449: if ($args->{'openall'}) {
15450: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
15451: my %storecontent = ($storeunder => time,
15452: $storeunder.'.type' => 'date_start');
15453:
15454: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
15455: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
15456: }
15457: #
15458: # Set first page
15459: #
15460: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
15461: || ($cloneid)) {
15462: use LONCAPA::map;
15463: $outcome .= &mt('Setting first resource').': ';
15464:
15465: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
15466: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
15467:
15468: $outcome .= ($fatal?$errtext:'read ok').' - ';
15469: my $title; my $url;
15470: if ($args->{'firstres'} eq 'syl') {
15471: $title=&mt('Syllabus');
15472: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
15473: } else {
15474: $title=&mt('Table of Contents');
15475: $url='/adm/navmaps';
15476: }
15477:
15478: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
15479: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
15480:
15481: if ($errtext) { $fatal=2; }
15482: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
15483: }
15484:
15485: return (1,$outcome);
15486: }
15487:
15488: sub make_unique_code {
15489: my ($cdom,$cnum) = @_;
15490: # get lock on uniquecodes db
15491: my $lockhash = {
15492: $cnum."\0".'uniquecodes' => $env{'user.name'}.
15493: ':'.$env{'user.domain'},
15494: };
15495: my $tries = 0;
15496: my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15497: my ($code,$error);
15498:
15499: while (($gotlock ne 'ok') && ($tries<3)) {
15500: $tries ++;
15501: sleep 1;
15502: $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15503: }
15504: if ($gotlock eq 'ok') {
15505: my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
15506: my $gotcode;
15507: my $attempts = 0;
15508: while ((!$gotcode) && ($attempts < 100)) {
15509: $code = &generate_code();
15510: if (!exists($currcodes{$code})) {
15511: $gotcode = 1;
15512: unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
15513: $error = 'nostore';
15514: }
15515: }
15516: $attempts ++;
15517: }
15518: my @del_lock = ($cnum."\0".'uniquecodes');
15519: my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
15520: } else {
15521: $error = 'nolock';
15522: }
15523: return ($code,$error);
15524: }
15525:
15526: sub generate_code {
15527: my $code;
15528: my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
15529: for (my $i=0; $i<6; $i++) {
15530: my $lettnum = int (rand 2);
15531: my $item = '';
15532: if ($lettnum) {
15533: $item = $letts[int( rand(18) )];
15534: } else {
15535: $item = 1+int( rand(8) );
15536: }
15537: $code .= $item;
15538: }
15539: return $code;
15540: }
15541:
15542: ############################################################
15543: ############################################################
15544:
15545: #SD
15546: # only Community and Course, or anything else?
15547: sub course_type {
15548: my ($cid) = @_;
15549: if (!defined($cid)) {
15550: $cid = $env{'request.course.id'};
15551: }
15552: if (defined($env{'course.'.$cid.'.type'})) {
15553: return $env{'course.'.$cid.'.type'};
15554: } else {
15555: return 'Course';
15556: }
15557: }
15558:
15559: sub group_term {
15560: my $crstype = &course_type();
15561: my %names = (
15562: 'Course' => 'group',
15563: 'Community' => 'group',
15564: );
15565: return $names{$crstype};
15566: }
15567:
15568: sub course_types {
15569: my @types = ('official','unofficial','community','textbook');
15570: my %typename = (
15571: official => 'Official course',
15572: unofficial => 'Unofficial course',
15573: community => 'Community',
15574: textbook => 'Textbook course',
15575: );
15576: return (\@types,\%typename);
15577: }
15578:
15579: sub icon {
15580: my ($file)=@_;
15581: my $curfext = lc((split(/\./,$file))[-1]);
15582: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
15583: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
15584: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
15585: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
15586: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15587: $curfext.".gif") {
15588: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15589: $curfext.".gif";
15590: }
15591: }
15592: return &lonhttpdurl($iconname);
15593: }
15594:
15595: sub lonhttpdurl {
15596: #
15597: # Had been used for "small fry" static images on separate port 8080.
15598: # Modify here if lightweight http functionality desired again.
15599: # Currently eliminated due to increasing firewall issues.
15600: #
15601: my ($url)=@_;
15602: return $url;
15603: }
15604:
15605: sub connection_aborted {
15606: my ($r)=@_;
15607: $r->print(" ");$r->rflush();
15608: my $c = $r->connection;
15609: return $c->aborted();
15610: }
15611:
15612: # Escapes strings that may have embedded 's that will be put into
15613: # strings as 'strings'.
15614: sub escape_single {
15615: my ($input) = @_;
15616: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
15617: $input =~ s/\'/\\\'/g; # Esacpe the 's....
15618: return $input;
15619: }
15620:
15621: # Same as escape_single, but escape's "'s This
15622: # can be used for "strings"
15623: sub escape_double {
15624: my ($input) = @_;
15625: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
15626: $input =~ s/\"/\\\"/g; # Esacpe the "s....
15627: return $input;
15628: }
15629:
15630: # Escapes the last element of a full URL.
15631: sub escape_url {
15632: my ($url) = @_;
15633: my @urlslices = split(/\//, $url,-1);
15634: my $lastitem = &escape(pop(@urlslices));
15635: return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
15636: }
15637:
15638: sub compare_arrays {
15639: my ($arrayref1,$arrayref2) = @_;
15640: my (@difference,%count);
15641: @difference = ();
15642: %count = ();
15643: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
15644: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
15645: foreach my $element (keys(%count)) {
15646: if ($count{$element} == 1) {
15647: push(@difference,$element);
15648: }
15649: }
15650: }
15651: return @difference;
15652: }
15653:
15654: # -------------------------------------------------------- Initialize user login
15655: sub init_user_environment {
15656: my ($r, $username, $domain, $authhost, $form, $args) = @_;
15657: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
15658:
15659: my $public=($username eq 'public' && $domain eq 'public');
15660:
15661: # See if old ID present, if so, remove
15662:
15663: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
15664: my $now=time;
15665:
15666: if ($public) {
15667: my $max_public=100;
15668: my $oldest;
15669: my $oldest_time=0;
15670: for(my $next=1;$next<=$max_public;$next++) {
15671: if (-e $lonids."/publicuser_$next.id") {
15672: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
15673: if ($mtime<$oldest_time || !$oldest_time) {
15674: $oldest_time=$mtime;
15675: $oldest=$next;
15676: }
15677: } else {
15678: $cookie="publicuser_$next";
15679: last;
15680: }
15681: }
15682: if (!$cookie) { $cookie="publicuser_$oldest"; }
15683: } else {
15684: # if this isn't a robot, kill any existing non-robot sessions
15685: if (!$args->{'robot'}) {
15686: opendir(DIR,$lonids);
15687: while ($filename=readdir(DIR)) {
15688: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
15689: if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
15690: &GDBM_READER(),0640)) {
15691: my $linkedfile;
15692: if (exists($oldenv{'user.linkedenv'})) {
15693: $linkedfile = $oldenv{'user.linkedenv'};
15694: }
15695: untie(%oldenv);
15696: if (unlink("$lonids/$filename")) {
15697: if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
15698: if (-l "$lonids/$linkedfile.id") {
15699: unlink("$lonids/$linkedfile.id");
15700: }
15701: }
15702: }
15703: } else {
15704: unlink($lonids.'/'.$filename);
15705: }
15706: }
15707: }
15708: closedir(DIR);
15709: # If there is a undeleted lockfile for the user's paste buffer remove it.
15710: my $namespace = 'nohist_courseeditor';
15711: my $lockingkey = 'paste'."\0".'locked_num';
15712: my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
15713: $domain,$username);
15714: if (exists($lockhash{$lockingkey})) {
15715: my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
15716: unless ($delresult eq 'ok') {
15717: &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
15718: }
15719: }
15720: }
15721: # Give them a new cookie
15722: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
15723: : $now.$$.int(rand(10000)));
15724: $cookie="$username\_$id\_$domain\_$authhost";
15725:
15726: # Initialize roles
15727:
15728: ($userroles,$firstaccenv,$timerintenv) =
15729: &Apache::lonnet::rolesinit($domain,$username,$authhost);
15730: }
15731: # ------------------------------------ Check browser type and MathML capability
15732:
15733: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
15734: $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
15735:
15736: # ------------------------------------------------------------- Get environment
15737:
15738: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
15739: my ($tmp) = keys(%userenv);
15740: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
15741: } else {
15742: undef(%userenv);
15743: }
15744: if (($userenv{'interface'}) && (!$form->{'interface'})) {
15745: $form->{'interface'}=$userenv{'interface'};
15746: }
15747: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
15748:
15749: # --------------- Do not trust query string to be put directly into environment
15750: foreach my $option ('interface','localpath','localres') {
15751: $form->{$option}=~s/[\n\r\=]//gs;
15752: }
15753: # --------------------------------------------------------- Write first profile
15754:
15755: {
15756: my %initial_env =
15757: ("user.name" => $username,
15758: "user.domain" => $domain,
15759: "user.home" => $authhost,
15760: "browser.type" => $clientbrowser,
15761: "browser.version" => $clientversion,
15762: "browser.mathml" => $clientmathml,
15763: "browser.unicode" => $clientunicode,
15764: "browser.os" => $clientos,
15765: "browser.mobile" => $clientmobile,
15766: "browser.info" => $clientinfo,
15767: "browser.osversion" => $clientosversion,
15768: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
15769: "request.course.fn" => '',
15770: "request.course.uri" => '',
15771: "request.course.sec" => '',
15772: "request.role" => 'cm',
15773: "request.role.adv" => $env{'user.adv'},
15774: "request.host" => $ENV{'REMOTE_ADDR'},);
15775:
15776: if ($form->{'localpath'}) {
15777: $initial_env{"browser.localpath"} = $form->{'localpath'};
15778: $initial_env{"browser.localres"} = $form->{'localres'};
15779: }
15780:
15781: if ($form->{'interface'}) {
15782: $form->{'interface'}=~s/\W//gs;
15783: $initial_env{"browser.interface"} = $form->{'interface'};
15784: $env{'browser.interface'}=$form->{'interface'};
15785: }
15786:
15787: if ($form->{'iptoken'}) {
15788: my $lonhost = $r->dir_config('lonHostID');
15789: $initial_env{"user.noloadbalance"} = $lonhost;
15790: $env{'user.noloadbalance'} = $lonhost;
15791: }
15792:
15793: if ($form->{'noloadbalance'}) {
15794: my @hosts = &Apache::lonnet::current_machine_ids();
15795: my $hosthere = $form->{'noloadbalance'};
15796: if (grep(/^\Q$hosthere\E$/,@hosts)) {
15797: $initial_env{"user.noloadbalance"} = $hosthere;
15798: $env{'user.noloadbalance'} = $hosthere;
15799: }
15800: }
15801:
15802: unless ($domain eq 'public') {
15803: my %is_adv = ( is_adv => $env{'user.adv'} );
15804: my %domdef = &Apache::lonnet::get_domain_defaults($domain);
15805:
15806: foreach my $tool ('aboutme','blog','webdav','portfolio') {
15807: $userenv{'availabletools.'.$tool} =
15808: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
15809: undef,\%userenv,\%domdef,\%is_adv);
15810: }
15811:
15812: foreach my $crstype ('official','unofficial','community','textbook') {
15813: $userenv{'canrequest.'.$crstype} =
15814: &Apache::lonnet::usertools_access($username,$domain,$crstype,
15815: 'reload','requestcourses',
15816: \%userenv,\%domdef,\%is_adv);
15817: }
15818:
15819: $userenv{'canrequest.author'} =
15820: &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
15821: 'reload','requestauthor',
15822: \%userenv,\%domdef,\%is_adv);
15823: my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
15824: $domain,$username);
15825: my $reqstatus = $reqauthor{'author_status'};
15826: if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
15827: if (ref($reqauthor{'author'}) eq 'HASH') {
15828: $userenv{'requestauthorqueued'} = $reqstatus.':'.
15829: $reqauthor{'author'}{'timestamp'};
15830: }
15831: }
15832: }
15833:
15834: $env{'user.environment'} = "$lonids/$cookie.id";
15835:
15836: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
15837: &GDBM_WRCREAT(),0640)) {
15838: &_add_to_env(\%disk_env,\%initial_env);
15839: &_add_to_env(\%disk_env,\%userenv,'environment.');
15840: &_add_to_env(\%disk_env,$userroles);
15841: if (ref($firstaccenv) eq 'HASH') {
15842: &_add_to_env(\%disk_env,$firstaccenv);
15843: }
15844: if (ref($timerintenv) eq 'HASH') {
15845: &_add_to_env(\%disk_env,$timerintenv);
15846: }
15847: if (ref($args->{'extra_env'})) {
15848: &_add_to_env(\%disk_env,$args->{'extra_env'});
15849: }
15850: untie(%disk_env);
15851: } else {
15852: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
15853: 'Could not create environment storage in lonauth: '.$!.'</span>');
15854: return 'error: '.$!;
15855: }
15856: }
15857: $env{'request.role'}='cm';
15858: $env{'request.role.adv'}=$env{'user.adv'};
15859: $env{'browser.type'}=$clientbrowser;
15860:
15861: return $cookie;
15862:
15863: }
15864:
15865: sub _add_to_env {
15866: my ($idf,$env_data,$prefix) = @_;
15867: if (ref($env_data) eq 'HASH') {
15868: while (my ($key,$value) = each(%$env_data)) {
15869: $idf->{$prefix.$key} = $value;
15870: $env{$prefix.$key} = $value;
15871: }
15872: }
15873: }
15874:
15875: # --- Get the symbolic name of a problem and the url
15876: sub get_symb {
15877: my ($request,$silent) = @_;
15878: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
15879: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
15880: if ($symb eq '') {
15881: if (!$silent) {
15882: if (ref($request)) {
15883: $request->print("Unable to handle ambiguous references:$url:.");
15884: }
15885: return ();
15886: }
15887: }
15888: &Apache::lonenc::check_decrypt(\$symb);
15889: return ($symb);
15890: }
15891:
15892: # --------------------------------------------------------------Get annotation
15893:
15894: sub get_annotation {
15895: my ($symb,$enc) = @_;
15896:
15897: my $key = $symb;
15898: if (!$enc) {
15899: $key =
15900: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
15901: }
15902: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
15903: return $annotation{$key};
15904: }
15905:
15906: sub clean_symb {
15907: my ($symb,$delete_enc) = @_;
15908:
15909: &Apache::lonenc::check_decrypt(\$symb);
15910: my $enc = $env{'request.enc'};
15911: if ($delete_enc) {
15912: delete($env{'request.enc'});
15913: }
15914:
15915: return ($symb,$enc);
15916: }
15917:
15918: ############################################################
15919: ############################################################
15920:
15921: =pod
15922:
15923: =head1 Routines for building display used to search for courses
15924:
15925:
15926: =over 4
15927:
15928: =item * &build_filters()
15929:
15930: Create markup for a table used to set filters to use when selecting
15931: courses in a domain. Used by lonpickcourse.pm, lonmodifycourse.pm
15932: and quotacheck.pl
15933:
15934:
15935: Inputs:
15936:
15937: filterlist - anonymous array of fields to include as potential filters
15938:
15939: crstype - course type
15940:
15941: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
15942: to pop-open a course selector (will contain "extra element").
15943:
15944: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
15945:
15946: filter - anonymous hash of criteria and their values
15947:
15948: action - form action
15949:
15950: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
15951:
15952: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
15953:
15954: cloneruname - username of owner of new course who wants to clone
15955:
15956: clonerudom - domain of owner of new course who wants to clone
15957:
15958: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
15959:
15960: codetitlesref - reference to array of titles of components in institutional codes (official courses)
15961:
15962: codedom - domain
15963:
15964: formname - value of form element named "form".
15965:
15966: fixeddom - domain, if fixed.
15967:
15968: prevphase - value to assign to form element named "phase" when going back to the previous screen
15969:
15970: cnameelement - name of form element in form on opener page which will receive title of selected course
15971:
15972: cnumelement - name of form element in form on opener page which will receive courseID of selected course
15973:
15974: cdomelement - name of form element in form on opener page which will receive domain of selected course
15975:
15976: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
15977:
15978: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
15979:
15980: clonewarning - warning message about missing information for intended course owner when DC creates a course
15981:
15982:
15983: Returns: $output - HTML for display of search criteria, and hidden form elements.
15984:
15985:
15986: Side Effects: None
15987:
15988: =cut
15989:
15990: # ---------------------------------------------- search for courses based on last activity etc.
15991:
15992: sub build_filters {
15993: my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
15994: $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
15995: $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
15996: $cnameelement,$cnumelement,$cdomelement,$setroles,
15997: $clonetext,$clonewarning) = @_;
15998: my ($list,$jscript);
15999: my $onchange = 'javascript:updateFilters(this)';
16000: my ($domainselectform,$sincefilterform,$createdfilterform,
16001: $ownerdomselectform,$persondomselectform,$instcodeform,
16002: $typeselectform,$instcodetitle);
16003: if ($formname eq '') {
16004: $formname = $caller;
16005: }
16006: foreach my $item (@{$filterlist}) {
16007: unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
16008: ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
16009: if ($item eq 'domainfilter') {
16010: $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
16011: } elsif ($item eq 'coursefilter') {
16012: $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
16013: } elsif ($item eq 'ownerfilter') {
16014: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16015: } elsif ($item eq 'ownerdomfilter') {
16016: $filter->{'ownerdomfilter'} =
16017: &LONCAPA::clean_domain($filter->{$item});
16018: $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
16019: 'ownerdomfilter',1);
16020: } elsif ($item eq 'personfilter') {
16021: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16022: } elsif ($item eq 'persondomfilter') {
16023: $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
16024: 'persondomfilter',1);
16025: } else {
16026: $filter->{$item} =~ s/\W//g;
16027: }
16028: if (!$filter->{$item}) {
16029: $filter->{$item} = '';
16030: }
16031: }
16032: if ($item eq 'domainfilter') {
16033: my $allow_blank = 1;
16034: if ($formname eq 'portform') {
16035: $allow_blank=0;
16036: } elsif ($formname eq 'studentform') {
16037: $allow_blank=0;
16038: }
16039: if ($fixeddom) {
16040: $domainselectform = '<input type="hidden" name="domainfilter"'.
16041: ' value="'.$codedom.'" />'.
16042: &Apache::lonnet::domain($codedom,'description');
16043: } else {
16044: $domainselectform = &select_dom_form($filter->{$item},
16045: 'domainfilter',
16046: $allow_blank,'',$onchange);
16047: }
16048: } else {
16049: $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
16050: }
16051: }
16052:
16053: # last course activity filter and selection
16054: $sincefilterform = &timebased_select_form('sincefilter',$filter);
16055:
16056: # course created filter and selection
16057: if (exists($filter->{'createdfilter'})) {
16058: $createdfilterform = &timebased_select_form('createdfilter',$filter);
16059: }
16060:
16061: my %lt = &Apache::lonlocal::texthash(
16062: 'cac' => "$crstype Activity",
16063: 'ccr' => "$crstype Created",
16064: 'cde' => "$crstype Title",
16065: 'cdo' => "$crstype Domain",
16066: 'ins' => 'Institutional Code',
16067: 'inc' => 'Institutional Categorization',
16068: 'cow' => "$crstype Owner/Co-owner",
16069: 'cop' => "$crstype Personnel Includes",
16070: 'cog' => 'Type',
16071: );
16072:
16073: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16074: my $typeval = 'Course';
16075: if ($crstype eq 'Community') {
16076: $typeval = 'Community';
16077: }
16078: $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
16079: } else {
16080: $typeselectform = '<select name="type" size="1"';
16081: if ($onchange) {
16082: $typeselectform .= ' onchange="'.$onchange.'"';
16083: }
16084: $typeselectform .= '>'."\n";
16085: foreach my $posstype ('Course','Community') {
16086: $typeselectform.='<option value="'.$posstype.'"'.
16087: ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
16088: }
16089: $typeselectform.="</select>";
16090: }
16091:
16092: my ($cloneableonlyform,$cloneabletitle);
16093: if (exists($filter->{'cloneableonly'})) {
16094: my $cloneableon = '';
16095: my $cloneableoff = ' checked="checked"';
16096: if ($filter->{'cloneableonly'}) {
16097: $cloneableon = $cloneableoff;
16098: $cloneableoff = '';
16099: }
16100: $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>';
16101: if ($formname eq 'ccrs') {
16102: $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
16103: } else {
16104: $cloneabletitle = &mt('Cloneable by you');
16105: }
16106: }
16107: my $officialjs;
16108: if ($crstype eq 'Course') {
16109: if (exists($filter->{'instcodefilter'})) {
16110: # if (($fixeddom) || ($formname eq 'requestcrs') ||
16111: # ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
16112: if ($codedom) {
16113: $officialjs = 1;
16114: ($instcodeform,$jscript,$$numtitlesref) =
16115: &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
16116: $officialjs,$codetitlesref);
16117: if ($jscript) {
16118: $jscript = '<script type="text/javascript">'."\n".
16119: '// <![CDATA['."\n".
16120: $jscript."\n".
16121: '// ]]>'."\n".
16122: '</script>'."\n";
16123: }
16124: }
16125: if ($instcodeform eq '') {
16126: $instcodeform =
16127: '<input type="text" name="instcodefilter" size="10" value="'.
16128: $list->{'instcodefilter'}.'" />';
16129: $instcodetitle = $lt{'ins'};
16130: } else {
16131: $instcodetitle = $lt{'inc'};
16132: }
16133: if ($fixeddom) {
16134: $instcodetitle .= '<br />('.$codedom.')';
16135: }
16136: }
16137: }
16138: my $output = qq|
16139: <form method="post" name="filterpicker" action="$action">
16140: <input type="hidden" name="form" value="$formname" />
16141: |;
16142: if ($formname eq 'modifycourse') {
16143: $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
16144: '<input type="hidden" name="prevphase" value="'.
16145: $prevphase.'" />'."\n";
16146: } elsif ($formname eq 'quotacheck') {
16147: $output .= qq|
16148: <input type="hidden" name="sortby" value="" />
16149: <input type="hidden" name="sortorder" value="" />
16150: |;
16151: } else {
16152: my $name_input;
16153: if ($cnameelement ne '') {
16154: $name_input = '<input type="hidden" name="cnameelement" value="'.
16155: $cnameelement.'" />';
16156: }
16157: $output .= qq|
16158: <input type="hidden" name="cnumelement" value="$cnumelement" />
16159: <input type="hidden" name="cdomelement" value="$cdomelement" />
16160: $name_input
16161: $roleelement
16162: $multelement
16163: $typeelement
16164: |;
16165: if ($formname eq 'portform') {
16166: $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
16167: }
16168: }
16169: if ($fixeddom) {
16170: $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
16171: }
16172: $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
16173: if ($sincefilterform) {
16174: $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
16175: .$sincefilterform
16176: .&Apache::lonhtmlcommon::row_closure();
16177: }
16178: if ($createdfilterform) {
16179: $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
16180: .$createdfilterform
16181: .&Apache::lonhtmlcommon::row_closure();
16182: }
16183: if ($domainselectform) {
16184: $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
16185: .$domainselectform
16186: .&Apache::lonhtmlcommon::row_closure();
16187: }
16188: if ($typeselectform) {
16189: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16190: $output .= $typeselectform;
16191: } else {
16192: $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
16193: .$typeselectform
16194: .&Apache::lonhtmlcommon::row_closure();
16195: }
16196: }
16197: if ($instcodeform) {
16198: $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
16199: .$instcodeform
16200: .&Apache::lonhtmlcommon::row_closure();
16201: }
16202: if (exists($filter->{'ownerfilter'})) {
16203: $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
16204: '<table><tr><td>'.&mt('Username').'<br />'.
16205: '<input type="text" name="ownerfilter" size="20" value="'.
16206: $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16207: $ownerdomselectform.'</td></tr></table>'.
16208: &Apache::lonhtmlcommon::row_closure();
16209: }
16210: if (exists($filter->{'personfilter'})) {
16211: $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
16212: '<table><tr><td>'.&mt('Username').'<br />'.
16213: '<input type="text" name="personfilter" size="20" value="'.
16214: $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16215: $persondomselectform.'</td></tr></table>'.
16216: &Apache::lonhtmlcommon::row_closure();
16217: }
16218: if (exists($filter->{'coursefilter'})) {
16219: $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
16220: .'<input type="text" name="coursefilter" size="25" value="'
16221: .$list->{'coursefilter'}.'" />'
16222: .&Apache::lonhtmlcommon::row_closure();
16223: }
16224: if ($cloneableonlyform) {
16225: $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
16226: $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
16227: }
16228: if (exists($filter->{'descriptfilter'})) {
16229: $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
16230: .'<input type="text" name="descriptfilter" size="40" value="'
16231: .$list->{'descriptfilter'}.'" />'
16232: .&Apache::lonhtmlcommon::row_closure(1);
16233: }
16234: $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
16235: '<input type="hidden" name="updater" value="" />'."\n".
16236: '<input type="submit" name="gosearch" value="'.
16237: &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
16238: return $jscript.$clonewarning.$output;
16239: }
16240:
16241: =pod
16242:
16243: =item * &timebased_select_form()
16244:
16245: Create markup for a dropdown list used to select a time-based
16246: filter e.g., Course Activity, Course Created, when searching for courses
16247: or communities
16248:
16249: Inputs:
16250:
16251: item - name of form element (sincefilter or createdfilter)
16252:
16253: filter - anonymous hash of criteria and their values
16254:
16255: Returns: HTML for a select box contained a blank, then six time selections,
16256: with value set in incoming form variables currently selected.
16257:
16258: Side Effects: None
16259:
16260: =cut
16261:
16262: sub timebased_select_form {
16263: my ($item,$filter) = @_;
16264: if (ref($filter) eq 'HASH') {
16265: $filter->{$item} =~ s/[^\d-]//g;
16266: if (!$filter->{$item}) { $filter->{$item}=-1; }
16267: return &select_form(
16268: $filter->{$item},
16269: $item,
16270: { '-1' => '',
16271: '86400' => &mt('today'),
16272: '604800' => &mt('last week'),
16273: '2592000' => &mt('last month'),
16274: '7776000' => &mt('last three months'),
16275: '15552000' => &mt('last six months'),
16276: '31104000' => &mt('last year'),
16277: 'select_form_order' =>
16278: ['-1','86400','604800','2592000','7776000',
16279: '15552000','31104000']});
16280: }
16281: }
16282:
16283: =pod
16284:
16285: =item * &js_changer()
16286:
16287: Create script tag containing Javascript used to submit course search form
16288: when course type or domain is changed, and also to hide 'Searching ...' on
16289: page load completion for page showing search result.
16290:
16291: Inputs: None
16292:
16293: Returns: markup containing updateFilters() and hideSearching() javascript functions.
16294:
16295: Side Effects: None
16296:
16297: =cut
16298:
16299: sub js_changer {
16300: return <<ENDJS;
16301: <script type="text/javascript">
16302: // <![CDATA[
16303: function updateFilters(caller) {
16304: if (typeof(caller) != "undefined") {
16305: document.filterpicker.updater.value = caller.name;
16306: }
16307: document.filterpicker.submit();
16308: }
16309:
16310: function hideSearching() {
16311: if (document.getElementById('searching')) {
16312: document.getElementById('searching').style.display = 'none';
16313: }
16314: return;
16315: }
16316:
16317: // ]]>
16318: </script>
16319:
16320: ENDJS
16321: }
16322:
16323: =pod
16324:
16325: =item * &search_courses()
16326:
16327: Process selected filters form course search form and pass to lonnet::courseiddump
16328: to retrieve a hash for which keys are courseIDs which match the selected filters.
16329:
16330: Inputs:
16331:
16332: dom - domain being searched
16333:
16334: type - course type ('Course' or 'Community' or '.' if any).
16335:
16336: filter - anonymous hash of criteria and their values
16337:
16338: numtitles - for institutional codes - number of categories
16339:
16340: cloneruname - optional username of new course owner
16341:
16342: clonerudom - optional domain of new course owner
16343:
16344: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
16345: (used when DC is using course creation form)
16346:
16347: codetitles - reference to array of titles of components in institutional codes (official courses).
16348:
16349: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16350: (and so can clone automatically)
16351:
16352: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16353:
16354: reqinstcode - institutional code of new course, where search_courses is used to identify potential
16355: courses to clone
16356:
16357: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
16358:
16359:
16360: Side Effects: None
16361:
16362: =cut
16363:
16364:
16365: sub search_courses {
16366: my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
16367: $cc_clone,$reqcrsdom,$reqinstcode) = @_;
16368: my (%courses,%showcourses,$cloner);
16369: if (($filter->{'ownerfilter'} ne '') ||
16370: ($filter->{'ownerdomfilter'} ne '')) {
16371: $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
16372: $filter->{'ownerdomfilter'};
16373: }
16374: foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
16375: if (!$filter->{$item}) {
16376: $filter->{$item}='.';
16377: }
16378: }
16379: my $now = time;
16380: my $timefilter =
16381: ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
16382: my ($createdbefore,$createdafter);
16383: if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
16384: $createdbefore = $now;
16385: $createdafter = $now-$filter->{'createdfilter'};
16386: }
16387: my ($instcodefilter,$regexpok);
16388: if ($numtitles) {
16389: if ($env{'form.official'} eq 'on') {
16390: $instcodefilter =
16391: &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16392: $regexpok = 1;
16393: } elsif ($env{'form.official'} eq 'off') {
16394: $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16395: unless ($instcodefilter eq '') {
16396: $regexpok = -1;
16397: }
16398: }
16399: } else {
16400: $instcodefilter = $filter->{'instcodefilter'};
16401: }
16402: if ($instcodefilter eq '') { $instcodefilter = '.'; }
16403: if ($type eq '') { $type = '.'; }
16404:
16405: if (($clonerudom ne '') && ($cloneruname ne '')) {
16406: $cloner = $cloneruname.':'.$clonerudom;
16407: }
16408: %courses = &Apache::lonnet::courseiddump($dom,
16409: $filter->{'descriptfilter'},
16410: $timefilter,
16411: $instcodefilter,
16412: $filter->{'combownerfilter'},
16413: $filter->{'coursefilter'},
16414: undef,undef,$type,$regexpok,undef,undef,
16415: undef,undef,$cloner,$cc_clone,
16416: $filter->{'cloneableonly'},
16417: $createdbefore,$createdafter,undef,
16418: $domcloner,undef,$reqcrsdom,$reqinstcode);
16419: if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
16420: my $ccrole;
16421: if ($type eq 'Community') {
16422: $ccrole = 'co';
16423: } else {
16424: $ccrole = 'cc';
16425: }
16426: my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
16427: $filter->{'persondomfilter'},
16428: 'userroles',undef,
16429: [$ccrole,'in','ad','ep','ta','cr'],
16430: $dom);
16431: foreach my $role (keys(%rolehash)) {
16432: my ($cnum,$cdom,$courserole) = split(':',$role);
16433: my $cid = $cdom.'_'.$cnum;
16434: if (exists($courses{$cid})) {
16435: if (ref($courses{$cid}) eq 'HASH') {
16436: if (ref($courses{$cid}{roles}) eq 'ARRAY') {
16437: if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
16438: push(@{$courses{$cid}{roles}},$courserole);
16439: }
16440: } else {
16441: $courses{$cid}{roles} = [$courserole];
16442: }
16443: $showcourses{$cid} = $courses{$cid};
16444: }
16445: }
16446: }
16447: %courses = %showcourses;
16448: }
16449: return %courses;
16450: }
16451:
16452: =pod
16453:
16454: =back
16455:
16456: =head1 Routines for version requirements for current course.
16457:
16458: =over 4
16459:
16460: =item * &check_release_required()
16461:
16462: Compares required LON-CAPA version with version on server, and
16463: if required version is newer looks for a server with the required version.
16464:
16465: Looks first at servers in user's owen domain; if none suitable, looks at
16466: servers in course's domain are permitted to host sessions for user's domain.
16467:
16468: Inputs:
16469:
16470: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16471:
16472: $courseid - Course ID of current course
16473:
16474: $rolecode - User's current role in course (for switchserver query string).
16475:
16476: $required - LON-CAPA version needed by course (format: Major.Minor).
16477:
16478:
16479: Returns:
16480:
16481: $switchserver - query string tp append to /adm/switchserver call (if
16482: current server's LON-CAPA version is too old.
16483:
16484: $warning - Message is displayed if no suitable server could be found.
16485:
16486: =cut
16487:
16488: sub check_release_required {
16489: my ($loncaparev,$courseid,$rolecode,$required) = @_;
16490: my ($switchserver,$warning);
16491: if ($required ne '') {
16492: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
16493: my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16494: if ($reqdmajor ne '' && $reqdminor ne '') {
16495: my $otherserver;
16496: if (($major eq '' && $minor eq '') ||
16497: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
16498: my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
16499: my $switchlcrev =
16500: &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
16501: $userdomserver);
16502: my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16503: if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
16504: (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
16505: my $cdom = $env{'course.'.$courseid.'.domain'};
16506: if ($cdom ne $env{'user.domain'}) {
16507: my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
16508: my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
16509: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16510: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
16511: my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
16512: my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
16513: my $canhost =
16514: &Apache::lonnet::can_host_session($env{'user.domain'},
16515: $coursedomserver,
16516: $remoterev,
16517: $udomdefaults{'remotesessions'},
16518: $defdomdefaults{'hostedsessions'});
16519:
16520: if ($canhost) {
16521: $otherserver = $coursedomserver;
16522: } else {
16523: $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.");
16524: }
16525: } else {
16526: $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).");
16527: }
16528: } else {
16529: $otherserver = $userdomserver;
16530: }
16531: }
16532: if ($otherserver ne '') {
16533: $switchserver = 'otherserver='.$otherserver.'&role='.$rolecode;
16534: }
16535: }
16536: }
16537: return ($switchserver,$warning);
16538: }
16539:
16540: =pod
16541:
16542: =item * &check_release_result()
16543:
16544: Inputs:
16545:
16546: $switchwarning - Warning message if no suitable server found to host session.
16547:
16548: $switchserver - query string to append to /adm/switchserver containing lonHostID
16549: and current role.
16550:
16551: Returns: HTML to display with information about requirement to switch server.
16552: Either displaying warning with link to Roles/Courses screen or
16553: display link to switchserver.
16554:
16555: =cut
16556:
16557: sub check_release_result {
16558: my ($switchwarning,$switchserver) = @_;
16559: my $output = &start_page('Selected course unavailable on this server').
16560: '<p class="LC_warning">';
16561: if ($switchwarning) {
16562: $output .= $switchwarning.'<br /><a href="/adm/roles">';
16563: if (&show_course()) {
16564: $output .= &mt('Display courses');
16565: } else {
16566: $output .= &mt('Display roles');
16567: }
16568: $output .= '</a>';
16569: } elsif ($switchserver) {
16570: $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
16571: '<br />'.
16572: '<a href="/adm/switchserver?'.$switchserver.'">'.
16573: &mt('Switch Server').
16574: '</a>';
16575: }
16576: $output .= '</p>'.&end_page();
16577: return $output;
16578: }
16579:
16580: =pod
16581:
16582: =item * &needs_coursereinit()
16583:
16584: Determine if course contents stored for user's session needs to be
16585: refreshed, because content has changed since "Big Hash" last tied.
16586:
16587: Check for change is made if time last checked is more than 10 minutes ago
16588: (by default).
16589:
16590: Inputs:
16591:
16592: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16593:
16594: $interval (optional) - Time which may elapse (in s) between last check for content
16595: change in current course. (default: 600 s).
16596:
16597: Returns: an array; first element is:
16598:
16599: =over 4
16600:
16601: 'switch' - if content updates mean user's session
16602: needs to be switched to a server running a newer LON-CAPA version
16603:
16604: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
16605: on current server hosting user's session
16606:
16607: '' - if no action required.
16608:
16609: =back
16610:
16611: If first item element is 'switch':
16612:
16613: second item is $switchwarning - Warning message if no suitable server found to host session.
16614:
16615: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
16616: and current role.
16617:
16618: otherwise: no other elements returned.
16619:
16620: =back
16621:
16622: =cut
16623:
16624: sub needs_coursereinit {
16625: my ($loncaparev,$interval) = @_;
16626: return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
16627: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
16628: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
16629: my $now = time;
16630: if ($interval eq '') {
16631: $interval = 600;
16632: }
16633: if (($now-$env{'request.course.timechecked'})>$interval) {
16634: my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
16635: &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
16636: if ($lastchange > $env{'request.course.tied'}) {
16637: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16638: if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
16639: my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
16640: if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
16641: &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
16642: $curr_reqd_hash{'internal.releaserequired'}});
16643: my ($switchserver,$switchwarning) =
16644: &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
16645: $curr_reqd_hash{'internal.releaserequired'});
16646: if ($switchwarning ne '' || $switchserver ne '') {
16647: return ('switch',$switchwarning,$switchserver);
16648: }
16649: }
16650: }
16651: return ('update');
16652: }
16653: }
16654: return ();
16655: }
16656:
16657: sub update_content_constraints {
16658: my ($cdom,$cnum,$chome,$cid) = @_;
16659: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16660: my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
16661: my %checkresponsetypes;
16662: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
16663: my ($item,$name,$value) = split(/:/,$key);
16664: if ($item eq 'resourcetag') {
16665: if ($name eq 'responsetype') {
16666: $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
16667: }
16668: }
16669: }
16670: my $navmap = Apache::lonnavmaps::navmap->new();
16671: if (defined($navmap)) {
16672: my %allresponses;
16673: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
16674: my %responses = $res->responseTypes();
16675: foreach my $key (keys(%responses)) {
16676: next unless(exists($checkresponsetypes{$key}));
16677: $allresponses{$key} += $responses{$key};
16678: }
16679: }
16680: foreach my $key (keys(%allresponses)) {
16681: my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
16682: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
16683: ($reqdmajor,$reqdminor) = ($major,$minor);
16684: }
16685: }
16686: undef($navmap);
16687: }
16688: unless (($reqdmajor eq '') && ($reqdminor eq '')) {
16689: &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
16690: }
16691: return;
16692: }
16693:
16694: sub allmaps_incourse {
16695: my ($cdom,$cnum,$chome,$cid) = @_;
16696: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
16697: $cid = $env{'request.course.id'};
16698: $cdom = $env{'course.'.$cid.'.domain'};
16699: $cnum = $env{'course.'.$cid.'.num'};
16700: $chome = $env{'course.'.$cid.'.home'};
16701: }
16702: my %allmaps = ();
16703: my $lastchange =
16704: &Apache::lonnet::get_coursechange($cdom,$cnum);
16705: if ($lastchange > $env{'request.course.tied'}) {
16706: my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
16707: unless ($ferr) {
16708: &update_content_constraints($cdom,$cnum,$chome,$cid);
16709: }
16710: }
16711: my $navmap = Apache::lonnavmaps::navmap->new();
16712: if (defined($navmap)) {
16713: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
16714: $allmaps{$res->src()} = 1;
16715: }
16716: }
16717: return \%allmaps;
16718: }
16719:
16720: sub parse_supplemental_title {
16721: my ($title) = @_;
16722:
16723: my ($foldertitle,$renametitle);
16724: if ($title =~ /&&&/) {
16725: $title = &HTML::Entites::decode($title);
16726: }
16727: if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
16728: $renametitle=$4;
16729: my ($time,$uname,$udom) = ($1,$2,$3);
16730: $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
16731: my $name = &plainname($uname,$udom);
16732: $name = &HTML::Entities::encode($name,'"<>&\'');
16733: $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
16734: $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
16735: $name.': <br />'.$foldertitle;
16736: }
16737: if (wantarray) {
16738: return ($title,$foldertitle,$renametitle);
16739: }
16740: return $title;
16741: }
16742:
16743: sub recurse_supplemental {
16744: my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
16745: if ($suppmap) {
16746: my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
16747: if ($fatal) {
16748: $errors ++;
16749: } else {
16750: if ($#LONCAPA::map::resources > 0) {
16751: foreach my $res (@LONCAPA::map::resources) {
16752: my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
16753: if (($src ne '') && ($status eq 'res')) {
16754: if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
16755: ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
16756: } else {
16757: $numfiles ++;
16758: }
16759: }
16760: }
16761: }
16762: }
16763: }
16764: return ($numfiles,$errors);
16765: }
16766:
16767: sub symb_to_docspath {
16768: my ($symb,$navmapref) = @_;
16769: return unless ($symb && ref($navmapref));
16770: my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
16771: if ($resurl=~/\.(sequence|page)$/) {
16772: $mapurl=$resurl;
16773: } elsif ($resurl eq 'adm/navmaps') {
16774: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
16775: }
16776: my $mapresobj;
16777: unless (ref($$navmapref)) {
16778: $$navmapref = Apache::lonnavmaps::navmap->new();
16779: }
16780: if (ref($$navmapref)) {
16781: $mapresobj = $$navmapref->getResourceByUrl($mapurl);
16782: }
16783: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
16784: my $type=$2;
16785: my $path;
16786: if (ref($mapresobj)) {
16787: my $pcslist = $mapresobj->map_hierarchy();
16788: if ($pcslist ne '') {
16789: foreach my $pc (split(/,/,$pcslist)) {
16790: next if ($pc <= 1);
16791: my $res = $$navmapref->getByMapPc($pc);
16792: if (ref($res)) {
16793: my $thisurl = $res->src();
16794: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
16795: my $thistitle = $res->title();
16796: $path .= '&'.
16797: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
16798: &escape($thistitle).
16799: ':'.$res->randompick().
16800: ':'.$res->randomout().
16801: ':'.$res->encrypted().
16802: ':'.$res->randomorder().
16803: ':'.$res->is_page();
16804: }
16805: }
16806: }
16807: $path =~ s/^\&//;
16808: my $maptitle = $mapresobj->title();
16809: if ($mapurl eq 'default') {
16810: $maptitle = 'Main Content';
16811: }
16812: $path .= (($path ne '')? '&' : '').
16813: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16814: &escape($maptitle).
16815: ':'.$mapresobj->randompick().
16816: ':'.$mapresobj->randomout().
16817: ':'.$mapresobj->encrypted().
16818: ':'.$mapresobj->randomorder().
16819: ':'.$mapresobj->is_page();
16820: } else {
16821: my $maptitle = &Apache::lonnet::gettitle($mapurl);
16822: my $ispage = (($type eq 'page')? 1 : '');
16823: if ($mapurl eq 'default') {
16824: $maptitle = 'Main Content';
16825: }
16826: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16827: &escape($maptitle).':::::'.$ispage;
16828: }
16829: unless ($mapurl eq 'default') {
16830: $path = 'default&'.
16831: &escape('Main Content').
16832: ':::::&'.$path;
16833: }
16834: return $path;
16835: }
16836:
16837: sub captcha_display {
16838: my ($context,$lonhost,$defdom) = @_;
16839: my ($output,$error);
16840: my ($captcha,$pubkey,$privkey,$version) =
16841: &get_captcha_config($context,$lonhost,$defdom);
16842: if ($captcha eq 'original') {
16843: $output = &create_captcha();
16844: unless ($output) {
16845: $error = 'captcha';
16846: }
16847: } elsif ($captcha eq 'recaptcha') {
16848: $output = &create_recaptcha($pubkey,$version);
16849: unless ($output) {
16850: $error = 'recaptcha';
16851: }
16852: }
16853: return ($output,$error,$captcha,$version);
16854: }
16855:
16856: sub captcha_response {
16857: my ($context,$lonhost,$defdom) = @_;
16858: my ($captcha_chk,$captcha_error);
16859: my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
16860: if ($captcha eq 'original') {
16861: ($captcha_chk,$captcha_error) = &check_captcha();
16862: } elsif ($captcha eq 'recaptcha') {
16863: $captcha_chk = &check_recaptcha($privkey,$version);
16864: } else {
16865: $captcha_chk = 1;
16866: }
16867: return ($captcha_chk,$captcha_error);
16868: }
16869:
16870: sub get_captcha_config {
16871: my ($context,$lonhost,$dom_in_effect) = @_;
16872: my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
16873: my $hostname = &Apache::lonnet::hostname($lonhost);
16874: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
16875: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16876: if ($context eq 'usercreation') {
16877: my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
16878: if (ref($domconfig{$context}) eq 'HASH') {
16879: $hashtocheck = $domconfig{$context}{'cancreate'};
16880: if (ref($hashtocheck) eq 'HASH') {
16881: if ($hashtocheck->{'captcha'} eq 'recaptcha') {
16882: if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
16883: $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
16884: $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
16885: }
16886: if ($privkey && $pubkey) {
16887: $captcha = 'recaptcha';
16888: $version = $hashtocheck->{'recaptchaversion'};
16889: if ($version ne '2') {
16890: $version = 1;
16891: }
16892: } else {
16893: $captcha = 'original';
16894: }
16895: } elsif ($hashtocheck->{'captcha'} ne 'notused') {
16896: $captcha = 'original';
16897: }
16898: }
16899: } else {
16900: $captcha = 'captcha';
16901: }
16902: } elsif ($context eq 'login') {
16903: my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
16904: if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
16905: $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
16906: $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
16907: if ($privkey && $pubkey) {
16908: $captcha = 'recaptcha';
16909: $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
16910: if ($version ne '2') {
16911: $version = 1;
16912: }
16913: } else {
16914: $captcha = 'original';
16915: }
16916: } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
16917: $captcha = 'original';
16918: }
16919: } elsif ($context eq 'passwords') {
16920: if ($dom_in_effect) {
16921: my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
16922: if ($passwdconf{'captcha'} eq 'recaptcha') {
16923: if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
16924: $pubkey = $passwdconf{'recaptchakeys'}{'public'};
16925: $privkey = $passwdconf{'recaptchakeys'}{'private'};
16926: }
16927: if ($privkey && $pubkey) {
16928: $captcha = 'recaptcha';
16929: $version = $passwdconf{'recaptchaversion'};
16930: if ($version ne '2') {
16931: $version = 1;
16932: }
16933: } else {
16934: $captcha = 'original';
16935: }
16936: } elsif ($passwdconf{'captcha'} ne 'notused') {
16937: $captcha = 'original';
16938: }
16939: }
16940: }
16941: return ($captcha,$pubkey,$privkey,$version);
16942: }
16943:
16944: sub create_captcha {
16945: my %captcha_params = &captcha_settings();
16946: my ($output,$maxtries,$tries) = ('',10,0);
16947: while ($tries < $maxtries) {
16948: $tries ++;
16949: my $captcha = Authen::Captcha->new (
16950: output_folder => $captcha_params{'output_dir'},
16951: data_folder => $captcha_params{'db_dir'},
16952: );
16953: my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
16954:
16955: if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
16956: $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
16957: &mt('Type in the letters/numbers shown below').' '.
16958: '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
16959: '<br />'.
16960: '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
16961: last;
16962: }
16963: }
16964: return $output;
16965: }
16966:
16967: sub captcha_settings {
16968: my %captcha_params = (
16969: output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'},
16970: www_output_dir => "/captchaspool",
16971: db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'},
16972: numchars => '5',
16973: );
16974: return %captcha_params;
16975: }
16976:
16977: sub check_captcha {
16978: my ($captcha_chk,$captcha_error);
16979: my $code = $env{'form.code'};
16980: my $md5sum = $env{'form.crypt'};
16981: my %captcha_params = &captcha_settings();
16982: my $captcha = Authen::Captcha->new(
16983: output_folder => $captcha_params{'output_dir'},
16984: data_folder => $captcha_params{'db_dir'},
16985: );
16986: $captcha_chk = $captcha->check_code($code,$md5sum);
16987: my %captcha_hash = (
16988: 0 => 'Code not checked (file error)',
16989: -1 => 'Failed: code expired',
16990: -2 => 'Failed: invalid code (not in database)',
16991: -3 => 'Failed: invalid code (code does not match crypt)',
16992: );
16993: if ($captcha_chk != 1) {
16994: $captcha_error = $captcha_hash{$captcha_chk}
16995: }
16996: return ($captcha_chk,$captcha_error);
16997: }
16998:
16999: sub create_recaptcha {
17000: my ($pubkey,$version) = @_;
17001: if ($version >= 2) {
17002: return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
17003: } else {
17004: my $use_ssl;
17005: if ($ENV{'SERVER_PORT'} == 443) {
17006: $use_ssl = 1;
17007: }
17008: my $captcha = Captcha::reCAPTCHA->new;
17009: return $captcha->get_options_setter({theme => 'white'})."\n".
17010: $captcha->get_html($pubkey,undef,$use_ssl).
17011: &mt('If the text is hard to read, [_1] will replace them.',
17012: '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
17013: '<br /><br />';
17014: }
17015: }
17016:
17017: sub check_recaptcha {
17018: my ($privkey,$version) = @_;
17019: my $captcha_chk;
17020: if ($version >= 2) {
17021: my $ua = LWP::UserAgent->new;
17022: $ua->timeout(10);
17023: my %info = (
17024: secret => $privkey,
17025: response => $env{'form.g-recaptcha-response'},
17026: remoteip => $ENV{'REMOTE_ADDR'},
17027: );
17028: my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
17029: if ($response->is_success) {
17030: my $data = JSON::DWIW->from_json($response->decoded_content);
17031: if (ref($data) eq 'HASH') {
17032: if ($data->{'success'}) {
17033: $captcha_chk = 1;
17034: }
17035: }
17036: }
17037: } else {
17038: my $captcha = Captcha::reCAPTCHA->new;
17039: my $captcha_result =
17040: $captcha->check_answer(
17041: $privkey,
17042: $ENV{'REMOTE_ADDR'},
17043: $env{'form.recaptcha_challenge_field'},
17044: $env{'form.recaptcha_response_field'},
17045: );
17046: if ($captcha_result->{is_valid}) {
17047: $captcha_chk = 1;
17048: }
17049: }
17050: return $captcha_chk;
17051: }
17052:
17053: sub emailusername_info {
17054: my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
17055: my %titles = &Apache::lonlocal::texthash (
17056: lastname => 'Last Name',
17057: firstname => 'First Name',
17058: institution => 'School/college/university',
17059: location => "School's city, state/province, country",
17060: web => "School's web address",
17061: officialemail => 'E-mail address at institution (if different)',
17062: id => 'Student/Employee ID',
17063: );
17064: return (\@fields,\%titles);
17065: }
17066:
17067: sub cleanup_html {
17068: my ($incoming) = @_;
17069: my $outgoing;
17070: if ($incoming ne '') {
17071: $outgoing = $incoming;
17072: $outgoing =~ s/;/;/g;
17073: $outgoing =~ s/\#/#/g;
17074: $outgoing =~ s/\&/&/g;
17075: $outgoing =~ s/</</g;
17076: $outgoing =~ s/>/>/g;
17077: $outgoing =~ s/\(/(/g;
17078: $outgoing =~ s/\)/)/g;
17079: $outgoing =~ s/"/"/g;
17080: $outgoing =~ s/'/'/g;
17081: $outgoing =~ s/\$/$/g;
17082: $outgoing =~ s{/}{/}g;
17083: $outgoing =~ s/=/=/g;
17084: $outgoing =~ s/\\/\/g
17085: }
17086: return $outgoing;
17087: }
17088:
17089: # Checks for critical messages and returns a redirect url if one exists.
17090: # $interval indicates how often to check for messages.
17091: sub critical_redirect {
17092: my ($interval) = @_;
17093: if ((time-$env{'user.criticalcheck.time'})>$interval) {
17094: my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
17095: $env{'user.name'});
17096: &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
17097: my $redirecturl;
17098: if ($what[0]) {
17099: if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
17100: $redirecturl='/adm/email?critical=display';
17101: my $url=&Apache::lonnet::absolute_url().$redirecturl;
17102: return (1, $url);
17103: }
17104: }
17105: }
17106: return ();
17107: }
17108:
17109: # Use:
17110: # my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
17111: #
17112: ##################################################
17113: # password associated functions #
17114: ##################################################
17115: sub des_keys {
17116: # Make a new key for DES encryption.
17117: # Each key has two parts which are returned separately.
17118: # Please note: Each key must be passed through the &hex function
17119: # before it is output to the web browser. The hex versions cannot
17120: # be used to decrypt.
17121: my @hexstr=('0','1','2','3','4','5','6','7',
17122: '8','9','a','b','c','d','e','f');
17123: my $lkey='';
17124: for (0..7) {
17125: $lkey.=$hexstr[rand(15)];
17126: }
17127: my $ukey='';
17128: for (0..7) {
17129: $ukey.=$hexstr[rand(15)];
17130: }
17131: return ($lkey,$ukey);
17132: }
17133:
17134: sub des_decrypt {
17135: my ($key,$cyphertext) = @_;
17136: my $keybin=pack("H16",$key);
17137: my $cypher;
17138: if ($Crypt::DES::VERSION>=2.03) {
17139: $cypher=new Crypt::DES $keybin;
17140: } else {
17141: $cypher=new DES $keybin;
17142: }
17143: my $plaintext='';
17144: my $cypherlength = length($cyphertext);
17145: my $numchunks = int($cypherlength/32);
17146: for (my $j=0; $j<$numchunks; $j++) {
17147: my $start = $j*32;
17148: my $cypherblock = substr($cyphertext,$start,32);
17149: my $chunk =
17150: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
17151: $chunk .=
17152: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
17153: $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
17154: $plaintext .= $chunk;
17155: }
17156: return $plaintext;
17157: }
17158:
17159: sub is_nonframeable {
17160: my ($url,$absolute,$hostname,$ip,$nocache) = @_;
17161: my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
17162: return if (($remprotocol eq '') || ($remhost eq ''));
17163:
17164: $remprotocol = lc($remprotocol);
17165: $remhost = lc($remhost);
17166: my $remport = 80;
17167: if ($remprotocol eq 'https') {
17168: $remport = 443;
17169: }
17170: my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
17171: if ($cached) {
17172: unless ($nocache) {
17173: if ($result) {
17174: return 1;
17175: } else {
17176: return 0;
17177: }
17178: }
17179: }
17180: my $uselink;
17181: my $request = new HTTP::Request('HEAD',$url);
17182: my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',5);
17183: if ($response->is_success()) {
17184: my $secpolicy = lc($response->header('content-security-policy'));
17185: my $xframeop = lc($response->header('x-frame-options'));
17186: $secpolicy =~ s/^\s+|\s+$//g;
17187: $xframeop =~ s/^\s+|\s+$//g;
17188: if (($secpolicy ne '') || ($xframeop ne '')) {
17189: my $remotehost = $remprotocol.'://'.$remhost;
17190: my ($origin,$protocol,$port);
17191: if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
17192: $port = $ENV{'SERVER_PORT'};
17193: } else {
17194: $port = 80;
17195: }
17196: if ($absolute eq '') {
17197: $protocol = 'http:';
17198: if ($port == 443) {
17199: $protocol = 'https:';
17200: }
17201: $origin = $protocol.'//'.lc($hostname);
17202: } else {
17203: $origin = lc($absolute);
17204: ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
17205: }
17206: if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
17207: my $framepolicy = $1;
17208: $framepolicy =~ s/^\s+|\s+$//g;
17209: my @policies = split(/\s+/,$framepolicy);
17210: if (@policies) {
17211: if (grep(/^\Q'none'\E$/,@policies)) {
17212: $uselink = 1;
17213: } else {
17214: $uselink = 1;
17215: if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
17216: (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
17217: (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
17218: undef($uselink);
17219: }
17220: if ($uselink) {
17221: if (grep(/^\Q'self'\E$/,@policies)) {
17222: if (($origin ne '') && ($remotehost eq $origin)) {
17223: undef($uselink);
17224: }
17225: }
17226: }
17227: if ($uselink) {
17228: my @possok;
17229: if ($ip ne '') {
17230: push(@possok,$ip);
17231: }
17232: my $hoststr = '';
17233: foreach my $part (reverse(split(/\./,$hostname))) {
17234: if ($hoststr eq '') {
17235: $hoststr = $part;
17236: } else {
17237: $hoststr = "$part.$hoststr";
17238: }
17239: if ($hoststr eq $hostname) {
17240: push(@possok,$hostname);
17241: } else {
17242: push(@possok,"*.$hoststr");
17243: }
17244: }
17245: if (@possok) {
17246: foreach my $poss (@possok) {
17247: last if (!$uselink);
17248: foreach my $policy (@policies) {
17249: if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
17250: undef($uselink);
17251: last;
17252: }
17253: }
17254: }
17255: }
17256: }
17257: }
17258: }
17259: } elsif ($xframeop ne '') {
17260: $uselink = 1;
17261: my @policies = split(/\s*,\s*/,$xframeop);
17262: if (@policies) {
17263: unless (grep(/^deny$/,@policies)) {
17264: if ($origin ne '') {
17265: if (grep(/^sameorigin$/,@policies)) {
17266: if ($remotehost eq $origin) {
17267: undef($uselink);
17268: }
17269: }
17270: if ($uselink) {
17271: foreach my $policy (@policies) {
17272: if ($policy =~ /^allow-from\s*(.+)$/) {
17273: my $allowfrom = $1;
17274: if (($allowfrom ne '') && ($allowfrom eq $origin)) {
17275: undef($uselink);
17276: last;
17277: }
17278: }
17279: }
17280: }
17281: }
17282: }
17283: }
17284: }
17285: }
17286: }
17287: if ($nocache) {
17288: if ($cached) {
17289: my $devalidate;
17290: if ($uselink && !$result) {
17291: $devalidate = 1;
17292: } elsif (!$uselink && $result) {
17293: $devalidate = 1;
17294: }
17295: if ($devalidate) {
17296: &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
17297: }
17298: }
17299: } else {
17300: if ($uselink) {
17301: $result = 1;
17302: } else {
17303: $result = 0;
17304: }
17305: &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
17306: }
17307: return $uselink;
17308: }
17309:
17310: 1;
17311: __END__;
17312:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>