1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1075.2.127.2.4 2017/11/16 15:06:35 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 DateTime::TimeZone;
75: use DateTime::Locale;
76: use Encode();
77: use Authen::Captcha;
78: use Captcha::reCAPTCHA;
79: use JSON::DWIW;
80: use LWP::UserAgent;
81: use Crypt::DES;
82: use DynaLoader; # for Crypt::DES version
83: use File::Copy();
84: use File::Path();
85:
86: # ---------------------------------------------- Designs
87: use vars qw(%defaultdesign);
88:
89: my $readit;
90:
91:
92: ##
93: ## Global Variables
94: ##
95:
96:
97: # ----------------------------------------------- SSI with retries:
98: #
99:
100: =pod
101:
102: =head1 Server Side include with retries:
103:
104: =over 4
105:
106: =item * &ssi_with_retries(resource,retries form)
107:
108: Performs an ssi with some number of retries. Retries continue either
109: until the result is ok or until the retry count supplied by the
110: caller is exhausted.
111:
112: Inputs:
113:
114: =over 4
115:
116: resource - Identifies the resource to insert.
117:
118: retries - Count of the number of retries allowed.
119:
120: form - Hash that identifies the rendering options.
121:
122: =back
123:
124: Returns:
125:
126: =over 4
127:
128: content - The content of the response. If retries were exhausted this is empty.
129:
130: response - The response from the last attempt (which may or may not have been successful.
131:
132: =back
133:
134: =back
135:
136: =cut
137:
138: sub ssi_with_retries {
139: my ($resource, $retries, %form) = @_;
140:
141:
142: my $ok = 0; # True if we got a good response.
143: my $content;
144: my $response;
145:
146: # Try to get the ssi done. within the retries count:
147:
148: do {
149: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
150: $ok = $response->is_success;
151: if (!$ok) {
152: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
153: }
154: $retries--;
155: } while (!$ok && ($retries > 0));
156:
157: if (!$ok) {
158: $content = ''; # On error return an empty content.
159: }
160: return ($content, $response);
161:
162: }
163:
164:
165:
166: # ----------------------------------------------- Filetypes/Languages/Copyright
167: my %language;
168: my %supported_language;
169: my %latex_language; # For choosing hyphenation in <transl..>
170: my %latex_language_bykey; # for choosing hyphenation from metadata
171: my %cprtag;
172: my %scprtag;
173: my %fe; my %fd; my %fm;
174: my %category_extensions;
175:
176: # ---------------------------------------------- Thesaurus variables
177: #
178: # %Keywords:
179: # A hash used by &keyword to determine if a word is considered a keyword.
180: # $thesaurus_db_file
181: # Scalar containing the full path to the thesaurus database.
182:
183: my %Keywords;
184: my $thesaurus_db_file;
185:
186: #
187: # Initialize values from language.tab, copyright.tab, filetypes.tab,
188: # thesaurus.tab, and filecategories.tab.
189: #
190: BEGIN {
191: # Variable initialization
192: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
193: #
194: unless ($readit) {
195: # ------------------------------------------------------------------- languages
196: {
197: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
198: '/language.tab';
199: if ( open(my $fh,"<$langtabfile") ) {
200: while (my $line = <$fh>) {
201: next if ($line=~/^\#/);
202: chomp($line);
203: my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
204: $language{$key}=$val.' - '.$enc;
205: if ($sup) {
206: $supported_language{$key}=$sup;
207: }
208: if ($latex) {
209: $latex_language_bykey{$key} = $latex;
210: $latex_language{$two} = $latex;
211: }
212: }
213: close($fh);
214: }
215: }
216: # ------------------------------------------------------------------ copyrights
217: {
218: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
219: '/copyright.tab';
220: if ( open (my $fh,"<$copyrightfile") ) {
221: while (my $line = <$fh>) {
222: next if ($line=~/^\#/);
223: chomp($line);
224: my ($key,$val)=(split(/\s+/,$line,2));
225: $cprtag{$key}=$val;
226: }
227: close($fh);
228: }
229: }
230: # ----------------------------------------------------------- source copyrights
231: {
232: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
233: '/source_copyright.tab';
234: if ( open (my $fh,"<$sourcecopyrightfile") ) {
235: while (my $line = <$fh>) {
236: next if ($line =~ /^\#/);
237: chomp($line);
238: my ($key,$val)=(split(/\s+/,$line,2));
239: $scprtag{$key}=$val;
240: }
241: close($fh);
242: }
243: }
244:
245: # -------------------------------------------------------------- default domain designs
246: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
247: my $designfile = $designdir.'/default.tab';
248: if ( open (my $fh,"<$designfile") ) {
249: while (my $line = <$fh>) {
250: next if ($line =~ /^\#/);
251: chomp($line);
252: my ($key,$val)=(split(/\=/,$line));
253: if ($val) { $defaultdesign{$key}=$val; }
254: }
255: close($fh);
256: }
257:
258: # ------------------------------------------------------------- file categories
259: {
260: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
261: '/filecategories.tab';
262: if ( open (my $fh,"<$categoryfile") ) {
263: while (my $line = <$fh>) {
264: next if ($line =~ /^\#/);
265: chomp($line);
266: my ($extension,$category)=(split(/\s+/,$line,2));
267: push(@{$category_extensions{lc($category)}},$extension);
268: }
269: close($fh);
270: }
271:
272: }
273: # ------------------------------------------------------------------ file types
274: {
275: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
276: '/filetypes.tab';
277: if ( open (my $fh,"<$typesfile") ) {
278: while (my $line = <$fh>) {
279: next if ($line =~ /^\#/);
280: chomp($line);
281: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
282: if ($descr ne '') {
283: $fe{$ending}=lc($emb);
284: $fd{$ending}=$descr;
285: if ($mime ne 'unk') { $fm{$ending}=$mime; }
286: }
287: }
288: close($fh);
289: }
290: }
291: &Apache::lonnet::logthis(
292: "<span style='color:yellow;'>INFO: Read file types</span>");
293: $readit=1;
294: } # end of unless($readit)
295:
296: }
297:
298: ###############################################################
299: ## HTML and Javascript Helper Functions ##
300: ###############################################################
301:
302: =pod
303:
304: =head1 HTML and Javascript Functions
305:
306: =over 4
307:
308: =item * &browser_and_searcher_javascript()
309:
310: X<browsing, javascript>X<searching, javascript>Returns a string
311: containing javascript with two functions, C<openbrowser> and
312: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
313: tags.
314:
315: =item * &openbrowser(formname,elementname,only,omit) [javascript]
316:
317: inputs: formname, elementname, only, omit
318:
319: formname and elementname indicate the name of the html form and name of
320: the element that the results of the browsing selection are to be placed in.
321:
322: Specifying 'only' will restrict the browser to displaying only files
323: with the given extension. Can be a comma separated list.
324:
325: Specifying 'omit' will restrict the browser to NOT displaying files
326: with the given extension. Can be a comma separated list.
327:
328: =item * &opensearcher(formname,elementname) [javascript]
329:
330: Inputs: formname, elementname
331:
332: formname and elementname specify the name of the html form and the name
333: of the element the selection from the search results will be placed in.
334:
335: =cut
336:
337: sub browser_and_searcher_javascript {
338: my ($mode)=@_;
339: if (!defined($mode)) { $mode='edit'; }
340: my $resurl=&escape_single(&lastresurl());
341: return <<END;
342: // <!-- BEGIN LON-CAPA Internal
343: var editbrowser = null;
344: function openbrowser(formname,elementname,only,omit,titleelement) {
345: var url = '$resurl/?';
346: if (editbrowser == null) {
347: url += 'launch=1&';
348: }
349: url += 'catalogmode=interactive&';
350: url += 'mode=$mode&';
351: url += 'inhibitmenu=yes&';
352: url += 'form=' + formname + '&';
353: if (only != null) {
354: url += 'only=' + only + '&';
355: } else {
356: url += 'only=&';
357: }
358: if (omit != null) {
359: url += 'omit=' + omit + '&';
360: } else {
361: url += 'omit=&';
362: }
363: if (titleelement != null) {
364: url += 'titleelement=' + titleelement + '&';
365: } else {
366: url += 'titleelement=&';
367: }
368: url += 'element=' + elementname + '';
369: var title = 'Browser';
370: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
371: options += ',width=700,height=600';
372: editbrowser = open(url,title,options,'1');
373: editbrowser.focus();
374: }
375: var editsearcher;
376: function opensearcher(formname,elementname,titleelement) {
377: var url = '/adm/searchcat?';
378: if (editsearcher == null) {
379: url += 'launch=1&';
380: }
381: url += 'catalogmode=interactive&';
382: url += 'mode=$mode&';
383: url += 'form=' + formname + '&';
384: if (titleelement != null) {
385: url += 'titleelement=' + titleelement + '&';
386: } else {
387: url += 'titleelement=&';
388: }
389: url += 'element=' + elementname + '';
390: var title = 'Search';
391: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
392: options += ',width=700,height=600';
393: editsearcher = open(url,title,options,'1');
394: editsearcher.focus();
395: }
396: // END LON-CAPA Internal -->
397: END
398: }
399:
400: sub lastresurl {
401: if ($env{'environment.lastresurl'}) {
402: return $env{'environment.lastresurl'}
403: } else {
404: return '/res';
405: }
406: }
407:
408: sub storeresurl {
409: my $resurl=&Apache::lonnet::clutter(shift);
410: unless ($resurl=~/^\/res/) { return 0; }
411: $resurl=~s/\/$//;
412: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
413: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
414: return 1;
415: }
416:
417: sub studentbrowser_javascript {
418: unless (
419: (($env{'request.course.id'}) &&
420: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
421: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
422: '/'.$env{'request.course.sec'})
423: ))
424: || ($env{'request.role'}=~/^(au|dc|su)/)
425: ) { return ''; }
426: return (<<'ENDSTDBRW');
427: <script type="text/javascript" language="Javascript">
428: // <![CDATA[
429: var stdeditbrowser;
430: function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
431: var url = '/adm/pickstudent?';
432: var filter;
433: if (!ignorefilter) {
434: eval('filter=document.'+formname+'.'+uname+'.value;');
435: }
436: if (filter != null) {
437: if (filter != '') {
438: url += 'filter='+filter+'&';
439: }
440: }
441: url += 'form=' + formname + '&unameelement='+uname+
442: '&udomelement='+udom+
443: '&clicker='+clicker;
444: if (roleflag) { url+="&roles=1"; }
445: if (courseadvonly) { url+="&courseadvonly=1"; }
446: var title = 'Student_Browser';
447: var options = 'scrollbars=1,resizable=1,menubar=0';
448: options += ',width=700,height=600';
449: stdeditbrowser = open(url,title,options,'1');
450: stdeditbrowser.focus();
451: }
452: // ]]>
453: </script>
454: ENDSTDBRW
455: }
456:
457: sub resourcebrowser_javascript {
458: unless ($env{'request.course.id'}) { return ''; }
459: return (<<'ENDRESBRW');
460: <script type="text/javascript" language="Javascript">
461: // <![CDATA[
462: var reseditbrowser;
463: function openresbrowser(formname,reslink) {
464: var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
465: var title = 'Resource_Browser';
466: var options = 'scrollbars=1,resizable=1,menubar=0';
467: options += ',width=700,height=500';
468: reseditbrowser = open(url,title,options,'1');
469: reseditbrowser.focus();
470: }
471: // ]]>
472: </script>
473: ENDRESBRW
474: }
475:
476: sub selectstudent_link {
477: my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
478: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
479: &Apache::lonhtmlcommon::entity_encode($unameele)."','".
480: &Apache::lonhtmlcommon::entity_encode($udomele)."'";
481: if ($env{'request.course.id'}) {
482: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
483: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
484: '/'.$env{'request.course.sec'})) {
485: return '';
486: }
487: $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
488: if ($courseadvonly) {
489: $callargs .= ",'',1,1";
490: }
491: return '<span class="LC_nobreak">'.
492: '<a href="javascript:openstdbrowser('.$callargs.');">'.
493: &mt('Select User').'</a></span>';
494: }
495: if ($env{'request.role'}=~/^(au|dc|su)/) {
496: $callargs .= ",'',1";
497: return '<span class="LC_nobreak">'.
498: '<a href="javascript:openstdbrowser('.$callargs.');">'.
499: &mt('Select User').'</a></span>';
500: }
501: return '';
502: }
503:
504: sub selectresource_link {
505: my ($form,$reslink,$arg)=@_;
506:
507: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
508: &Apache::lonhtmlcommon::entity_encode($reslink)."'";
509: unless ($env{'request.course.id'}) { return $arg; }
510: return '<span class="LC_nobreak">'.
511: '<a href="javascript:openresbrowser('.$callargs.');">'.
512: $arg.'</a></span>';
513: }
514:
515:
516:
517: sub authorbrowser_javascript {
518: return <<"ENDAUTHORBRW";
519: <script type="text/javascript" language="JavaScript">
520: // <![CDATA[
521: var stdeditbrowser;
522:
523: function openauthorbrowser(formname,udom) {
524: var url = '/adm/pickauthor?';
525: url += 'form='+formname+'&roledom='+udom;
526: var title = 'Author_Browser';
527: var options = 'scrollbars=1,resizable=1,menubar=0';
528: options += ',width=700,height=600';
529: stdeditbrowser = open(url,title,options,'1');
530: stdeditbrowser.focus();
531: }
532:
533: // ]]>
534: </script>
535: ENDAUTHORBRW
536: }
537:
538: sub coursebrowser_javascript {
539: my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
540: $credits_element,$instcode) = @_;
541: my $wintitle = 'Course_Browser';
542: if ($crstype eq 'Community') {
543: $wintitle = 'Community_Browser';
544: }
545: my $id_functions = &javascript_index_functions();
546: my $output = '
547: <script type="text/javascript" language="JavaScript">
548: // <![CDATA[
549: var stdeditbrowser;'."\n";
550:
551: $output .= <<"ENDSTDBRW";
552: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
553: var url = '/adm/pickcourse?';
554: var formid = getFormIdByName(formname);
555: var domainfilter = getDomainFromSelectbox(formname,udom);
556: if (domainfilter != null) {
557: if (domainfilter != '') {
558: url += 'domainfilter='+domainfilter+'&';
559: }
560: }
561: url += 'form=' + formname + '&cnumelement='+uname+
562: '&cdomelement='+udom+
563: '&cnameelement='+desc;
564: if (extra_element !=null && extra_element != '') {
565: if (formname == 'rolechoice' || formname == 'studentform') {
566: url += '&roleelement='+extra_element;
567: if (domainfilter == null || domainfilter == '') {
568: url += '&domainfilter='+extra_element;
569: }
570: }
571: else {
572: if (formname == 'portform') {
573: url += '&setroles='+extra_element;
574: } else {
575: if (formname == 'rules') {
576: url += '&fixeddom='+extra_element;
577: }
578: }
579: }
580: }
581: if (type != null && type != '') {
582: url += '&type='+type;
583: }
584: if (type_elem != null && type_elem != '') {
585: url += '&typeelement='+type_elem;
586: }
587: if (formname == 'ccrs') {
588: var ownername = document.forms[formid].ccuname.value;
589: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
590: url += '&cloner='+ownername+':'+ownerdom;
591: if (type == 'Course') {
592: url += '&crscode='+document.forms[formid].crscode.value;
593: }
594: }
595: if (formname == 'requestcrs') {
596: url += '&crsdom=$domainfilter&crscode=$instcode';
597: }
598: if (multflag !=null && multflag != '') {
599: url += '&multiple='+multflag;
600: }
601: var title = '$wintitle';
602: var options = 'scrollbars=1,resizable=1,menubar=0';
603: options += ',width=700,height=600';
604: stdeditbrowser = open(url,title,options,'1');
605: stdeditbrowser.focus();
606: }
607: $id_functions
608: ENDSTDBRW
609: if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
610: $output .= &setsec_javascript($sec_element,$formname,$role_element,
611: $credits_element);
612: }
613: $output .= '
614: // ]]>
615: </script>';
616: return $output;
617: }
618:
619: sub javascript_index_functions {
620: return <<"ENDJS";
621:
622: function getFormIdByName(formname) {
623: for (var i=0;i<document.forms.length;i++) {
624: if (document.forms[i].name == formname) {
625: return i;
626: }
627: }
628: return -1;
629: }
630:
631: function getIndexByName(formid,item) {
632: for (var i=0;i<document.forms[formid].elements.length;i++) {
633: if (document.forms[formid].elements[i].name == item) {
634: return i;
635: }
636: }
637: return -1;
638: }
639:
640: function getDomainFromSelectbox(formname,udom) {
641: var userdom;
642: var formid = getFormIdByName(formname);
643: if (formid > -1) {
644: var domid = getIndexByName(formid,udom);
645: if (domid > -1) {
646: if (document.forms[formid].elements[domid].type == 'select-one') {
647: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
648: }
649: if (document.forms[formid].elements[domid].type == 'hidden') {
650: userdom=document.forms[formid].elements[domid].value;
651: }
652: }
653: }
654: return userdom;
655: }
656:
657: ENDJS
658:
659: }
660:
661: sub javascript_array_indexof {
662: return <<ENDJS;
663: <script type="text/javascript" language="JavaScript">
664: // <![CDATA[
665:
666: if (!Array.prototype.indexOf) {
667: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
668: "use strict";
669: if (this === void 0 || this === null) {
670: throw new TypeError();
671: }
672: var t = Object(this);
673: var len = t.length >>> 0;
674: if (len === 0) {
675: return -1;
676: }
677: var n = 0;
678: if (arguments.length > 0) {
679: n = Number(arguments[1]);
680: if (n !== n) { // shortcut for verifying if it's NaN
681: n = 0;
682: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
683: n = (n > 0 || -1) * Math.floor(Math.abs(n));
684: }
685: }
686: if (n >= len) {
687: return -1;
688: }
689: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
690: for (; k < len; k++) {
691: if (k in t && t[k] === searchElement) {
692: return k;
693: }
694: }
695: return -1;
696: }
697: }
698:
699: // ]]>
700: </script>
701:
702: ENDJS
703:
704: }
705:
706: sub userbrowser_javascript {
707: my $id_functions = &javascript_index_functions();
708: return <<"ENDUSERBRW";
709:
710: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
711: var url = '/adm/pickuser?';
712: var userdom = getDomainFromSelectbox(formname,udom);
713: if (userdom != null) {
714: if (userdom != '') {
715: url += 'srchdom='+userdom+'&';
716: }
717: }
718: url += 'form=' + formname + '&unameelement='+uname+
719: '&udomelement='+udom+
720: '&ulastelement='+ulast+
721: '&ufirstelement='+ufirst+
722: '&uemailelement='+uemail+
723: '&hideudomelement='+hideudom+
724: '&coursedom='+crsdom;
725: if ((caller != null) && (caller != undefined)) {
726: url += '&caller='+caller;
727: }
728: var title = 'User_Browser';
729: var options = 'scrollbars=1,resizable=1,menubar=0';
730: options += ',width=700,height=600';
731: var stdeditbrowser = open(url,title,options,'1');
732: stdeditbrowser.focus();
733: }
734:
735: function fix_domain (formname,udom,origdom,uname) {
736: var formid = getFormIdByName(formname);
737: if (formid > -1) {
738: var unameid = getIndexByName(formid,uname);
739: var domid = getIndexByName(formid,udom);
740: var hidedomid = getIndexByName(formid,origdom);
741: if (hidedomid > -1) {
742: var fixeddom = document.forms[formid].elements[hidedomid].value;
743: var unameval = document.forms[formid].elements[unameid].value;
744: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
745: if (domid > -1) {
746: var slct = document.forms[formid].elements[domid];
747: if (slct.type == 'select-one') {
748: var i;
749: for (i=0;i<slct.length;i++) {
750: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
751: }
752: }
753: if (slct.type == 'hidden') {
754: slct.value = fixeddom;
755: }
756: }
757: }
758: }
759: }
760: return;
761: }
762:
763: $id_functions
764: ENDUSERBRW
765: }
766:
767: sub setsec_javascript {
768: my ($sec_element,$formname,$role_element,$credits_element) = @_;
769: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
770: $communityrolestr);
771: if ($role_element ne '') {
772: my @allroles = ('st','ta','ep','in','ad');
773: foreach my $crstype ('Course','Community') {
774: if ($crstype eq 'Community') {
775: foreach my $role (@allroles) {
776: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
777: }
778: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
779: } else {
780: foreach my $role (@allroles) {
781: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
782: }
783: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
784: }
785: }
786: $rolestr = '"'.join('","',@allroles).'"';
787: $courserolestr = '"'.join('","',@courserolenames).'"';
788: $communityrolestr = '"'.join('","',@communityrolenames).'"';
789: }
790: my $setsections = qq|
791: function setSect(sectionlist) {
792: var sectionsArray = new Array();
793: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
794: sectionsArray = sectionlist.split(",");
795: }
796: var numSections = sectionsArray.length;
797: document.$formname.$sec_element.length = 0;
798: if (numSections == 0) {
799: document.$formname.$sec_element.multiple=false;
800: document.$formname.$sec_element.size=1;
801: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
802: } else {
803: if (numSections == 1) {
804: document.$formname.$sec_element.multiple=false;
805: document.$formname.$sec_element.size=1;
806: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
807: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
808: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
809: } else {
810: for (var i=0; i<numSections; i++) {
811: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
812: }
813: document.$formname.$sec_element.multiple=true
814: if (numSections < 3) {
815: document.$formname.$sec_element.size=numSections;
816: } else {
817: document.$formname.$sec_element.size=3;
818: }
819: document.$formname.$sec_element.options[0].selected = false
820: }
821: }
822: }
823:
824: function setRole(crstype) {
825: |;
826: if ($role_element eq '') {
827: $setsections .= ' return;
828: }
829: ';
830: } else {
831: $setsections .= qq|
832: var elementLength = document.$formname.$role_element.length;
833: var allroles = Array($rolestr);
834: var courserolenames = Array($courserolestr);
835: var communityrolenames = Array($communityrolestr);
836: if (elementLength != undefined) {
837: if (document.$formname.$role_element.options[5].value == 'cc') {
838: if (crstype == 'Course') {
839: return;
840: } else {
841: allroles[5] = 'co';
842: for (var i=0; i<6; i++) {
843: document.$formname.$role_element.options[i].value = allroles[i];
844: document.$formname.$role_element.options[i].text = communityrolenames[i];
845: }
846: }
847: } else {
848: if (crstype == 'Community') {
849: return;
850: } else {
851: allroles[5] = 'cc';
852: for (var i=0; i<6; i++) {
853: document.$formname.$role_element.options[i].value = allroles[i];
854: document.$formname.$role_element.options[i].text = courserolenames[i];
855: }
856: }
857: }
858: }
859: return;
860: }
861: |;
862: }
863: if ($credits_element) {
864: $setsections .= qq|
865: function setCredits(defaultcredits) {
866: document.$formname.$credits_element.value = defaultcredits;
867: return;
868: }
869: |;
870: }
871: return $setsections;
872: }
873:
874: sub selectcourse_link {
875: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
876: $typeelement) = @_;
877: my $type = $selecttype;
878: my $linktext = &mt('Select Course');
879: if ($selecttype eq 'Community') {
880: $linktext = &mt('Select Community');
881: } elsif ($selecttype eq 'Course/Community') {
882: $linktext = &mt('Select Course/Community');
883: $type = '';
884: } elsif ($selecttype eq 'Select') {
885: $linktext = &mt('Select');
886: $type = '';
887: }
888: return '<span class="LC_nobreak">'
889: ."<a href='"
890: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
891: .'","'.$udomele.'","'.$desc.'","'.$extra_element
892: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
893: ."'>".$linktext.'</a>'
894: .'</span>';
895: }
896:
897: sub selectauthor_link {
898: my ($form,$udom)=@_;
899: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
900: &mt('Select Author').'</a>';
901: }
902:
903: sub selectuser_link {
904: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
905: $coursedom,$linktext,$caller) = @_;
906: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
907: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
908: ');">'.$linktext.'</a>';
909: }
910:
911: sub check_uncheck_jscript {
912: my $jscript = <<"ENDSCRT";
913: function checkAll(field) {
914: if (field.length > 0) {
915: for (i = 0; i < field.length; i++) {
916: if (!field[i].disabled) {
917: field[i].checked = true;
918: }
919: }
920: } else {
921: if (!field.disabled) {
922: field.checked = true;
923: }
924: }
925: }
926:
927: function uncheckAll(field) {
928: if (field.length > 0) {
929: for (i = 0; i < field.length; i++) {
930: field[i].checked = false ;
931: }
932: } else {
933: field.checked = false ;
934: }
935: }
936: ENDSCRT
937: return $jscript;
938: }
939:
940: sub select_timezone {
941: my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
942: my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
943: if ($includeempty) {
944: $output .= '<option value=""';
945: if (($selected eq '') || ($selected eq 'local')) {
946: $output .= ' selected="selected" ';
947: }
948: $output .= '> </option>';
949: }
950: my @timezones = DateTime::TimeZone->all_names;
951: foreach my $tzone (@timezones) {
952: $output.= '<option value="'.$tzone.'"';
953: if ($tzone eq $selected) {
954: $output.=' selected="selected"';
955: }
956: $output.=">$tzone</option>\n";
957: }
958: $output.="</select>";
959: return $output;
960: }
961:
962: sub select_datelocale {
963: my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
964: my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
965: if ($includeempty) {
966: $output .= '<option value=""';
967: if ($selected eq '') {
968: $output .= ' selected="selected" ';
969: }
970: $output .= '> </option>';
971: }
972: my @languages = &Apache::lonlocal::preferred_languages();
973: my (@possibles,%locale_names);
974: my @locales = DateTime::Locale->ids();
975: foreach my $id (@locales) {
976: if ($id ne '') {
977: my ($en_terr,$native_terr);
978: my $loc = DateTime::Locale->load($id);
979: if (ref($loc)) {
980: $en_terr = $loc->name();
981: $native_terr = $loc->native_name();
982: if (grep(/^en$/,@languages) || !@languages) {
983: if ($en_terr ne '') {
984: $locale_names{$id} = '('.$en_terr.')';
985: } elsif ($native_terr ne '') {
986: $locale_names{$id} = $native_terr;
987: }
988: } else {
989: if ($native_terr ne '') {
990: $locale_names{$id} = $native_terr.' ';
991: } elsif ($en_terr ne '') {
992: $locale_names{$id} = '('.$en_terr.')';
993: }
994: }
995: $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
996: push(@possibles,$id);
997: }
998: }
999: }
1000: foreach my $item (sort(@possibles)) {
1001: $output.= '<option value="'.$item.'"';
1002: if ($item eq $selected) {
1003: $output.=' selected="selected"';
1004: }
1005: $output.=">$item";
1006: if ($locale_names{$item} ne '') {
1007: $output.=' '.$locale_names{$item};
1008: }
1009: $output.="</option>\n";
1010: }
1011: $output.="</select>";
1012: return $output;
1013: }
1014:
1015: sub select_language {
1016: my ($name,$selected,$includeempty,$noedit) = @_;
1017: my %langchoices;
1018: if ($includeempty) {
1019: %langchoices = ('' => 'No language preference');
1020: }
1021: foreach my $id (&languageids()) {
1022: my $code = &supportedlanguagecode($id);
1023: if ($code) {
1024: $langchoices{$code} = &plainlanguagedescription($id);
1025: }
1026: }
1027: %langchoices = &Apache::lonlocal::texthash(%langchoices);
1028: return &select_form($selected,$name,\%langchoices,undef,$noedit);
1029: }
1030:
1031: =pod
1032:
1033: =item * &linked_select_forms(...)
1034:
1035: linked_select_forms returns a string containing a <script></script> block
1036: and html for two <select> menus. The select menus will be linked in that
1037: changing the value of the first menu will result in new values being placed
1038: in the second menu. The values in the select menu will appear in alphabetical
1039: order unless a defined order is provided.
1040:
1041: linked_select_forms takes the following ordered inputs:
1042:
1043: =over 4
1044:
1045: =item * $formname, the name of the <form> tag
1046:
1047: =item * $middletext, the text which appears between the <select> tags
1048:
1049: =item * $firstdefault, the default value for the first menu
1050:
1051: =item * $firstselectname, the name of the first <select> tag
1052:
1053: =item * $secondselectname, the name of the second <select> tag
1054:
1055: =item * $hashref, a reference to a hash containing the data for the menus.
1056:
1057: =item * $menuorder, the order of values in the first menu
1058:
1059: =item * $onchangefirst, additional javascript call to execute for an onchange
1060: event for the first <select> tag
1061:
1062: =item * $onchangesecond, additional javascript call to execute for an onchange
1063: event for the second <select> tag
1064:
1065: =back
1066:
1067: Below is an example of such a hash. Only the 'text', 'default', and
1068: 'select2' keys must appear as stated. keys(%menu) are the possible
1069: values for the first select menu. The text that coincides with the
1070: first menu value is given in $menu{$choice1}->{'text'}. The values
1071: and text for the second menu are given in the hash pointed to by
1072: $menu{$choice1}->{'select2'}.
1073:
1074: my %menu = ( A1 => { text =>"Choice A1" ,
1075: default => "B3",
1076: select2 => {
1077: B1 => "Choice B1",
1078: B2 => "Choice B2",
1079: B3 => "Choice B3",
1080: B4 => "Choice B4"
1081: },
1082: order => ['B4','B3','B1','B2'],
1083: },
1084: A2 => { text =>"Choice A2" ,
1085: default => "C2",
1086: select2 => {
1087: C1 => "Choice C1",
1088: C2 => "Choice C2",
1089: C3 => "Choice C3"
1090: },
1091: order => ['C2','C1','C3'],
1092: },
1093: A3 => { text =>"Choice A3" ,
1094: default => "D6",
1095: select2 => {
1096: D1 => "Choice D1",
1097: D2 => "Choice D2",
1098: D3 => "Choice D3",
1099: D4 => "Choice D4",
1100: D5 => "Choice D5",
1101: D6 => "Choice D6",
1102: D7 => "Choice D7"
1103: },
1104: order => ['D4','D3','D2','D1','D7','D6','D5'],
1105: }
1106: );
1107:
1108: =cut
1109:
1110: sub linked_select_forms {
1111: my ($formname,
1112: $middletext,
1113: $firstdefault,
1114: $firstselectname,
1115: $secondselectname,
1116: $hashref,
1117: $menuorder,
1118: $onchangefirst,
1119: $onchangesecond
1120: ) = @_;
1121: my $second = "document.$formname.$secondselectname";
1122: my $first = "document.$formname.$firstselectname";
1123: # output the javascript to do the changing
1124: my $result = '';
1125: $result.='<script type="text/javascript" language="JavaScript">'."\n";
1126: $result.="// <![CDATA[\n";
1127: $result.="var select2data = new Object();\n";
1128: $" = '","';
1129: my $debug = '';
1130: foreach my $s1 (sort(keys(%$hashref))) {
1131: $result.="select2data.d_$s1 = new Object();\n";
1132: $result.="select2data.d_$s1.def = new String('".
1133: $hashref->{$s1}->{'default'}."');\n";
1134: $result.="select2data.d_$s1.values = new Array(";
1135: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1136: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1137: @s2values = @{$hashref->{$s1}->{'order'}};
1138: }
1139: $result.="\"@s2values\");\n";
1140: $result.="select2data.d_$s1.texts = new Array(";
1141: my @s2texts;
1142: foreach my $value (@s2values) {
1143: push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1144: }
1145: $result.="\"@s2texts\");\n";
1146: }
1147: $"=' ';
1148: $result.= <<"END";
1149:
1150: function select1_changed() {
1151: // Determine new choice
1152: var newvalue = "d_" + $first.value;
1153: // update select2
1154: var values = select2data[newvalue].values;
1155: var texts = select2data[newvalue].texts;
1156: var select2def = select2data[newvalue].def;
1157: var i;
1158: // out with the old
1159: for (i = 0; i < $second.options.length; i++) {
1160: $second.options[i] = null;
1161: }
1162: // in with the nuclear
1163: for (i=0;i<values.length; i++) {
1164: $second.options[i] = new Option(values[i]);
1165: $second.options[i].value = values[i];
1166: $second.options[i].text = texts[i];
1167: if (values[i] == select2def) {
1168: $second.options[i].selected = true;
1169: }
1170: }
1171: }
1172: // ]]>
1173: </script>
1174: END
1175: # output the initial values for the selection lists
1176: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1177: my @order = sort(keys(%{$hashref}));
1178: if (ref($menuorder) eq 'ARRAY') {
1179: @order = @{$menuorder};
1180: }
1181: foreach my $value (@order) {
1182: $result.=" <option value=\"$value\" ";
1183: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1184: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1185: }
1186: $result .= "</select>\n";
1187: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1188: $result .= $middletext;
1189: $result .= "<select size=\"1\" name=\"$secondselectname\"";
1190: if ($onchangesecond) {
1191: $result .= ' onchange="'.$onchangesecond.'"';
1192: }
1193: $result .= ">\n";
1194: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1195:
1196: my @secondorder = sort(keys(%select2));
1197: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1198: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1199: }
1200: foreach my $value (@secondorder) {
1201: $result.=" <option value=\"$value\" ";
1202: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1203: $result.=">".&mt($select2{$value})."</option>\n";
1204: }
1205: $result .= "</select>\n";
1206: # return $debug;
1207: return $result;
1208: } # end of sub linked_select_forms {
1209:
1210: =pod
1211:
1212: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1213:
1214: Returns a string corresponding to an HTML link to the given help
1215: $topic, where $topic corresponds to the name of a .tex file in
1216: /home/httpd/html/adm/help/tex, with underscores replaced by
1217: spaces.
1218:
1219: $text will optionally be linked to the same topic, allowing you to
1220: link text in addition to the graphic. If you do not want to link
1221: text, but wish to specify one of the later parameters, pass an
1222: empty string.
1223:
1224: $stayOnPage is a value that will be interpreted as a boolean. If true,
1225: the link will not open a new window. If false, the link will open
1226: a new window using Javascript. (Default is false.)
1227:
1228: $width and $height are optional numerical parameters that will
1229: override the width and height of the popped up window, which may
1230: be useful for certain help topics with big pictures included.
1231:
1232: $imgid is the id of the img tag used for the help icon. This may be
1233: used in a javascript call to switch the image src. See
1234: lonhtmlcommon::htmlareaselectactive() for an example.
1235:
1236: =cut
1237:
1238: sub help_open_topic {
1239: my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1240: $text = "" if (not defined $text);
1241: $stayOnPage = 0 if (not defined $stayOnPage);
1242: $width = 500 if (not defined $width);
1243: $height = 400 if (not defined $height);
1244: my $filename = $topic;
1245: $filename =~ s/ /_/g;
1246:
1247: my $template = "";
1248: my $link;
1249:
1250: $topic=~s/\W/\_/g;
1251:
1252: if (!$stayOnPage) {
1253: if ($env{'browser.mobile'}) {
1254: $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1255: } else {
1256: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1257: }
1258: } elsif ($stayOnPage eq 'popup') {
1259: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1260: } else {
1261: $link = "/adm/help/${filename}.hlp";
1262: }
1263:
1264: # Add the text
1265: if ($text ne "") {
1266: $template.='<span class="LC_help_open_topic">'
1267: .'<a target="_top" href="'.$link.'">'
1268: .$text.'</a>';
1269: }
1270:
1271: # (Always) Add the graphic
1272: my $title = &mt('Online Help');
1273: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1274: if ($imgid ne '') {
1275: $imgid = ' id="'.$imgid.'"';
1276: }
1277: $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
1278: .'<img src="'.$helpicon.'" border="0"'
1279: .' alt="'.&mt('Help: [_1]',$topic).'"'
1280: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
1281: .' /></a>';
1282: if ($text ne "") {
1283: $template.='</span>';
1284: }
1285: return $template;
1286:
1287: }
1288:
1289: # This is a quicky function for Latex cheatsheet editing, since it
1290: # appears in at least four places
1291: sub helpLatexCheatsheet {
1292: my ($topic,$text,$not_author,$stayOnPage) = @_;
1293: my $out;
1294: my $addOther = '';
1295: if ($topic) {
1296: $addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1297: }
1298: $out = '<span>' # Start cheatsheet
1299: .$addOther
1300: .'<span>'
1301: .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1302: .'</span> <span>'
1303: .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1304: .'</span>';
1305: unless ($not_author) {
1306: $out .= ' <span>'
1307: .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1308: .'</span> <span>'
1309: .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1310: .'</span>';
1311: }
1312: $out .= '</span>'; # End cheatsheet
1313: return $out;
1314: }
1315:
1316: sub general_help {
1317: my $helptopic='Student_Intro';
1318: if ($env{'request.role'}=~/^(ca|au)/) {
1319: $helptopic='Authoring_Intro';
1320: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1321: $helptopic='Course_Coordination_Intro';
1322: } elsif ($env{'request.role'}=~/^dc/) {
1323: $helptopic='Domain_Coordination_Intro';
1324: }
1325: return $helptopic;
1326: }
1327:
1328: sub update_help_link {
1329: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1330: my $origurl = $ENV{'REQUEST_URI'};
1331: $origurl=~s|^/~|/priv/|;
1332: my $timestamp = time;
1333: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1334: $$datum = &escape($$datum);
1335: }
1336:
1337: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1338: my $output .= <<"ENDOUTPUT";
1339: <script type="text/javascript">
1340: // <![CDATA[
1341: banner_link = '$banner_link';
1342: // ]]>
1343: </script>
1344: ENDOUTPUT
1345: return $output;
1346: }
1347:
1348: # now just updates the help link and generates a blue icon
1349: sub help_open_menu {
1350: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
1351: = @_;
1352: $stayOnPage = 1;
1353: my $output;
1354: if ($component_help) {
1355: if (!$text) {
1356: $output=&help_open_topic($component_help,undef,$stayOnPage,
1357: $width,$height);
1358: } else {
1359: my $help_text;
1360: $help_text=&unescape($topic);
1361: $output='<table><tr><td>'.
1362: &help_open_topic($component_help,$help_text,$stayOnPage,
1363: $width,$height).'</td></tr></table>';
1364: }
1365: }
1366: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1367: return $output.$banner_link;
1368: }
1369:
1370: sub top_nav_help {
1371: my ($text) = @_;
1372: $text = &mt($text);
1373: my $stay_on_page;
1374: unless ($env{'environment.remote'} eq 'on') {
1375: $stay_on_page = 1;
1376: }
1377: my ($link,$banner_link);
1378: unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
1379: $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1380: : "javascript:helpMenu('open')";
1381: $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1382: }
1383: my $title = &mt('Get help');
1384: if ($link) {
1385: return <<"END";
1386: $banner_link
1387: <a href="$link" title="$title">$text</a>
1388: END
1389: } else {
1390: return ' '.$text.' ';
1391: }
1392: }
1393:
1394: sub help_menu_js {
1395: my ($httphost) = @_;
1396: my $stayOnPage = 1;
1397: my $width = 620;
1398: my $height = 600;
1399: my $helptopic=&general_help();
1400: my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1401: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1402: my $start_page =
1403: &Apache::loncommon::start_page('Help Menu', undef,
1404: {'frameset' => 1,
1405: 'js_ready' => 1,
1406: 'use_absolute' => $httphost,
1407: 'add_entries' => {
1408: 'border' => '0',
1409: 'rows' => "110,*",},});
1410: my $end_page =
1411: &Apache::loncommon::end_page({'frameset' => 1,
1412: 'js_ready' => 1,});
1413:
1414: my $template .= <<"ENDTEMPLATE";
1415: <script type="text/javascript">
1416: // <![CDATA[
1417: // <!-- BEGIN LON-CAPA Internal
1418: var banner_link = '';
1419: function helpMenu(target) {
1420: var caller = this;
1421: if (target == 'open') {
1422: var newWindow = null;
1423: try {
1424: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1425: }
1426: catch(error) {
1427: writeHelp(caller);
1428: return;
1429: }
1430: if (newWindow) {
1431: caller = newWindow;
1432: }
1433: }
1434: writeHelp(caller);
1435: return;
1436: }
1437: function writeHelp(caller) {
1438: caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
1439: caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
1440: caller.document.close();
1441: caller.focus();
1442: }
1443: // END LON-CAPA Internal -->
1444: // ]]>
1445: </script>
1446: ENDTEMPLATE
1447: return $template;
1448: }
1449:
1450: sub help_open_bug {
1451: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1452: unless ($env{'user.adv'}) { return ''; }
1453: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1454: $text = "" if (not defined $text);
1455: $stayOnPage=1;
1456: $width = 600 if (not defined $width);
1457: $height = 600 if (not defined $height);
1458:
1459: $topic=~s/\W+/\+/g;
1460: my $link='';
1461: my $template='';
1462: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1463: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1464: if (!$stayOnPage)
1465: {
1466: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1467: }
1468: else
1469: {
1470: $link = $url;
1471: }
1472: # Add the text
1473: if ($text ne "")
1474: {
1475: $template .=
1476: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1477: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1478: }
1479:
1480: # Add the graphic
1481: my $title = &mt('Report a Bug');
1482: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1483: $template .= <<"ENDTEMPLATE";
1484: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1485: ENDTEMPLATE
1486: if ($text ne '') { $template.='</td></tr></table>' };
1487: return $template;
1488:
1489: }
1490:
1491: sub help_open_faq {
1492: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1493: unless ($env{'user.adv'}) { return ''; }
1494: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1495: $text = "" if (not defined $text);
1496: $stayOnPage=1;
1497: $width = 350 if (not defined $width);
1498: $height = 400 if (not defined $height);
1499:
1500: $topic=~s/\W+/\+/g;
1501: my $link='';
1502: my $template='';
1503: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1504: if (!$stayOnPage)
1505: {
1506: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1507: }
1508: else
1509: {
1510: $link = $url;
1511: }
1512:
1513: # Add the text
1514: if ($text ne "")
1515: {
1516: $template .=
1517: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1518: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1519: }
1520:
1521: # Add the graphic
1522: my $title = &mt('View the FAQ');
1523: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1524: $template .= <<"ENDTEMPLATE";
1525: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1526: ENDTEMPLATE
1527: if ($text ne '') { $template.='</td></tr></table>' };
1528: return $template;
1529:
1530: }
1531:
1532: ###############################################################
1533: ###############################################################
1534:
1535: =pod
1536:
1537: =item * &change_content_javascript():
1538:
1539: This and the next function allow you to create small sections of an
1540: otherwise static HTML page that you can update on the fly with
1541: Javascript, even in Netscape 4.
1542:
1543: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1544: must be written to the HTML page once. It will prove the Javascript
1545: function "change(name, content)". Calling the change function with the
1546: name of the section
1547: you want to update, matching the name passed to C<changable_area>, and
1548: the new content you want to put in there, will put the content into
1549: that area.
1550:
1551: B<Note>: Netscape 4 only reserves enough space for the changable area
1552: to contain room for the original contents. You need to "make space"
1553: for whatever changes you wish to make, and be B<sure> to check your
1554: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1555: it's adequate for updating a one-line status display, but little more.
1556: This script will set the space to 100% width, so you only need to
1557: worry about height in Netscape 4.
1558:
1559: Modern browsers are much less limiting, and if you can commit to the
1560: user not using Netscape 4, this feature may be used freely with
1561: pretty much any HTML.
1562:
1563: =cut
1564:
1565: sub change_content_javascript {
1566: # If we're on Netscape 4, we need to use Layer-based code
1567: if ($env{'browser.type'} eq 'netscape' &&
1568: $env{'browser.version'} =~ /^4\./) {
1569: return (<<NETSCAPE4);
1570: function change(name, content) {
1571: doc = document.layers[name+"___escape"].layers[0].document;
1572: doc.open();
1573: doc.write(content);
1574: doc.close();
1575: }
1576: NETSCAPE4
1577: } else {
1578: # Otherwise, we need to use semi-standards-compliant code
1579: # (technically, "innerHTML" isn't standard but the equivalent
1580: # is really scary, and every useful browser supports it
1581: return (<<DOMBASED);
1582: function change(name, content) {
1583: element = document.getElementById(name);
1584: element.innerHTML = content;
1585: }
1586: DOMBASED
1587: }
1588: }
1589:
1590: =pod
1591:
1592: =item * &changable_area($name,$origContent):
1593:
1594: This provides a "changable area" that can be modified on the fly via
1595: the Javascript code provided in C<change_content_javascript>. $name is
1596: the name you will use to reference the area later; do not repeat the
1597: same name on a given HTML page more then once. $origContent is what
1598: the area will originally contain, which can be left blank.
1599:
1600: =cut
1601:
1602: sub changable_area {
1603: my ($name, $origContent) = @_;
1604:
1605: if ($env{'browser.type'} eq 'netscape' &&
1606: $env{'browser.version'} =~ /^4\./) {
1607: # If this is netscape 4, we need to use the Layer tag
1608: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1609: } else {
1610: return "<span id='$name'>$origContent</span>";
1611: }
1612: }
1613:
1614: =pod
1615:
1616: =item * &viewport_geometry_js
1617:
1618: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1619:
1620: =cut
1621:
1622:
1623: sub viewport_geometry_js {
1624: return <<"GEOMETRY";
1625: var Geometry = {};
1626: function init_geometry() {
1627: if (Geometry.init) { return };
1628: Geometry.init=1;
1629: if (window.innerHeight) {
1630: Geometry.getViewportHeight = function() { return window.innerHeight; };
1631: Geometry.getViewportWidth = function() { return window.innerWidth; };
1632: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1633: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1634: }
1635: else if (document.documentElement && document.documentElement.clientHeight) {
1636: Geometry.getViewportHeight =
1637: function() { return document.documentElement.clientHeight; };
1638: Geometry.getViewportWidth =
1639: function() { return document.documentElement.clientWidth; };
1640:
1641: Geometry.getHorizontalScroll =
1642: function() { return document.documentElement.scrollLeft; };
1643: Geometry.getVerticalScroll =
1644: function() { return document.documentElement.scrollTop; };
1645: }
1646: else if (document.body.clientHeight) {
1647: Geometry.getViewportHeight =
1648: function() { return document.body.clientHeight; };
1649: Geometry.getViewportWidth =
1650: function() { return document.body.clientWidth; };
1651: Geometry.getHorizontalScroll =
1652: function() { return document.body.scrollLeft; };
1653: Geometry.getVerticalScroll =
1654: function() { return document.body.scrollTop; };
1655: }
1656: }
1657:
1658: GEOMETRY
1659: }
1660:
1661: =pod
1662:
1663: =item * &viewport_size_js()
1664:
1665: 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.
1666:
1667: =cut
1668:
1669: sub viewport_size_js {
1670: my $geometry = &viewport_geometry_js();
1671: return <<"DIMS";
1672:
1673: $geometry
1674:
1675: function getViewportDims(width,height) {
1676: init_geometry();
1677: width.value = Geometry.getViewportWidth();
1678: height.value = Geometry.getViewportHeight();
1679: return;
1680: }
1681:
1682: DIMS
1683: }
1684:
1685: =pod
1686:
1687: =item * &resize_textarea_js()
1688:
1689: emits the needed javascript to resize a textarea to be as big as possible
1690:
1691: creates a function resize_textrea that takes two IDs first should be
1692: the id of the element to resize, second should be the id of a div that
1693: surrounds everything that comes after the textarea, this routine needs
1694: to be attached to the <body> for the onload and onresize events.
1695:
1696: =back
1697:
1698: =cut
1699:
1700: sub resize_textarea_js {
1701: my $geometry = &viewport_geometry_js();
1702: return <<"RESIZE";
1703: <script type="text/javascript">
1704: // <![CDATA[
1705: $geometry
1706:
1707: function getX(element) {
1708: var x = 0;
1709: while (element) {
1710: x += element.offsetLeft;
1711: element = element.offsetParent;
1712: }
1713: return x;
1714: }
1715: function getY(element) {
1716: var y = 0;
1717: while (element) {
1718: y += element.offsetTop;
1719: element = element.offsetParent;
1720: }
1721: return y;
1722: }
1723:
1724:
1725: function resize_textarea(textarea_id,bottom_id) {
1726: init_geometry();
1727: var textarea = document.getElementById(textarea_id);
1728: //alert(textarea);
1729:
1730: var textarea_top = getY(textarea);
1731: var textarea_height = textarea.offsetHeight;
1732: var bottom = document.getElementById(bottom_id);
1733: var bottom_top = getY(bottom);
1734: var bottom_height = bottom.offsetHeight;
1735: var window_height = Geometry.getViewportHeight();
1736: var fudge = 23;
1737: var new_height = window_height-fudge-textarea_top-bottom_height;
1738: if (new_height < 300) {
1739: new_height = 300;
1740: }
1741: textarea.style.height=new_height+'px';
1742: }
1743: // ]]>
1744: </script>
1745: RESIZE
1746:
1747: }
1748:
1749: sub colorfuleditor_js {
1750: return <<"COLORFULEDIT"
1751: <script type="text/javascript">
1752: // <![CDATA[>
1753: function fold_box(curDepth, lastresource){
1754:
1755: // we need a list because there can be several blocks you need to fold in one tag
1756: var block = document.getElementsByName('foldblock_'+curDepth);
1757: // but there is only one folding button per tag
1758: var foldbutton = document.getElementById('folding_btn_'+curDepth);
1759:
1760: if(block.item(0).style.display == 'none'){
1761:
1762: foldbutton.value = '@{[&mt("Hide")]}';
1763: for (i = 0; i < block.length; i++){
1764: block.item(i).style.display = '';
1765: }
1766: }else{
1767:
1768: foldbutton.value = '@{[&mt("Show")]}';
1769: for (i = 0; i < block.length; i++){
1770: // block.item(i).style.visibility = 'collapse';
1771: block.item(i).style.display = 'none';
1772: }
1773: };
1774: saveState(lastresource);
1775: }
1776:
1777: function saveState (lastresource) {
1778:
1779: var tag_list = getTagList();
1780: if(tag_list != null){
1781: var timestamp = new Date().getTime();
1782: var key = lastresource;
1783:
1784: // the value pattern is: 'time;key1,value1;key2,value2; ... '
1785: // starting with timestamp
1786: var value = timestamp+';';
1787:
1788: // building the list of key-value pairs
1789: for(var i = 0; i < tag_list.length; i++){
1790: value += tag_list[i]+',';
1791: value += document.getElementsByName(tag_list[i])[0].style.display+';';
1792: }
1793:
1794: // only iterate whole storage if nothing to override
1795: if(localStorage.getItem(key) == null){
1796:
1797: // prevent storage from growing large
1798: if(localStorage.length > 50){
1799: var regex_getTimestamp = /^(?:\d)+;/;
1800: var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
1801: var oldest_key;
1802:
1803: for(var i = 1; i < localStorage.length; i++){
1804: if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
1805: oldest_key = localStorage.key(i);
1806: oldest_timestamp = regex_getTimestamp.exec(oldest_key);
1807: }
1808: }
1809: localStorage.removeItem(oldest_key);
1810: }
1811: }
1812: localStorage.setItem(key,value);
1813: }
1814: }
1815:
1816: // restore folding status of blocks (on page load)
1817: function restoreState (lastresource) {
1818: if(localStorage.getItem(lastresource) != null){
1819: var key = lastresource;
1820: var value = localStorage.getItem(key);
1821: var regex_delTimestamp = /^\d+;/;
1822:
1823: value.replace(regex_delTimestamp, '');
1824:
1825: var valueArr = value.split(';');
1826: var pairs;
1827: var elements;
1828: for (var i = 0; i < valueArr.length; i++){
1829: pairs = valueArr[i].split(',');
1830: elements = document.getElementsByName(pairs[0]);
1831:
1832: for (var j = 0; j < elements.length; j++){
1833: elements[j].style.display = pairs[1];
1834: if (pairs[1] == "none"){
1835: var regex_id = /([_\\d]+)\$/;
1836: regex_id.exec(pairs[0]);
1837: document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
1838: }
1839: }
1840: }
1841: }
1842: }
1843:
1844: function getTagList () {
1845:
1846: var stringToSearch = document.lonhomework.innerHTML;
1847:
1848: var ret = new Array();
1849: var regex_findBlock = /(foldblock_.*?)"/g;
1850: var tag_list = stringToSearch.match(regex_findBlock);
1851:
1852: if(tag_list != null){
1853: for(var i = 0; i < tag_list.length; i++){
1854: ret.push(tag_list[i].replace(/"/, ''));
1855: }
1856: }
1857: return ret;
1858: }
1859:
1860: function saveScrollPosition (resource) {
1861: var tag_list = getTagList();
1862:
1863: // we dont always want to jump to the first block
1864: // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
1865: if(\$(window).scrollTop() > 170){
1866: if(tag_list != null){
1867: var result;
1868: for(var i = 0; i < tag_list.length; i++){
1869: if(isElementInViewport(tag_list[i])){
1870: result += tag_list[i]+';';
1871: }
1872: }
1873: sessionStorage.setItem('anchor_'+resource, result);
1874: }
1875: } else {
1876: // we dont need to save zero, just delete the item to leave everything tidy
1877: sessionStorage.removeItem('anchor_'+resource);
1878: }
1879: }
1880:
1881: function restoreScrollPosition(resource){
1882:
1883: var elem = sessionStorage.getItem('anchor_'+resource);
1884: if(elem != null){
1885: var tag_list = elem.split(';');
1886: var elem_list;
1887:
1888: for(var i = 0; i < tag_list.length; i++){
1889: elem_list = document.getElementsByName(tag_list[i]);
1890:
1891: if(elem_list.length > 0){
1892: elem = elem_list[0];
1893: break;
1894: }
1895: }
1896: elem.scrollIntoView();
1897: }
1898: }
1899:
1900: function isElementInViewport(el) {
1901:
1902: // change to last element instead of first
1903: var elem = document.getElementsByName(el);
1904: var rect = elem[0].getBoundingClientRect();
1905:
1906: return (
1907: rect.top >= 0 &&
1908: rect.left >= 0 &&
1909: rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
1910: rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
1911: );
1912: }
1913:
1914: function autosize(depth){
1915: var cmInst = window['cm'+depth];
1916: var fitsizeButton = document.getElementById('fitsize'+depth);
1917:
1918: // is fixed size, switching to dynamic
1919: if (sessionStorage.getItem("autosized_"+depth) == null) {
1920: cmInst.setSize("","auto");
1921: fitsizeButton.value = "@{[&mt('Fixed size')]}";
1922: sessionStorage.setItem("autosized_"+depth, "yes");
1923:
1924: // is dynamic size, switching to fixed
1925: } else {
1926: cmInst.setSize("","300px");
1927: fitsizeButton.value = "@{[&mt('Dynamic size')]}";
1928: sessionStorage.removeItem("autosized_"+depth);
1929: }
1930: }
1931:
1932:
1933:
1934: // ]]>
1935: </script>
1936: COLORFULEDIT
1937: }
1938:
1939: sub xmleditor_js {
1940: return <<XMLEDIT
1941: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
1942: <script type="text/javascript">
1943: // <![CDATA[>
1944:
1945: function saveScrollPosition (resource) {
1946:
1947: var scrollPos = \$(window).scrollTop();
1948: sessionStorage.setItem(resource,scrollPos);
1949: }
1950:
1951: function restoreScrollPosition(resource){
1952:
1953: var scrollPos = sessionStorage.getItem(resource);
1954: \$(window).scrollTop(scrollPos);
1955: }
1956:
1957: // unless internet explorer
1958: if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
1959:
1960: \$(document).ready(function() {
1961: \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
1962: });
1963: }
1964:
1965: // inserts text at cursor position into codemirror (xml editor only)
1966: function insertText(text){
1967: cm.focus();
1968: var curPos = cm.getCursor();
1969: cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
1970: }
1971: // ]]>
1972: </script>
1973: XMLEDIT
1974: }
1975:
1976: sub insert_folding_button {
1977: my $curDepth = $Apache::lonxml::curdepth;
1978: my $lastresource = $env{'request.ambiguous'};
1979:
1980: return "<input type=\"button\" id=\"folding_btn_$curDepth\"
1981: value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
1982: }
1983:
1984:
1985: =pod
1986:
1987: =head1 Excel and CSV file utility routines
1988:
1989: =cut
1990:
1991: ###############################################################
1992: ###############################################################
1993:
1994: =pod
1995:
1996: =over 4
1997:
1998: =item * &csv_translate($text)
1999:
2000: Translate $text to allow it to be output as a 'comma separated values'
2001: format.
2002:
2003: =cut
2004:
2005: ###############################################################
2006: ###############################################################
2007: sub csv_translate {
2008: my $text = shift;
2009: $text =~ s/\"/\"\"/g;
2010: $text =~ s/\n/ /g;
2011: return $text;
2012: }
2013:
2014: ###############################################################
2015: ###############################################################
2016:
2017: =pod
2018:
2019: =item * &define_excel_formats()
2020:
2021: Define some commonly used Excel cell formats.
2022:
2023: Currently supported formats:
2024:
2025: =over 4
2026:
2027: =item header
2028:
2029: =item bold
2030:
2031: =item h1
2032:
2033: =item h2
2034:
2035: =item h3
2036:
2037: =item h4
2038:
2039: =item i
2040:
2041: =item date
2042:
2043: =back
2044:
2045: Inputs: $workbook
2046:
2047: Returns: $format, a hash reference.
2048:
2049:
2050: =cut
2051:
2052: ###############################################################
2053: ###############################################################
2054: sub define_excel_formats {
2055: my ($workbook) = @_;
2056: my $format;
2057: $format->{'header'} = $workbook->add_format(bold => 1,
2058: bottom => 1,
2059: align => 'center');
2060: $format->{'bold'} = $workbook->add_format(bold=>1);
2061: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
2062: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
2063: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
2064: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
2065: $format->{'i'} = $workbook->add_format(italic=>1);
2066: $format->{'date'} = $workbook->add_format(num_format=>
2067: 'mm/dd/yyyy hh:mm:ss');
2068: return $format;
2069: }
2070:
2071: ###############################################################
2072: ###############################################################
2073:
2074: =pod
2075:
2076: =item * &create_workbook()
2077:
2078: Create an Excel worksheet. If it fails, output message on the
2079: request object and return undefs.
2080:
2081: Inputs: Apache request object
2082:
2083: Returns (undef) on failure,
2084: Excel worksheet object, scalar with filename, and formats
2085: from &Apache::loncommon::define_excel_formats on success
2086:
2087: =cut
2088:
2089: ###############################################################
2090: ###############################################################
2091: sub create_workbook {
2092: my ($r) = @_;
2093: #
2094: # Create the excel spreadsheet
2095: my $filename = '/prtspool/'.
2096: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2097: time.'_'.rand(1000000000).'.xls';
2098: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
2099: if (! defined($workbook)) {
2100: $r->log_error("Error creating excel spreadsheet $filename: $!");
2101: $r->print(
2102: '<p class="LC_error">'
2103: .&mt('Problems occurred in creating the new Excel file.')
2104: .' '.&mt('This error has been logged.')
2105: .' '.&mt('Please alert your LON-CAPA administrator.')
2106: .'</p>'
2107: );
2108: return (undef);
2109: }
2110: #
2111: $workbook->set_tempdir(LONCAPA::tempdir());
2112: #
2113: my $format = &Apache::loncommon::define_excel_formats($workbook);
2114: return ($workbook,$filename,$format);
2115: }
2116:
2117: ###############################################################
2118: ###############################################################
2119:
2120: =pod
2121:
2122: =item * &create_text_file()
2123:
2124: Create a file to write to and eventually make available to the user.
2125: If file creation fails, outputs an error message on the request object and
2126: return undefs.
2127:
2128: Inputs: Apache request object, and file suffix
2129:
2130: Returns (undef) on failure,
2131: Filehandle and filename on success.
2132:
2133: =cut
2134:
2135: ###############################################################
2136: ###############################################################
2137: sub create_text_file {
2138: my ($r,$suffix) = @_;
2139: if (! defined($suffix)) { $suffix = 'txt'; };
2140: my $fh;
2141: my $filename = '/prtspool/'.
2142: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2143: time.'_'.rand(1000000000).'.'.$suffix;
2144: $fh = Apache::File->new('>/home/httpd'.$filename);
2145: if (! defined($fh)) {
2146: $r->log_error("Couldn't open $filename for output $!");
2147: $r->print(
2148: '<p class="LC_error">'
2149: .&mt('Problems occurred in creating the output file.')
2150: .' '.&mt('This error has been logged.')
2151: .' '.&mt('Please alert your LON-CAPA administrator.')
2152: .'</p>'
2153: );
2154: }
2155: return ($fh,$filename)
2156: }
2157:
2158:
2159: =pod
2160:
2161: =back
2162:
2163: =cut
2164:
2165: ###############################################################
2166: ## Home server <option> list generating code ##
2167: ###############################################################
2168:
2169: # ------------------------------------------
2170:
2171: sub domain_select {
2172: my ($name,$value,$multiple)=@_;
2173: my %domains=map {
2174: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
2175: } &Apache::lonnet::all_domains();
2176: if ($multiple) {
2177: $domains{''}=&mt('Any domain');
2178: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2179: return &multiple_select_form($name,$value,4,\%domains);
2180: } else {
2181: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2182: return &select_form($name,$value,\%domains);
2183: }
2184: }
2185:
2186: #-------------------------------------------
2187:
2188: =pod
2189:
2190: =head1 Routines for form select boxes
2191:
2192: =over 4
2193:
2194: =item * &multiple_select_form($name,$value,$size,$hash,$order)
2195:
2196: Returns a string containing a <select> element int multiple mode
2197:
2198:
2199: Args:
2200: $name - name of the <select> element
2201: $value - scalar or array ref of values that should already be selected
2202: $size - number of rows long the select element is
2203: $hash - the elements should be 'option' => 'shown text'
2204: (shown text should already have been &mt())
2205: $order - (optional) array ref of the order to show the elements in
2206:
2207: =cut
2208:
2209: #-------------------------------------------
2210: sub multiple_select_form {
2211: my ($name,$value,$size,$hash,$order)=@_;
2212: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
2213: my $output='';
2214: if (! defined($size)) {
2215: $size = 4;
2216: if (scalar(keys(%$hash))<4) {
2217: $size = scalar(keys(%$hash));
2218: }
2219: }
2220: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
2221: my @order;
2222: if (ref($order) eq 'ARRAY') {
2223: @order = @{$order};
2224: } else {
2225: @order = sort(keys(%$hash));
2226: }
2227: if (exists($$hash{'select_form_order'})) {
2228: @order = @{$$hash{'select_form_order'}};
2229: }
2230:
2231: foreach my $key (@order) {
2232: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
2233: $output.='selected="selected" ' if ($selected{$key});
2234: $output.='>'.$hash->{$key}."</option>\n";
2235: }
2236: $output.="</select>\n";
2237: return $output;
2238: }
2239:
2240: #-------------------------------------------
2241:
2242: =pod
2243:
2244: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
2245:
2246: Returns a string containing a <select name='$name' size='1'> form to
2247: allow a user to select options from a ref to a hash containing:
2248: option_name => displayed text. An optional $onchange can include
2249: a javascript onchange item, e.g., onchange="this.form.submit();".
2250: An optional arg -- $readonly -- if true will cause the select form
2251: to be disabled, e.g., for the case where an instructor has a section-
2252: specific role, and is viewing/modifying parameters.
2253:
2254: See lonrights.pm for an example invocation and use.
2255:
2256: =cut
2257:
2258: #-------------------------------------------
2259: sub select_form {
2260: my ($def,$name,$hashref,$onchange,$readonly) = @_;
2261: return unless (ref($hashref) eq 'HASH');
2262: if ($onchange) {
2263: $onchange = ' onchange="'.$onchange.'"';
2264: }
2265: my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
2266: my @keys;
2267: if (exists($hashref->{'select_form_order'})) {
2268: @keys=@{$hashref->{'select_form_order'}};
2269: } else {
2270: @keys=sort(keys(%{$hashref}));
2271: }
2272: foreach my $key (@keys) {
2273: $selectform.=
2274: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
2275: ($key eq $def ? 'selected="selected" ' : '').
2276: ">".$hashref->{$key}."</option>\n";
2277: }
2278: $selectform.="</select>";
2279: return $selectform;
2280: }
2281:
2282: # For display filters
2283:
2284: sub display_filter {
2285: my ($context) = @_;
2286: if (!$env{'form.show'}) { $env{'form.show'}=10; }
2287: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
2288: my $phraseinput = 'hidden';
2289: my $includeinput = 'hidden';
2290: my ($checked,$includetypestext);
2291: if ($env{'form.displayfilter'} eq 'containing') {
2292: $phraseinput = 'text';
2293: if ($context eq 'parmslog') {
2294: $includeinput = 'checkbox';
2295: if ($env{'form.includetypes'}) {
2296: $checked = ' checked="checked"';
2297: }
2298: $includetypestext = &mt('Include parameter types');
2299: }
2300: } else {
2301: $includetypestext = ' ';
2302: }
2303: my ($additional,$secondid,$thirdid);
2304: if ($context eq 'parmslog') {
2305: $additional =
2306: '<label><input type="'.$includeinput.'" name="includetypes"'.
2307: $checked.' name="includetypes" value="1" id="includetypes" />'.
2308: ' <span id="includetypestext">'.$includetypestext.'</span>'.
2309: '</label>';
2310: $secondid = 'includetypes';
2311: $thirdid = 'includetypestext';
2312: }
2313: my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
2314: '$secondid','$thirdid')";
2315: return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
2316: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
2317: (&mt('all'),10,20,50,100,1000,10000))).
2318: '</label></span> <span class="LC_nobreak">'.
2319: &mt('Filter: [_1]',
2320: &select_form($env{'form.displayfilter'},
2321: 'displayfilter',
2322: {'currentfolder' => 'Current folder/page',
2323: 'containing' => 'Containing phrase',
2324: 'none' => 'None'},$onchange)).' '.
2325: '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
2326: &HTML::Entities::encode($env{'form.containingphrase'}).
2327: '" />'.$additional;
2328: }
2329:
2330: sub display_filter_js {
2331: my $includetext = &mt('Include parameter types');
2332: return <<"ENDJS";
2333:
2334: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
2335: var firstType = 'hidden';
2336: if (setter.options[setter.selectedIndex].value == 'containing') {
2337: firstType = 'text';
2338: }
2339: firstObject = document.getElementById(firstid);
2340: if (typeof(firstObject) == 'object') {
2341: if (firstObject.type != firstType) {
2342: changeInputType(firstObject,firstType);
2343: }
2344: }
2345: if (context == 'parmslog') {
2346: var secondType = 'hidden';
2347: if (firstType == 'text') {
2348: secondType = 'checkbox';
2349: }
2350: secondObject = document.getElementById(secondid);
2351: if (typeof(secondObject) == 'object') {
2352: if (secondObject.type != secondType) {
2353: changeInputType(secondObject,secondType);
2354: }
2355: }
2356: var textItem = document.getElementById(thirdid);
2357: var currtext = textItem.innerHTML;
2358: var newtext;
2359: if (firstType == 'text') {
2360: newtext = '$includetext';
2361: } else {
2362: newtext = ' ';
2363: }
2364: if (currtext != newtext) {
2365: textItem.innerHTML = newtext;
2366: }
2367: }
2368: return;
2369: }
2370:
2371: function changeInputType(oldObject,newType) {
2372: var newObject = document.createElement('input');
2373: newObject.type = newType;
2374: if (oldObject.size) {
2375: newObject.size = oldObject.size;
2376: }
2377: if (oldObject.value) {
2378: newObject.value = oldObject.value;
2379: }
2380: if (oldObject.name) {
2381: newObject.name = oldObject.name;
2382: }
2383: if (oldObject.id) {
2384: newObject.id = oldObject.id;
2385: }
2386: oldObject.parentNode.replaceChild(newObject,oldObject);
2387: return;
2388: }
2389:
2390: ENDJS
2391: }
2392:
2393: sub gradeleveldescription {
2394: my $gradelevel=shift;
2395: my %gradelevels=(0 => 'Not specified',
2396: 1 => 'Grade 1',
2397: 2 => 'Grade 2',
2398: 3 => 'Grade 3',
2399: 4 => 'Grade 4',
2400: 5 => 'Grade 5',
2401: 6 => 'Grade 6',
2402: 7 => 'Grade 7',
2403: 8 => 'Grade 8',
2404: 9 => 'Grade 9',
2405: 10 => 'Grade 10',
2406: 11 => 'Grade 11',
2407: 12 => 'Grade 12',
2408: 13 => 'Grade 13',
2409: 14 => '100 Level',
2410: 15 => '200 Level',
2411: 16 => '300 Level',
2412: 17 => '400 Level',
2413: 18 => 'Graduate Level');
2414: return &mt($gradelevels{$gradelevel});
2415: }
2416:
2417: sub select_level_form {
2418: my ($deflevel,$name)=@_;
2419: unless ($deflevel) { $deflevel=0; }
2420: my $selectform = "<select name=\"$name\" size=\"1\">\n";
2421: for (my $i=0; $i<=18; $i++) {
2422: $selectform.="<option value=\"$i\" ".
2423: ($i==$deflevel ? 'selected="selected" ' : '').
2424: ">".&gradeleveldescription($i)."</option>\n";
2425: }
2426: $selectform.="</select>";
2427: return $selectform;
2428: }
2429:
2430: #-------------------------------------------
2431:
2432: =pod
2433:
2434: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
2435:
2436: Returns a string containing a <select name='$name' size='1'> form to
2437: allow a user to select the domain to preform an operation in.
2438: See loncreateuser.pm for an example invocation and use.
2439:
2440: If the $includeempty flag is set, it also includes an empty choice ("no domain
2441: selected");
2442:
2443: If the $showdomdesc flag is set, the domain name is followed by the domain description.
2444:
2445: 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.
2446:
2447: The optional $incdoms is a reference to an array of domains which will be the only available options.
2448:
2449: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
2450:
2451: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
2452:
2453: =cut
2454:
2455: #-------------------------------------------
2456: sub select_dom_form {
2457: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
2458: if ($onchange) {
2459: $onchange = ' onchange="'.$onchange.'"';
2460: }
2461: if ($disabled) {
2462: $disabled = ' disabled="disabled"';
2463: }
2464: my (@domains,%exclude);
2465: if (ref($incdoms) eq 'ARRAY') {
2466: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
2467: } else {
2468: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
2469: }
2470: if ($includeempty) { @domains=('',@domains); }
2471: if (ref($excdoms) eq 'ARRAY') {
2472: map { $exclude{$_} = 1; } @{$excdoms};
2473: }
2474: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2475: foreach my $dom (@domains) {
2476: next if ($exclude{$dom});
2477: $selectdomain.="<option value=\"$dom\" ".
2478: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
2479: if ($showdomdesc) {
2480: if ($dom ne '') {
2481: my $domdesc = &Apache::lonnet::domain($dom,'description');
2482: if ($domdesc ne '') {
2483: $selectdomain .= ' ('.$domdesc.')';
2484: }
2485: }
2486: }
2487: $selectdomain .= "</option>\n";
2488: }
2489: $selectdomain.="</select>";
2490: return $selectdomain;
2491: }
2492:
2493: #-------------------------------------------
2494:
2495: =pod
2496:
2497: =item * &home_server_form_item($domain,$name,$defaultflag)
2498:
2499: input: 4 arguments (two required, two optional) -
2500: $domain - domain of new user
2501: $name - name of form element
2502: $default - Value of 'default' causes a default item to be first
2503: option, and selected by default.
2504: $hide - Value of 'hide' causes hiding of the name of the server,
2505: if 1 server found, or default, if 0 found.
2506: output: returns 2 items:
2507: (a) form element which contains either:
2508: (i) <select name="$name">
2509: <option value="$hostid1">$hostid $servers{$hostid}</option>
2510: <option value="$hostid2">$hostid $servers{$hostid}</option>
2511: </select>
2512: form item if there are multiple library servers in $domain, or
2513: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2514: if there is only one library server in $domain.
2515:
2516: (b) number of library servers found.
2517:
2518: See loncreateuser.pm for example of use.
2519:
2520: =cut
2521:
2522: #-------------------------------------------
2523: sub home_server_form_item {
2524: my ($domain,$name,$default,$hide) = @_;
2525: my %servers = &Apache::lonnet::get_servers($domain,'library');
2526: my $result;
2527: my $numlib = keys(%servers);
2528: if ($numlib > 1) {
2529: $result .= '<select name="'.$name.'" />'."\n";
2530: if ($default) {
2531: $result .= '<option value="default" selected="selected">'.&mt('default').
2532: '</option>'."\n";
2533: }
2534: foreach my $hostid (sort(keys(%servers))) {
2535: $result.= '<option value="'.$hostid.'">'.
2536: $hostid.' '.$servers{$hostid}."</option>\n";
2537: }
2538: $result .= '</select>'."\n";
2539: } elsif ($numlib == 1) {
2540: my $hostid;
2541: foreach my $item (keys(%servers)) {
2542: $hostid = $item;
2543: }
2544: $result .= '<input type="hidden" name="'.$name.'" value="'.
2545: $hostid.'" />';
2546: if (!$hide) {
2547: $result .= $hostid.' '.$servers{$hostid};
2548: }
2549: $result .= "\n";
2550: } elsif ($default) {
2551: $result .= '<input type="hidden" name="'.$name.
2552: '" value="default" />';
2553: if (!$hide) {
2554: $result .= &mt('default');
2555: }
2556: $result .= "\n";
2557: }
2558: return ($result,$numlib);
2559: }
2560:
2561: =pod
2562:
2563: =back
2564:
2565: =cut
2566:
2567: ###############################################################
2568: ## Decoding User Agent ##
2569: ###############################################################
2570:
2571: =pod
2572:
2573: =head1 Decoding the User Agent
2574:
2575: =over 4
2576:
2577: =item * &decode_user_agent()
2578:
2579: Inputs: $r
2580:
2581: Outputs:
2582:
2583: =over 4
2584:
2585: =item * $httpbrowser
2586:
2587: =item * $clientbrowser
2588:
2589: =item * $clientversion
2590:
2591: =item * $clientmathml
2592:
2593: =item * $clientunicode
2594:
2595: =item * $clientos
2596:
2597: =item * $clientmobile
2598:
2599: =item * $clientinfo
2600:
2601: =item * $clientosversion
2602:
2603: =back
2604:
2605: =back
2606:
2607: =cut
2608:
2609: ###############################################################
2610: ###############################################################
2611: sub decode_user_agent {
2612: my ($r)=@_;
2613: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
2614: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
2615: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
2616: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
2617: my $clientbrowser='unknown';
2618: my $clientversion='0';
2619: my $clientmathml='';
2620: my $clientunicode='0';
2621: my $clientmobile=0;
2622: my $clientosversion='';
2623: for (my $i=0;$i<=$#browsertype;$i++) {
2624: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
2625: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
2626: $clientbrowser=$bname;
2627: $httpbrowser=~/$vreg/i;
2628: $clientversion=$1;
2629: $clientmathml=($clientversion>=$minv);
2630: $clientunicode=($clientversion>=$univ);
2631: }
2632: }
2633: my $clientos='unknown';
2634: my $clientinfo;
2635: if (($httpbrowser=~/linux/i) ||
2636: ($httpbrowser=~/unix/i) ||
2637: ($httpbrowser=~/ux/i) ||
2638: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
2639: if (($httpbrowser=~/vax/i) ||
2640: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
2641: if ($httpbrowser=~/next/i) { $clientos='next'; }
2642: if (($httpbrowser=~/mac/i) ||
2643: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
2644: if ($httpbrowser=~/win/i) {
2645: $clientos='win';
2646: if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
2647: $clientosversion = $1;
2648: }
2649: }
2650: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
2651: if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
2652: $clientmobile=lc($1);
2653: }
2654: if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
2655: $clientinfo = 'firefox-'.$1;
2656: } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
2657: $clientinfo = 'chromeframe-'.$1;
2658: }
2659: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
2660: $clientunicode,$clientos,$clientmobile,$clientinfo,
2661: $clientosversion);
2662: }
2663:
2664: ###############################################################
2665: ## Authentication changing form generation subroutines ##
2666: ###############################################################
2667: ##
2668: ## All of the authform_xxxxxxx subroutines take their inputs in a
2669: ## hash, and have reasonable default values.
2670: ##
2671: ## formname = the name given in the <form> tag.
2672: #-------------------------------------------
2673:
2674: =pod
2675:
2676: =head1 Authentication Routines
2677:
2678: =over 4
2679:
2680: =item * &authform_xxxxxx()
2681:
2682: The authform_xxxxxx subroutines provide javascript and html forms which
2683: handle some of the conveniences required for authentication forms.
2684: This is not an optimal method, but it works.
2685:
2686: =over 4
2687:
2688: =item * authform_header
2689:
2690: =item * authform_authorwarning
2691:
2692: =item * authform_nochange
2693:
2694: =item * authform_kerberos
2695:
2696: =item * authform_internal
2697:
2698: =item * authform_filesystem
2699:
2700: =back
2701:
2702: See loncreateuser.pm for invocation and use examples.
2703:
2704: =cut
2705:
2706: #-------------------------------------------
2707: sub authform_header{
2708: my %in = (
2709: formname => 'cu',
2710: kerb_def_dom => '',
2711: @_,
2712: );
2713: $in{'formname'} = 'document.' . $in{'formname'};
2714: my $result='';
2715:
2716: #---------------------------------------------- Code for upper case translation
2717: my $Javascript_toUpperCase;
2718: unless ($in{kerb_def_dom}) {
2719: $Javascript_toUpperCase =<<"END";
2720: switch (choice) {
2721: case 'krb': currentform.elements[choicearg].value =
2722: currentform.elements[choicearg].value.toUpperCase();
2723: break;
2724: default:
2725: }
2726: END
2727: } else {
2728: $Javascript_toUpperCase = "";
2729: }
2730:
2731: my $radioval = "'nochange'";
2732: if (defined($in{'curr_authtype'})) {
2733: if ($in{'curr_authtype'} ne '') {
2734: $radioval = "'".$in{'curr_authtype'}."arg'";
2735: }
2736: }
2737: my $argfield = 'null';
2738: if (defined($in{'mode'})) {
2739: if ($in{'mode'} eq 'modifycourse') {
2740: if (defined($in{'curr_autharg'})) {
2741: if ($in{'curr_autharg'} ne '') {
2742: $argfield = "'$in{'curr_autharg'}'";
2743: }
2744: }
2745: }
2746: }
2747:
2748: $result.=<<"END";
2749: var current = new Object();
2750: current.radiovalue = $radioval;
2751: current.argfield = $argfield;
2752:
2753: function changed_radio(choice,currentform) {
2754: var choicearg = choice + 'arg';
2755: // If a radio button in changed, we need to change the argfield
2756: if (current.radiovalue != choice) {
2757: current.radiovalue = choice;
2758: if (current.argfield != null) {
2759: currentform.elements[current.argfield].value = '';
2760: }
2761: if (choice == 'nochange') {
2762: current.argfield = null;
2763: } else {
2764: current.argfield = choicearg;
2765: switch(choice) {
2766: case 'krb':
2767: currentform.elements[current.argfield].value =
2768: "$in{'kerb_def_dom'}";
2769: break;
2770: default:
2771: break;
2772: }
2773: }
2774: }
2775: return;
2776: }
2777:
2778: function changed_text(choice,currentform) {
2779: var choicearg = choice + 'arg';
2780: if (currentform.elements[choicearg].value !='') {
2781: $Javascript_toUpperCase
2782: // clear old field
2783: if ((current.argfield != choicearg) && (current.argfield != null)) {
2784: currentform.elements[current.argfield].value = '';
2785: }
2786: current.argfield = choicearg;
2787: }
2788: set_auth_radio_buttons(choice,currentform);
2789: return;
2790: }
2791:
2792: function set_auth_radio_buttons(newvalue,currentform) {
2793: var numauthchoices = currentform.login.length;
2794: if (typeof numauthchoices == "undefined") {
2795: return;
2796: }
2797: var i=0;
2798: while (i < numauthchoices) {
2799: if (currentform.login[i].value == newvalue) { break; }
2800: i++;
2801: }
2802: if (i == numauthchoices) {
2803: return;
2804: }
2805: current.radiovalue = newvalue;
2806: currentform.login[i].checked = true;
2807: return;
2808: }
2809: END
2810: return $result;
2811: }
2812:
2813: sub authform_authorwarning {
2814: my $result='';
2815: $result='<i>'.
2816: &mt('As a general rule, only authors or co-authors should be '.
2817: 'filesystem authenticated '.
2818: '(which allows access to the server filesystem).')."</i>\n";
2819: return $result;
2820: }
2821:
2822: sub authform_nochange {
2823: my %in = (
2824: formname => 'document.cu',
2825: kerb_def_dom => 'MSU.EDU',
2826: @_,
2827: );
2828: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2829: my $result;
2830: if (!$authnum) {
2831: $result = &mt('Under your current role you are not permitted to change login settings for this user');
2832: } else {
2833: $result = '<label>'.&mt('[_1] Do not change login data',
2834: '<input type="radio" name="login" value="nochange" '.
2835: 'checked="checked" onclick="'.
2836: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
2837: '</label>';
2838: }
2839: return $result;
2840: }
2841:
2842: sub authform_kerberos {
2843: my %in = (
2844: formname => 'document.cu',
2845: kerb_def_dom => 'MSU.EDU',
2846: kerb_def_auth => 'krb4',
2847: @_,
2848: );
2849: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2850: $autharg,$jscall,$disabled);
2851: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2852: if ($in{'kerb_def_auth'} eq 'krb5') {
2853: $check5 = ' checked="checked"';
2854: } else {
2855: $check4 = ' checked="checked"';
2856: }
2857: if ($in{'readonly'}) {
2858: $disabled = ' disabled="disabled"';
2859: }
2860: $krbarg = $in{'kerb_def_dom'};
2861: if (defined($in{'curr_authtype'})) {
2862: if ($in{'curr_authtype'} eq 'krb') {
2863: $krbcheck = ' checked="checked"';
2864: if (defined($in{'mode'})) {
2865: if ($in{'mode'} eq 'modifyuser') {
2866: $krbcheck = '';
2867: }
2868: }
2869: if (defined($in{'curr_kerb_ver'})) {
2870: if ($in{'curr_krb_ver'} eq '5') {
2871: $check5 = ' checked="checked"';
2872: $check4 = '';
2873: } else {
2874: $check4 = ' checked="checked"';
2875: $check5 = '';
2876: }
2877: }
2878: if (defined($in{'curr_autharg'})) {
2879: $krbarg = $in{'curr_autharg'};
2880: }
2881: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2882: if (defined($in{'curr_autharg'})) {
2883: $result =
2884: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
2885: $in{'curr_autharg'},$krbver);
2886: } else {
2887: $result =
2888: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
2889: }
2890: return $result;
2891: }
2892: }
2893: } else {
2894: if ($authnum == 1) {
2895: $authtype = '<input type="hidden" name="login" value="krb" />';
2896: }
2897: }
2898: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2899: return;
2900: } elsif ($authtype eq '') {
2901: if (defined($in{'mode'})) {
2902: if ($in{'mode'} eq 'modifycourse') {
2903: if ($authnum == 1) {
2904: $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
2905: }
2906: }
2907: }
2908: }
2909: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
2910: if ($authtype eq '') {
2911: $authtype = '<input type="radio" name="login" value="krb" '.
2912: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
2913: $krbcheck.$disabled.' />';
2914: }
2915: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
2916: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
2917: $in{'curr_authtype'} eq 'krb5') ||
2918: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
2919: $in{'curr_authtype'} eq 'krb4')) {
2920: $result .= &mt
2921: ('[_1] Kerberos authenticated with domain [_2] '.
2922: '[_3] Version 4 [_4] Version 5 [_5]',
2923: '<label>'.$authtype,
2924: '</label><input type="text" size="10" name="krbarg" '.
2925: 'value="'.$krbarg.'" '.
2926: 'onchange="'.$jscall.'"'.$disabled.' />',
2927: '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
2928: '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
2929: '</label>');
2930: } elsif ($can_assign{'krb4'}) {
2931: $result .= &mt
2932: ('[_1] Kerberos authenticated with domain [_2] '.
2933: '[_3] Version 4 [_4]',
2934: '<label>'.$authtype,
2935: '</label><input type="text" size="10" name="krbarg" '.
2936: 'value="'.$krbarg.'" '.
2937: 'onchange="'.$jscall.'"'.$disabled.' />',
2938: '<label><input type="hidden" name="krbver" value="4" />',
2939: '</label>');
2940: } elsif ($can_assign{'krb5'}) {
2941: $result .= &mt
2942: ('[_1] Kerberos authenticated with domain [_2] '.
2943: '[_3] Version 5 [_4]',
2944: '<label>'.$authtype,
2945: '</label><input type="text" size="10" name="krbarg" '.
2946: 'value="'.$krbarg.'" '.
2947: 'onchange="'.$jscall.'"'.$disabled.' />',
2948: '<label><input type="hidden" name="krbver" value="5" />',
2949: '</label>');
2950: }
2951: return $result;
2952: }
2953:
2954: sub authform_internal {
2955: my %in = (
2956: formname => 'document.cu',
2957: kerb_def_dom => 'MSU.EDU',
2958: @_,
2959: );
2960: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
2961: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2962: if ($in{'readonly'}) {
2963: $disabled = ' disabled="disabled"';
2964: }
2965: if (defined($in{'curr_authtype'})) {
2966: if ($in{'curr_authtype'} eq 'int') {
2967: if ($can_assign{'int'}) {
2968: $intcheck = 'checked="checked" ';
2969: if (defined($in{'mode'})) {
2970: if ($in{'mode'} eq 'modifyuser') {
2971: $intcheck = '';
2972: }
2973: }
2974: if (defined($in{'curr_autharg'})) {
2975: $intarg = $in{'curr_autharg'};
2976: }
2977: } else {
2978: $result = &mt('Currently internally authenticated.');
2979: return $result;
2980: }
2981: }
2982: } else {
2983: if ($authnum == 1) {
2984: $authtype = '<input type="hidden" name="login" value="int" />';
2985: }
2986: }
2987: if (!$can_assign{'int'}) {
2988: return;
2989: } elsif ($authtype eq '') {
2990: if (defined($in{'mode'})) {
2991: if ($in{'mode'} eq 'modifycourse') {
2992: if ($authnum == 1) {
2993: $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
2994: }
2995: }
2996: }
2997: }
2998: $jscall = "javascript:changed_radio('int',$in{'formname'});";
2999: if ($authtype eq '') {
3000: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
3001: ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
3002: }
3003: $autharg = '<input type="password" size="10" name="intarg" value="'.
3004: $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3005: $result = &mt
3006: ('[_1] Internally authenticated (with initial password [_2])',
3007: '<label>'.$authtype,'</label>'.$autharg);
3008: $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>';
3009: return $result;
3010: }
3011:
3012: sub authform_local {
3013: my %in = (
3014: formname => 'document.cu',
3015: kerb_def_dom => 'MSU.EDU',
3016: @_,
3017: );
3018: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
3019: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3020: if ($in{'readonly'}) {
3021: $disabled = ' disabled="disabled"';
3022: }
3023: if (defined($in{'curr_authtype'})) {
3024: if ($in{'curr_authtype'} eq 'loc') {
3025: if ($can_assign{'loc'}) {
3026: $loccheck = 'checked="checked" ';
3027: if (defined($in{'mode'})) {
3028: if ($in{'mode'} eq 'modifyuser') {
3029: $loccheck = '';
3030: }
3031: }
3032: if (defined($in{'curr_autharg'})) {
3033: $locarg = $in{'curr_autharg'};
3034: }
3035: } else {
3036: $result = &mt('Currently using local (institutional) authentication.');
3037: return $result;
3038: }
3039: }
3040: } else {
3041: if ($authnum == 1) {
3042: $authtype = '<input type="hidden" name="login" value="loc" />';
3043: }
3044: }
3045: if (!$can_assign{'loc'}) {
3046: return;
3047: } elsif ($authtype eq '') {
3048: if (defined($in{'mode'})) {
3049: if ($in{'mode'} eq 'modifycourse') {
3050: if ($authnum == 1) {
3051: $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
3052: }
3053: }
3054: }
3055: }
3056: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
3057: if ($authtype eq '') {
3058: $authtype = '<input type="radio" name="login" value="loc" '.
3059: $loccheck.' onchange="'.$jscall.'" onclick="'.
3060: $jscall.'"'.$disabled.' />';
3061: }
3062: $autharg = '<input type="text" size="10" name="locarg" value="'.
3063: $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3064: $result = &mt('[_1] Local Authentication with argument [_2]',
3065: '<label>'.$authtype,'</label>'.$autharg);
3066: return $result;
3067: }
3068:
3069: sub authform_filesystem {
3070: my %in = (
3071: formname => 'document.cu',
3072: kerb_def_dom => 'MSU.EDU',
3073: @_,
3074: );
3075: my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
3076: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3077: if ($in{'readonly'}) {
3078: $disabled = ' disabled="disabled"';
3079: }
3080: if (defined($in{'curr_authtype'})) {
3081: if ($in{'curr_authtype'} eq 'fsys') {
3082: if ($can_assign{'fsys'}) {
3083: $fsyscheck = 'checked="checked" ';
3084: if (defined($in{'mode'})) {
3085: if ($in{'mode'} eq 'modifyuser') {
3086: $fsyscheck = '';
3087: }
3088: }
3089: } else {
3090: $result = &mt('Currently Filesystem Authenticated.');
3091: return $result;
3092: }
3093: }
3094: } else {
3095: if ($authnum == 1) {
3096: $authtype = '<input type="hidden" name="login" value="fsys" />';
3097: }
3098: }
3099: if (!$can_assign{'fsys'}) {
3100: return;
3101: } elsif ($authtype eq '') {
3102: if (defined($in{'mode'})) {
3103: if ($in{'mode'} eq 'modifycourse') {
3104: if ($authnum == 1) {
3105: $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
3106: }
3107: }
3108: }
3109: }
3110: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
3111: if ($authtype eq '') {
3112: $authtype = '<input type="radio" name="login" value="fsys" '.
3113: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
3114: $jscall.'"'.$disabled.' />';
3115: }
3116: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
3117: ' onchange="'.$jscall.'"'.$disabled.' />';
3118: $result = &mt
3119: ('[_1] Filesystem Authenticated (with initial password [_2])',
3120: '<label><input type="radio" name="login" value="fsys" '.
3121: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
3122: '</label><input type="password" size="10" name="fsysarg" value="" '.
3123: 'onchange="'.$jscall.'"'.$disabled.' />');
3124: return $result;
3125: }
3126:
3127: sub get_assignable_auth {
3128: my ($dom) = @_;
3129: if ($dom eq '') {
3130: $dom = $env{'request.role.domain'};
3131: }
3132: my %can_assign = (
3133: krb4 => 1,
3134: krb5 => 1,
3135: int => 1,
3136: loc => 1,
3137: );
3138: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
3139: if (ref($domconfig{'usercreation'}) eq 'HASH') {
3140: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
3141: my $authhash = $domconfig{'usercreation'}{'authtypes'};
3142: my $context;
3143: if ($env{'request.role'} =~ /^au/) {
3144: $context = 'author';
3145: } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
3146: $context = 'domain';
3147: } elsif ($env{'request.course.id'}) {
3148: $context = 'course';
3149: }
3150: if ($context) {
3151: if (ref($authhash->{$context}) eq 'HASH') {
3152: %can_assign = %{$authhash->{$context}};
3153: }
3154: }
3155: }
3156: }
3157: my $authnum = 0;
3158: foreach my $key (keys(%can_assign)) {
3159: if ($can_assign{$key}) {
3160: $authnum ++;
3161: }
3162: }
3163: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
3164: $authnum --;
3165: }
3166: return ($authnum,%can_assign);
3167: }
3168:
3169: ###############################################################
3170: ## Get Kerberos Defaults for Domain ##
3171: ###############################################################
3172: ##
3173: ## Returns default kerberos version and an associated argument
3174: ## as listed in file domain.tab. If not listed, provides
3175: ## appropriate default domain and kerberos version.
3176: ##
3177: #-------------------------------------------
3178:
3179: =pod
3180:
3181: =item * &get_kerberos_defaults()
3182:
3183: get_kerberos_defaults($target_domain) returns the default kerberos
3184: version and domain. If not found, it defaults to version 4 and the
3185: domain of the server.
3186:
3187: =over 4
3188:
3189: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
3190:
3191: =back
3192:
3193: =back
3194:
3195: =cut
3196:
3197: #-------------------------------------------
3198: sub get_kerberos_defaults {
3199: my $domain=shift;
3200: my ($krbdef,$krbdefdom);
3201: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
3202: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
3203: $krbdef = $domdefaults{'auth_def'};
3204: $krbdefdom = $domdefaults{'auth_arg_def'};
3205: } else {
3206: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
3207: my $krbdefdom=$1;
3208: $krbdefdom=~tr/a-z/A-Z/;
3209: $krbdef = "krb4";
3210: }
3211: return ($krbdef,$krbdefdom);
3212: }
3213:
3214:
3215: ###############################################################
3216: ## Thesaurus Functions ##
3217: ###############################################################
3218:
3219: =pod
3220:
3221: =head1 Thesaurus Functions
3222:
3223: =over 4
3224:
3225: =item * &initialize_keywords()
3226:
3227: Initializes the package variable %Keywords if it is empty. Uses the
3228: package variable $thesaurus_db_file.
3229:
3230: =cut
3231:
3232: ###################################################
3233:
3234: sub initialize_keywords {
3235: return 1 if (scalar keys(%Keywords));
3236: # If we are here, %Keywords is empty, so fill it up
3237: # Make sure the file we need exists...
3238: if (! -e $thesaurus_db_file) {
3239: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
3240: " failed because it does not exist");
3241: return 0;
3242: }
3243: # Set up the hash as a database
3244: my %thesaurus_db;
3245: if (! tie(%thesaurus_db,'GDBM_File',
3246: $thesaurus_db_file,&GDBM_READER(),0640)){
3247: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
3248: $thesaurus_db_file);
3249: return 0;
3250: }
3251: # Get the average number of appearances of a word.
3252: my $avecount = $thesaurus_db{'average.count'};
3253: # Put keywords (those that appear > average) into %Keywords
3254: while (my ($word,$data)=each (%thesaurus_db)) {
3255: my ($count,undef) = split /:/,$data;
3256: $Keywords{$word}++ if ($count > $avecount);
3257: }
3258: untie %thesaurus_db;
3259: # Remove special values from %Keywords.
3260: foreach my $value ('total.count','average.count') {
3261: delete($Keywords{$value}) if (exists($Keywords{$value}));
3262: }
3263: return 1;
3264: }
3265:
3266: ###################################################
3267:
3268: =pod
3269:
3270: =item * &keyword($word)
3271:
3272: Returns true if $word is a keyword. A keyword is a word that appears more
3273: than the average number of times in the thesaurus database. Calls
3274: &initialize_keywords
3275:
3276: =cut
3277:
3278: ###################################################
3279:
3280: sub keyword {
3281: return if (!&initialize_keywords());
3282: my $word=lc(shift());
3283: $word=~s/\W//g;
3284: return exists($Keywords{$word});
3285: }
3286:
3287: ###############################################################
3288:
3289: =pod
3290:
3291: =item * &get_related_words()
3292:
3293: Look up a word in the thesaurus. Takes a scalar argument and returns
3294: an array of words. If the keyword is not in the thesaurus, an empty array
3295: will be returned. The order of the words returned is determined by the
3296: database which holds them.
3297:
3298: Uses global $thesaurus_db_file.
3299:
3300:
3301: =cut
3302:
3303: ###############################################################
3304: sub get_related_words {
3305: my $keyword = shift;
3306: my %thesaurus_db;
3307: if (! -e $thesaurus_db_file) {
3308: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
3309: "failed because the file does not exist");
3310: return ();
3311: }
3312: if (! tie(%thesaurus_db,'GDBM_File',
3313: $thesaurus_db_file,&GDBM_READER(),0640)){
3314: return ();
3315: }
3316: my @Words=();
3317: my $count=0;
3318: if (exists($thesaurus_db{$keyword})) {
3319: # The first element is the number of times
3320: # the word appears. We do not need it now.
3321: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
3322: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
3323: my $threshold=$mostfrequentcount/10;
3324: foreach my $possibleword (@RelatedWords) {
3325: my ($word,$wordcount)=split(/\,/,$possibleword);
3326: if ($wordcount>$threshold) {
3327: push(@Words,$word);
3328: $count++;
3329: if ($count>10) { last; }
3330: }
3331: }
3332: }
3333: untie %thesaurus_db;
3334: return @Words;
3335: }
3336:
3337: =pod
3338:
3339: =back
3340:
3341: =cut
3342:
3343: # -------------------------------------------------------------- Plaintext name
3344: =pod
3345:
3346: =head1 User Name Functions
3347:
3348: =over 4
3349:
3350: =item * &plainname($uname,$udom,$first)
3351:
3352: Takes a users logon name and returns it as a string in
3353: "first middle last generation" form
3354: if $first is set to 'lastname' then it returns it as
3355: 'lastname generation, firstname middlename' if their is a lastname
3356:
3357: =cut
3358:
3359:
3360: ###############################################################
3361: sub plainname {
3362: my ($uname,$udom,$first)=@_;
3363: return if (!defined($uname) || !defined($udom));
3364: my %names=&getnames($uname,$udom);
3365: my $name=&Apache::lonnet::format_name($names{'firstname'},
3366: $names{'middlename'},
3367: $names{'lastname'},
3368: $names{'generation'},$first);
3369: $name=~s/^\s+//;
3370: $name=~s/\s+$//;
3371: $name=~s/\s+/ /g;
3372: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
3373: return $name;
3374: }
3375:
3376: # -------------------------------------------------------------------- Nickname
3377: =pod
3378:
3379: =item * &nickname($uname,$udom)
3380:
3381: Gets a users name and returns it as a string as
3382:
3383: ""nickname""
3384:
3385: if the user has a nickname or
3386:
3387: "first middle last generation"
3388:
3389: if the user does not
3390:
3391: =cut
3392:
3393: sub nickname {
3394: my ($uname,$udom)=@_;
3395: return if (!defined($uname) || !defined($udom));
3396: my %names=&getnames($uname,$udom);
3397: my $name=$names{'nickname'};
3398: if ($name) {
3399: $name='"'.$name.'"';
3400: } else {
3401: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
3402: $names{'lastname'}.' '.$names{'generation'};
3403: $name=~s/\s+$//;
3404: $name=~s/\s+/ /g;
3405: }
3406: return $name;
3407: }
3408:
3409: sub getnames {
3410: my ($uname,$udom)=@_;
3411: return if (!defined($uname) || !defined($udom));
3412: if ($udom eq 'public' && $uname eq 'public') {
3413: return ('lastname' => &mt('Public'));
3414: }
3415: my $id=$uname.':'.$udom;
3416: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
3417: if ($cached) {
3418: return %{$names};
3419: } else {
3420: my %loadnames=&Apache::lonnet::get('environment',
3421: ['firstname','middlename','lastname','generation','nickname'],
3422: $udom,$uname);
3423: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
3424: return %loadnames;
3425: }
3426: }
3427:
3428: # -------------------------------------------------------------------- getemails
3429:
3430: =pod
3431:
3432: =item * &getemails($uname,$udom)
3433:
3434: Gets a user's email information and returns it as a hash with keys:
3435: notification, critnotification, permanentemail
3436:
3437: For notification and critnotification, values are comma-separated lists
3438: of e-mail addresses; for permanentemail, value is a single e-mail address.
3439:
3440:
3441: =cut
3442:
3443:
3444: sub getemails {
3445: my ($uname,$udom)=@_;
3446: if ($udom eq 'public' && $uname eq 'public') {
3447: return;
3448: }
3449: if (!$udom) { $udom=$env{'user.domain'}; }
3450: if (!$uname) { $uname=$env{'user.name'}; }
3451: my $id=$uname.':'.$udom;
3452: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
3453: if ($cached) {
3454: return %{$names};
3455: } else {
3456: my %loadnames=&Apache::lonnet::get('environment',
3457: ['notification','critnotification',
3458: 'permanentemail'],
3459: $udom,$uname);
3460: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
3461: return %loadnames;
3462: }
3463: }
3464:
3465: sub flush_email_cache {
3466: my ($uname,$udom)=@_;
3467: if (!$udom) { $udom =$env{'user.domain'}; }
3468: if (!$uname) { $uname=$env{'user.name'}; }
3469: return if ($udom eq 'public' && $uname eq 'public');
3470: my $id=$uname.':'.$udom;
3471: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
3472: }
3473:
3474: # -------------------------------------------------------------------- getlangs
3475:
3476: =pod
3477:
3478: =item * &getlangs($uname,$udom)
3479:
3480: Gets a user's language preference and returns it as a hash with key:
3481: language.
3482:
3483: =cut
3484:
3485:
3486: sub getlangs {
3487: my ($uname,$udom) = @_;
3488: if (!$udom) { $udom =$env{'user.domain'}; }
3489: if (!$uname) { $uname=$env{'user.name'}; }
3490: my $id=$uname.':'.$udom;
3491: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
3492: if ($cached) {
3493: return %{$langs};
3494: } else {
3495: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
3496: $udom,$uname);
3497: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
3498: return %loadlangs;
3499: }
3500: }
3501:
3502: sub flush_langs_cache {
3503: my ($uname,$udom)=@_;
3504: if (!$udom) { $udom =$env{'user.domain'}; }
3505: if (!$uname) { $uname=$env{'user.name'}; }
3506: return if ($udom eq 'public' && $uname eq 'public');
3507: my $id=$uname.':'.$udom;
3508: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
3509: }
3510:
3511: # ------------------------------------------------------------------ Screenname
3512:
3513: =pod
3514:
3515: =item * &screenname($uname,$udom)
3516:
3517: Gets a users screenname and returns it as a string
3518:
3519: =cut
3520:
3521: sub screenname {
3522: my ($uname,$udom)=@_;
3523: if ($uname eq $env{'user.name'} &&
3524: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
3525: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
3526: return $names{'screenname'};
3527: }
3528:
3529:
3530: # ------------------------------------------------------------- Confirm Wrapper
3531: =pod
3532:
3533: =item * &confirmwrapper($message)
3534:
3535: Wrap messages about completion of operation in box
3536:
3537: =cut
3538:
3539: sub confirmwrapper {
3540: my ($message)=@_;
3541: if ($message) {
3542: return "\n".'<div class="LC_confirm_box">'."\n"
3543: .$message."\n"
3544: .'</div>'."\n";
3545: } else {
3546: return $message;
3547: }
3548: }
3549:
3550: # ------------------------------------------------------------- Message Wrapper
3551:
3552: sub messagewrapper {
3553: my ($link,$username,$domain,$subject,$text)=@_;
3554: return
3555: '<a href="/adm/email?compose=individual&'.
3556: 'recname='.$username.'&recdom='.$domain.
3557: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
3558: 'title="'.&mt('Send message').'">'.$link.'</a>';
3559: }
3560:
3561: # --------------------------------------------------------------- Notes Wrapper
3562:
3563: sub noteswrapper {
3564: my ($link,$un,$do)=@_;
3565: return
3566: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
3567: }
3568:
3569: # ------------------------------------------------------------- Aboutme Wrapper
3570:
3571: sub aboutmewrapper {
3572: my ($link,$username,$domain,$target,$class)=@_;
3573: if (!defined($username) && !defined($domain)) {
3574: return;
3575: }
3576: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
3577: ($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
3578: }
3579:
3580: # ------------------------------------------------------------ Syllabus Wrapper
3581:
3582: sub syllabuswrapper {
3583: my ($linktext,$coursedir,$domain)=@_;
3584: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
3585: }
3586:
3587: # -----------------------------------------------------------------------------
3588:
3589: sub track_student_link {
3590: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
3591: my $link ="/adm/trackstudent?";
3592: my $title = 'View recent activity';
3593: if (defined($sname) && $sname !~ /^\s*$/ &&
3594: defined($sdom) && $sdom !~ /^\s*$/) {
3595: $link .= "selected_student=$sname:$sdom";
3596: $title .= ' of this student';
3597: }
3598: if (defined($target) && $target !~ /^\s*$/) {
3599: $target = qq{target="$target"};
3600: } else {
3601: $target = '';
3602: }
3603: if ($start) { $link.='&start='.$start; }
3604: if ($only_body) { $link .= '&only_body=1'; }
3605: $title = &mt($title);
3606: $linktext = &mt($linktext);
3607: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
3608: &help_open_topic('View_recent_activity');
3609: }
3610:
3611: sub slot_reservations_link {
3612: my ($linktext,$sname,$sdom,$target) = @_;
3613: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
3614: my $title = 'View slot reservation history';
3615: if (defined($sname) && $sname !~ /^\s*$/ &&
3616: defined($sdom) && $sdom !~ /^\s*$/) {
3617: $link .= "&uname=$sname&udom=$sdom";
3618: $title .= ' of this student';
3619: }
3620: if (defined($target) && $target !~ /^\s*$/) {
3621: $target = qq{target="$target"};
3622: } else {
3623: $target = '';
3624: }
3625: $title = &mt($title);
3626: $linktext = &mt($linktext);
3627: return qq{<a href="$link" title="$title" $target>$linktext</a>};
3628: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
3629:
3630: }
3631:
3632: # ===================================================== Display a student photo
3633:
3634:
3635: sub student_image_tag {
3636: my ($domain,$user)=@_;
3637: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
3638: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
3639: return '<img src="'.$imgsrc.'" align="right" />';
3640: } else {
3641: return '';
3642: }
3643: }
3644:
3645: =pod
3646:
3647: =back
3648:
3649: =head1 Access .tab File Data
3650:
3651: =over 4
3652:
3653: =item * &languageids()
3654:
3655: returns list of all language ids
3656:
3657: =cut
3658:
3659: sub languageids {
3660: return sort(keys(%language));
3661: }
3662:
3663: =pod
3664:
3665: =item * &languagedescription()
3666:
3667: returns description of a specified language id
3668:
3669: =cut
3670:
3671: sub languagedescription {
3672: my $code=shift;
3673: return ($supported_language{$code}?'* ':'').
3674: $language{$code}.
3675: ($supported_language{$code}?' ('.&mt('interface available').')':'');
3676: }
3677:
3678: =pod
3679:
3680: =item * &plainlanguagedescription
3681:
3682: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
3683: and the language character encoding (e.g. ISO) separated by a ' - ' string.
3684:
3685: =cut
3686:
3687: sub plainlanguagedescription {
3688: my $code=shift;
3689: return $language{$code};
3690: }
3691:
3692: =pod
3693:
3694: =item * &supportedlanguagecode
3695:
3696: Returns the supported language code (e.g. sptutf maps to pt) given a language
3697: code.
3698:
3699: =cut
3700:
3701: sub supportedlanguagecode {
3702: my $code=shift;
3703: return $supported_language{$code};
3704: }
3705:
3706: =pod
3707:
3708: =item * &latexlanguage()
3709:
3710: Given a language key code returns the correspondnig language to use
3711: to select the correct hyphenation on LaTeX printouts. This is undef if there
3712: is no supported hyphenation for the language code.
3713:
3714: =cut
3715:
3716: sub latexlanguage {
3717: my $code = shift;
3718: return $latex_language{$code};
3719: }
3720:
3721: =pod
3722:
3723: =item * &latexhyphenation()
3724:
3725: Same as above but what's supplied is the language as it might be stored
3726: in the metadata.
3727:
3728: =cut
3729:
3730: sub latexhyphenation {
3731: my $key = shift;
3732: return $latex_language_bykey{$key};
3733: }
3734:
3735: =pod
3736:
3737: =item * ©rightids()
3738:
3739: returns list of all copyrights
3740:
3741: =cut
3742:
3743: sub copyrightids {
3744: return sort(keys(%cprtag));
3745: }
3746:
3747: =pod
3748:
3749: =item * ©rightdescription()
3750:
3751: returns description of a specified copyright id
3752:
3753: =cut
3754:
3755: sub copyrightdescription {
3756: return &mt($cprtag{shift(@_)});
3757: }
3758:
3759: =pod
3760:
3761: =item * &source_copyrightids()
3762:
3763: returns list of all source copyrights
3764:
3765: =cut
3766:
3767: sub source_copyrightids {
3768: return sort(keys(%scprtag));
3769: }
3770:
3771: =pod
3772:
3773: =item * &source_copyrightdescription()
3774:
3775: returns description of a specified source copyright id
3776:
3777: =cut
3778:
3779: sub source_copyrightdescription {
3780: return &mt($scprtag{shift(@_)});
3781: }
3782:
3783: =pod
3784:
3785: =item * &filecategories()
3786:
3787: returns list of all file categories
3788:
3789: =cut
3790:
3791: sub filecategories {
3792: return sort(keys(%category_extensions));
3793: }
3794:
3795: =pod
3796:
3797: =item * &filecategorytypes()
3798:
3799: returns list of file types belonging to a given file
3800: category
3801:
3802: =cut
3803:
3804: sub filecategorytypes {
3805: my ($cat) = @_;
3806: return @{$category_extensions{lc($cat)}};
3807: }
3808:
3809: =pod
3810:
3811: =item * &fileembstyle()
3812:
3813: returns embedding style for a specified file type
3814:
3815: =cut
3816:
3817: sub fileembstyle {
3818: return $fe{lc(shift(@_))};
3819: }
3820:
3821: sub filemimetype {
3822: return $fm{lc(shift(@_))};
3823: }
3824:
3825:
3826: sub filecategoryselect {
3827: my ($name,$value)=@_;
3828: return &select_form($value,$name,
3829: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
3830: }
3831:
3832: =pod
3833:
3834: =item * &filedescription()
3835:
3836: returns description for a specified file type
3837:
3838: =cut
3839:
3840: sub filedescription {
3841: my $file_description = $fd{lc(shift())};
3842: $file_description =~ s:([\[\]]):~$1:g;
3843: return &mt($file_description);
3844: }
3845:
3846: =pod
3847:
3848: =item * &filedescriptionex()
3849:
3850: returns description for a specified file type with
3851: extra formatting
3852:
3853: =cut
3854:
3855: sub filedescriptionex {
3856: my $ex=shift;
3857: my $file_description = $fd{lc($ex)};
3858: $file_description =~ s:([\[\]]):~$1:g;
3859: return '.'.$ex.' '.&mt($file_description);
3860: }
3861:
3862: # End of .tab access
3863: =pod
3864:
3865: =back
3866:
3867: =cut
3868:
3869: # ------------------------------------------------------------------ File Types
3870: sub fileextensions {
3871: return sort(keys(%fe));
3872: }
3873:
3874: # ----------------------------------------------------------- Display Languages
3875: # returns a hash with all desired display languages
3876: #
3877:
3878: sub display_languages {
3879: my %languages=();
3880: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
3881: $languages{$lang}=1;
3882: }
3883: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3884: if ($env{'form.displaylanguage'}) {
3885: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3886: $languages{$lang}=1;
3887: }
3888: }
3889: return %languages;
3890: }
3891:
3892: sub languages {
3893: my ($possible_langs) = @_;
3894: my @preferred_langs = &Apache::lonlocal::preferred_languages();
3895: if (!ref($possible_langs)) {
3896: if( wantarray ) {
3897: return @preferred_langs;
3898: } else {
3899: return $preferred_langs[0];
3900: }
3901: }
3902: my %possibilities = map { $_ => 1 } (@$possible_langs);
3903: my @preferred_possibilities;
3904: foreach my $preferred_lang (@preferred_langs) {
3905: if (exists($possibilities{$preferred_lang})) {
3906: push(@preferred_possibilities, $preferred_lang);
3907: }
3908: }
3909: if( wantarray ) {
3910: return @preferred_possibilities;
3911: }
3912: return $preferred_possibilities[0];
3913: }
3914:
3915: sub user_lang {
3916: my ($touname,$toudom,$fromcid) = @_;
3917: my @userlangs;
3918: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
3919: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
3920: $env{'course.'.$fromcid.'.languages'}));
3921: } else {
3922: my %langhash = &getlangs($touname,$toudom);
3923: if ($langhash{'languages'} ne '') {
3924: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
3925: } else {
3926: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
3927: if ($domdefs{'lang_def'} ne '') {
3928: @userlangs = ($domdefs{'lang_def'});
3929: }
3930: }
3931: }
3932: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
3933: my $user_lh = Apache::localize->get_handle(@languages);
3934: return $user_lh;
3935: }
3936:
3937:
3938: ###############################################################
3939: ## Student Answer Attempts ##
3940: ###############################################################
3941:
3942: =pod
3943:
3944: =head1 Alternate Problem Views
3945:
3946: =over 4
3947:
3948: =item * &get_previous_attempt($symb, $username, $domain, $course,
3949: $getattempt, $regexp, $gradesub, $usec, $identifier)
3950:
3951: Return string with previous attempt on problem. Arguments:
3952:
3953: =over 4
3954:
3955: =item * $symb: Problem, including path
3956:
3957: =item * $username: username of the desired student
3958:
3959: =item * $domain: domain of the desired student
3960:
3961: =item * $course: Course ID
3962:
3963: =item * $getattempt: Leave blank for all attempts, otherwise put
3964: something
3965:
3966: =item * $regexp: if string matches this regexp, the string will be
3967: sent to $gradesub
3968:
3969: =item * $gradesub: routine that processes the string if it matches $regexp
3970:
3971: =item * $usec: section of the desired student
3972:
3973: =item * $identifier: counter for student (multiple students one problem) or
3974: problem (one student; whole sequence).
3975:
3976: =back
3977:
3978: The output string is a table containing all desired attempts, if any.
3979:
3980: =cut
3981:
3982: sub get_previous_attempt {
3983: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
3984: my $prevattempts='';
3985: no strict 'refs';
3986: if ($symb) {
3987: my (%returnhash)=
3988: &Apache::lonnet::restore($symb,$course,$domain,$username);
3989: if ($returnhash{'version'}) {
3990: my %lasthash=();
3991: my $version;
3992: for ($version=1;$version<=$returnhash{'version'};$version++) {
3993: foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
3994: if ($key =~ /\.rawrndseed$/) {
3995: my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
3996: $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
3997: } else {
3998: $lasthash{$key}=$returnhash{$version.':'.$key};
3999: }
4000: }
4001: }
4002: $prevattempts=&start_data_table().&start_data_table_header_row();
4003: $prevattempts.='<th>'.&mt('History').'</th>';
4004: my (%typeparts,%lasthidden,%regraded,%hidestatus);
4005: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
4006: foreach my $key (sort(keys(%lasthash))) {
4007: my ($ign,@parts) = split(/\./,$key);
4008: if ($#parts > 0) {
4009: my $data=$parts[-1];
4010: next if ($data eq 'foilorder');
4011: pop(@parts);
4012: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
4013: if ($data eq 'type') {
4014: unless ($showsurv) {
4015: my $id = join(',',@parts);
4016: $typeparts{$ign.'.'.$id} = $lasthash{$key};
4017: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
4018: $lasthidden{$ign.'.'.$id} = 1;
4019: }
4020: }
4021: if ($identifier ne '') {
4022: my $id = join(',',@parts);
4023: if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
4024: $domain,$username,$usec,undef,$course) =~ /^no/) {
4025: $hidestatus{$ign.'.'.$id} = 1;
4026: }
4027: }
4028: } elsif ($data eq 'regrader') {
4029: if (($identifier ne '') && (@parts)) {
4030: my $id = join(',',@parts);
4031: $regraded{$ign.'.'.$id} = 1;
4032: }
4033: }
4034: } else {
4035: if ($#parts == 0) {
4036: $prevattempts.='<th>'.$parts[0].'</th>';
4037: } else {
4038: $prevattempts.='<th>'.$ign.'</th>';
4039: }
4040: }
4041: }
4042: $prevattempts.=&end_data_table_header_row();
4043: if ($getattempt eq '') {
4044: my (%solved,%resets,%probstatus);
4045: if (($identifier ne '') && (keys(%regraded) > 0)) {
4046: for ($version=1;$version<=$returnhash{'version'};$version++) {
4047: foreach my $id (keys(%regraded)) {
4048: if (($returnhash{$version.':'.$id.'.regrader'}) &&
4049: ($returnhash{$version.':'.$id.'.tries'} eq '') &&
4050: ($returnhash{$version.':'.$id.'.award'} eq '')) {
4051: push(@{$resets{$id}},$version);
4052: }
4053: }
4054: }
4055: }
4056: for ($version=1;$version<=$returnhash{'version'};$version++) {
4057: my (@hidden,@unsolved);
4058: if (%typeparts) {
4059: foreach my $id (keys(%typeparts)) {
4060: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
4061: ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
4062: push(@hidden,$id);
4063: } elsif ($identifier ne '') {
4064: unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
4065: ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
4066: ($hidestatus{$id})) {
4067: next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
4068: if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
4069: push(@{$solved{$id}},$version);
4070: } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
4071: (ref($solved{$id}) eq 'ARRAY')) {
4072: my $skip;
4073: if (ref($resets{$id}) eq 'ARRAY') {
4074: foreach my $reset (@{$resets{$id}}) {
4075: if ($reset > $solved{$id}[-1]) {
4076: $skip=1;
4077: last;
4078: }
4079: }
4080: }
4081: unless ($skip) {
4082: my ($ign,$partslist) = split(/\./,$id,2);
4083: push(@unsolved,$partslist);
4084: }
4085: }
4086: }
4087: }
4088: }
4089: }
4090: $prevattempts.=&start_data_table_row().
4091: '<td>'.&mt('Transaction [_1]',$version);
4092: if (@unsolved) {
4093: $prevattempts .= '<span class="LC_nobreak"><label>'.
4094: '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
4095: &mt('Hide').'</label></span>';
4096: }
4097: $prevattempts .= '</td>';
4098: if (@hidden) {
4099: foreach my $key (sort(keys(%lasthash))) {
4100: next if ($key =~ /\.foilorder$/);
4101: my $hide;
4102: foreach my $id (@hidden) {
4103: if ($key =~ /^\Q$id\E/) {
4104: $hide = 1;
4105: last;
4106: }
4107: }
4108: if ($hide) {
4109: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4110: if (($data eq 'award') || ($data eq 'awarddetail')) {
4111: my $value = &format_previous_attempt_value($key,
4112: $returnhash{$version.':'.$key});
4113: $prevattempts.='<td>'.$value.' </td>';
4114: } else {
4115: $prevattempts.='<td> </td>';
4116: }
4117: } else {
4118: if ($key =~ /\./) {
4119: my $value = $returnhash{$version.':'.$key};
4120: if ($key =~ /\.rndseed$/) {
4121: my ($id) = ($key =~ /^(.+)\.rndseed$/);
4122: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4123: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4124: }
4125: }
4126: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4127: ' </td>';
4128: } else {
4129: $prevattempts.='<td> </td>';
4130: }
4131: }
4132: }
4133: } else {
4134: foreach my $key (sort(keys(%lasthash))) {
4135: next if ($key =~ /\.foilorder$/);
4136: my $value = $returnhash{$version.':'.$key};
4137: if ($key =~ /\.rndseed$/) {
4138: my ($id) = ($key =~ /^(.+)\.rndseed$/);
4139: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4140: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4141: }
4142: }
4143: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4144: ' </td>';
4145: }
4146: }
4147: $prevattempts.=&end_data_table_row();
4148: }
4149: }
4150: my @currhidden = keys(%lasthidden);
4151: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
4152: foreach my $key (sort(keys(%lasthash))) {
4153: next if ($key =~ /\.foilorder$/);
4154: if (%typeparts) {
4155: my $hidden;
4156: foreach my $id (@currhidden) {
4157: if ($key =~ /^\Q$id\E/) {
4158: $hidden = 1;
4159: last;
4160: }
4161: }
4162: if ($hidden) {
4163: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4164: if (($data eq 'award') || ($data eq 'awarddetail')) {
4165: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4166: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4167: $value = &$gradesub($value);
4168: }
4169: $prevattempts.='<td>'.$value.' </td>';
4170: } else {
4171: $prevattempts.='<td> </td>';
4172: }
4173: } else {
4174: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4175: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4176: $value = &$gradesub($value);
4177: }
4178: $prevattempts.='<td>'.$value.' </td>';
4179: }
4180: } else {
4181: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4182: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4183: $value = &$gradesub($value);
4184: }
4185: $prevattempts.='<td>'.$value.' </td>';
4186: }
4187: }
4188: $prevattempts.= &end_data_table_row().&end_data_table();
4189: } else {
4190: $prevattempts=
4191: &start_data_table().&start_data_table_row().
4192: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
4193: &end_data_table_row().&end_data_table();
4194: }
4195: } else {
4196: $prevattempts=
4197: &start_data_table().&start_data_table_row().
4198: '<td>'.&mt('No data.').'</td>'.
4199: &end_data_table_row().&end_data_table();
4200: }
4201: }
4202:
4203: sub format_previous_attempt_value {
4204: my ($key,$value) = @_;
4205: if (($key =~ /timestamp/) || ($key=~/duedate/)) {
4206: $value = &Apache::lonlocal::locallocaltime($value);
4207: } elsif (ref($value) eq 'ARRAY') {
4208: $value = '('.join(', ', @{ $value }).')';
4209: } elsif ($key =~ /answerstring$/) {
4210: my %answers = &Apache::lonnet::str2hash($value);
4211: my @anskeys = sort(keys(%answers));
4212: if (@anskeys == 1) {
4213: my $answer = $answers{$anskeys[0]};
4214: if ($answer =~ m{\0}) {
4215: $answer =~ s{\0}{,}g;
4216: }
4217: my $tag_internal_answer_name = 'INTERNAL';
4218: if ($anskeys[0] eq $tag_internal_answer_name) {
4219: $value = $answer;
4220: } else {
4221: $value = $anskeys[0].'='.$answer;
4222: }
4223: } else {
4224: foreach my $ans (@anskeys) {
4225: my $answer = $answers{$ans};
4226: if ($answer =~ m{\0}) {
4227: $answer =~ s{\0}{,}g;
4228: }
4229: $value .= $ans.'='.$answer.'<br />';;
4230: }
4231: }
4232: } else {
4233: $value = &unescape($value);
4234: }
4235: return $value;
4236: }
4237:
4238:
4239: sub relative_to_absolute {
4240: my ($url,$output)=@_;
4241: my $parser=HTML::TokeParser->new(\$output);
4242: my $token;
4243: my $thisdir=$url;
4244: my @rlinks=();
4245: while ($token=$parser->get_token) {
4246: if ($token->[0] eq 'S') {
4247: if ($token->[1] eq 'a') {
4248: if ($token->[2]->{'href'}) {
4249: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
4250: }
4251: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
4252: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
4253: } elsif ($token->[1] eq 'base') {
4254: $thisdir=$token->[2]->{'href'};
4255: }
4256: }
4257: }
4258: $thisdir=~s-/[^/]*$--;
4259: foreach my $link (@rlinks) {
4260: unless (($link=~/^https?\:\/\//i) ||
4261: ($link=~/^\//) ||
4262: ($link=~/^javascript:/i) ||
4263: ($link=~/^mailto:/i) ||
4264: ($link=~/^\#/)) {
4265: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
4266: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
4267: }
4268: }
4269: # -------------------------------------------------- Deal with Applet codebases
4270: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
4271: return $output;
4272: }
4273:
4274: =pod
4275:
4276: =item * &get_student_view()
4277:
4278: show a snapshot of what student was looking at
4279:
4280: =cut
4281:
4282: sub get_student_view {
4283: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
4284: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4285: my (%form);
4286: my @elements=('symb','courseid','domain','username');
4287: foreach my $element (@elements) {
4288: $form{'grade_'.$element}=eval '$'.$element #'
4289: }
4290: if (defined($moreenv)) {
4291: %form=(%form,%{$moreenv});
4292: }
4293: if (defined($target)) { $form{'grade_target'} = $target; }
4294: $feedurl=&Apache::lonnet::clutter($feedurl);
4295: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
4296: $userview=~s/\<body[^\>]*\>//gi;
4297: $userview=~s/\<\/body\>//gi;
4298: $userview=~s/\<html\>//gi;
4299: $userview=~s/\<\/html\>//gi;
4300: $userview=~s/\<head\>//gi;
4301: $userview=~s/\<\/head\>//gi;
4302: $userview=~s/action\s*\=/would_be_action\=/gi;
4303: $userview=&relative_to_absolute($feedurl,$userview);
4304: if (wantarray) {
4305: return ($userview,$response);
4306: } else {
4307: return $userview;
4308: }
4309: }
4310:
4311: sub get_student_view_with_retries {
4312: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
4313:
4314: my $ok = 0; # True if we got a good response.
4315: my $content;
4316: my $response;
4317:
4318: # Try to get the student_view done. within the retries count:
4319:
4320: do {
4321: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
4322: $ok = $response->is_success;
4323: if (!$ok) {
4324: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
4325: }
4326: $retries--;
4327: } while (!$ok && ($retries > 0));
4328:
4329: if (!$ok) {
4330: $content = ''; # On error return an empty content.
4331: }
4332: if (wantarray) {
4333: return ($content, $response);
4334: } else {
4335: return $content;
4336: }
4337: }
4338:
4339: =pod
4340:
4341: =item * &get_student_answers()
4342:
4343: show a snapshot of how student was answering problem
4344:
4345: =cut
4346:
4347: sub get_student_answers {
4348: my ($symb,$username,$domain,$courseid,%form) = @_;
4349: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4350: my (%moreenv);
4351: my @elements=('symb','courseid','domain','username');
4352: foreach my $element (@elements) {
4353: $moreenv{'grade_'.$element}=eval '$'.$element #'
4354: }
4355: $moreenv{'grade_target'}='answer';
4356: %moreenv=(%form,%moreenv);
4357: $feedurl = &Apache::lonnet::clutter($feedurl);
4358: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
4359: return $userview;
4360: }
4361:
4362: =pod
4363:
4364: =item * &submlink()
4365:
4366: Inputs: $text $uname $udom $symb $target
4367:
4368: Returns: A link to grades.pm such as to see the SUBM view of a student
4369:
4370: =cut
4371:
4372: ###############################################
4373: sub submlink {
4374: my ($text,$uname,$udom,$symb,$target)=@_;
4375: if (!($uname && $udom)) {
4376: (my $cursymb, my $courseid,$udom,$uname)=
4377: &Apache::lonnet::whichuser($symb);
4378: if (!$symb) { $symb=$cursymb; }
4379: }
4380: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4381: $symb=&escape($symb);
4382: if ($target) { $target=" target=\"$target\""; }
4383: return
4384: '<a href="/adm/grades?command=submission'.
4385: '&symb='.$symb.
4386: '&student='.$uname.
4387: '&userdom='.$udom.'"'.
4388: $target.'>'.$text.'</a>';
4389: }
4390: ##############################################
4391:
4392: =pod
4393:
4394: =item * &pgrdlink()
4395:
4396: Inputs: $text $uname $udom $symb $target
4397:
4398: Returns: A link to grades.pm such as to see the PGRD view of a student
4399:
4400: =cut
4401:
4402: ###############################################
4403: sub pgrdlink {
4404: my $link=&submlink(@_);
4405: $link=~s/(&command=submission)/$1&showgrading=yes/;
4406: return $link;
4407: }
4408: ##############################################
4409:
4410: =pod
4411:
4412: =item * &pprmlink()
4413:
4414: Inputs: $text $uname $udom $symb $target
4415:
4416: Returns: A link to parmset.pm such as to see the PPRM view of a
4417: student and a specific resource
4418:
4419: =cut
4420:
4421: ###############################################
4422: sub pprmlink {
4423: my ($text,$uname,$udom,$symb,$target)=@_;
4424: if (!($uname && $udom)) {
4425: (my $cursymb, my $courseid,$udom,$uname)=
4426: &Apache::lonnet::whichuser($symb);
4427: if (!$symb) { $symb=$cursymb; }
4428: }
4429: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4430: $symb=&escape($symb);
4431: if ($target) { $target="target=\"$target\""; }
4432: return '<a href="/adm/parmset?command=set&'.
4433: 'symb='.$symb.'&uname='.$uname.
4434: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
4435: }
4436: ##############################################
4437:
4438: =pod
4439:
4440: =back
4441:
4442: =cut
4443:
4444: ###############################################
4445:
4446:
4447: sub timehash {
4448: my ($thistime) = @_;
4449: my $timezone = &Apache::lonlocal::gettimezone();
4450: my $dt = DateTime->from_epoch(epoch => $thistime)
4451: ->set_time_zone($timezone);
4452: my $wday = $dt->day_of_week();
4453: if ($wday == 7) { $wday = 0; }
4454: return ( 'second' => $dt->second(),
4455: 'minute' => $dt->minute(),
4456: 'hour' => $dt->hour(),
4457: 'day' => $dt->day_of_month(),
4458: 'month' => $dt->month(),
4459: 'year' => $dt->year(),
4460: 'weekday' => $wday,
4461: 'dayyear' => $dt->day_of_year(),
4462: 'dlsav' => $dt->is_dst() );
4463: }
4464:
4465: sub utc_string {
4466: my ($date)=@_;
4467: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
4468: }
4469:
4470: sub maketime {
4471: my %th=@_;
4472: my ($epoch_time,$timezone,$dt);
4473: $timezone = &Apache::lonlocal::gettimezone();
4474: eval {
4475: $dt = DateTime->new( year => $th{'year'},
4476: month => $th{'month'},
4477: day => $th{'day'},
4478: hour => $th{'hour'},
4479: minute => $th{'minute'},
4480: second => $th{'second'},
4481: time_zone => $timezone,
4482: );
4483: };
4484: if (!$@) {
4485: $epoch_time = $dt->epoch;
4486: if ($epoch_time) {
4487: return $epoch_time;
4488: }
4489: }
4490: return POSIX::mktime(
4491: ($th{'seconds'},$th{'minutes'},$th{'hours'},
4492: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
4493: }
4494:
4495: #########################################
4496:
4497: sub findallcourses {
4498: my ($roles,$uname,$udom) = @_;
4499: my %roles;
4500: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
4501: my %courses;
4502: my $now=time;
4503: if (!defined($uname)) {
4504: $uname = $env{'user.name'};
4505: }
4506: if (!defined($udom)) {
4507: $udom = $env{'user.domain'};
4508: }
4509: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
4510: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
4511: if (!%roles) {
4512: %roles = (
4513: cc => 1,
4514: co => 1,
4515: in => 1,
4516: ep => 1,
4517: ta => 1,
4518: cr => 1,
4519: st => 1,
4520: );
4521: }
4522: foreach my $entry (keys(%roleshash)) {
4523: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
4524: if ($trole =~ /^cr/) {
4525: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
4526: } else {
4527: next if (!exists($roles{$trole}));
4528: }
4529: if ($tend) {
4530: next if ($tend < $now);
4531: }
4532: if ($tstart) {
4533: next if ($tstart > $now);
4534: }
4535: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
4536: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
4537: my $value = $trole.'/'.$cdom.'/';
4538: if ($secpart eq '') {
4539: ($cnum,$role) = split(/_/,$cnumpart);
4540: $sec = 'none';
4541: $value .= $cnum.'/';
4542: } else {
4543: $cnum = $cnumpart;
4544: ($sec,$role) = split(/_/,$secpart);
4545: $value .= $cnum.'/'.$sec;
4546: }
4547: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4548: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4549: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4550: }
4551: } else {
4552: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4553: }
4554: }
4555: } else {
4556: foreach my $key (keys(%env)) {
4557: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
4558: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
4559: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
4560: next if ($role eq 'ca' || $role eq 'aa');
4561: next if (%roles && !exists($roles{$role}));
4562: my ($starttime,$endtime)=split(/\./,$env{$key});
4563: my $active=1;
4564: if ($starttime) {
4565: if ($now<$starttime) { $active=0; }
4566: }
4567: if ($endtime) {
4568: if ($now>$endtime) { $active=0; }
4569: }
4570: if ($active) {
4571: my $value = $role.'/'.$cdom.'/'.$cnum.'/';
4572: if ($sec eq '') {
4573: $sec = 'none';
4574: } else {
4575: $value .= $sec;
4576: }
4577: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4578: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4579: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4580: }
4581: } else {
4582: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4583: }
4584: }
4585: }
4586: }
4587: }
4588: return %courses;
4589: }
4590:
4591: ###############################################
4592:
4593: sub blockcheck {
4594: my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
4595:
4596: if (defined($udom) && defined($uname)) {
4597: # If uname and udom are for a course, check for blocks in the course.
4598: if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
4599: my ($startblock,$endblock,$triggerblock) =
4600: &get_blocks($setters,$activity,$udom,$uname,$url);
4601: return ($startblock,$endblock,$triggerblock);
4602: }
4603: } else {
4604: $udom = $env{'user.domain'};
4605: $uname = $env{'user.name'};
4606: }
4607:
4608: my $startblock = 0;
4609: my $endblock = 0;
4610: my $triggerblock = '';
4611: my %live_courses = &findallcourses(undef,$uname,$udom);
4612:
4613: # If uname is for a user, and activity is course-specific, i.e.,
4614: # boards, chat or groups, check for blocking in current course only.
4615:
4616: if (($activity eq 'boards' || $activity eq 'chat' ||
4617: $activity eq 'groups' || $activity eq 'printout') &&
4618: ($env{'request.course.id'})) {
4619: foreach my $key (keys(%live_courses)) {
4620: if ($key ne $env{'request.course.id'}) {
4621: delete($live_courses{$key});
4622: }
4623: }
4624: }
4625:
4626: my $otheruser = 0;
4627: my %own_courses;
4628: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
4629: # Resource belongs to user other than current user.
4630: $otheruser = 1;
4631: # Gather courses for current user
4632: %own_courses =
4633: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
4634: }
4635:
4636: # Gather active course roles - course coordinator, instructor,
4637: # exam proctor, ta, student, or custom role.
4638:
4639: foreach my $course (keys(%live_courses)) {
4640: my ($cdom,$cnum);
4641: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
4642: $cdom = $env{'course.'.$course.'.domain'};
4643: $cnum = $env{'course.'.$course.'.num'};
4644: } else {
4645: ($cdom,$cnum) = split(/_/,$course);
4646: }
4647: my $no_ownblock = 0;
4648: my $no_userblock = 0;
4649: if ($otheruser && $activity ne 'com') {
4650: # Check if current user has 'evb' priv for this
4651: if (defined($own_courses{$course})) {
4652: foreach my $sec (keys(%{$own_courses{$course}})) {
4653: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4654: if ($sec ne 'none') {
4655: $checkrole .= '/'.$sec;
4656: }
4657: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4658: $no_ownblock = 1;
4659: last;
4660: }
4661: }
4662: }
4663: # if they have 'evb' priv and are currently not playing student
4664: next if (($no_ownblock) &&
4665: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
4666: }
4667: foreach my $sec (keys(%{$live_courses{$course}})) {
4668: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4669: if ($sec ne 'none') {
4670: $checkrole .= '/'.$sec;
4671: }
4672: if ($otheruser) {
4673: # Resource belongs to user other than current user.
4674: # Assemble privs for that user, and check for 'evb' priv.
4675: my (%allroles,%userroles);
4676: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
4677: foreach my $entry (@{$live_courses{$course}{$sec}}) {
4678: my ($trole,$tdom,$tnum,$tsec);
4679: if ($entry =~ /^cr/) {
4680: ($trole,$tdom,$tnum,$tsec) =
4681: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
4682: } else {
4683: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
4684: }
4685: my ($spec,$area,$trest);
4686: $area = '/'.$tdom.'/'.$tnum;
4687: $trest = $tnum;
4688: if ($tsec ne '') {
4689: $area .= '/'.$tsec;
4690: $trest .= '/'.$tsec;
4691: }
4692: $spec = $trole.'.'.$area;
4693: if ($trole =~ /^cr/) {
4694: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
4695: $tdom,$spec,$trest,$area);
4696: } else {
4697: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
4698: $tdom,$spec,$trest,$area);
4699: }
4700: }
4701: my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
4702: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
4703: if ($1) {
4704: $no_userblock = 1;
4705: last;
4706: }
4707: }
4708: }
4709: } else {
4710: # Resource belongs to current user
4711: # Check for 'evb' priv via lonnet::allowed().
4712: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4713: $no_ownblock = 1;
4714: last;
4715: }
4716: }
4717: }
4718: # if they have the evb priv and are currently not playing student
4719: next if (($no_ownblock) &&
4720: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
4721: next if ($no_userblock);
4722:
4723: # Retrieve blocking times and identity of locker for course
4724: # of specified user, unless user has 'evb' privilege.
4725:
4726: my ($start,$end,$trigger) =
4727: &get_blocks($setters,$activity,$cdom,$cnum,$url);
4728: if (($start != 0) &&
4729: (($startblock == 0) || ($startblock > $start))) {
4730: $startblock = $start;
4731: if ($trigger ne '') {
4732: $triggerblock = $trigger;
4733: }
4734: }
4735: if (($end != 0) &&
4736: (($endblock == 0) || ($endblock < $end))) {
4737: $endblock = $end;
4738: if ($trigger ne '') {
4739: $triggerblock = $trigger;
4740: }
4741: }
4742: }
4743: return ($startblock,$endblock,$triggerblock);
4744: }
4745:
4746: sub get_blocks {
4747: my ($setters,$activity,$cdom,$cnum,$url) = @_;
4748: my $startblock = 0;
4749: my $endblock = 0;
4750: my $triggerblock = '';
4751: my $course = $cdom.'_'.$cnum;
4752: $setters->{$course} = {};
4753: $setters->{$course}{'staff'} = [];
4754: $setters->{$course}{'times'} = [];
4755: $setters->{$course}{'triggers'} = [];
4756: my (@blockers,%triggered);
4757: my $now = time;
4758: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
4759: if ($activity eq 'docs') {
4760: @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
4761: foreach my $block (@blockers) {
4762: if ($block =~ /^firstaccess____(.+)$/) {
4763: my $item = $1;
4764: my $type = 'map';
4765: my $timersymb = $item;
4766: if ($item eq 'course') {
4767: $type = 'course';
4768: } elsif ($item =~ /___\d+___/) {
4769: $type = 'resource';
4770: } else {
4771: $timersymb = &Apache::lonnet::symbread($item);
4772: }
4773: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4774: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4775: $triggered{$block} = {
4776: start => $start,
4777: end => $end,
4778: type => $type,
4779: };
4780: }
4781: }
4782: } else {
4783: foreach my $block (keys(%commblocks)) {
4784: if ($block =~ m/^(\d+)____(\d+)$/) {
4785: my ($start,$end) = ($1,$2);
4786: if ($start <= time && $end >= time) {
4787: if (ref($commblocks{$block}) eq 'HASH') {
4788: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
4789: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
4790: unless(grep(/^\Q$block\E$/,@blockers)) {
4791: push(@blockers,$block);
4792: }
4793: }
4794: }
4795: }
4796: }
4797: } elsif ($block =~ /^firstaccess____(.+)$/) {
4798: my $item = $1;
4799: my $timersymb = $item;
4800: my $type = 'map';
4801: if ($item eq 'course') {
4802: $type = 'course';
4803: } elsif ($item =~ /___\d+___/) {
4804: $type = 'resource';
4805: } else {
4806: $timersymb = &Apache::lonnet::symbread($item);
4807: }
4808: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4809: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4810: if ($start && $end) {
4811: if (($start <= time) && ($end >= time)) {
4812: unless (grep(/^\Q$block\E$/,@blockers)) {
4813: push(@blockers,$block);
4814: $triggered{$block} = {
4815: start => $start,
4816: end => $end,
4817: type => $type,
4818: };
4819: }
4820: }
4821: }
4822: }
4823: }
4824: }
4825: foreach my $blocker (@blockers) {
4826: my ($staff_name,$staff_dom,$title,$blocks) =
4827: &parse_block_record($commblocks{$blocker});
4828: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
4829: my ($start,$end,$triggertype);
4830: if ($blocker =~ m/^(\d+)____(\d+)$/) {
4831: ($start,$end) = ($1,$2);
4832: } elsif (ref($triggered{$blocker}) eq 'HASH') {
4833: $start = $triggered{$blocker}{'start'};
4834: $end = $triggered{$blocker}{'end'};
4835: $triggertype = $triggered{$blocker}{'type'};
4836: }
4837: if ($start) {
4838: push(@{$$setters{$course}{'times'}}, [$start,$end]);
4839: if ($triggertype) {
4840: push(@{$$setters{$course}{'triggers'}},$triggertype);
4841: } else {
4842: push(@{$$setters{$course}{'triggers'}},0);
4843: }
4844: if ( ($startblock == 0) || ($startblock > $start) ) {
4845: $startblock = $start;
4846: if ($triggertype) {
4847: $triggerblock = $blocker;
4848: }
4849: }
4850: if ( ($endblock == 0) || ($endblock < $end) ) {
4851: $endblock = $end;
4852: if ($triggertype) {
4853: $triggerblock = $blocker;
4854: }
4855: }
4856: }
4857: }
4858: return ($startblock,$endblock,$triggerblock);
4859: }
4860:
4861: sub parse_block_record {
4862: my ($record) = @_;
4863: my ($setuname,$setudom,$title,$blocks);
4864: if (ref($record) eq 'HASH') {
4865: ($setuname,$setudom) = split(/:/,$record->{'setter'});
4866: $title = &unescape($record->{'event'});
4867: $blocks = $record->{'blocks'};
4868: } else {
4869: my @data = split(/:/,$record,3);
4870: if (scalar(@data) eq 2) {
4871: $title = $data[1];
4872: ($setuname,$setudom) = split(/@/,$data[0]);
4873: } else {
4874: ($setuname,$setudom,$title) = @data;
4875: }
4876: $blocks = { 'com' => 'on' };
4877: }
4878: return ($setuname,$setudom,$title,$blocks);
4879: }
4880:
4881: sub blocking_status {
4882: my ($activity,$uname,$udom,$url,$is_course) = @_;
4883: my %setters;
4884:
4885: # check for active blocking
4886: my ($startblock,$endblock,$triggerblock) =
4887: &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
4888: my $blocked = 0;
4889: if ($startblock && $endblock) {
4890: $blocked = 1;
4891: }
4892:
4893: # caller just wants to know whether a block is active
4894: if (!wantarray) { return $blocked; }
4895:
4896: # build a link to a popup window containing the details
4897: my $querystring = "?activity=$activity";
4898: # $uname and $udom decide whose portfolio the user is trying to look at
4899: if (($activity eq 'port') || ($activity eq 'passwd')) {
4900: $querystring .= "&udom=$udom" if ($udom =~ /^$match_domain$/);
4901: $querystring .= "&uname=$uname" if ($uname =~ /^$match_username$/);
4902: } elsif ($activity eq 'docs') {
4903: $querystring .= '&url='.&HTML::Entities::encode($url,'&"');
4904: }
4905:
4906: my $output .= <<'END_MYBLOCK';
4907: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
4908: var options = "width=" + w + ",height=" + h + ",";
4909: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
4910: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
4911: var newWin = window.open(url, wdwName, options);
4912: newWin.focus();
4913: }
4914: END_MYBLOCK
4915:
4916: $output = Apache::lonhtmlcommon::scripttag($output);
4917:
4918: my $popupUrl = "/adm/blockingstatus/$querystring";
4919: my $text = &mt('Communication Blocked');
4920: my $class = 'LC_comblock';
4921: if ($activity eq 'docs') {
4922: $text = &mt('Content Access Blocked');
4923: $class = '';
4924: } elsif ($activity eq 'printout') {
4925: $text = &mt('Printing Blocked');
4926: } elsif ($activity eq 'passwd') {
4927: $text = &mt('Password Changing Blocked');
4928: }
4929: $output .= <<"END_BLOCK";
4930: <div class='$class'>
4931: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4932: title='$text'>
4933: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
4934: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4935: title='$text'>$text</a>
4936: </div>
4937:
4938: END_BLOCK
4939:
4940: return ($blocked, $output);
4941: }
4942:
4943: ###############################################
4944:
4945: sub check_ip_acc {
4946: my ($acc,$clientip)=@_;
4947: &Apache::lonxml::debug("acc is $acc");
4948: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
4949: return 1;
4950: }
4951: my $allowed=0;
4952: my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
4953:
4954: my $name;
4955: foreach my $pattern (split(',',$acc)) {
4956: $pattern =~ s/^\s*//;
4957: $pattern =~ s/\s*$//;
4958: if ($pattern =~ /\*$/) {
4959: #35.8.*
4960: $pattern=~s/\*//;
4961: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4962: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
4963: #35.8.3.[34-56]
4964: my $low=$2;
4965: my $high=$3;
4966: $pattern=$1;
4967: if ($ip =~ /^\Q$pattern\E/) {
4968: my $last=(split(/\./,$ip))[3];
4969: if ($last <=$high && $last >=$low) { $allowed=1; }
4970: }
4971: } elsif ($pattern =~ /^\*/) {
4972: #*.msu.edu
4973: $pattern=~s/\*//;
4974: if (!defined($name)) {
4975: use Socket;
4976: my $netaddr=inet_aton($ip);
4977: ($name)=gethostbyaddr($netaddr,AF_INET);
4978: }
4979: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4980: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
4981: #127.0.0.1
4982: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4983: } else {
4984: #some.name.com
4985: if (!defined($name)) {
4986: use Socket;
4987: my $netaddr=inet_aton($ip);
4988: ($name)=gethostbyaddr($netaddr,AF_INET);
4989: }
4990: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4991: }
4992: if ($allowed) { last; }
4993: }
4994: return $allowed;
4995: }
4996:
4997: sub check_slotip_acc {
4998: my ($acc,$clientip)=@_;
4999: &Apache::lonxml::debug("acc is $acc");
5000: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
5001: return 1;
5002: }
5003: my $allowed;
5004: my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
5005:
5006: my $name;
5007: my %access = (
5008: allowfrom => 1,
5009: denyfrom => 0,
5010: );
5011: my @allows;
5012: my @denies;
5013: foreach my $item (split(',',$acc)) {
5014: $item =~ s/^\s*//;
5015: $item =~ s/\s*$//;
5016: my $pattern;
5017: if ($item =~ /^\!(.+)$/) {
5018: push(@denies,$1);
5019: } else {
5020: push(@allows,$item);
5021: }
5022: }
5023: my $numdenies = scalar(@denies);
5024: my $numallows = scalar(@allows);
5025: my $count = 0;
5026: foreach my $pattern (@denies,@allows) {
5027: $count ++;
5028: my $acctype = 'allowfrom';
5029: if ($count <= $numdenies) {
5030: $acctype = 'denyfrom';
5031: }
5032: if ($pattern =~ /\*$/) {
5033: #35.8.*
5034: $pattern=~s/\*//;
5035: if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
5036: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
5037: #35.8.3.[34-56]
5038: my $low=$2;
5039: my $high=$3;
5040: $pattern=$1;
5041: if ($ip =~ /^\Q$pattern\E/) {
5042: my $last=(split(/\./,$ip))[3];
5043: if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
5044: }
5045: } elsif ($pattern =~ /^\*/) {
5046: #*.msu.edu
5047: $pattern=~s/\*//;
5048: if (!defined($name)) {
5049: use Socket;
5050: my $netaddr=inet_aton($ip);
5051: ($name)=gethostbyaddr($netaddr,AF_INET);
5052: }
5053: if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
5054: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
5055: #127.0.0.1
5056: if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
5057: } else {
5058: #some.name.com
5059: if (!defined($name)) {
5060: use Socket;
5061: my $netaddr=inet_aton($ip);
5062: ($name)=gethostbyaddr($netaddr,AF_INET);
5063: }
5064: if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
5065: }
5066: if ($allowed =~ /^(0|1)$/) { last; }
5067: }
5068: if ($allowed eq '') {
5069: if ($numdenies && !$numallows) {
5070: $allowed = 1;
5071: } else {
5072: $allowed = 0;
5073: }
5074: }
5075: return $allowed;
5076: }
5077:
5078: ###############################################
5079:
5080: =pod
5081:
5082: =head1 Domain Template Functions
5083:
5084: =over 4
5085:
5086: =item * &determinedomain()
5087:
5088: Inputs: $domain (usually will be undef)
5089:
5090: Returns: Determines which domain should be used for designs
5091:
5092: =cut
5093:
5094: ###############################################
5095: sub determinedomain {
5096: my $domain=shift;
5097: if (! $domain) {
5098: # Determine domain if we have not been given one
5099: $domain = &Apache::lonnet::default_login_domain();
5100: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
5101: if ($env{'request.role.domain'}) {
5102: $domain=$env{'request.role.domain'};
5103: }
5104: }
5105: return $domain;
5106: }
5107: ###############################################
5108:
5109: sub devalidate_domconfig_cache {
5110: my ($udom)=@_;
5111: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
5112: }
5113:
5114: # ---------------------- Get domain configuration for a domain
5115: sub get_domainconf {
5116: my ($udom) = @_;
5117: my $cachetime=1800;
5118: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
5119: if (defined($cached)) { return %{$result}; }
5120:
5121: my %domconfig = &Apache::lonnet::get_dom('configuration',
5122: ['login','rolecolors','autoenroll'],$udom);
5123: my (%designhash,%legacy);
5124: if (keys(%domconfig) > 0) {
5125: if (ref($domconfig{'login'}) eq 'HASH') {
5126: if (keys(%{$domconfig{'login'}})) {
5127: foreach my $key (keys(%{$domconfig{'login'}})) {
5128: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5129: if (($key eq 'loginvia') || ($key eq 'headtag')) {
5130: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5131: foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
5132: if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
5133: if ($key eq 'loginvia') {
5134: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
5135: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
5136: $designhash{$udom.'.login.loginvia'} = $server;
5137: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
5138: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
5139: } else {
5140: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
5141: }
5142: }
5143: } elsif ($key eq 'headtag') {
5144: if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
5145: $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
5146: }
5147: }
5148: if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
5149: $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
5150: }
5151: }
5152: }
5153: }
5154: } else {
5155: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
5156: $designhash{$udom.'.login.'.$key.'_'.$img} =
5157: $domconfig{'login'}{$key}{$img};
5158: }
5159: }
5160: } else {
5161: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
5162: }
5163: }
5164: } else {
5165: $legacy{'login'} = 1;
5166: }
5167: } else {
5168: $legacy{'login'} = 1;
5169: }
5170: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
5171: if (keys(%{$domconfig{'rolecolors'}})) {
5172: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
5173: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
5174: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
5175: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
5176: }
5177: }
5178: }
5179: } else {
5180: $legacy{'rolecolors'} = 1;
5181: }
5182: } else {
5183: $legacy{'rolecolors'} = 1;
5184: }
5185: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5186: if ($domconfig{'autoenroll'}{'co-owners'}) {
5187: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
5188: }
5189: }
5190: if (keys(%legacy) > 0) {
5191: my %legacyhash = &get_legacy_domconf($udom);
5192: foreach my $item (keys(%legacyhash)) {
5193: if ($item =~ /^\Q$udom\E\.login/) {
5194: if ($legacy{'login'}) {
5195: $designhash{$item} = $legacyhash{$item};
5196: }
5197: } else {
5198: if ($legacy{'rolecolors'}) {
5199: $designhash{$item} = $legacyhash{$item};
5200: }
5201: }
5202: }
5203: }
5204: } else {
5205: %designhash = &get_legacy_domconf($udom);
5206: }
5207: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
5208: $cachetime);
5209: return %designhash;
5210: }
5211:
5212: sub get_legacy_domconf {
5213: my ($udom) = @_;
5214: my %legacyhash;
5215: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
5216: my $designfile = $designdir.'/'.$udom.'.tab';
5217: if (-e $designfile) {
5218: if ( open (my $fh,"<$designfile") ) {
5219: while (my $line = <$fh>) {
5220: next if ($line =~ /^\#/);
5221: chomp($line);
5222: my ($key,$val)=(split(/\=/,$line));
5223: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
5224: }
5225: close($fh);
5226: }
5227: }
5228: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
5229: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
5230: }
5231: return %legacyhash;
5232: }
5233:
5234: =pod
5235:
5236: =item * &domainlogo()
5237:
5238: Inputs: $domain (usually will be undef)
5239:
5240: Returns: A link to a domain logo, if the domain logo exists.
5241: If the domain logo does not exist, a description of the domain.
5242:
5243: =cut
5244:
5245: ###############################################
5246: sub domainlogo {
5247: my $domain = &determinedomain(shift);
5248: my %designhash = &get_domainconf($domain);
5249: # See if there is a logo
5250: if ($designhash{$domain.'.login.domlogo'} ne '') {
5251: my $imgsrc = $designhash{$domain.'.login.domlogo'};
5252: if ($imgsrc =~ m{^/(adm|res)/}) {
5253: if ($imgsrc =~ m{^/res/}) {
5254: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
5255: &Apache::lonnet::repcopy($local_name);
5256: }
5257: $imgsrc = &lonhttpdurl($imgsrc);
5258: }
5259: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
5260: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
5261: return &Apache::lonnet::domain($domain,'description');
5262: } else {
5263: return '';
5264: }
5265: }
5266: ##############################################
5267:
5268: =pod
5269:
5270: =item * &designparm()
5271:
5272: Inputs: $which parameter; $domain (usually will be undef)
5273:
5274: Returns: value of designparamter $which
5275:
5276: =cut
5277:
5278:
5279: ##############################################
5280: sub designparm {
5281: my ($which,$domain)=@_;
5282: if (exists($env{'environment.color.'.$which})) {
5283: return $env{'environment.color.'.$which};
5284: }
5285: $domain=&determinedomain($domain);
5286: my %domdesign;
5287: unless ($domain eq 'public') {
5288: %domdesign = &get_domainconf($domain);
5289: }
5290: my $output;
5291: if ($domdesign{$domain.'.'.$which} ne '') {
5292: $output = $domdesign{$domain.'.'.$which};
5293: } else {
5294: $output = $defaultdesign{$which};
5295: }
5296: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
5297: ($which =~ /login\.(img|logo|domlogo|login)/)) {
5298: if ($output =~ m{^/(adm|res)/}) {
5299: if ($output =~ m{^/res/}) {
5300: my $local_name = &Apache::lonnet::filelocation('',$output);
5301: &Apache::lonnet::repcopy($local_name);
5302: }
5303: $output = &lonhttpdurl($output);
5304: }
5305: }
5306: return $output;
5307: }
5308:
5309: ##############################################
5310: =pod
5311:
5312: =item * &authorspace()
5313:
5314: Inputs: $url (usually will be undef).
5315:
5316: Returns: Path to Authoring Space containing the resource or
5317: directory being viewed (or for which action is being taken).
5318: If $url is provided, and begins /priv/<domain>/<uname>
5319: the path will be that portion of the $context argument.
5320: Otherwise the path will be for the author space of the current
5321: user when the current role is author, or for that of the
5322: co-author/assistant co-author space when the current role
5323: is co-author or assistant co-author.
5324:
5325: =cut
5326:
5327: sub authorspace {
5328: my ($url) = @_;
5329: if ($url ne '') {
5330: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
5331: return $1;
5332: }
5333: }
5334: my $caname = '';
5335: my $cadom = '';
5336: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
5337: ($cadom,$caname) =
5338: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
5339: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
5340: $caname = $env{'user.name'};
5341: $cadom = $env{'user.domain'};
5342: }
5343: if (($caname ne '') && ($cadom ne '')) {
5344: return "/priv/$cadom/$caname/";
5345: }
5346: return;
5347: }
5348:
5349: ##############################################
5350: =pod
5351:
5352: =item * &head_subbox()
5353:
5354: Inputs: $content (contains HTML code with page functions, etc.)
5355:
5356: Returns: HTML div with $content
5357: To be included in page header
5358:
5359: =cut
5360:
5361: sub head_subbox {
5362: my ($content)=@_;
5363: my $output =
5364: '<div class="LC_head_subbox">'
5365: .$content
5366: .'</div>'
5367: }
5368:
5369: ##############################################
5370: =pod
5371:
5372: =item * &CSTR_pageheader()
5373:
5374: Input: (optional) filename from which breadcrumb trail is built.
5375: In most cases no input as needed, as $env{'request.filename'}
5376: is appropriate for use in building the breadcrumb trail.
5377:
5378: Returns: HTML div with CSTR path and recent box
5379: To be included on Authoring Space pages
5380:
5381: =cut
5382:
5383: sub CSTR_pageheader {
5384: my ($trailfile) = @_;
5385: if ($trailfile eq '') {
5386: $trailfile = $env{'request.filename'};
5387: }
5388:
5389: # this is for resources; directories have customtitle, and crumbs
5390: # and select recent are created in lonpubdir.pm
5391:
5392: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
5393: my ($udom,$uname,$thisdisfn)=
5394: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
5395: my $formaction = "/priv/$udom/$uname/$thisdisfn";
5396: $formaction =~ s{/+}{/}g;
5397:
5398: my $parentpath = '';
5399: my $lastitem = '';
5400: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
5401: $parentpath = $1;
5402: $lastitem = $2;
5403: } else {
5404: $lastitem = $thisdisfn;
5405: }
5406:
5407: my $output =
5408: '<div>'
5409: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
5410: .'<b>'.&mt('Authoring Space:').'</b> '
5411: .'<form name="dirs" method="post" action="'.$formaction
5412: .'" target="_top">' #FIXME lonpubdir: target="_parent"
5413: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
5414:
5415: if ($lastitem) {
5416: $output .=
5417: '<span class="LC_filename">'
5418: .$lastitem
5419: .'</span>';
5420: }
5421: $output .=
5422: '<br />'
5423: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
5424: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
5425: .'</form>'
5426: .&Apache::lonmenu::constspaceform()
5427: .'</div>';
5428:
5429: return $output;
5430: }
5431:
5432: ###############################################
5433: ###############################################
5434:
5435: =pod
5436:
5437: =back
5438:
5439: =head1 HTML Helpers
5440:
5441: =over 4
5442:
5443: =item * &bodytag()
5444:
5445: Returns a uniform header for LON-CAPA web pages.
5446:
5447: Inputs:
5448:
5449: =over 4
5450:
5451: =item * $title, A title to be displayed on the page.
5452:
5453: =item * $function, the current role (can be undef).
5454:
5455: =item * $addentries, extra parameters for the <body> tag.
5456:
5457: =item * $bodyonly, if defined, only return the <body> tag.
5458:
5459: =item * $domain, if defined, force a given domain.
5460:
5461: =item * $forcereg, if page should register as content page (relevant for
5462: text interface only)
5463:
5464: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
5465: navigational links
5466:
5467: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
5468:
5469: =item * $no_inline_link, if true and in remote mode, don't show the
5470: 'Switch To Inline Menu' link
5471:
5472: =item * $args, optional argument valid values are
5473: no_auto_mt_title -> prevents &mt()ing the title arg
5474:
5475: =item * $advtoolsref, optional argument, ref to an array containing
5476: inlineremote items to be added in "Functions" menu below
5477: breadcrumbs.
5478:
5479: =back
5480:
5481: Returns: A uniform header for LON-CAPA web pages.
5482: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
5483: If $bodyonly is undef or zero, an html string containing a <body> tag and
5484: other decorations will be returned.
5485:
5486: =cut
5487:
5488: sub bodytag {
5489: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
5490: $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
5491:
5492: my $public;
5493: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
5494: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
5495: $public = 1;
5496: }
5497: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
5498: my $httphost = $args->{'use_absolute'};
5499:
5500: $function = &get_users_function() if (!$function);
5501: my $img = &designparm($function.'.img',$domain);
5502: my $font = &designparm($function.'.font',$domain);
5503: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
5504:
5505: my %design = ( 'style' => 'margin-top: 0',
5506: 'bgcolor' => $pgbg,
5507: 'text' => $font,
5508: 'alink' => &designparm($function.'.alink',$domain),
5509: 'vlink' => &designparm($function.'.vlink',$domain),
5510: 'link' => &designparm($function.'.link',$domain),);
5511: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
5512:
5513: # role and realm
5514: my ($role,$realm) = split(m{\./},$env{'request.role'},2);
5515: if ($realm) {
5516: $realm = '/'.$realm;
5517: }
5518: if ($role eq 'ca') {
5519: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
5520: $realm = &plainname($rname,$rdom);
5521: }
5522: # realm
5523: if ($env{'request.course.id'}) {
5524: if ($env{'request.role'} !~ /^cr/) {
5525: $role = &Apache::lonnet::plaintext($role,&course_type());
5526: } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
5527: if ($env{'request.role.desc'}) {
5528: $role = $env{'request.role.desc'};
5529: } else {
5530: $role = &mt('Helpdesk[_1]',' '.$2);
5531: }
5532: } else {
5533: $role = (split(/\//,$role,4))[-1];
5534: }
5535: if ($env{'request.course.sec'}) {
5536: $role .= (' 'x2).'- '.&mt('section:').' '.$env{'request.course.sec'};
5537: }
5538: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
5539: } else {
5540: $role = &Apache::lonnet::plaintext($role);
5541: }
5542:
5543: if (!$realm) { $realm=' '; }
5544:
5545: my $extra_body_attr = &make_attr_string($forcereg,\%design);
5546:
5547: # construct main body tag
5548: my $bodytag = "<body $extra_body_attr>".
5549: &Apache::lontexconvert::init_math_support();
5550:
5551: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
5552:
5553: if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
5554: return $bodytag;
5555: }
5556:
5557: if ($public) {
5558: undef($role);
5559: }
5560:
5561: my $titleinfo = '<h1>'.$title.'</h1>';
5562: #
5563: # Extra info if you are the DC
5564: my $dc_info = '';
5565: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
5566: $env{'course.'.$env{'request.course.id'}.
5567: '.domain'}.'/'})) {
5568: my $cid = $env{'request.course.id'};
5569: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
5570: $dc_info =~ s/\s+$//;
5571: }
5572:
5573: $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
5574:
5575: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
5576:
5577:
5578:
5579: my $funclist;
5580: if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
5581: $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
5582: Apache::lonmenu::serverform();
5583: my $forbodytag;
5584: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
5585: $forcereg,$args->{'group'},
5586: $args->{'bread_crumbs'},
5587: $advtoolsref,'',\$forbodytag);
5588: unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
5589: $funclist = $forbodytag;
5590: }
5591: } else {
5592:
5593: # if ($env{'request.state'} eq 'construct') {
5594: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
5595: # }
5596:
5597: $bodytag .= Apache::lonhtmlcommon::scripttag(
5598: Apache::lonmenu::utilityfunctions($httphost), 'start');
5599:
5600: my ($left,$right) = Apache::lonmenu::primary_menu();
5601:
5602: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
5603: if ($dc_info) {
5604: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
5605: }
5606: $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
5607: <em>$realm</em> $dc_info</div>|;
5608: return $bodytag;
5609: }
5610:
5611: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
5612: $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
5613: }
5614:
5615: $bodytag .= $right;
5616:
5617: if ($dc_info) {
5618: $dc_info = &dc_courseid_toggle($dc_info);
5619: }
5620: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
5621:
5622: #if directed to not display the secondary menu, don't.
5623: if ($args->{'no_secondary_menu'}) {
5624: return $bodytag;
5625: }
5626: #don't show menus for public users
5627: if (!$public){
5628: $bodytag .= Apache::lonmenu::secondary_menu($httphost);
5629: $bodytag .= Apache::lonmenu::serverform();
5630: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5631: if ($env{'request.state'} eq 'construct') {
5632: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
5633: $args->{'bread_crumbs'});
5634: } elsif ($forcereg) {
5635: $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
5636: $args->{'group'},
5637: $args->{'hide_buttons'});
5638: } else {
5639: my $forbodytag;
5640: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
5641: $forcereg,$args->{'group'},
5642: $args->{'bread_crumbs'},
5643: $advtoolsref,'',\$forbodytag);
5644: unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
5645: $bodytag .= $forbodytag;
5646: }
5647: }
5648: }else{
5649: # this is to seperate menu from content when there's no secondary
5650: # menu. Especially needed for public accessible ressources.
5651: $bodytag .= '<hr style="clear:both" />';
5652: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5653: }
5654:
5655: return $bodytag;
5656: }
5657:
5658: #
5659: # Top frame rendering, Remote is up
5660: #
5661:
5662: my $imgsrc = $img;
5663: if ($img =~ /^\/adm/) {
5664: $imgsrc = &lonhttpdurl($img);
5665: }
5666: my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
5667:
5668: my $help=($no_inline_link?''
5669: :&Apache::loncommon::top_nav_help('Help'));
5670:
5671: # Explicit link to get inline menu
5672: my $menu= ($no_inline_link?''
5673: :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
5674:
5675: if ($dc_info) {
5676: $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
5677: }
5678:
5679: my $name = &plainname($env{'user.name'},$env{'user.domain'});
5680: unless ($public) {
5681: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
5682: undef,'LC_menubuttons_link');
5683: }
5684:
5685: unless ($env{'form.inhibitmenu'}) {
5686: $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
5687: <ol class="LC_primary_menu LC_floatright LC_right">
5688: <li>$help</li>
5689: <li>$menu</li>
5690: </ol><div id="LC_realm"> $realm $dc_info</div>|;
5691: }
5692: if ($env{'request.state'} eq 'construct') {
5693: if (!$public){
5694: if ($env{'request.state'} eq 'construct') {
5695: $funclist = &Apache::lonhtmlcommon::scripttag(
5696: &Apache::lonmenu::utilityfunctions($httphost), 'start').
5697: &Apache::lonhtmlcommon::scripttag('','end').
5698: &Apache::lonmenu::innerregister($forcereg,
5699: $args->{'bread_crumbs'});
5700: }
5701: }
5702: }
5703: return $bodytag."\n".$funclist;
5704: }
5705:
5706: sub dc_courseid_toggle {
5707: my ($dc_info) = @_;
5708: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
5709: '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
5710: &mt('(More ...)').'</a></span>'.
5711: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
5712: }
5713:
5714: sub make_attr_string {
5715: my ($register,$attr_ref) = @_;
5716:
5717: if ($attr_ref && !ref($attr_ref)) {
5718: die("addentries Must be a hash ref ".
5719: join(':',caller(1))." ".
5720: join(':',caller(0))." ");
5721: }
5722:
5723: if ($register) {
5724: my ($on_load,$on_unload);
5725: foreach my $key (keys(%{$attr_ref})) {
5726: if (lc($key) eq 'onload') {
5727: $on_load.=$attr_ref->{$key}.';';
5728: delete($attr_ref->{$key});
5729:
5730: } elsif (lc($key) eq 'onunload') {
5731: $on_unload.=$attr_ref->{$key}.';';
5732: delete($attr_ref->{$key});
5733: }
5734: }
5735: if ($env{'environment.remote'} eq 'on') {
5736: $attr_ref->{'onload'} =
5737: &Apache::lonmenu::loadevents(). $on_load;
5738: $attr_ref->{'onunload'}=
5739: &Apache::lonmenu::unloadevents().$on_unload;
5740: } else {
5741: $attr_ref->{'onload'} = $on_load;
5742: $attr_ref->{'onunload'}= $on_unload;
5743: }
5744: }
5745:
5746: my $attr_string;
5747: foreach my $attr (sort(keys(%$attr_ref))) {
5748: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
5749: }
5750: return $attr_string;
5751: }
5752:
5753:
5754: ###############################################
5755: ###############################################
5756:
5757: =pod
5758:
5759: =item * &endbodytag()
5760:
5761: Returns a uniform footer for LON-CAPA web pages.
5762:
5763: Inputs: 1 - optional reference to an args hash
5764: If in the hash, key for noredirectlink has a value which evaluates to true,
5765: a 'Continue' link is not displayed if the page contains an
5766: internal redirect in the <head></head> section,
5767: i.e., $env{'internal.head.redirect'} exists
5768:
5769: =cut
5770:
5771: sub endbodytag {
5772: my ($args) = @_;
5773: my $endbodytag;
5774: unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
5775: $endbodytag='</body>';
5776: }
5777: if ( exists( $env{'internal.head.redirect'} ) ) {
5778: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
5779: $endbodytag=
5780: "<br /><a href=\"$env{'internal.head.redirect'}\">".
5781: &mt('Continue').'</a>'.
5782: $endbodytag;
5783: }
5784: }
5785: return $endbodytag;
5786: }
5787:
5788: =pod
5789:
5790: =item * &standard_css()
5791:
5792: Returns a style sheet
5793:
5794: Inputs: (all optional)
5795: domain -> force to color decorate a page for a specific
5796: domain
5797: function -> force usage of a specific rolish color scheme
5798: bgcolor -> override the default page bgcolor
5799:
5800: =cut
5801:
5802: sub standard_css {
5803: my ($function,$domain,$bgcolor) = @_;
5804: $function = &get_users_function() if (!$function);
5805: my $img = &designparm($function.'.img', $domain);
5806: my $tabbg = &designparm($function.'.tabbg', $domain);
5807: my $font = &designparm($function.'.font', $domain);
5808: my $fontmenu = &designparm($function.'.fontmenu', $domain);
5809: #second colour for later usage
5810: my $sidebg = &designparm($function.'.sidebg',$domain);
5811: my $pgbg_or_bgcolor =
5812: $bgcolor ||
5813: &designparm($function.'.pgbg', $domain);
5814: my $pgbg = &designparm($function.'.pgbg', $domain);
5815: my $alink = &designparm($function.'.alink', $domain);
5816: my $vlink = &designparm($function.'.vlink', $domain);
5817: my $link = &designparm($function.'.link', $domain);
5818:
5819: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
5820: my $mono = 'monospace';
5821: my $data_table_head = $sidebg;
5822: my $data_table_light = '#FAFAFA';
5823: my $data_table_dark = '#E0E0E0';
5824: my $data_table_darker = '#CCCCCC';
5825: my $data_table_highlight = '#FFFF00';
5826: my $mail_new = '#FFBB77';
5827: my $mail_new_hover = '#DD9955';
5828: my $mail_read = '#BBBB77';
5829: my $mail_read_hover = '#999944';
5830: my $mail_replied = '#AAAA88';
5831: my $mail_replied_hover = '#888855';
5832: my $mail_other = '#99BBBB';
5833: my $mail_other_hover = '#669999';
5834: my $table_header = '#DDDDDD';
5835: my $feedback_link_bg = '#BBBBBB';
5836: my $lg_border_color = '#C8C8C8';
5837: my $button_hover = '#BF2317';
5838:
5839: my $border = ($env{'browser.type'} eq 'explorer' ||
5840: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
5841: : '0 3px 0 4px';
5842:
5843:
5844: return <<END;
5845:
5846: /* needed for iframe to allow 100% height in FF */
5847: body, html {
5848: margin: 0;
5849: padding: 0 0.5%;
5850: height: 99%; /* to avoid scrollbars */
5851: }
5852:
5853: body {
5854: font-family: $sans;
5855: line-height:130%;
5856: font-size:0.83em;
5857: color:$font;
5858: }
5859:
5860: a:focus,
5861: a:focus img {
5862: color: red;
5863: }
5864:
5865: form, .inline {
5866: display: inline;
5867: }
5868:
5869: .LC_right {
5870: text-align:right;
5871: }
5872:
5873: .LC_middle {
5874: vertical-align:middle;
5875: }
5876:
5877: .LC_floatleft {
5878: float: left;
5879: }
5880:
5881: .LC_floatright {
5882: float: right;
5883: }
5884:
5885: .LC_400Box {
5886: width:400px;
5887: }
5888:
5889: .LC_iframecontainer {
5890: width: 98%;
5891: margin: 0;
5892: position: fixed;
5893: top: 8.5em;
5894: bottom: 0;
5895: }
5896:
5897: .LC_iframecontainer iframe{
5898: border: none;
5899: width: 100%;
5900: height: 100%;
5901: }
5902:
5903: .LC_filename {
5904: font-family: $mono;
5905: white-space:pre;
5906: font-size: 120%;
5907: }
5908:
5909: .LC_fileicon {
5910: border: none;
5911: height: 1.3em;
5912: vertical-align: text-bottom;
5913: margin-right: 0.3em;
5914: text-decoration:none;
5915: }
5916:
5917: .LC_setting {
5918: text-decoration:underline;
5919: }
5920:
5921: .LC_error {
5922: color: red;
5923: }
5924:
5925: .LC_warning {
5926: color: darkorange;
5927: }
5928:
5929: .LC_diff_removed {
5930: color: red;
5931: }
5932:
5933: .LC_info,
5934: .LC_success,
5935: .LC_diff_added {
5936: color: green;
5937: }
5938:
5939: div.LC_confirm_box {
5940: background-color: #FAFAFA;
5941: border: 1px solid $lg_border_color;
5942: margin-right: 0;
5943: padding: 5px;
5944: }
5945:
5946: div.LC_confirm_box .LC_error img,
5947: div.LC_confirm_box .LC_success img {
5948: vertical-align: middle;
5949: }
5950:
5951: .LC_maxwidth {
5952: max-width: 100%;
5953: height: auto;
5954: }
5955:
5956: .LC_textsize_mobile {
5957: \@media only screen and (max-device-width: 480px) {
5958: -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
5959: }
5960: }
5961:
5962: .LC_icon {
5963: border: none;
5964: vertical-align: middle;
5965: }
5966:
5967: .LC_docs_spacer {
5968: width: 25px;
5969: height: 1px;
5970: border: none;
5971: }
5972:
5973: .LC_internal_info {
5974: color: #999999;
5975: }
5976:
5977: .LC_discussion {
5978: background: $data_table_dark;
5979: border: 1px solid black;
5980: margin: 2px;
5981: }
5982:
5983: .LC_disc_action_left {
5984: background: $sidebg;
5985: text-align: left;
5986: padding: 4px;
5987: margin: 2px;
5988: }
5989:
5990: .LC_disc_action_right {
5991: background: $sidebg;
5992: text-align: right;
5993: padding: 4px;
5994: margin: 2px;
5995: }
5996:
5997: .LC_disc_new_item {
5998: background: white;
5999: border: 2px solid red;
6000: margin: 4px;
6001: padding: 4px;
6002: }
6003:
6004: .LC_disc_old_item {
6005: background: white;
6006: margin: 4px;
6007: padding: 4px;
6008: }
6009:
6010: table.LC_pastsubmission {
6011: border: 1px solid black;
6012: margin: 2px;
6013: }
6014:
6015: table#LC_menubuttons {
6016: width: 100%;
6017: background: $pgbg;
6018: border: 2px;
6019: border-collapse: separate;
6020: padding: 0;
6021: }
6022:
6023: table#LC_title_bar a {
6024: color: $fontmenu;
6025: }
6026:
6027: table#LC_title_bar {
6028: clear: both;
6029: display: none;
6030: }
6031:
6032: table#LC_title_bar,
6033: table.LC_breadcrumbs, /* obsolete? */
6034: table#LC_title_bar.LC_with_remote {
6035: width: 100%;
6036: border-color: $pgbg;
6037: border-style: solid;
6038: border-width: $border;
6039: background: $pgbg;
6040: color: $fontmenu;
6041: border-collapse: collapse;
6042: padding: 0;
6043: margin: 0;
6044: }
6045:
6046: ul.LC_breadcrumb_tools_outerlist {
6047: margin: 0;
6048: padding: 0;
6049: position: relative;
6050: list-style: none;
6051: }
6052: ul.LC_breadcrumb_tools_outerlist li {
6053: display: inline;
6054: }
6055:
6056: .LC_breadcrumb_tools_navigation {
6057: padding: 0;
6058: margin: 0;
6059: float: left;
6060: }
6061: .LC_breadcrumb_tools_tools {
6062: padding: 0;
6063: margin: 0;
6064: float: right;
6065: }
6066:
6067: table#LC_title_bar td {
6068: background: $tabbg;
6069: }
6070:
6071: table#LC_menubuttons img {
6072: border: none;
6073: }
6074:
6075: .LC_breadcrumbs_component {
6076: float: right;
6077: margin: 0 1em;
6078: }
6079: .LC_breadcrumbs_component img {
6080: vertical-align: middle;
6081: }
6082:
6083: .LC_breadcrumbs_hoverable {
6084: background: $sidebg;
6085: }
6086:
6087: td.LC_table_cell_checkbox {
6088: text-align: center;
6089: }
6090:
6091: .LC_fontsize_small {
6092: font-size: 70%;
6093: }
6094:
6095: #LC_breadcrumbs {
6096: clear:both;
6097: background: $sidebg;
6098: border-bottom: 1px solid $lg_border_color;
6099: line-height: 2.5em;
6100: overflow: hidden;
6101: margin: 0;
6102: padding: 0;
6103: text-align: left;
6104: }
6105:
6106: .LC_head_subbox, .LC_actionbox {
6107: clear:both;
6108: background: #F8F8F8; /* $sidebg; */
6109: border: 1px solid $sidebg;
6110: margin: 0 0 10px 0;
6111: padding: 3px;
6112: text-align: left;
6113: }
6114:
6115: .LC_fontsize_medium {
6116: font-size: 85%;
6117: }
6118:
6119: .LC_fontsize_large {
6120: font-size: 120%;
6121: }
6122:
6123: .LC_menubuttons_inline_text {
6124: color: $font;
6125: font-size: 90%;
6126: padding-left:3px;
6127: }
6128:
6129: .LC_menubuttons_inline_text img{
6130: vertical-align: middle;
6131: }
6132:
6133: li.LC_menubuttons_inline_text img {
6134: cursor:pointer;
6135: text-decoration: none;
6136: }
6137:
6138: .LC_menubuttons_link {
6139: text-decoration: none;
6140: }
6141:
6142: .LC_menubuttons_category {
6143: color: $font;
6144: background: $pgbg;
6145: font-size: larger;
6146: font-weight: bold;
6147: }
6148:
6149: td.LC_menubuttons_text {
6150: color: $font;
6151: }
6152:
6153: .LC_current_location {
6154: background: $tabbg;
6155: }
6156:
6157: table.LC_data_table {
6158: border: 1px solid #000000;
6159: border-collapse: separate;
6160: border-spacing: 1px;
6161: background: $pgbg;
6162: }
6163:
6164: .LC_data_table_dense {
6165: font-size: small;
6166: }
6167:
6168: table.LC_nested_outer {
6169: border: 1px solid #000000;
6170: border-collapse: collapse;
6171: border-spacing: 0;
6172: width: 100%;
6173: }
6174:
6175: table.LC_innerpickbox,
6176: table.LC_nested {
6177: border: none;
6178: border-collapse: collapse;
6179: border-spacing: 0;
6180: width: 100%;
6181: }
6182:
6183: table.LC_data_table tr th,
6184: table.LC_calendar tr th,
6185: table.LC_prior_tries tr th,
6186: table.LC_innerpickbox tr th {
6187: font-weight: bold;
6188: background-color: $data_table_head;
6189: color:$fontmenu;
6190: font-size:90%;
6191: }
6192:
6193: table.LC_innerpickbox tr th,
6194: table.LC_innerpickbox tr td {
6195: vertical-align: top;
6196: }
6197:
6198: table.LC_data_table tr.LC_info_row > td {
6199: background-color: #CCCCCC;
6200: font-weight: bold;
6201: text-align: left;
6202: }
6203:
6204: table.LC_data_table tr.LC_odd_row > td {
6205: background-color: $data_table_light;
6206: padding: 2px;
6207: vertical-align: top;
6208: }
6209:
6210: table.LC_pick_box tr > td.LC_odd_row {
6211: background-color: $data_table_light;
6212: vertical-align: top;
6213: }
6214:
6215: table.LC_data_table tr.LC_even_row > td {
6216: background-color: $data_table_dark;
6217: padding: 2px;
6218: vertical-align: top;
6219: }
6220:
6221: table.LC_pick_box tr > td.LC_even_row {
6222: background-color: $data_table_dark;
6223: vertical-align: top;
6224: }
6225:
6226: table.LC_data_table tr.LC_data_table_highlight td {
6227: background-color: $data_table_darker;
6228: }
6229:
6230: table.LC_data_table tr td.LC_leftcol_header {
6231: background-color: $data_table_head;
6232: font-weight: bold;
6233: }
6234:
6235: table.LC_data_table tr.LC_empty_row td,
6236: table.LC_nested tr.LC_empty_row td {
6237: font-weight: bold;
6238: font-style: italic;
6239: text-align: center;
6240: padding: 8px;
6241: }
6242:
6243: table.LC_data_table tr.LC_empty_row td,
6244: table.LC_data_table tr.LC_footer_row td {
6245: background-color: $sidebg;
6246: }
6247:
6248: table.LC_nested tr.LC_empty_row td {
6249: background-color: #FFFFFF;
6250: }
6251:
6252: table.LC_caption {
6253: }
6254:
6255: table.LC_nested tr.LC_empty_row td {
6256: padding: 4ex
6257: }
6258:
6259: table.LC_nested_outer tr th {
6260: font-weight: bold;
6261: color:$fontmenu;
6262: background-color: $data_table_head;
6263: font-size: small;
6264: border-bottom: 1px solid #000000;
6265: }
6266:
6267: table.LC_nested_outer tr td.LC_subheader {
6268: background-color: $data_table_head;
6269: font-weight: bold;
6270: font-size: small;
6271: border-bottom: 1px solid #000000;
6272: text-align: right;
6273: }
6274:
6275: table.LC_nested tr.LC_info_row td {
6276: background-color: #CCCCCC;
6277: font-weight: bold;
6278: font-size: small;
6279: text-align: center;
6280: }
6281:
6282: table.LC_nested tr.LC_info_row td.LC_left_item,
6283: table.LC_nested_outer tr th.LC_left_item {
6284: text-align: left;
6285: }
6286:
6287: table.LC_nested td {
6288: background-color: #FFFFFF;
6289: font-size: small;
6290: }
6291:
6292: table.LC_nested_outer tr th.LC_right_item,
6293: table.LC_nested tr.LC_info_row td.LC_right_item,
6294: table.LC_nested tr.LC_odd_row td.LC_right_item,
6295: table.LC_nested tr td.LC_right_item {
6296: text-align: right;
6297: }
6298:
6299: table.LC_nested tr.LC_odd_row td {
6300: background-color: #EEEEEE;
6301: }
6302:
6303: table.LC_createuser {
6304: }
6305:
6306: table.LC_createuser tr.LC_section_row td {
6307: font-size: small;
6308: }
6309:
6310: table.LC_createuser tr.LC_info_row td {
6311: background-color: #CCCCCC;
6312: font-weight: bold;
6313: text-align: center;
6314: }
6315:
6316: table.LC_calendar {
6317: border: 1px solid #000000;
6318: border-collapse: collapse;
6319: width: 98%;
6320: }
6321:
6322: table.LC_calendar_pickdate {
6323: font-size: xx-small;
6324: }
6325:
6326: table.LC_calendar tr td {
6327: border: 1px solid #000000;
6328: vertical-align: top;
6329: width: 14%;
6330: }
6331:
6332: table.LC_calendar tr td.LC_calendar_day_empty {
6333: background-color: $data_table_dark;
6334: }
6335:
6336: table.LC_calendar tr td.LC_calendar_day_current {
6337: background-color: $data_table_highlight;
6338: }
6339:
6340: table.LC_data_table tr td.LC_mail_new {
6341: background-color: $mail_new;
6342: }
6343:
6344: table.LC_data_table tr.LC_mail_new:hover {
6345: background-color: $mail_new_hover;
6346: }
6347:
6348: table.LC_data_table tr td.LC_mail_read {
6349: background-color: $mail_read;
6350: }
6351:
6352: /*
6353: table.LC_data_table tr.LC_mail_read:hover {
6354: background-color: $mail_read_hover;
6355: }
6356: */
6357:
6358: table.LC_data_table tr td.LC_mail_replied {
6359: background-color: $mail_replied;
6360: }
6361:
6362: /*
6363: table.LC_data_table tr.LC_mail_replied:hover {
6364: background-color: $mail_replied_hover;
6365: }
6366: */
6367:
6368: table.LC_data_table tr td.LC_mail_other {
6369: background-color: $mail_other;
6370: }
6371:
6372: /*
6373: table.LC_data_table tr.LC_mail_other:hover {
6374: background-color: $mail_other_hover;
6375: }
6376: */
6377:
6378: table.LC_data_table tr > td.LC_browser_file,
6379: table.LC_data_table tr > td.LC_browser_file_published {
6380: background: #AAEE77;
6381: }
6382:
6383: table.LC_data_table tr > td.LC_browser_file_locked,
6384: table.LC_data_table tr > td.LC_browser_file_unpublished {
6385: background: #FFAA99;
6386: }
6387:
6388: table.LC_data_table tr > td.LC_browser_file_obsolete {
6389: background: #888888;
6390: }
6391:
6392: table.LC_data_table tr > td.LC_browser_file_modified,
6393: table.LC_data_table tr > td.LC_browser_file_metamodified {
6394: background: #F8F866;
6395: }
6396:
6397: table.LC_data_table tr.LC_browser_folder > td {
6398: background: #E0E8FF;
6399: }
6400:
6401: table.LC_data_table tr > td.LC_roles_is {
6402: /* background: #77FF77; */
6403: }
6404:
6405: table.LC_data_table tr > td.LC_roles_future {
6406: border-right: 8px solid #FFFF77;
6407: }
6408:
6409: table.LC_data_table tr > td.LC_roles_will {
6410: border-right: 8px solid #FFAA77;
6411: }
6412:
6413: table.LC_data_table tr > td.LC_roles_expired {
6414: border-right: 8px solid #FF7777;
6415: }
6416:
6417: table.LC_data_table tr > td.LC_roles_will_not {
6418: border-right: 8px solid #AAFF77;
6419: }
6420:
6421: table.LC_data_table tr > td.LC_roles_selected {
6422: border-right: 8px solid #11CC55;
6423: }
6424:
6425: span.LC_current_location {
6426: font-size:larger;
6427: background: $pgbg;
6428: }
6429:
6430: span.LC_current_nav_location {
6431: font-weight:bold;
6432: background: $sidebg;
6433: }
6434:
6435: span.LC_parm_menu_item {
6436: font-size: larger;
6437: }
6438:
6439: span.LC_parm_scope_all {
6440: color: red;
6441: }
6442:
6443: span.LC_parm_scope_folder {
6444: color: green;
6445: }
6446:
6447: span.LC_parm_scope_resource {
6448: color: orange;
6449: }
6450:
6451: span.LC_parm_part {
6452: color: blue;
6453: }
6454:
6455: span.LC_parm_folder,
6456: span.LC_parm_symb {
6457: font-size: x-small;
6458: font-family: $mono;
6459: color: #AAAAAA;
6460: }
6461:
6462: ul.LC_parm_parmlist li {
6463: display: inline-block;
6464: padding: 0.3em 0.8em;
6465: vertical-align: top;
6466: width: 150px;
6467: border-top:1px solid $lg_border_color;
6468: }
6469:
6470: td.LC_parm_overview_level_menu,
6471: td.LC_parm_overview_map_menu,
6472: td.LC_parm_overview_parm_selectors,
6473: td.LC_parm_overview_restrictions {
6474: border: 1px solid black;
6475: border-collapse: collapse;
6476: }
6477:
6478: table.LC_parm_overview_restrictions td {
6479: border-width: 1px 4px 1px 4px;
6480: border-style: solid;
6481: border-color: $pgbg;
6482: text-align: center;
6483: }
6484:
6485: table.LC_parm_overview_restrictions th {
6486: background: $tabbg;
6487: border-width: 1px 4px 1px 4px;
6488: border-style: solid;
6489: border-color: $pgbg;
6490: }
6491:
6492: table#LC_helpmenu {
6493: border: none;
6494: height: 55px;
6495: border-spacing: 0;
6496: }
6497:
6498: table#LC_helpmenu fieldset legend {
6499: font-size: larger;
6500: }
6501:
6502: table#LC_helpmenu_links {
6503: width: 100%;
6504: border: 1px solid black;
6505: background: $pgbg;
6506: padding: 0;
6507: border-spacing: 1px;
6508: }
6509:
6510: table#LC_helpmenu_links tr td {
6511: padding: 1px;
6512: background: $tabbg;
6513: text-align: center;
6514: font-weight: bold;
6515: }
6516:
6517: table#LC_helpmenu_links a:link,
6518: table#LC_helpmenu_links a:visited,
6519: table#LC_helpmenu_links a:active {
6520: text-decoration: none;
6521: color: $font;
6522: }
6523:
6524: table#LC_helpmenu_links a:hover {
6525: text-decoration: underline;
6526: color: $vlink;
6527: }
6528:
6529: .LC_chrt_popup_exists {
6530: border: 1px solid #339933;
6531: margin: -1px;
6532: }
6533:
6534: .LC_chrt_popup_up {
6535: border: 1px solid yellow;
6536: margin: -1px;
6537: }
6538:
6539: .LC_chrt_popup {
6540: border: 1px solid #8888FF;
6541: background: #CCCCFF;
6542: }
6543:
6544: table.LC_pick_box {
6545: border-collapse: separate;
6546: background: white;
6547: border: 1px solid black;
6548: border-spacing: 1px;
6549: }
6550:
6551: table.LC_pick_box td.LC_pick_box_title {
6552: background: $sidebg;
6553: font-weight: bold;
6554: text-align: left;
6555: vertical-align: top;
6556: width: 184px;
6557: padding: 8px;
6558: }
6559:
6560: table.LC_pick_box td.LC_pick_box_value {
6561: text-align: left;
6562: padding: 8px;
6563: }
6564:
6565: table.LC_pick_box td.LC_pick_box_select {
6566: text-align: left;
6567: padding: 8px;
6568: }
6569:
6570: table.LC_pick_box td.LC_pick_box_separator {
6571: padding: 0;
6572: height: 1px;
6573: background: black;
6574: }
6575:
6576: table.LC_pick_box td.LC_pick_box_submit {
6577: text-align: right;
6578: }
6579:
6580: table.LC_pick_box td.LC_evenrow_value {
6581: text-align: left;
6582: padding: 8px;
6583: background-color: $data_table_light;
6584: }
6585:
6586: table.LC_pick_box td.LC_oddrow_value {
6587: text-align: left;
6588: padding: 8px;
6589: background-color: $data_table_light;
6590: }
6591:
6592: span.LC_helpform_receipt_cat {
6593: font-weight: bold;
6594: }
6595:
6596: table.LC_group_priv_box {
6597: background: white;
6598: border: 1px solid black;
6599: border-spacing: 1px;
6600: }
6601:
6602: table.LC_group_priv_box td.LC_pick_box_title {
6603: background: $tabbg;
6604: font-weight: bold;
6605: text-align: right;
6606: width: 184px;
6607: }
6608:
6609: table.LC_group_priv_box td.LC_groups_fixed {
6610: background: $data_table_light;
6611: text-align: center;
6612: }
6613:
6614: table.LC_group_priv_box td.LC_groups_optional {
6615: background: $data_table_dark;
6616: text-align: center;
6617: }
6618:
6619: table.LC_group_priv_box td.LC_groups_functionality {
6620: background: $data_table_darker;
6621: text-align: center;
6622: font-weight: bold;
6623: }
6624:
6625: table.LC_group_priv td {
6626: text-align: left;
6627: padding: 0;
6628: }
6629:
6630: .LC_navbuttons {
6631: margin: 2ex 0ex 2ex 0ex;
6632: }
6633:
6634: .LC_topic_bar {
6635: font-weight: bold;
6636: background: $tabbg;
6637: margin: 1em 0em 1em 2em;
6638: padding: 3px;
6639: font-size: 1.2em;
6640: }
6641:
6642: .LC_topic_bar span {
6643: left: 0.5em;
6644: position: absolute;
6645: vertical-align: middle;
6646: font-size: 1.2em;
6647: }
6648:
6649: table.LC_course_group_status {
6650: margin: 20px;
6651: }
6652:
6653: table.LC_status_selector td {
6654: vertical-align: top;
6655: text-align: center;
6656: padding: 4px;
6657: }
6658:
6659: div.LC_feedback_link {
6660: clear: both;
6661: background: $sidebg;
6662: width: 100%;
6663: padding-bottom: 10px;
6664: border: 1px $tabbg solid;
6665: height: 22px;
6666: line-height: 22px;
6667: padding-top: 5px;
6668: }
6669:
6670: div.LC_feedback_link img {
6671: height: 22px;
6672: vertical-align:middle;
6673: }
6674:
6675: div.LC_feedback_link a {
6676: text-decoration: none;
6677: }
6678:
6679: div.LC_comblock {
6680: display:inline;
6681: color:$font;
6682: font-size:90%;
6683: }
6684:
6685: div.LC_feedback_link div.LC_comblock {
6686: padding-left:5px;
6687: }
6688:
6689: div.LC_feedback_link div.LC_comblock a {
6690: color:$font;
6691: }
6692:
6693: span.LC_feedback_link {
6694: /* background: $feedback_link_bg; */
6695: font-size: larger;
6696: }
6697:
6698: span.LC_message_link {
6699: /* background: $feedback_link_bg; */
6700: font-size: larger;
6701: position: absolute;
6702: right: 1em;
6703: }
6704:
6705: table.LC_prior_tries {
6706: border: 1px solid #000000;
6707: border-collapse: separate;
6708: border-spacing: 1px;
6709: }
6710:
6711: table.LC_prior_tries td {
6712: padding: 2px;
6713: }
6714:
6715: .LC_answer_correct {
6716: background: lightgreen;
6717: color: darkgreen;
6718: padding: 6px;
6719: }
6720:
6721: .LC_answer_charged_try {
6722: background: #FFAAAA;
6723: color: darkred;
6724: padding: 6px;
6725: }
6726:
6727: .LC_answer_not_charged_try,
6728: .LC_answer_no_grade,
6729: .LC_answer_late {
6730: background: lightyellow;
6731: color: black;
6732: padding: 6px;
6733: }
6734:
6735: .LC_answer_previous {
6736: background: lightblue;
6737: color: darkblue;
6738: padding: 6px;
6739: }
6740:
6741: .LC_answer_no_message {
6742: background: #FFFFFF;
6743: color: black;
6744: padding: 6px;
6745: }
6746:
6747: .LC_answer_unknown {
6748: background: orange;
6749: color: black;
6750: padding: 6px;
6751: }
6752:
6753: span.LC_prior_numerical,
6754: span.LC_prior_string,
6755: span.LC_prior_custom,
6756: span.LC_prior_reaction,
6757: span.LC_prior_math {
6758: font-family: $mono;
6759: white-space: pre;
6760: }
6761:
6762: span.LC_prior_string {
6763: font-family: $mono;
6764: white-space: pre;
6765: }
6766:
6767: table.LC_prior_option {
6768: width: 100%;
6769: border-collapse: collapse;
6770: }
6771:
6772: table.LC_prior_rank,
6773: table.LC_prior_match {
6774: border-collapse: collapse;
6775: }
6776:
6777: table.LC_prior_option tr td,
6778: table.LC_prior_rank tr td,
6779: table.LC_prior_match tr td {
6780: border: 1px solid #000000;
6781: }
6782:
6783: .LC_nobreak {
6784: white-space: nowrap;
6785: }
6786:
6787: span.LC_cusr_emph {
6788: font-style: italic;
6789: }
6790:
6791: span.LC_cusr_subheading {
6792: font-weight: normal;
6793: font-size: 85%;
6794: }
6795:
6796: div.LC_docs_entry_move {
6797: border: 1px solid #BBBBBB;
6798: background: #DDDDDD;
6799: width: 22px;
6800: padding: 1px;
6801: margin: 0;
6802: }
6803:
6804: table.LC_data_table tr > td.LC_docs_entry_commands,
6805: table.LC_data_table tr > td.LC_docs_entry_parameter {
6806: font-size: x-small;
6807: }
6808:
6809: .LC_docs_entry_parameter {
6810: white-space: nowrap;
6811: }
6812:
6813: .LC_docs_copy {
6814: color: #000099;
6815: }
6816:
6817: .LC_docs_cut {
6818: color: #550044;
6819: }
6820:
6821: .LC_docs_rename {
6822: color: #009900;
6823: }
6824:
6825: .LC_docs_remove {
6826: color: #990000;
6827: }
6828:
6829: .LC_docs_reinit_warn,
6830: .LC_docs_ext_edit {
6831: font-size: x-small;
6832: }
6833:
6834: table.LC_docs_adddocs td,
6835: table.LC_docs_adddocs th {
6836: border: 1px solid #BBBBBB;
6837: padding: 4px;
6838: background: #DDDDDD;
6839: }
6840:
6841: table.LC_sty_begin {
6842: background: #BBFFBB;
6843: }
6844:
6845: table.LC_sty_end {
6846: background: #FFBBBB;
6847: }
6848:
6849: table.LC_double_column {
6850: border-width: 0;
6851: border-collapse: collapse;
6852: width: 100%;
6853: padding: 2px;
6854: }
6855:
6856: table.LC_double_column tr td.LC_left_col {
6857: top: 2px;
6858: left: 2px;
6859: width: 47%;
6860: vertical-align: top;
6861: }
6862:
6863: table.LC_double_column tr td.LC_right_col {
6864: top: 2px;
6865: right: 2px;
6866: width: 47%;
6867: vertical-align: top;
6868: }
6869:
6870: div.LC_left_float {
6871: float: left;
6872: padding-right: 5%;
6873: padding-bottom: 4px;
6874: }
6875:
6876: div.LC_clear_float_header {
6877: padding-bottom: 2px;
6878: }
6879:
6880: div.LC_clear_float_footer {
6881: padding-top: 10px;
6882: clear: both;
6883: }
6884:
6885: div.LC_grade_show_user {
6886: /* border-left: 5px solid $sidebg; */
6887: border-top: 5px solid #000000;
6888: margin: 50px 0 0 0;
6889: padding: 15px 0 5px 10px;
6890: }
6891:
6892: div.LC_grade_show_user_odd_row {
6893: /* border-left: 5px solid #000000; */
6894: }
6895:
6896: div.LC_grade_show_user div.LC_Box {
6897: margin-right: 50px;
6898: }
6899:
6900: div.LC_grade_submissions,
6901: div.LC_grade_message_center,
6902: div.LC_grade_info_links {
6903: margin: 5px;
6904: width: 99%;
6905: background: #FFFFFF;
6906: }
6907:
6908: div.LC_grade_submissions_header,
6909: div.LC_grade_message_center_header {
6910: font-weight: bold;
6911: font-size: large;
6912: }
6913:
6914: div.LC_grade_submissions_body,
6915: div.LC_grade_message_center_body {
6916: border: 1px solid black;
6917: width: 99%;
6918: background: #FFFFFF;
6919: }
6920:
6921: table.LC_scantron_action {
6922: width: 100%;
6923: }
6924:
6925: table.LC_scantron_action tr th {
6926: font-weight:bold;
6927: font-style:normal;
6928: }
6929:
6930: .LC_edit_problem_header,
6931: div.LC_edit_problem_footer {
6932: font-weight: normal;
6933: font-size: medium;
6934: margin: 2px;
6935: background-color: $sidebg;
6936: }
6937:
6938: div.LC_edit_problem_header,
6939: div.LC_edit_problem_header div,
6940: div.LC_edit_problem_footer,
6941: div.LC_edit_problem_footer div,
6942: div.LC_edit_problem_editxml_header,
6943: div.LC_edit_problem_editxml_header div {
6944: z-index: 100;
6945: }
6946:
6947: div.LC_edit_problem_header_title {
6948: font-weight: bold;
6949: font-size: larger;
6950: background: $tabbg;
6951: padding: 3px;
6952: margin: 0 0 5px 0;
6953: }
6954:
6955: table.LC_edit_problem_header_title {
6956: width: 100%;
6957: background: $tabbg;
6958: }
6959:
6960: div.LC_edit_actionbar {
6961: background-color: $sidebg;
6962: margin: 0;
6963: padding: 0;
6964: line-height: 200%;
6965: }
6966:
6967: div.LC_edit_actionbar div{
6968: padding: 0;
6969: margin: 0;
6970: display: inline-block;
6971: }
6972:
6973: .LC_edit_opt {
6974: padding-left: 1em;
6975: white-space: nowrap;
6976: }
6977:
6978: .LC_edit_problem_latexhelper{
6979: text-align: right;
6980: }
6981:
6982: #LC_edit_problem_colorful div{
6983: margin-left: 40px;
6984: }
6985:
6986: #LC_edit_problem_codemirror div{
6987: margin-left: 0px;
6988: }
6989:
6990: img.stift {
6991: border-width: 0;
6992: vertical-align: middle;
6993: }
6994:
6995: table td.LC_mainmenu_col_fieldset {
6996: vertical-align: top;
6997: }
6998:
6999: div.LC_createcourse {
7000: margin: 10px 10px 10px 10px;
7001: }
7002:
7003: .LC_dccid {
7004: float: right;
7005: margin: 0.2em 0 0 0;
7006: padding: 0;
7007: font-size: 90%;
7008: display:none;
7009: }
7010:
7011: ol.LC_primary_menu a:hover,
7012: ol#LC_MenuBreadcrumbs a:hover,
7013: ol#LC_PathBreadcrumbs a:hover,
7014: ul#LC_secondary_menu a:hover,
7015: .LC_FormSectionClearButton input:hover
7016: ul.LC_TabContent li:hover a {
7017: color:$button_hover;
7018: text-decoration:none;
7019: }
7020:
7021: h1 {
7022: padding: 0;
7023: line-height:130%;
7024: }
7025:
7026: h2,
7027: h3,
7028: h4,
7029: h5,
7030: h6 {
7031: margin: 5px 0 5px 0;
7032: padding: 0;
7033: line-height:130%;
7034: }
7035:
7036: .LC_hcell {
7037: padding:3px 15px 3px 15px;
7038: margin: 0;
7039: background-color:$tabbg;
7040: color:$fontmenu;
7041: border-bottom:solid 1px $lg_border_color;
7042: }
7043:
7044: .LC_Box > .LC_hcell {
7045: margin: 0 -10px 10px -10px;
7046: }
7047:
7048: .LC_noBorder {
7049: border: 0;
7050: }
7051:
7052: .LC_FormSectionClearButton input {
7053: background-color:transparent;
7054: border: none;
7055: cursor:pointer;
7056: text-decoration:underline;
7057: }
7058:
7059: .LC_help_open_topic {
7060: color: #FFFFFF;
7061: background-color: #EEEEFF;
7062: margin: 1px;
7063: padding: 4px;
7064: border: 1px solid #000033;
7065: white-space: nowrap;
7066: /* vertical-align: middle; */
7067: }
7068:
7069: dl,
7070: ul,
7071: div,
7072: fieldset {
7073: margin: 10px 10px 10px 0;
7074: /* overflow: hidden; */
7075: }
7076:
7077: article.geogebraweb div {
7078: margin: 0;
7079: }
7080:
7081: fieldset > legend {
7082: font-weight: bold;
7083: padding: 0 5px 0 5px;
7084: }
7085:
7086: #LC_nav_bar {
7087: float: left;
7088: background-color: $pgbg_or_bgcolor;
7089: margin: 0 0 2px 0;
7090: }
7091:
7092: #LC_realm {
7093: margin: 0.2em 0 0 0;
7094: padding: 0;
7095: font-weight: bold;
7096: text-align: center;
7097: background-color: $pgbg_or_bgcolor;
7098: }
7099:
7100: #LC_nav_bar em {
7101: font-weight: bold;
7102: font-style: normal;
7103: }
7104:
7105: ol.LC_primary_menu {
7106: margin: 0;
7107: padding: 0;
7108: }
7109:
7110: ol#LC_PathBreadcrumbs {
7111: margin: 0;
7112: }
7113:
7114: ol.LC_primary_menu li {
7115: color: RGB(80, 80, 80);
7116: vertical-align: middle;
7117: text-align: left;
7118: list-style: none;
7119: position: relative;
7120: float: left;
7121: z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
7122: line-height: 1.5em;
7123: }
7124:
7125: ol.LC_primary_menu li a,
7126: ol.LC_primary_menu li p {
7127: display: block;
7128: margin: 0;
7129: padding: 0 5px 0 10px;
7130: text-decoration: none;
7131: }
7132:
7133: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
7134: display: inline-block;
7135: width: 95%;
7136: text-align: left;
7137: }
7138:
7139: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
7140: display: inline-block;
7141: width: 5%;
7142: float: right;
7143: text-align: right;
7144: font-size: 70%;
7145: }
7146:
7147: ol.LC_primary_menu ul {
7148: display: none;
7149: width: 15em;
7150: background-color: $data_table_light;
7151: position: absolute;
7152: top: 100%;
7153: }
7154:
7155: ol.LC_primary_menu ul ul {
7156: left: 100%;
7157: top: 0;
7158: }
7159:
7160: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
7161: display: block;
7162: position: absolute;
7163: margin: 0;
7164: padding: 0;
7165: z-index: 2;
7166: }
7167:
7168: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
7169: /* First Submenu -> size should be smaller than the menu title of the whole menu */
7170: font-size: 90%;
7171: vertical-align: top;
7172: float: none;
7173: border-left: 1px solid black;
7174: border-right: 1px solid black;
7175: /* A dark bottom border to visualize different menu options;
7176: overwritten in the create_submenu routine for the last border-bottom of the menu */
7177: border-bottom: 1px solid $data_table_dark;
7178: }
7179:
7180: ol.LC_primary_menu li li p:hover {
7181: color:$button_hover;
7182: text-decoration:none;
7183: background-color:$data_table_dark;
7184: }
7185:
7186: ol.LC_primary_menu li li a:hover {
7187: color:$button_hover;
7188: background-color:$data_table_dark;
7189: }
7190:
7191: /* Font-size equal to the size of the predecessors*/
7192: ol.LC_primary_menu li:hover li li {
7193: font-size: 100%;
7194: }
7195:
7196: ol.LC_primary_menu li img {
7197: vertical-align: bottom;
7198: height: 1.1em;
7199: margin: 0.2em 0 0 0;
7200: }
7201:
7202: ol.LC_primary_menu a {
7203: color: RGB(80, 80, 80);
7204: text-decoration: none;
7205: }
7206:
7207: ol.LC_primary_menu a.LC_new_message {
7208: font-weight:bold;
7209: color: darkred;
7210: }
7211:
7212: ol.LC_docs_parameters {
7213: margin-left: 0;
7214: padding: 0;
7215: list-style: none;
7216: }
7217:
7218: ol.LC_docs_parameters li {
7219: margin: 0;
7220: padding-right: 20px;
7221: display: inline;
7222: }
7223:
7224: ol.LC_docs_parameters li:before {
7225: content: "\\002022 \\0020";
7226: }
7227:
7228: li.LC_docs_parameters_title {
7229: font-weight: bold;
7230: }
7231:
7232: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
7233: content: "";
7234: }
7235:
7236: ul#LC_secondary_menu {
7237: clear: right;
7238: color: $fontmenu;
7239: background: $tabbg;
7240: list-style: none;
7241: padding: 0;
7242: margin: 0;
7243: width: 100%;
7244: text-align: left;
7245: float: left;
7246: }
7247:
7248: ul#LC_secondary_menu li {
7249: font-weight: bold;
7250: line-height: 1.8em;
7251: border-right: 1px solid black;
7252: float: left;
7253: }
7254:
7255: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
7256: background-color: $data_table_light;
7257: }
7258:
7259: ul#LC_secondary_menu li a {
7260: padding: 0 0.8em;
7261: }
7262:
7263: ul#LC_secondary_menu li ul {
7264: display: none;
7265: }
7266:
7267: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
7268: display: block;
7269: position: absolute;
7270: margin: 0;
7271: padding: 0;
7272: list-style:none;
7273: float: none;
7274: background-color: $data_table_light;
7275: z-index: 2;
7276: margin-left: -1px;
7277: }
7278:
7279: ul#LC_secondary_menu li ul li {
7280: font-size: 90%;
7281: vertical-align: top;
7282: border-left: 1px solid black;
7283: border-right: 1px solid black;
7284: background-color: $data_table_light;
7285: list-style:none;
7286: float: none;
7287: }
7288:
7289: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
7290: background-color: $data_table_dark;
7291: }
7292:
7293: ul.LC_TabContent {
7294: display:block;
7295: background: $sidebg;
7296: border-bottom: solid 1px $lg_border_color;
7297: list-style:none;
7298: margin: -1px -10px 0 -10px;
7299: padding: 0;
7300: }
7301:
7302: ul.LC_TabContent li,
7303: ul.LC_TabContentBigger li {
7304: float:left;
7305: }
7306:
7307: ul#LC_secondary_menu li a {
7308: color: $fontmenu;
7309: text-decoration: none;
7310: }
7311:
7312: ul.LC_TabContent {
7313: min-height:20px;
7314: }
7315:
7316: ul.LC_TabContent li {
7317: vertical-align:middle;
7318: padding: 0 16px 0 10px;
7319: background-color:$tabbg;
7320: border-bottom:solid 1px $lg_border_color;
7321: border-left: solid 1px $font;
7322: }
7323:
7324: ul.LC_TabContent .right {
7325: float:right;
7326: }
7327:
7328: ul.LC_TabContent li a,
7329: ul.LC_TabContent li {
7330: color:rgb(47,47,47);
7331: text-decoration:none;
7332: font-size:95%;
7333: font-weight:bold;
7334: min-height:20px;
7335: }
7336:
7337: ul.LC_TabContent li a:hover,
7338: ul.LC_TabContent li a:focus {
7339: color: $button_hover;
7340: background:none;
7341: outline:none;
7342: }
7343:
7344: ul.LC_TabContent li:hover {
7345: color: $button_hover;
7346: cursor:pointer;
7347: }
7348:
7349: ul.LC_TabContent li.active {
7350: color: $font;
7351: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
7352: border-bottom:solid 1px #FFFFFF;
7353: cursor: default;
7354: }
7355:
7356: ul.LC_TabContent li.active a {
7357: color:$font;
7358: background:#FFFFFF;
7359: outline: none;
7360: }
7361:
7362: ul.LC_TabContent li.goback {
7363: float: left;
7364: border-left: none;
7365: }
7366:
7367: #maincoursedoc {
7368: clear:both;
7369: }
7370:
7371: ul.LC_TabContentBigger {
7372: display:block;
7373: list-style:none;
7374: padding: 0;
7375: }
7376:
7377: ul.LC_TabContentBigger li {
7378: vertical-align:bottom;
7379: height: 30px;
7380: font-size:110%;
7381: font-weight:bold;
7382: color: #737373;
7383: }
7384:
7385: ul.LC_TabContentBigger li.active {
7386: position: relative;
7387: top: 1px;
7388: }
7389:
7390: ul.LC_TabContentBigger li a {
7391: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
7392: height: 30px;
7393: line-height: 30px;
7394: text-align: center;
7395: display: block;
7396: text-decoration: none;
7397: outline: none;
7398: }
7399:
7400: ul.LC_TabContentBigger li.active a {
7401: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
7402: color:$font;
7403: }
7404:
7405: ul.LC_TabContentBigger li b {
7406: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
7407: display: block;
7408: float: left;
7409: padding: 0 30px;
7410: border-bottom: 1px solid $lg_border_color;
7411: }
7412:
7413: ul.LC_TabContentBigger li:hover b {
7414: color:$button_hover;
7415: }
7416:
7417: ul.LC_TabContentBigger li.active b {
7418: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
7419: color:$font;
7420: border: 0;
7421: }
7422:
7423:
7424: ul.LC_CourseBreadcrumbs {
7425: background: $sidebg;
7426: height: 2em;
7427: padding-left: 10px;
7428: margin: 0;
7429: list-style-position: inside;
7430: }
7431:
7432: ol#LC_MenuBreadcrumbs,
7433: ol#LC_PathBreadcrumbs {
7434: padding-left: 10px;
7435: margin: 0;
7436: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
7437: }
7438:
7439: ol#LC_MenuBreadcrumbs li,
7440: ol#LC_PathBreadcrumbs li,
7441: ul.LC_CourseBreadcrumbs li {
7442: display: inline;
7443: white-space: normal;
7444: }
7445:
7446: ol#LC_MenuBreadcrumbs li a,
7447: ul.LC_CourseBreadcrumbs li a {
7448: text-decoration: none;
7449: font-size:90%;
7450: }
7451:
7452: ol#LC_MenuBreadcrumbs h1 {
7453: display: inline;
7454: font-size: 90%;
7455: line-height: 2.5em;
7456: margin: 0;
7457: padding: 0;
7458: }
7459:
7460: ol#LC_PathBreadcrumbs li a {
7461: text-decoration:none;
7462: font-size:100%;
7463: font-weight:bold;
7464: }
7465:
7466: .LC_Box {
7467: border: solid 1px $lg_border_color;
7468: padding: 0 10px 10px 10px;
7469: }
7470:
7471: .LC_DocsBox {
7472: border: solid 1px $lg_border_color;
7473: padding: 0 0 10px 10px;
7474: }
7475:
7476: .LC_AboutMe_Image {
7477: float:left;
7478: margin-right:10px;
7479: }
7480:
7481: .LC_Clear_AboutMe_Image {
7482: clear:left;
7483: }
7484:
7485: dl.LC_ListStyleClean dt {
7486: padding-right: 5px;
7487: display: table-header-group;
7488: }
7489:
7490: dl.LC_ListStyleClean dd {
7491: display: table-row;
7492: }
7493:
7494: .LC_ListStyleClean,
7495: .LC_ListStyleSimple,
7496: .LC_ListStyleNormal,
7497: .LC_ListStyleSpecial {
7498: /* display:block; */
7499: list-style-position: inside;
7500: list-style-type: none;
7501: overflow: hidden;
7502: padding: 0;
7503: }
7504:
7505: .LC_ListStyleSimple li,
7506: .LC_ListStyleSimple dd,
7507: .LC_ListStyleNormal li,
7508: .LC_ListStyleNormal dd,
7509: .LC_ListStyleSpecial li,
7510: .LC_ListStyleSpecial dd {
7511: margin: 0;
7512: padding: 5px 5px 5px 10px;
7513: clear: both;
7514: }
7515:
7516: .LC_ListStyleClean li,
7517: .LC_ListStyleClean dd {
7518: padding-top: 0;
7519: padding-bottom: 0;
7520: }
7521:
7522: .LC_ListStyleSimple dd,
7523: .LC_ListStyleSimple li {
7524: border-bottom: solid 1px $lg_border_color;
7525: }
7526:
7527: .LC_ListStyleSpecial li,
7528: .LC_ListStyleSpecial dd {
7529: list-style-type: none;
7530: background-color: RGB(220, 220, 220);
7531: margin-bottom: 4px;
7532: }
7533:
7534: table.LC_SimpleTable {
7535: margin:5px;
7536: border:solid 1px $lg_border_color;
7537: }
7538:
7539: table.LC_SimpleTable tr {
7540: padding: 0;
7541: border:solid 1px $lg_border_color;
7542: }
7543:
7544: table.LC_SimpleTable thead {
7545: background:rgb(220,220,220);
7546: }
7547:
7548: div.LC_columnSection {
7549: display: block;
7550: clear: both;
7551: overflow: hidden;
7552: margin: 0;
7553: }
7554:
7555: div.LC_columnSection>* {
7556: float: left;
7557: margin: 10px 20px 10px 0;
7558: overflow:hidden;
7559: }
7560:
7561: table em {
7562: font-weight: bold;
7563: font-style: normal;
7564: }
7565:
7566: table.LC_tableBrowseRes,
7567: table.LC_tableOfContent {
7568: border:none;
7569: border-spacing: 1px;
7570: padding: 3px;
7571: background-color: #FFFFFF;
7572: font-size: 90%;
7573: }
7574:
7575: table.LC_tableOfContent {
7576: border-collapse: collapse;
7577: }
7578:
7579: table.LC_tableBrowseRes a,
7580: table.LC_tableOfContent a {
7581: background-color: transparent;
7582: text-decoration: none;
7583: }
7584:
7585: table.LC_tableOfContent img {
7586: border: none;
7587: height: 1.3em;
7588: vertical-align: text-bottom;
7589: margin-right: 0.3em;
7590: }
7591:
7592: a#LC_content_toolbar_firsthomework {
7593: background-image:url(/res/adm/pages/open-first-problem.gif);
7594: }
7595:
7596: a#LC_content_toolbar_everything {
7597: background-image:url(/res/adm/pages/show-all.gif);
7598: }
7599:
7600: a#LC_content_toolbar_uncompleted {
7601: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
7602: }
7603:
7604: #LC_content_toolbar_clearbubbles {
7605: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
7606: }
7607:
7608: a#LC_content_toolbar_changefolder {
7609: background : url(/res/adm/pages/close-all-folders.gif) top center ;
7610: }
7611:
7612: a#LC_content_toolbar_changefolder_toggled {
7613: background-image:url(/res/adm/pages/open-all-folders.gif);
7614: }
7615:
7616: a#LC_content_toolbar_edittoplevel {
7617: background-image:url(/res/adm/pages/edittoplevel.gif);
7618: }
7619:
7620: ul#LC_toolbar li a:hover {
7621: background-position: bottom center;
7622: }
7623:
7624: ul#LC_toolbar {
7625: padding: 0;
7626: margin: 2px;
7627: list-style:none;
7628: position:relative;
7629: background-color:white;
7630: overflow: auto;
7631: }
7632:
7633: ul#LC_toolbar li {
7634: border:1px solid white;
7635: padding: 0;
7636: margin: 0;
7637: float: left;
7638: display:inline;
7639: vertical-align:middle;
7640: white-space: nowrap;
7641: }
7642:
7643:
7644: a.LC_toolbarItem {
7645: display:block;
7646: padding: 0;
7647: margin: 0;
7648: height: 32px;
7649: width: 32px;
7650: color:white;
7651: border: none;
7652: background-repeat:no-repeat;
7653: background-color:transparent;
7654: }
7655:
7656: ul.LC_funclist {
7657: margin: 0;
7658: padding: 0.5em 1em 0.5em 0;
7659: }
7660:
7661: ul.LC_funclist > li:first-child {
7662: font-weight:bold;
7663: margin-left:0.8em;
7664: }
7665:
7666: ul.LC_funclist + ul.LC_funclist {
7667: /*
7668: left border as a seperator if we have more than
7669: one list
7670: */
7671: border-left: 1px solid $sidebg;
7672: /*
7673: this hides the left border behind the border of the
7674: outer box if element is wrapped to the next 'line'
7675: */
7676: margin-left: -1px;
7677: }
7678:
7679: ul.LC_funclist li {
7680: display: inline;
7681: white-space: nowrap;
7682: margin: 0 0 0 25px;
7683: line-height: 150%;
7684: }
7685:
7686: .LC_hidden {
7687: display: none;
7688: }
7689:
7690: .LCmodal-overlay {
7691: position:fixed;
7692: top:0;
7693: right:0;
7694: bottom:0;
7695: left:0;
7696: height:100%;
7697: width:100%;
7698: margin:0;
7699: padding:0;
7700: background:#999;
7701: opacity:.75;
7702: filter: alpha(opacity=75);
7703: -moz-opacity: 0.75;
7704: z-index:101;
7705: }
7706:
7707: * html .LCmodal-overlay {
7708: position: absolute;
7709: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
7710: }
7711:
7712: .LCmodal-window {
7713: position:fixed;
7714: top:50%;
7715: left:50%;
7716: margin:0;
7717: padding:0;
7718: z-index:102;
7719: }
7720:
7721: * html .LCmodal-window {
7722: position:absolute;
7723: }
7724:
7725: .LCclose-window {
7726: position:absolute;
7727: width:32px;
7728: height:32px;
7729: right:8px;
7730: top:8px;
7731: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
7732: text-indent:-99999px;
7733: overflow:hidden;
7734: cursor:pointer;
7735: }
7736:
7737: /*
7738: styles used by TTH when "Default set of options to pass to tth/m
7739: when converting TeX" in course settings has been set
7740:
7741: option passed: -t
7742:
7743: */
7744:
7745: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
7746: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
7747: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
7748: td div.norm {line-height:normal;}
7749:
7750: /*
7751: option passed -y3
7752: */
7753:
7754: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
7755: span.overacc2 {position: relative; left: .8em; top: -1.2ex;}
7756: span.overacc1 {position: relative; left: .6em; top: -1.2ex;}
7757:
7758: #LC_minitab_header {
7759: float:left;
7760: width:100%;
7761: background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
7762: font-size:93%;
7763: line-height:normal;
7764: margin: 0.5em 0 0.5em 0;
7765: }
7766: #LC_minitab_header ul {
7767: margin:0;
7768: padding:10px 10px 0;
7769: list-style:none;
7770: }
7771: #LC_minitab_header li {
7772: float:left;
7773: background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
7774: margin:0;
7775: padding:0 0 0 9px;
7776: }
7777: #LC_minitab_header a {
7778: display:block;
7779: background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
7780: padding:5px 15px 4px 6px;
7781: }
7782: #LC_minitab_header #LC_current_minitab {
7783: background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
7784: }
7785: #LC_minitab_header #LC_current_minitab a {
7786: background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
7787: padding-bottom:5px;
7788: }
7789:
7790:
7791: END
7792: }
7793:
7794: =pod
7795:
7796: =item * &headtag()
7797:
7798: Returns a uniform footer for LON-CAPA web pages.
7799:
7800: Inputs: $title - optional title for the head
7801: $head_extra - optional extra HTML to put inside the <head>
7802: $args - optional arguments
7803: force_register - if is true call registerurl so the remote is
7804: informed
7805: redirect -> array ref of
7806: 1- seconds before redirect occurs
7807: 2- url to redirect to
7808: 3- whether the side effect should occur
7809: (side effect of setting
7810: $env{'internal.head.redirect'} to the url
7811: redirected too)
7812: domain -> force to color decorate a page for a specific
7813: domain
7814: function -> force usage of a specific rolish color scheme
7815: bgcolor -> override the default page bgcolor
7816: no_auto_mt_title
7817: -> prevent &mt()ing the title arg
7818:
7819: =cut
7820:
7821: sub headtag {
7822: my ($title,$head_extra,$args) = @_;
7823:
7824: my $function = $args->{'function'} || &get_users_function();
7825: my $domain = $args->{'domain'} || &determinedomain();
7826: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
7827: my $httphost = $args->{'use_absolute'};
7828: my $url = join(':',$env{'user.name'},$env{'user.domain'},
7829: $Apache::lonnet::perlvar{'lonVersion'},
7830: #time(),
7831: $env{'environment.color.timestamp'},
7832: $function,$domain,$bgcolor);
7833:
7834: $url = '/adm/css/'.&escape($url).'.css';
7835:
7836: my $result =
7837: '<head>'.
7838: &font_settings($args);
7839:
7840: my $inhibitprint;
7841: if ($args->{'print_suppress'}) {
7842: $inhibitprint = &print_suppression();
7843: }
7844:
7845: if (!$args->{'frameset'}) {
7846: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
7847: }
7848: if ($args->{'force_register'}) {
7849: $result .= &Apache::lonmenu::registerurl(1);
7850: }
7851: if (!$args->{'no_nav_bar'}
7852: && !$args->{'only_body'}
7853: && !$args->{'frameset'}) {
7854: $result .= &help_menu_js($httphost);
7855: $result.=&modal_window();
7856: $result.=&togglebox_script();
7857: $result.=&wishlist_window();
7858: $result.=&LCprogressbarUpdate_script();
7859: } else {
7860: if ($args->{'add_modal'}) {
7861: $result.=&modal_window();
7862: }
7863: if ($args->{'add_wishlist'}) {
7864: $result.=&wishlist_window();
7865: }
7866: if ($args->{'add_togglebox'}) {
7867: $result.=&togglebox_script();
7868: }
7869: if ($args->{'add_progressbar'}) {
7870: $result.=&LCprogressbarUpdate_script();
7871: }
7872: }
7873: if (ref($args->{'redirect'})) {
7874: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
7875: $url = &Apache::lonenc::check_encrypt($url);
7876: if (!$inhibit_continue) {
7877: $env{'internal.head.redirect'} = $url;
7878: }
7879: $result.=<<ADDMETA
7880: <meta http-equiv="pragma" content="no-cache" />
7881: <meta http-equiv="Refresh" content="$time; url=$url" />
7882: ADDMETA
7883: } else {
7884: unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
7885: my $requrl = $env{'request.uri'};
7886: if ($requrl eq '') {
7887: $requrl = $ENV{'REQUEST_URI'};
7888: $requrl =~ s/\?.+$//;
7889: }
7890: unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
7891: (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
7892: ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
7893: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
7894: unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
7895: my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
7896: if (ref($domdefs{'offloadnow'}) eq 'HASH') {
7897: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
7898: if ($domdefs{'offloadnow'}{$lonhost}) {
7899: my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
7900: if (($newserver) && ($newserver ne $lonhost)) {
7901: my $numsec = 5;
7902: my $timeout = $numsec * 1000;
7903: my ($newurl,$locknum,%locks,$msg);
7904: if ($env{'request.role.adv'}) {
7905: ($locknum,%locks) = &Apache::lonnet::get_locks();
7906: }
7907: my $disable_submit = 0;
7908: if ($requrl =~ /$LONCAPA::assess_re/) {
7909: $disable_submit = 1;
7910: }
7911: if ($locknum) {
7912: my @lockinfo = sort(values(%locks));
7913: $msg = &mt('Once the following tasks are complete: ')."\\n".
7914: join(", ",sort(values(%locks)))."\\n".
7915: &mt('your session will be transferred to a different server, after you click "Roles".');
7916: } else {
7917: if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
7918: $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
7919: }
7920: $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
7921: $newurl = '/adm/switchserver?otherserver='.$newserver;
7922: if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
7923: $newurl .= '&role='.$env{'request.role'};
7924: }
7925: if ($env{'request.symb'}) {
7926: $newurl .= '&symb='.$env{'request.symb'};
7927: } else {
7928: $newurl .= '&origurl='.$requrl;
7929: }
7930: }
7931: &js_escape(\$msg);
7932: $result.=<<OFFLOAD
7933: <meta http-equiv="pragma" content="no-cache" />
7934: <script type="text/javascript">
7935: // <![CDATA[
7936: function LC_Offload_Now() {
7937: var dest = "$newurl";
7938: if (dest != '') {
7939: window.location.href="$newurl";
7940: }
7941: }
7942: \$(document).ready(function () {
7943: window.alert('$msg');
7944: if ($disable_submit) {
7945: \$(".LC_hwk_submit").prop("disabled", true);
7946: \$( ".LC_textline" ).prop( "readonly", "readonly");
7947: }
7948: setTimeout('LC_Offload_Now()', $timeout);
7949: });
7950: // ]]>
7951: </script>
7952: OFFLOAD
7953: }
7954: }
7955: }
7956: }
7957: }
7958: }
7959: }
7960: if (!defined($title)) {
7961: $title = 'The LearningOnline Network with CAPA';
7962: }
7963: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
7964: $result .= '<title> LON-CAPA '.$title.'</title>'
7965: .'<link rel="stylesheet" type="text/css" href="'.$url.'"';
7966: if (!$args->{'frameset'}) {
7967: $result .= ' /';
7968: }
7969: $result .= '>'
7970: .$inhibitprint
7971: .$head_extra;
7972: my $clientmobile;
7973: if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
7974: (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
7975: } else {
7976: $clientmobile = $env{'browser.mobile'};
7977: }
7978: if ($clientmobile) {
7979: $result .= '
7980: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
7981: <meta name="apple-mobile-web-app-capable" content="yes" />';
7982: }
7983: $result .= '<meta name="google" content="notranslate" />'."\n";
7984: return $result.'</head>';
7985: }
7986:
7987: =pod
7988:
7989: =item * &font_settings()
7990:
7991: Returns neccessary <meta> to set the proper encoding
7992:
7993: Inputs: optional reference to HASH -- $args passed to &headtag()
7994:
7995: =cut
7996:
7997: sub font_settings {
7998: my ($args) = @_;
7999: my $headerstring='';
8000: if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
8001: ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
8002: $headerstring.=
8003: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
8004: if (!$args->{'frameset'}) {
8005: $headerstring.= ' /';
8006: }
8007: $headerstring .= '>'."\n";
8008: }
8009: return $headerstring;
8010: }
8011:
8012: =pod
8013:
8014: =item * &print_suppression()
8015:
8016: In course context returns css which causes the body to be blank when media="print",
8017: if printout generation is unavailable for the current resource.
8018:
8019: This could be because:
8020:
8021: (a) printstartdate is in the future
8022:
8023: (b) printenddate is in the past
8024:
8025: (c) there is an active exam block with "printout"
8026: functionality blocked
8027:
8028: Users with pav, pfo or evb privileges are exempt.
8029:
8030: Inputs: none
8031:
8032: =cut
8033:
8034:
8035: sub print_suppression {
8036: my $noprint;
8037: if ($env{'request.course.id'}) {
8038: my $scope = $env{'request.course.id'};
8039: if ((&Apache::lonnet::allowed('pav',$scope)) ||
8040: (&Apache::lonnet::allowed('pfo',$scope))) {
8041: return;
8042: }
8043: if ($env{'request.course.sec'} ne '') {
8044: $scope .= "/$env{'request.course.sec'}";
8045: if ((&Apache::lonnet::allowed('pav',$scope)) ||
8046: (&Apache::lonnet::allowed('pfo',$scope))) {
8047: return;
8048: }
8049: }
8050: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8051: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8052: my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
8053: if ($blocked) {
8054: my $checkrole = "cm./$cdom/$cnum";
8055: if ($env{'request.course.sec'} ne '') {
8056: $checkrole .= "/$env{'request.course.sec'}";
8057: }
8058: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
8059: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
8060: $noprint = 1;
8061: }
8062: }
8063: unless ($noprint) {
8064: my $symb = &Apache::lonnet::symbread();
8065: if ($symb ne '') {
8066: my $navmap = Apache::lonnavmaps::navmap->new();
8067: if (ref($navmap)) {
8068: my $res = $navmap->getBySymb($symb);
8069: if (ref($res)) {
8070: if (!$res->resprintable()) {
8071: $noprint = 1;
8072: }
8073: }
8074: }
8075: }
8076: }
8077: if ($noprint) {
8078: return <<"ENDSTYLE";
8079: <style type="text/css" media="print">
8080: body { display:none }
8081: </style>
8082: ENDSTYLE
8083: }
8084: }
8085: return;
8086: }
8087:
8088: =pod
8089:
8090: =item * &xml_begin()
8091:
8092: Returns the needed doctype and <html>
8093:
8094: Inputs: none
8095:
8096: =cut
8097:
8098: sub xml_begin {
8099: my ($is_frameset) = @_;
8100: my $output='';
8101:
8102: if ($env{'browser.mathml'}) {
8103: $output='<?xml version="1.0"?>'
8104: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
8105: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
8106:
8107: # .'<!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">] >'
8108: .'<!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">'
8109: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
8110: .'xmlns="http://www.w3.org/1999/xhtml">';
8111: } elsif ($is_frameset) {
8112: $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
8113: '<html>'."\n";
8114: } else {
8115: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
8116: '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
8117: }
8118: return $output;
8119: }
8120:
8121: =pod
8122:
8123: =item * &start_page()
8124:
8125: Returns a complete <html> .. <body> section for LON-CAPA web pages.
8126:
8127: Inputs:
8128:
8129: =over 4
8130:
8131: $title - optional title for the page
8132:
8133: $head_extra - optional extra HTML to incude inside the <head>
8134:
8135: $args - additional optional args supported are:
8136:
8137: =over 8
8138:
8139: only_body -> is true will set &bodytag() onlybodytag
8140: arg on
8141: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
8142: add_entries -> additional attributes to add to the <body>
8143: domain -> force to color decorate a page for a
8144: specific domain
8145: function -> force usage of a specific rolish color
8146: scheme
8147: redirect -> see &headtag()
8148: bgcolor -> override the default page bg color
8149: js_ready -> return a string ready for being used in
8150: a javascript writeln
8151: html_encode -> return a string ready for being used in
8152: a html attribute
8153: force_register -> if is true will turn on the &bodytag()
8154: $forcereg arg
8155: frameset -> if true will start with a <frameset>
8156: rather than <body>
8157: skip_phases -> hash ref of
8158: head -> skip the <html><head> generation
8159: body -> skip all <body> generation
8160: no_inline_link -> if true and in remote mode, don't show the
8161: 'Switch To Inline Menu' link
8162: no_auto_mt_title -> prevent &mt()ing the title arg
8163: bread_crumbs -> Array containing breadcrumbs
8164: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
8165: bread_crumbs_nomenu -> if true will pass false as the value of $menulink
8166: to lonhtmlcommon::breadcrumbs
8167: group -> includes the current group, if page is for a
8168: specific group
8169:
8170: =back
8171:
8172: =back
8173:
8174: =cut
8175:
8176: sub start_page {
8177: my ($title,$head_extra,$args) = @_;
8178: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
8179:
8180: $env{'internal.start_page'}++;
8181: my ($result,@advtools);
8182:
8183: if (! exists($args->{'skip_phases'}{'head'}) ) {
8184: $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
8185: }
8186:
8187: if (! exists($args->{'skip_phases'}{'body'}) ) {
8188: if ($args->{'frameset'}) {
8189: my $attr_string = &make_attr_string($args->{'force_register'},
8190: $args->{'add_entries'});
8191: $result .= "\n<frameset $attr_string>\n";
8192: } else {
8193: $result .=
8194: &bodytag($title,
8195: $args->{'function'}, $args->{'add_entries'},
8196: $args->{'only_body'}, $args->{'domain'},
8197: $args->{'force_register'}, $args->{'no_nav_bar'},
8198: $args->{'bgcolor'}, $args->{'no_inline_link'},
8199: $args, \@advtools);
8200: }
8201: }
8202:
8203: if ($args->{'js_ready'}) {
8204: $result = &js_ready($result);
8205: }
8206: if ($args->{'html_encode'}) {
8207: $result = &html_encode($result);
8208: }
8209:
8210: # Preparation for new and consistent functionlist at top of screen
8211: # if ($args->{'functionlist'}) {
8212: # $result .= &build_functionlist();
8213: #}
8214:
8215: # Don't add anything more if only_body wanted or in const space
8216: return $result if $args->{'only_body'}
8217: || $env{'request.state'} eq 'construct';
8218:
8219: #Breadcrumbs
8220: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
8221: &Apache::lonhtmlcommon::clear_breadcrumbs();
8222: #if any br links exists, add them to the breadcrumbs
8223: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
8224: foreach my $crumb (@{$args->{'bread_crumbs'}}){
8225: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
8226: }
8227: }
8228: # if @advtools array contains items add then to the breadcrumbs
8229: if (@advtools > 0) {
8230: &Apache::lonmenu::advtools_crumbs(@advtools);
8231: }
8232: my $menulink;
8233: # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
8234: if (exists($args->{'bread_crumbs_nomenu'})) {
8235: $menulink = 0;
8236: } else {
8237: undef($menulink);
8238: }
8239: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
8240: if(exists($args->{'bread_crumbs_component'})){
8241: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
8242: }else{
8243: $result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
8244: }
8245: } elsif (($env{'environment.remote'} eq 'on') &&
8246: ($env{'form.inhibitmenu'} ne 'yes') &&
8247: ($env{'request.noversionuri'} =~ m{^/res/}) &&
8248: ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
8249: $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
8250: }
8251: return $result;
8252: }
8253:
8254: sub end_page {
8255: my ($args) = @_;
8256: $env{'internal.end_page'}++;
8257: my $result;
8258: if ($args->{'discussion'}) {
8259: my ($target,$parser);
8260: if (ref($args->{'discussion'})) {
8261: ($target,$parser) =($args->{'discussion'}{'target'},
8262: $args->{'discussion'}{'parser'});
8263: }
8264: $result .= &Apache::lonxml::xmlend($target,$parser);
8265: }
8266: if ($args->{'frameset'}) {
8267: $result .= '</frameset>';
8268: } else {
8269: $result .= &endbodytag($args);
8270: }
8271: unless ($args->{'notbody'}) {
8272: $result .= "\n</html>";
8273: }
8274:
8275: if ($args->{'js_ready'}) {
8276: $result = &js_ready($result);
8277: }
8278:
8279: if ($args->{'html_encode'}) {
8280: $result = &html_encode($result);
8281: }
8282:
8283: return $result;
8284: }
8285:
8286: sub wishlist_window {
8287: return(<<'ENDWISHLIST');
8288: <script type="text/javascript">
8289: // <![CDATA[
8290: // <!-- BEGIN LON-CAPA Internal
8291: function set_wishlistlink(title, path) {
8292: if (!title) {
8293: title = document.title;
8294: title = title.replace(/^LON-CAPA /,'');
8295: }
8296: title = encodeURIComponent(title);
8297: title = title.replace("'","\\\'");
8298: if (!path) {
8299: path = location.pathname;
8300: }
8301: path = encodeURIComponent(path);
8302: path = path.replace("'","\\\'");
8303: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
8304: 'wishlistNewLink','width=560,height=350,scrollbars=0');
8305: }
8306: // END LON-CAPA Internal -->
8307: // ]]>
8308: </script>
8309: ENDWISHLIST
8310: }
8311:
8312: sub modal_window {
8313: return(<<'ENDMODAL');
8314: <script type="text/javascript">
8315: // <![CDATA[
8316: // <!-- BEGIN LON-CAPA Internal
8317: var modalWindow = {
8318: parent:"body",
8319: windowId:null,
8320: content:null,
8321: width:null,
8322: height:null,
8323: close:function()
8324: {
8325: $(".LCmodal-window").remove();
8326: $(".LCmodal-overlay").remove();
8327: },
8328: open:function()
8329: {
8330: var modal = "";
8331: modal += "<div class=\"LCmodal-overlay\"></div>";
8332: 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;\">";
8333: modal += this.content;
8334: modal += "</div>";
8335:
8336: $(this.parent).append(modal);
8337:
8338: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
8339: $(".LCclose-window").click(function(){modalWindow.close();});
8340: $(".LCmodal-overlay").click(function(){modalWindow.close();});
8341: }
8342: };
8343: var openMyModal = function(source,width,height,scrolling,transparency,style)
8344: {
8345: source = source.replace(/'/g,"'");
8346: modalWindow.windowId = "myModal";
8347: modalWindow.width = width;
8348: modalWindow.height = height;
8349: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
8350: modalWindow.open();
8351: };
8352: // END LON-CAPA Internal -->
8353: // ]]>
8354: </script>
8355: ENDMODAL
8356: }
8357:
8358: sub modal_link {
8359: my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
8360: unless ($width) { $width=480; }
8361: unless ($height) { $height=400; }
8362: unless ($scrolling) { $scrolling='yes'; }
8363: unless ($transparency) { $transparency='true'; }
8364:
8365: my $target_attr;
8366: if (defined($target)) {
8367: $target_attr = 'target="'.$target.'"';
8368: }
8369: return <<"ENDLINK";
8370: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
8371: $linktext</a>
8372: ENDLINK
8373: }
8374:
8375: sub modal_adhoc_script {
8376: my ($funcname,$width,$height,$content)=@_;
8377: return (<<ENDADHOC);
8378: <script type="text/javascript">
8379: // <![CDATA[
8380: var $funcname = function()
8381: {
8382: modalWindow.windowId = "myModal";
8383: modalWindow.width = $width;
8384: modalWindow.height = $height;
8385: modalWindow.content = '$content';
8386: modalWindow.open();
8387: };
8388: // ]]>
8389: </script>
8390: ENDADHOC
8391: }
8392:
8393: sub modal_adhoc_inner {
8394: my ($funcname,$width,$height,$content)=@_;
8395: my $innerwidth=$width-20;
8396: $content=&js_ready(
8397: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
8398: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
8399: $content.
8400: &end_scrollbox().
8401: &end_page()
8402: );
8403: return &modal_adhoc_script($funcname,$width,$height,$content);
8404: }
8405:
8406: sub modal_adhoc_window {
8407: my ($funcname,$width,$height,$content,$linktext)=@_;
8408: return &modal_adhoc_inner($funcname,$width,$height,$content).
8409: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
8410: }
8411:
8412: sub modal_adhoc_launch {
8413: my ($funcname,$width,$height,$content)=@_;
8414: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
8415: <script type="text/javascript">
8416: // <![CDATA[
8417: $funcname();
8418: // ]]>
8419: </script>
8420: ENDLAUNCH
8421: }
8422:
8423: sub modal_adhoc_close {
8424: return (<<ENDCLOSE);
8425: <script type="text/javascript">
8426: // <![CDATA[
8427: modalWindow.close();
8428: // ]]>
8429: </script>
8430: ENDCLOSE
8431: }
8432:
8433: sub togglebox_script {
8434: return(<<ENDTOGGLE);
8435: <script type="text/javascript">
8436: // <![CDATA[
8437: function LCtoggleDisplay(id,hidetext,showtext) {
8438: link = document.getElementById(id + "link").childNodes[0];
8439: with (document.getElementById(id).style) {
8440: if (display == "none" ) {
8441: display = "inline";
8442: link.nodeValue = hidetext;
8443: } else {
8444: display = "none";
8445: link.nodeValue = showtext;
8446: }
8447: }
8448: }
8449: // ]]>
8450: </script>
8451: ENDTOGGLE
8452: }
8453:
8454: sub start_togglebox {
8455: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
8456: unless ($heading) { $heading=''; } else { $heading.=' '; }
8457: unless ($showtext) { $showtext=&mt('show'); }
8458: unless ($hidetext) { $hidetext=&mt('hide'); }
8459: unless ($headerbg) { $headerbg='#FFFFFF'; }
8460: return &start_data_table().
8461: &start_data_table_header_row().
8462: '<td bgcolor="'.$headerbg.'">'.$heading.
8463: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
8464: $showtext.'\')">'.$showtext.'</a>]</td>'.
8465: &end_data_table_header_row().
8466: '<tr id="'.$id.'" style="display:none""><td>';
8467: }
8468:
8469: sub end_togglebox {
8470: return '</td></tr>'.&end_data_table();
8471: }
8472:
8473: sub LCprogressbar_script {
8474: my ($id)=@_;
8475: return(<<ENDPROGRESS);
8476: <script type="text/javascript">
8477: // <![CDATA[
8478: \$('#progressbar$id').progressbar({
8479: value: 0,
8480: change: function(event, ui) {
8481: var newVal = \$(this).progressbar('option', 'value');
8482: \$('.pblabel', this).text(LCprogressTxt);
8483: }
8484: });
8485: // ]]>
8486: </script>
8487: ENDPROGRESS
8488: }
8489:
8490: sub LCprogressbarUpdate_script {
8491: return(<<ENDPROGRESSUPDATE);
8492: <style type="text/css">
8493: .ui-progressbar { position:relative; }
8494: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
8495: </style>
8496: <script type="text/javascript">
8497: // <![CDATA[
8498: var LCprogressTxt='---';
8499:
8500: function LCupdateProgress(percent,progresstext,id) {
8501: LCprogressTxt=progresstext;
8502: \$('#progressbar'+id).progressbar('value',percent);
8503: }
8504: // ]]>
8505: </script>
8506: ENDPROGRESSUPDATE
8507: }
8508:
8509: my $LClastpercent;
8510: my $LCidcnt;
8511: my $LCcurrentid;
8512:
8513: sub LCprogressbar {
8514: my ($r)=(@_);
8515: $LClastpercent=0;
8516: $LCidcnt++;
8517: $LCcurrentid=$$.'_'.$LCidcnt;
8518: my $starting=&mt('Starting');
8519: my $content=(<<ENDPROGBAR);
8520: <div id="progressbar$LCcurrentid">
8521: <span class="pblabel">$starting</span>
8522: </div>
8523: ENDPROGBAR
8524: &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
8525: }
8526:
8527: sub LCprogressbarUpdate {
8528: my ($r,$val,$text)=@_;
8529: unless ($val) {
8530: if ($LClastpercent) {
8531: $val=$LClastpercent;
8532: } else {
8533: $val=0;
8534: }
8535: }
8536: if ($val<0) { $val=0; }
8537: if ($val>100) { $val=0; }
8538: $LClastpercent=$val;
8539: unless ($text) { $text=$val.'%'; }
8540: $text=&js_ready($text);
8541: &r_print($r,<<ENDUPDATE);
8542: <script type="text/javascript">
8543: // <![CDATA[
8544: LCupdateProgress($val,'$text','$LCcurrentid');
8545: // ]]>
8546: </script>
8547: ENDUPDATE
8548: }
8549:
8550: sub LCprogressbarClose {
8551: my ($r)=@_;
8552: $LClastpercent=0;
8553: &r_print($r,<<ENDCLOSE);
8554: <script type="text/javascript">
8555: // <![CDATA[
8556: \$("#progressbar$LCcurrentid").hide('slow');
8557: // ]]>
8558: </script>
8559: ENDCLOSE
8560: }
8561:
8562: sub r_print {
8563: my ($r,$to_print)=@_;
8564: if ($r) {
8565: $r->print($to_print);
8566: $r->rflush();
8567: } else {
8568: print($to_print);
8569: }
8570: }
8571:
8572: sub html_encode {
8573: my ($result) = @_;
8574:
8575: $result = &HTML::Entities::encode($result,'<>&"');
8576:
8577: return $result;
8578: }
8579:
8580: sub js_ready {
8581: my ($result) = @_;
8582:
8583: $result =~ s/[\n\r]/ /xmsg;
8584: $result =~ s/\\/\\\\/xmsg;
8585: $result =~ s/'/\\'/xmsg;
8586: $result =~ s{</}{<\\/}xmsg;
8587:
8588: return $result;
8589: }
8590:
8591: sub validate_page {
8592: if ( exists($env{'internal.start_page'})
8593: && $env{'internal.start_page'} > 1) {
8594: &Apache::lonnet::logthis('start_page called multiple times '.
8595: $env{'internal.start_page'}.' '.
8596: $ENV{'request.filename'});
8597: }
8598: if ( exists($env{'internal.end_page'})
8599: && $env{'internal.end_page'} > 1) {
8600: &Apache::lonnet::logthis('end_page called multiple times '.
8601: $env{'internal.end_page'}.' '.
8602: $env{'request.filename'});
8603: }
8604: if ( exists($env{'internal.start_page'})
8605: && ! exists($env{'internal.end_page'})) {
8606: &Apache::lonnet::logthis('start_page called without end_page '.
8607: $env{'request.filename'});
8608: }
8609: if ( ! exists($env{'internal.start_page'})
8610: && exists($env{'internal.end_page'})) {
8611: &Apache::lonnet::logthis('end_page called without start_page'.
8612: $env{'request.filename'});
8613: }
8614: }
8615:
8616:
8617: sub start_scrollbox {
8618: my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
8619: unless ($outerwidth) { $outerwidth='520px'; }
8620: unless ($width) { $width='500px'; }
8621: unless ($height) { $height='200px'; }
8622: my ($table_id,$div_id,$tdcol);
8623: if ($id ne '') {
8624: $table_id = ' id="table_'.$id.'"';
8625: $div_id = ' id="div_'.$id.'"';
8626: }
8627: if ($bgcolor ne '') {
8628: $tdcol = "background-color: $bgcolor;";
8629: }
8630: my $nicescroll_js;
8631: if ($env{'browser.mobile'}) {
8632: $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
8633: }
8634: return <<"END";
8635: $nicescroll_js
8636:
8637: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
8638: <div style="overflow:auto; width:$width; height:$height;"$div_id>
8639: END
8640: }
8641:
8642: sub end_scrollbox {
8643: return '</div></td></tr></table>';
8644: }
8645:
8646: sub nicescroll_javascript {
8647: my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
8648: my %options;
8649: if (ref($cursor) eq 'HASH') {
8650: %options = %{$cursor};
8651: }
8652: unless ($options{'railalign'} =~ /^left|right$/) {
8653: $options{'railalign'} = 'left';
8654: }
8655: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
8656: my $function = &get_users_function();
8657: $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
8658: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
8659: $options{'cursorcolor'} = '#00F';
8660: }
8661: }
8662: if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
8663: unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
8664: $options{'cursoropacity'}='1.0';
8665: }
8666: } else {
8667: $options{'cursoropacity'}='1.0';
8668: }
8669: if ($options{'cursorfixedheight'} eq 'none') {
8670: delete($options{'cursorfixedheight'});
8671: } else {
8672: unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
8673: }
8674: unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
8675: delete($options{'railoffset'});
8676: }
8677: my @niceoptions;
8678: while (my($key,$value) = each(%options)) {
8679: if ($value =~ /^\{.+\}$/) {
8680: push(@niceoptions,$key.':'.$value);
8681: } else {
8682: push(@niceoptions,$key.':"'.$value.'"');
8683: }
8684: }
8685: my $nicescroll_js = '
8686: $(document).ready(
8687: function() {
8688: $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
8689: }
8690: );
8691: ';
8692: if ($framecheck) {
8693: $nicescroll_js .= '
8694: function expand_div(caller) {
8695: if (top === self) {
8696: document.getElementById("'.$id.'").style.width = "auto";
8697: document.getElementById("'.$id.'").style.height = "auto";
8698: } else {
8699: try {
8700: if (parent.frames) {
8701: if (parent.frames.length > 1) {
8702: var framesrc = parent.frames[1].location.href;
8703: var currsrc = framesrc.replace(/\#.*$/,"");
8704: if ((caller == "search") || (currsrc == "'.$location.'")) {
8705: document.getElementById("'.$id.'").style.width = "auto";
8706: document.getElementById("'.$id.'").style.height = "auto";
8707: }
8708: }
8709: }
8710: } catch (e) {
8711: return;
8712: }
8713: }
8714: return;
8715: }
8716: ';
8717: }
8718: if ($needjsready) {
8719: $nicescroll_js = '
8720: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
8721: } else {
8722: $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
8723: }
8724: return $nicescroll_js;
8725: }
8726:
8727: sub simple_error_page {
8728: my ($r,$title,$msg,$args) = @_;
8729: if (ref($args) eq 'HASH') {
8730: if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
8731: } else {
8732: $msg = &mt($msg);
8733: }
8734:
8735: my $page =
8736: &Apache::loncommon::start_page($title).
8737: '<p class="LC_error">'.$msg.'</p>'.
8738: &Apache::loncommon::end_page();
8739: if (ref($r)) {
8740: $r->print($page);
8741: return;
8742: }
8743: return $page;
8744: }
8745:
8746: {
8747: my @row_count;
8748:
8749: sub start_data_table_count {
8750: unshift(@row_count, 0);
8751: return;
8752: }
8753:
8754: sub end_data_table_count {
8755: shift(@row_count);
8756: return;
8757: }
8758:
8759: sub start_data_table {
8760: my ($add_class,$id) = @_;
8761: my $css_class = (join(' ','LC_data_table',$add_class));
8762: my $table_id;
8763: if (defined($id)) {
8764: $table_id = ' id="'.$id.'"';
8765: }
8766: &start_data_table_count();
8767: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
8768: }
8769:
8770: sub end_data_table {
8771: &end_data_table_count();
8772: return '</table>'."\n";;
8773: }
8774:
8775: sub start_data_table_row {
8776: my ($add_class, $id) = @_;
8777: $row_count[0]++;
8778: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
8779: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
8780: $id = (' id="'.$id.'"') unless ($id eq '');
8781: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
8782: }
8783:
8784: sub continue_data_table_row {
8785: my ($add_class, $id) = @_;
8786: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
8787: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
8788: $id = (' id="'.$id.'"') unless ($id eq '');
8789: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
8790: }
8791:
8792: sub end_data_table_row {
8793: return '</tr>'."\n";;
8794: }
8795:
8796: sub start_data_table_empty_row {
8797: # $row_count[0]++;
8798: return '<tr class="LC_empty_row" >'."\n";;
8799: }
8800:
8801: sub end_data_table_empty_row {
8802: return '</tr>'."\n";;
8803: }
8804:
8805: sub start_data_table_header_row {
8806: return '<tr class="LC_header_row">'."\n";;
8807: }
8808:
8809: sub end_data_table_header_row {
8810: return '</tr>'."\n";;
8811: }
8812:
8813: sub data_table_caption {
8814: my $caption = shift;
8815: return "<caption class=\"LC_caption\">$caption</caption>";
8816: }
8817: }
8818:
8819: =pod
8820:
8821: =item * &inhibit_menu_check($arg)
8822:
8823: Checks for a inhibitmenu state and generates output to preserve it
8824:
8825: Inputs: $arg - can be any of
8826: - undef - in which case the return value is a string
8827: to add into arguments list of a uri
8828: - 'input' - in which case the return value is a HTML
8829: <form> <input> field of type hidden to
8830: preserve the value
8831: - a url - in which case the return value is the url with
8832: the neccesary cgi args added to preserve the
8833: inhibitmenu state
8834: - a ref to a url - no return value, but the string is
8835: updated to include the neccessary cgi
8836: args to preserve the inhibitmenu state
8837:
8838: =cut
8839:
8840: sub inhibit_menu_check {
8841: my ($arg) = @_;
8842: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
8843: if ($arg eq 'input') {
8844: if ($env{'form.inhibitmenu'}) {
8845: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
8846: } else {
8847: return
8848: }
8849: }
8850: if ($env{'form.inhibitmenu'}) {
8851: if (ref($arg)) {
8852: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
8853: } elsif ($arg eq '') {
8854: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
8855: } else {
8856: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
8857: }
8858: }
8859: if (!ref($arg)) {
8860: return $arg;
8861: }
8862: }
8863:
8864: ###############################################
8865:
8866: =pod
8867:
8868: =back
8869:
8870: =head1 User Information Routines
8871:
8872: =over 4
8873:
8874: =item * &get_users_function()
8875:
8876: Used by &bodytag to determine the current users primary role.
8877: Returns either 'student','coordinator','admin', or 'author'.
8878:
8879: =cut
8880:
8881: ###############################################
8882: sub get_users_function {
8883: my $function = 'norole';
8884: if ($env{'request.role'}=~/^(st)/) {
8885: $function='student';
8886: }
8887: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
8888: $function='coordinator';
8889: }
8890: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
8891: $function='admin';
8892: }
8893: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
8894: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
8895: $function='author';
8896: }
8897: return $function;
8898: }
8899:
8900: ###############################################
8901:
8902: =pod
8903:
8904: =item * &show_course()
8905:
8906: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
8907: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
8908:
8909: Inputs:
8910: None
8911:
8912: Outputs:
8913: Scalar: 1 if 'Course' to be used, 0 otherwise.
8914:
8915: =cut
8916:
8917: ###############################################
8918: sub show_course {
8919: my $course = !$env{'user.adv'};
8920: if (!$env{'user.adv'}) {
8921: foreach my $env (keys(%env)) {
8922: next if ($env !~ m/^user\.priv\./);
8923: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
8924: $course = 0;
8925: last;
8926: }
8927: }
8928: }
8929: return $course;
8930: }
8931:
8932: ###############################################
8933:
8934: =pod
8935:
8936: =item * &check_user_status()
8937:
8938: Determines current status of supplied role for a
8939: specific user. Roles can be active, previous or future.
8940:
8941: Inputs:
8942: user's domain, user's username, course's domain,
8943: course's number, optional section ID.
8944:
8945: Outputs:
8946: role status: active, previous or future.
8947:
8948: =cut
8949:
8950: sub check_user_status {
8951: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
8952: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
8953: my @uroles = keys(%userinfo);
8954: my $srchstr;
8955: my $active_chk = 'none';
8956: my $now = time;
8957: if (@uroles > 0) {
8958: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
8959: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
8960: } else {
8961: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
8962: }
8963: if (grep/^\Q$srchstr\E$/,@uroles) {
8964: my $role_end = 0;
8965: my $role_start = 0;
8966: $active_chk = 'active';
8967: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
8968: $role_end = $1;
8969: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
8970: $role_start = $1;
8971: }
8972: }
8973: if ($role_start > 0) {
8974: if ($now < $role_start) {
8975: $active_chk = 'future';
8976: }
8977: }
8978: if ($role_end > 0) {
8979: if ($now > $role_end) {
8980: $active_chk = 'previous';
8981: }
8982: }
8983: }
8984: }
8985: return $active_chk;
8986: }
8987:
8988: ###############################################
8989:
8990: =pod
8991:
8992: =item * &get_sections()
8993:
8994: Determines all the sections for a course including
8995: sections with students and sections containing other roles.
8996: Incoming parameters:
8997:
8998: 1. domain
8999: 2. course number
9000: 3. reference to array containing roles for which sections should
9001: be gathered (optional).
9002: 4. reference to array containing status types for which sections
9003: should be gathered (optional).
9004:
9005: If the third argument is undefined, sections are gathered for any role.
9006: If the fourth argument is undefined, sections are gathered for any status.
9007: Permissible values are 'active' or 'future' or 'previous'.
9008:
9009: Returns section hash (keys are section IDs, values are
9010: number of users in each section), subject to the
9011: optional roles filter, optional status filter
9012:
9013: =cut
9014:
9015: ###############################################
9016: sub get_sections {
9017: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
9018: if (!defined($cdom) || !defined($cnum)) {
9019: my $cid = $env{'request.course.id'};
9020:
9021: return if (!defined($cid));
9022:
9023: $cdom = $env{'course.'.$cid.'.domain'};
9024: $cnum = $env{'course.'.$cid.'.num'};
9025: }
9026:
9027: my %sectioncount;
9028: my $now = time;
9029:
9030: my $check_students = 1;
9031: my $only_students = 0;
9032: if (ref($possible_roles) eq 'ARRAY') {
9033: if (grep(/^st$/,@{$possible_roles})) {
9034: if (@{$possible_roles} == 1) {
9035: $only_students = 1;
9036: }
9037: } else {
9038: $check_students = 0;
9039: }
9040: }
9041:
9042: if ($check_students) {
9043: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
9044: my $sec_index = &Apache::loncoursedata::CL_SECTION();
9045: my $status_index = &Apache::loncoursedata::CL_STATUS();
9046: my $start_index = &Apache::loncoursedata::CL_START();
9047: my $end_index = &Apache::loncoursedata::CL_END();
9048: my $status;
9049: while (my ($student,$data) = each(%$classlist)) {
9050: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
9051: $data->[$status_index],
9052: $data->[$start_index],
9053: $data->[$end_index]);
9054: if ($stu_status eq 'Active') {
9055: $status = 'active';
9056: } elsif ($end < $now) {
9057: $status = 'previous';
9058: } elsif ($start > $now) {
9059: $status = 'future';
9060: }
9061: if ($section ne '-1' && $section !~ /^\s*$/) {
9062: if ((!defined($possible_status)) || (($status ne '') &&
9063: (grep/^\Q$status\E$/,@{$possible_status}))) {
9064: $sectioncount{$section}++;
9065: }
9066: }
9067: }
9068: }
9069: if ($only_students) {
9070: return %sectioncount;
9071: }
9072: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9073: foreach my $user (sort(keys(%courseroles))) {
9074: if ($user !~ /^(\w{2})/) { next; }
9075: my ($role) = ($user =~ /^(\w{2})/);
9076: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
9077: my ($section,$status);
9078: if ($role eq 'cr' &&
9079: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
9080: $section=$1;
9081: }
9082: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
9083: if (!defined($section) || $section eq '-1') { next; }
9084: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
9085: if ($end == -1 && $start == -1) {
9086: next; #deleted role
9087: }
9088: if (!defined($possible_status)) {
9089: $sectioncount{$section}++;
9090: } else {
9091: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
9092: $status = 'active';
9093: } elsif ($end < $now) {
9094: $status = 'future';
9095: } elsif ($start > $now) {
9096: $status = 'previous';
9097: }
9098: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
9099: $sectioncount{$section}++;
9100: }
9101: }
9102: }
9103: return %sectioncount;
9104: }
9105:
9106: ###############################################
9107:
9108: =pod
9109:
9110: =item * &get_course_users()
9111:
9112: Retrieves usernames:domains for users in the specified course
9113: with specific role(s), and access status.
9114:
9115: Incoming parameters:
9116: 1. course domain
9117: 2. course number
9118: 3. access status: users must have - either active,
9119: previous, future, or all.
9120: 4. reference to array of permissible roles
9121: 5. reference to array of section restrictions (optional)
9122: 6. reference to results object (hash of hashes).
9123: 7. reference to optional userdata hash
9124: 8. reference to optional statushash
9125: 9. flag if privileged users (except those set to unhide in
9126: course settings) should be excluded
9127: Keys of top level results hash are roles.
9128: Keys of inner hashes are username:domain, with
9129: values set to access type.
9130: Optional userdata hash returns an array with arguments in the
9131: same order as loncoursedata::get_classlist() for student data.
9132:
9133: Optional statushash returns
9134:
9135: Entries for end, start, section and status are blank because
9136: of the possibility of multiple values for non-student roles.
9137:
9138: =cut
9139:
9140: ###############################################
9141:
9142: sub get_course_users {
9143: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
9144: my %idx = ();
9145: my %seclists;
9146:
9147: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
9148: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
9149: $idx{end} = &Apache::loncoursedata::CL_END();
9150: $idx{start} = &Apache::loncoursedata::CL_START();
9151: $idx{id} = &Apache::loncoursedata::CL_ID();
9152: $idx{section} = &Apache::loncoursedata::CL_SECTION();
9153: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
9154: $idx{status} = &Apache::loncoursedata::CL_STATUS();
9155:
9156: if (grep(/^st$/,@{$roles})) {
9157: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
9158: my $now = time;
9159: foreach my $student (keys(%{$classlist})) {
9160: my $match = 0;
9161: my $secmatch = 0;
9162: my $section = $$classlist{$student}[$idx{section}];
9163: my $status = $$classlist{$student}[$idx{status}];
9164: if ($section eq '') {
9165: $section = 'none';
9166: }
9167: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
9168: if (grep(/^all$/,@{$sections})) {
9169: $secmatch = 1;
9170: } elsif ($$classlist{$student}[$idx{section}] eq '') {
9171: if (grep(/^none$/,@{$sections})) {
9172: $secmatch = 1;
9173: }
9174: } else {
9175: if (grep(/^\Q$section\E$/,@{$sections})) {
9176: $secmatch = 1;
9177: }
9178: }
9179: if (!$secmatch) {
9180: next;
9181: }
9182: }
9183: if (defined($$types{'active'})) {
9184: if ($$classlist{$student}[$idx{status}] eq 'Active') {
9185: push(@{$$users{st}{$student}},'active');
9186: $match = 1;
9187: }
9188: }
9189: if (defined($$types{'previous'})) {
9190: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
9191: push(@{$$users{st}{$student}},'previous');
9192: $match = 1;
9193: }
9194: }
9195: if (defined($$types{'future'})) {
9196: if ($$classlist{$student}[$idx{status}] eq 'Future') {
9197: push(@{$$users{st}{$student}},'future');
9198: $match = 1;
9199: }
9200: }
9201: if ($match) {
9202: push(@{$seclists{$student}},$section);
9203: if (ref($userdata) eq 'HASH') {
9204: $$userdata{$student} = $$classlist{$student};
9205: }
9206: if (ref($statushash) eq 'HASH') {
9207: $statushash->{$student}{'st'}{$section} = $status;
9208: }
9209: }
9210: }
9211: }
9212: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
9213: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9214: my $now = time;
9215: my %displaystatus = ( previous => 'Expired',
9216: active => 'Active',
9217: future => 'Future',
9218: );
9219: my (%nothide,@possdoms);
9220: if ($hidepriv) {
9221: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
9222: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
9223: if ($user !~ /:/) {
9224: $nothide{join(':',split(/[\@]/,$user))}=1;
9225: } else {
9226: $nothide{$user} = 1;
9227: }
9228: }
9229: my @possdoms = ($cdom);
9230: if ($coursehash{'checkforpriv'}) {
9231: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
9232: }
9233: }
9234: foreach my $person (sort(keys(%coursepersonnel))) {
9235: my $match = 0;
9236: my $secmatch = 0;
9237: my $status;
9238: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
9239: $user =~ s/:$//;
9240: my ($end,$start) = split(/:/,$coursepersonnel{$person});
9241: if ($end == -1 || $start == -1) {
9242: next;
9243: }
9244: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
9245: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
9246: my ($uname,$udom) = split(/:/,$user);
9247: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
9248: if (grep(/^all$/,@{$sections})) {
9249: $secmatch = 1;
9250: } elsif ($usec eq '') {
9251: if (grep(/^none$/,@{$sections})) {
9252: $secmatch = 1;
9253: }
9254: } else {
9255: if (grep(/^\Q$usec\E$/,@{$sections})) {
9256: $secmatch = 1;
9257: }
9258: }
9259: if (!$secmatch) {
9260: next;
9261: }
9262: }
9263: if ($usec eq '') {
9264: $usec = 'none';
9265: }
9266: if ($uname ne '' && $udom ne '') {
9267: if ($hidepriv) {
9268: if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
9269: (!$nothide{$uname.':'.$udom})) {
9270: next;
9271: }
9272: }
9273: if ($end > 0 && $end < $now) {
9274: $status = 'previous';
9275: } elsif ($start > $now) {
9276: $status = 'future';
9277: } else {
9278: $status = 'active';
9279: }
9280: foreach my $type (keys(%{$types})) {
9281: if ($status eq $type) {
9282: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
9283: push(@{$$users{$role}{$user}},$type);
9284: }
9285: $match = 1;
9286: }
9287: }
9288: if (($match) && (ref($userdata) eq 'HASH')) {
9289: if (!exists($$userdata{$uname.':'.$udom})) {
9290: &get_user_info($udom,$uname,\%idx,$userdata);
9291: }
9292: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
9293: push(@{$seclists{$uname.':'.$udom}},$usec);
9294: }
9295: if (ref($statushash) eq 'HASH') {
9296: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
9297: }
9298: }
9299: }
9300: }
9301: }
9302: if (grep(/^ow$/,@{$roles})) {
9303: if ((defined($cdom)) && (defined($cnum))) {
9304: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
9305: if ( defined($csettings{'internal.courseowner'}) ) {
9306: my $owner = $csettings{'internal.courseowner'};
9307: next if ($owner eq '');
9308: my ($ownername,$ownerdom);
9309: if ($owner =~ /^([^:]+):([^:]+)$/) {
9310: $ownername = $1;
9311: $ownerdom = $2;
9312: } else {
9313: $ownername = $owner;
9314: $ownerdom = $cdom;
9315: $owner = $ownername.':'.$ownerdom;
9316: }
9317: @{$$users{'ow'}{$owner}} = 'any';
9318: if (defined($userdata) &&
9319: !exists($$userdata{$owner})) {
9320: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
9321: if (!grep(/^none$/,@{$seclists{$owner}})) {
9322: push(@{$seclists{$owner}},'none');
9323: }
9324: if (ref($statushash) eq 'HASH') {
9325: $statushash->{$owner}{'ow'}{'none'} = 'Any';
9326: }
9327: }
9328: }
9329: }
9330: }
9331: foreach my $user (keys(%seclists)) {
9332: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
9333: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
9334: }
9335: }
9336: return;
9337: }
9338:
9339: sub get_user_info {
9340: my ($udom,$uname,$idx,$userdata) = @_;
9341: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
9342: &plainname($uname,$udom,'lastname');
9343: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
9344: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
9345: my %idhash = &Apache::lonnet::idrget($udom,($uname));
9346: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
9347: return;
9348: }
9349:
9350: ###############################################
9351:
9352: =pod
9353:
9354: =item * &get_user_quota()
9355:
9356: Retrieves quota assigned for storage of user files.
9357: Default is to report quota for portfolio files.
9358:
9359: Incoming parameters:
9360: 1. user's username
9361: 2. user's domain
9362: 3. quota name - portfolio, author, or course
9363: (if no quota name provided, defaults to portfolio).
9364: 4. crstype - official, unofficial, textbook or community, if quota name is
9365: course
9366:
9367: Returns:
9368: 1. Disk quota (in MB) assigned to student.
9369: 2. (Optional) Type of setting: custom or default
9370: (individually assigned or default for user's
9371: institutional status).
9372: 3. (Optional) - User's institutional status (e.g., faculty, staff
9373: or student - types as defined in localenroll::inst_usertypes
9374: for user's domain, which determines default quota for user.
9375: 4. (Optional) - Default quota which would apply to the user.
9376:
9377: If a value has been stored in the user's environment,
9378: it will return that, otherwise it returns the maximal default
9379: defined for the user's institutional status(es) in the domain.
9380:
9381: =cut
9382:
9383: ###############################################
9384:
9385:
9386: sub get_user_quota {
9387: my ($uname,$udom,$quotaname,$crstype) = @_;
9388: my ($quota,$quotatype,$settingstatus,$defquota);
9389: if (!defined($udom)) {
9390: $udom = $env{'user.domain'};
9391: }
9392: if (!defined($uname)) {
9393: $uname = $env{'user.name'};
9394: }
9395: if (($udom eq '' || $uname eq '') ||
9396: ($udom eq 'public') && ($uname eq 'public')) {
9397: $quota = 0;
9398: $quotatype = 'default';
9399: $defquota = 0;
9400: } else {
9401: my $inststatus;
9402: if ($quotaname eq 'course') {
9403: if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
9404: ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
9405: $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
9406: } else {
9407: my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
9408: $quota = $cenv{'internal.uploadquota'};
9409: }
9410: } else {
9411: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
9412: if ($quotaname eq 'author') {
9413: $quota = $env{'environment.authorquota'};
9414: } else {
9415: $quota = $env{'environment.portfolioquota'};
9416: }
9417: $inststatus = $env{'environment.inststatus'};
9418: } else {
9419: my %userenv =
9420: &Apache::lonnet::get('environment',['portfolioquota',
9421: 'authorquota','inststatus'],$udom,$uname);
9422: my ($tmp) = keys(%userenv);
9423: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9424: if ($quotaname eq 'author') {
9425: $quota = $userenv{'authorquota'};
9426: } else {
9427: $quota = $userenv{'portfolioquota'};
9428: }
9429: $inststatus = $userenv{'inststatus'};
9430: } else {
9431: undef(%userenv);
9432: }
9433: }
9434: }
9435: if ($quota eq '' || wantarray) {
9436: if ($quotaname eq 'course') {
9437: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
9438: if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
9439: ($crstype eq 'community') || ($crstype eq 'textbook')) {
9440: $defquota = $domdefs{$crstype.'quota'};
9441: }
9442: if ($defquota eq '') {
9443: $defquota = 500;
9444: }
9445: } else {
9446: ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
9447: }
9448: if ($quota eq '') {
9449: $quota = $defquota;
9450: $quotatype = 'default';
9451: } else {
9452: $quotatype = 'custom';
9453: }
9454: }
9455: }
9456: if (wantarray) {
9457: return ($quota,$quotatype,$settingstatus,$defquota);
9458: } else {
9459: return $quota;
9460: }
9461: }
9462:
9463: ###############################################
9464:
9465: =pod
9466:
9467: =item * &default_quota()
9468:
9469: Retrieves default quota assigned for storage of user portfolio files,
9470: given an (optional) user's institutional status.
9471:
9472: Incoming parameters:
9473:
9474: 1. domain
9475: 2. (Optional) institutional status(es). This is a : separated list of
9476: status types (e.g., faculty, staff, student etc.)
9477: which apply to the user for whom the default is being retrieved.
9478: If the institutional status string in undefined, the domain
9479: default quota will be returned.
9480: 3. quota name - portfolio, author, or course
9481: (if no quota name provided, defaults to portfolio).
9482:
9483: Returns:
9484:
9485: 1. Default disk quota (in MB) for user portfolios in the domain.
9486: 2. (Optional) institutional type which determined the value of the
9487: default quota.
9488:
9489: If a value has been stored in the domain's configuration db,
9490: it will return that, otherwise it returns 20 (for backwards
9491: compatibility with domains which have not set up a configuration
9492: db file; the original statically defined portfolio quota was 20 MB).
9493:
9494: If the user's status includes multiple types (e.g., staff and student),
9495: the largest default quota which applies to the user determines the
9496: default quota returned.
9497:
9498: =cut
9499:
9500: ###############################################
9501:
9502:
9503: sub default_quota {
9504: my ($udom,$inststatus,$quotaname) = @_;
9505: my ($defquota,$settingstatus);
9506: my %quotahash = &Apache::lonnet::get_dom('configuration',
9507: ['quotas'],$udom);
9508: my $key = 'defaultquota';
9509: if ($quotaname eq 'author') {
9510: $key = 'authorquota';
9511: }
9512: if (ref($quotahash{'quotas'}) eq 'HASH') {
9513: if ($inststatus ne '') {
9514: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
9515: foreach my $item (@statuses) {
9516: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
9517: if ($quotahash{'quotas'}{$key}{$item} ne '') {
9518: if ($defquota eq '') {
9519: $defquota = $quotahash{'quotas'}{$key}{$item};
9520: $settingstatus = $item;
9521: } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
9522: $defquota = $quotahash{'quotas'}{$key}{$item};
9523: $settingstatus = $item;
9524: }
9525: }
9526: } elsif ($key eq 'defaultquota') {
9527: if ($quotahash{'quotas'}{$item} ne '') {
9528: if ($defquota eq '') {
9529: $defquota = $quotahash{'quotas'}{$item};
9530: $settingstatus = $item;
9531: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
9532: $defquota = $quotahash{'quotas'}{$item};
9533: $settingstatus = $item;
9534: }
9535: }
9536: }
9537: }
9538: }
9539: if ($defquota eq '') {
9540: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
9541: $defquota = $quotahash{'quotas'}{$key}{'default'};
9542: } elsif ($key eq 'defaultquota') {
9543: $defquota = $quotahash{'quotas'}{'default'};
9544: }
9545: $settingstatus = 'default';
9546: if ($defquota eq '') {
9547: if ($quotaname eq 'author') {
9548: $defquota = 500;
9549: }
9550: }
9551: }
9552: } else {
9553: $settingstatus = 'default';
9554: if ($quotaname eq 'author') {
9555: $defquota = 500;
9556: } else {
9557: $defquota = 20;
9558: }
9559: }
9560: if (wantarray) {
9561: return ($defquota,$settingstatus);
9562: } else {
9563: return $defquota;
9564: }
9565: }
9566:
9567: ###############################################
9568:
9569: =pod
9570:
9571: =item * &excess_filesize_warning()
9572:
9573: Returns warning message if upload of file to authoring space, or copying
9574: of existing file within authoring space will cause quota for the authoring
9575: space to be exceeded.
9576:
9577: Same, if upload of a file directly to a course/community via Course Editor
9578: will cause quota for uploaded content for the course to be exceeded.
9579:
9580: Inputs: 7
9581: 1. username or coursenum
9582: 2. domain
9583: 3. context ('author' or 'course')
9584: 4. filename of file for which action is being requested
9585: 5. filesize (kB) of file
9586: 6. action being taken: copy or upload.
9587: 7. quotatype (in course context -- official, unofficial, community or textbook).
9588:
9589: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
9590: otherwise return null.
9591:
9592: =back
9593:
9594: =cut
9595:
9596: sub excess_filesize_warning {
9597: my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
9598: my $current_disk_usage = 0;
9599: my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
9600: if ($context eq 'author') {
9601: my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
9602: $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
9603: } else {
9604: foreach my $subdir ('docs','supplemental') {
9605: $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
9606: }
9607: }
9608: $disk_quota = int($disk_quota * 1000);
9609: if (($current_disk_usage + $filesize) > $disk_quota) {
9610: return '<p class="LC_warning">'.
9611: &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
9612: '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
9613: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
9614: $disk_quota,$current_disk_usage).
9615: '</p>';
9616: }
9617: return;
9618: }
9619:
9620: ###############################################
9621:
9622:
9623: sub get_secgrprole_info {
9624: my ($cdom,$cnum,$needroles,$type) = @_;
9625: my %sections_count = &get_sections($cdom,$cnum);
9626: my @sections = (sort {$a <=> $b} keys(%sections_count));
9627: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
9628: my @groups = sort(keys(%curr_groups));
9629: my $allroles = [];
9630: my $rolehash;
9631: my $accesshash = {
9632: active => 'Currently has access',
9633: future => 'Will have future access',
9634: previous => 'Previously had access',
9635: };
9636: if ($needroles) {
9637: $rolehash = {'all' => 'all'};
9638: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9639: if (&Apache::lonnet::error(%user_roles)) {
9640: undef(%user_roles);
9641: }
9642: foreach my $item (keys(%user_roles)) {
9643: my ($role)=split(/\:/,$item,2);
9644: if ($role eq 'cr') { next; }
9645: if ($role =~ /^cr/) {
9646: $$rolehash{$role} = (split('/',$role))[3];
9647: } else {
9648: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
9649: }
9650: }
9651: foreach my $key (sort(keys(%{$rolehash}))) {
9652: push(@{$allroles},$key);
9653: }
9654: push (@{$allroles},'st');
9655: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
9656: }
9657: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
9658: }
9659:
9660: sub user_picker {
9661: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
9662: my $currdom = $dom;
9663: my @alldoms = &Apache::lonnet::all_domains();
9664: if (@alldoms == 1) {
9665: my %domsrch = &Apache::lonnet::get_dom('configuration',
9666: ['directorysrch'],$alldoms[0]);
9667: my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
9668: my $showdom = $domdesc;
9669: if ($showdom eq '') {
9670: $showdom = $dom;
9671: }
9672: if (ref($domsrch{'directorysrch'}) eq 'HASH') {
9673: if ((!$domsrch{'directorysrch'}{'available'}) &&
9674: ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
9675: return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
9676: }
9677: }
9678: }
9679: my %curr_selected = (
9680: srchin => 'dom',
9681: srchby => 'lastname',
9682: );
9683: my $srchterm;
9684: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
9685: if ($srch->{'srchby'} ne '') {
9686: $curr_selected{'srchby'} = $srch->{'srchby'};
9687: }
9688: if ($srch->{'srchin'} ne '') {
9689: $curr_selected{'srchin'} = $srch->{'srchin'};
9690: }
9691: if ($srch->{'srchtype'} ne '') {
9692: $curr_selected{'srchtype'} = $srch->{'srchtype'};
9693: }
9694: if ($srch->{'srchdomain'} ne '') {
9695: $currdom = $srch->{'srchdomain'};
9696: }
9697: $srchterm = $srch->{'srchterm'};
9698: }
9699: my %html_lt=&Apache::lonlocal::texthash(
9700: 'usr' => 'Search criteria',
9701: 'doma' => 'Domain/institution to search',
9702: 'uname' => 'username',
9703: 'lastname' => 'last name',
9704: 'lastfirst' => 'last name, first name',
9705: 'crs' => 'in this course',
9706: 'dom' => 'in selected LON-CAPA domain',
9707: 'alc' => 'all LON-CAPA',
9708: 'instd' => 'in institutional directory for selected domain',
9709: 'exact' => 'is',
9710: 'contains' => 'contains',
9711: 'begins' => 'begins with',
9712: );
9713: my %js_lt=&Apache::lonlocal::texthash(
9714: 'youm' => "You must include some text to search for.",
9715: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
9716: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
9717: 'yomc' => "You must choose a domain when using an institutional directory search.",
9718: 'ymcd' => "You must choose a domain when using a domain search.",
9719: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
9720: 'whse' => "When searching by last,first you must include at least one character in the first name.",
9721: 'thfo' => "The following need to be corrected before the search can be run:",
9722: );
9723: &html_escape(\%html_lt);
9724: &js_escape(\%js_lt);
9725: my $domform;
9726: my $allow_blank = 1;
9727: if ($fixeddom) {
9728: $allow_blank = 0;
9729: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
9730: } else {
9731: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
9732: }
9733: my $srchinsel = ' <select name="srchin">';
9734:
9735: my @srchins = ('crs','dom','alc','instd');
9736:
9737: foreach my $option (@srchins) {
9738: # FIXME 'alc' option unavailable until
9739: # loncreateuser::print_user_query_page()
9740: # has been completed.
9741: next if ($option eq 'alc');
9742: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
9743: next if ($option eq 'crs' && !$env{'request.course.id'});
9744: next if (($option eq 'instd') && ($noinstd));
9745: if ($curr_selected{'srchin'} eq $option) {
9746: $srchinsel .= '
9747: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
9748: } else {
9749: $srchinsel .= '
9750: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
9751: }
9752: }
9753: $srchinsel .= "\n </select>\n";
9754:
9755: my $srchbysel = ' <select name="srchby">';
9756: foreach my $option ('lastname','lastfirst','uname') {
9757: if ($curr_selected{'srchby'} eq $option) {
9758: $srchbysel .= '
9759: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
9760: } else {
9761: $srchbysel .= '
9762: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
9763: }
9764: }
9765: $srchbysel .= "\n </select>\n";
9766:
9767: my $srchtypesel = ' <select name="srchtype">';
9768: foreach my $option ('begins','contains','exact') {
9769: if ($curr_selected{'srchtype'} eq $option) {
9770: $srchtypesel .= '
9771: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
9772: } else {
9773: $srchtypesel .= '
9774: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
9775: }
9776: }
9777: $srchtypesel .= "\n </select>\n";
9778:
9779: my ($newuserscript,$new_user_create);
9780: my $context_dom = $env{'request.role.domain'};
9781: if ($context eq 'requestcrs') {
9782: if ($env{'form.coursedom'} ne '') {
9783: $context_dom = $env{'form.coursedom'};
9784: }
9785: }
9786: if ($forcenewuser) {
9787: if (ref($srch) eq 'HASH') {
9788: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
9789: if ($cancreate) {
9790: $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>';
9791: } else {
9792: my $helplink = 'javascript:helpMenu('."'display'".')';
9793: my %usertypetext = (
9794: official => 'institutional',
9795: unofficial => 'non-institutional',
9796: );
9797: $new_user_create = '<p class="LC_warning">'
9798: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
9799: .' '
9800: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
9801: ,'<a href="'.$helplink.'">','</a>')
9802: .'</p><br />';
9803: }
9804: }
9805: }
9806:
9807: $newuserscript = <<"ENDSCRIPT";
9808:
9809: function setSearch(createnew,callingForm) {
9810: if (createnew == 1) {
9811: for (var i=0; i<callingForm.srchby.length; i++) {
9812: if (callingForm.srchby.options[i].value == 'uname') {
9813: callingForm.srchby.selectedIndex = i;
9814: }
9815: }
9816: for (var i=0; i<callingForm.srchin.length; i++) {
9817: if ( callingForm.srchin.options[i].value == 'dom') {
9818: callingForm.srchin.selectedIndex = i;
9819: }
9820: }
9821: for (var i=0; i<callingForm.srchtype.length; i++) {
9822: if (callingForm.srchtype.options[i].value == 'exact') {
9823: callingForm.srchtype.selectedIndex = i;
9824: }
9825: }
9826: for (var i=0; i<callingForm.srchdomain.length; i++) {
9827: if (callingForm.srchdomain.options[i].value == '$context_dom') {
9828: callingForm.srchdomain.selectedIndex = i;
9829: }
9830: }
9831: }
9832: }
9833: ENDSCRIPT
9834:
9835: }
9836:
9837: my $output = <<"END_BLOCK";
9838: <script type="text/javascript">
9839: // <![CDATA[
9840: function validateEntry(callingForm) {
9841:
9842: var checkok = 1;
9843: var srchin;
9844: for (var i=0; i<callingForm.srchin.length; i++) {
9845: if ( callingForm.srchin[i].checked ) {
9846: srchin = callingForm.srchin[i].value;
9847: }
9848: }
9849:
9850: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
9851: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
9852: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
9853: var srchterm = callingForm.srchterm.value;
9854: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
9855: var msg = "";
9856:
9857: if (srchterm == "") {
9858: checkok = 0;
9859: msg += "$js_lt{'youm'}\\n";
9860: }
9861:
9862: if (srchtype== 'begins') {
9863: if (srchterm.length < 2) {
9864: checkok = 0;
9865: msg += "$js_lt{'thte'}\\n";
9866: }
9867: }
9868:
9869: if (srchtype== 'contains') {
9870: if (srchterm.length < 3) {
9871: checkok = 0;
9872: msg += "$js_lt{'thet'}\\n";
9873: }
9874: }
9875: if (srchin == 'instd') {
9876: if (srchdomain == '') {
9877: checkok = 0;
9878: msg += "$js_lt{'yomc'}\\n";
9879: }
9880: }
9881: if (srchin == 'dom') {
9882: if (srchdomain == '') {
9883: checkok = 0;
9884: msg += "$js_lt{'ymcd'}\\n";
9885: }
9886: }
9887: if (srchby == 'lastfirst') {
9888: if (srchterm.indexOf(",") == -1) {
9889: checkok = 0;
9890: msg += "$js_lt{'whus'}\\n";
9891: }
9892: if (srchterm.indexOf(",") == srchterm.length -1) {
9893: checkok = 0;
9894: msg += "$js_lt{'whse'}\\n";
9895: }
9896: }
9897: if (checkok == 0) {
9898: alert("$js_lt{'thfo'}\\n"+msg);
9899: return;
9900: }
9901: if (checkok == 1) {
9902: callingForm.submit();
9903: }
9904: }
9905:
9906: $newuserscript
9907:
9908: // ]]>
9909: </script>
9910:
9911: $new_user_create
9912:
9913: END_BLOCK
9914:
9915: $output .= &Apache::lonhtmlcommon::start_pick_box().
9916: &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
9917: $domform.
9918: &Apache::lonhtmlcommon::row_closure().
9919: &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
9920: $srchbysel.
9921: $srchtypesel.
9922: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
9923: $srchinsel.
9924: &Apache::lonhtmlcommon::row_closure(1).
9925: &Apache::lonhtmlcommon::end_pick_box().
9926: '<br />';
9927: return ($output,1);
9928: }
9929:
9930: sub user_rule_check {
9931: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
9932: my ($response,%inst_response);
9933: if (ref($usershash) eq 'HASH') {
9934: if (keys(%{$usershash}) > 1) {
9935: my (%by_username,%by_id,%userdoms);
9936: my $checkid;
9937: if (ref($checks) eq 'HASH') {
9938: if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
9939: $checkid = 1;
9940: }
9941: }
9942: foreach my $user (keys(%{$usershash})) {
9943: my ($uname,$udom) = split(/:/,$user);
9944: if ($checkid) {
9945: if (ref($usershash->{$user}) eq 'HASH') {
9946: if ($usershash->{$user}->{'id'} ne '') {
9947: $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
9948: $userdoms{$udom} = 1;
9949: if (ref($inst_results) eq 'HASH') {
9950: $inst_results->{$uname.':'.$udom} = {};
9951: }
9952: }
9953: }
9954: } else {
9955: $by_username{$udom}{$uname} = 1;
9956: $userdoms{$udom} = 1;
9957: if (ref($inst_results) eq 'HASH') {
9958: $inst_results->{$uname.':'.$udom} = {};
9959: }
9960: }
9961: }
9962: foreach my $udom (keys(%userdoms)) {
9963: if (!$got_rules->{$udom}) {
9964: my %domconfig = &Apache::lonnet::get_dom('configuration',
9965: ['usercreation'],$udom);
9966: if (ref($domconfig{'usercreation'}) eq 'HASH') {
9967: foreach my $item ('username','id') {
9968: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
9969: $$curr_rules{$udom}{$item} =
9970: $domconfig{'usercreation'}{$item.'_rule'};
9971: }
9972: }
9973: }
9974: $got_rules->{$udom} = 1;
9975: }
9976: }
9977: if ($checkid) {
9978: foreach my $udom (keys(%by_id)) {
9979: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
9980: if ($outcome eq 'ok') {
9981: foreach my $id (keys(%{$by_id{$udom}})) {
9982: my $uname = $by_id{$udom}{$id};
9983: $inst_response{$uname.':'.$udom} = $outcome;
9984: }
9985: if (ref($results) eq 'HASH') {
9986: foreach my $uname (keys(%{$results})) {
9987: if (exists($inst_response{$uname.':'.$udom})) {
9988: $inst_response{$uname.':'.$udom} = $outcome;
9989: $inst_results->{$uname.':'.$udom} = $results->{$uname};
9990: }
9991: }
9992: }
9993: }
9994: }
9995: } else {
9996: foreach my $udom (keys(%by_username)) {
9997: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
9998: if ($outcome eq 'ok') {
9999: foreach my $uname (keys(%{$by_username{$udom}})) {
10000: $inst_response{$uname.':'.$udom} = $outcome;
10001: }
10002: if (ref($results) eq 'HASH') {
10003: foreach my $uname (keys(%{$results})) {
10004: $inst_results->{$uname.':'.$udom} = $results->{$uname};
10005: }
10006: }
10007: }
10008: }
10009: }
10010: } elsif (keys(%{$usershash}) == 1) {
10011: my $user = (keys(%{$usershash}))[0];
10012: my ($uname,$udom) = split(/:/,$user);
10013: if (($udom ne '') && ($uname ne '')) {
10014: if (ref($usershash->{$user}) eq 'HASH') {
10015: if (ref($checks) eq 'HASH') {
10016: if (defined($checks->{'username'})) {
10017: ($inst_response{$user},%{$inst_results->{$user}}) =
10018: &Apache::lonnet::get_instuser($udom,$uname);
10019: } elsif (defined($checks->{'id'})) {
10020: if ($usershash->{$user}->{'id'} ne '') {
10021: ($inst_response{$user},%{$inst_results->{$user}}) =
10022: &Apache::lonnet::get_instuser($udom,undef,
10023: $usershash->{$user}->{'id'});
10024: } else {
10025: ($inst_response{$user},%{$inst_results->{$user}}) =
10026: &Apache::lonnet::get_instuser($udom,$uname);
10027: }
10028: }
10029: } else {
10030: ($inst_response{$user},%{$inst_results->{$user}}) =
10031: &Apache::lonnet::get_instuser($udom,$uname);
10032: return;
10033: }
10034: if (!$got_rules->{$udom}) {
10035: my %domconfig = &Apache::lonnet::get_dom('configuration',
10036: ['usercreation'],$udom);
10037: if (ref($domconfig{'usercreation'}) eq 'HASH') {
10038: foreach my $item ('username','id') {
10039: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10040: $$curr_rules{$udom}{$item} =
10041: $domconfig{'usercreation'}{$item.'_rule'};
10042: }
10043: }
10044: }
10045: $got_rules->{$udom} = 1;
10046: }
10047: }
10048: } else {
10049: return;
10050: }
10051: } else {
10052: return;
10053: }
10054: foreach my $user (keys(%{$usershash})) {
10055: my ($uname,$udom) = split(/:/,$user);
10056: next if (($udom eq '') || ($uname eq ''));
10057: my $id;
10058: if (ref($inst_results) eq 'HASH') {
10059: if (ref($inst_results->{$user}) eq 'HASH') {
10060: $id = $inst_results->{$user}->{'id'};
10061: }
10062: }
10063: if ($id eq '') {
10064: if (ref($usershash->{$user})) {
10065: $id = $usershash->{$user}->{'id'};
10066: }
10067: }
10068: foreach my $item (keys(%{$checks})) {
10069: if (ref($$curr_rules{$udom}) eq 'HASH') {
10070: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10071: if (@{$$curr_rules{$udom}{$item}} > 0) {
10072: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10073: $$curr_rules{$udom}{$item});
10074: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10075: if ($rule_check{$rule}) {
10076: $$rulematch{$user}{$item} = $rule;
10077: if ($inst_response{$user} eq 'ok') {
10078: if (ref($inst_results) eq 'HASH') {
10079: if (ref($inst_results->{$user}) eq 'HASH') {
10080: if (keys(%{$inst_results->{$user}}) == 0) {
10081: $$alerts{$item}{$udom}{$uname} = 1;
10082: } elsif ($item eq 'id') {
10083: if ($inst_results->{$user}->{'id'} eq '') {
10084: $$alerts{$item}{$udom}{$uname} = 1;
10085: }
10086: }
10087: }
10088: }
10089: }
10090: last;
10091: }
10092: }
10093: }
10094: }
10095: }
10096: }
10097: }
10098: }
10099: return;
10100: }
10101:
10102: sub user_rule_formats {
10103: my ($domain,$domdesc,$curr_rules,$check) = @_;
10104: my %text = (
10105: 'username' => 'Usernames',
10106: 'id' => 'IDs',
10107: );
10108: my $output;
10109: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10110: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10111: if (@{$ruleorder} > 0) {
10112: $output = '<br />'.
10113: &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10114: '<span class="LC_cusr_emph">','</span>',$domdesc).
10115: ' <ul>';
10116: foreach my $rule (@{$ruleorder}) {
10117: if (ref($curr_rules) eq 'ARRAY') {
10118: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10119: if (ref($rules->{$rule}) eq 'HASH') {
10120: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10121: $rules->{$rule}{'desc'}.'</li>';
10122: }
10123: }
10124: }
10125: }
10126: $output .= '</ul>';
10127: }
10128: }
10129: return $output;
10130: }
10131:
10132: sub instrule_disallow_msg {
10133: my ($checkitem,$domdesc,$count,$mode) = @_;
10134: my $response;
10135: my %text = (
10136: item => 'username',
10137: items => 'usernames',
10138: match => 'matches',
10139: do => 'does',
10140: action => 'a username',
10141: one => 'one',
10142: );
10143: if ($count > 1) {
10144: $text{'item'} = 'usernames';
10145: $text{'match'} ='match';
10146: $text{'do'} = 'do';
10147: $text{'action'} = 'usernames',
10148: $text{'one'} = 'ones';
10149: }
10150: if ($checkitem eq 'id') {
10151: $text{'items'} = 'IDs';
10152: $text{'item'} = 'ID';
10153: $text{'action'} = 'an ID';
10154: if ($count > 1) {
10155: $text{'item'} = 'IDs';
10156: $text{'action'} = 'IDs';
10157: }
10158: }
10159: $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 />';
10160: if ($mode eq 'upload') {
10161: if ($checkitem eq 'username') {
10162: $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'}.");
10163: } elsif ($checkitem eq 'id') {
10164: $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.");
10165: }
10166: } elsif ($mode eq 'selfcreate') {
10167: if ($checkitem eq 'id') {
10168: $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.");
10169: }
10170: } else {
10171: if ($checkitem eq 'username') {
10172: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10173: } elsif ($checkitem eq 'id') {
10174: $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.");
10175: }
10176: }
10177: return $response;
10178: }
10179:
10180: sub personal_data_fieldtitles {
10181: my %fieldtitles = &Apache::lonlocal::texthash (
10182: id => 'Student/Employee ID',
10183: permanentemail => 'E-mail address',
10184: lastname => 'Last Name',
10185: firstname => 'First Name',
10186: middlename => 'Middle Name',
10187: generation => 'Generation',
10188: gen => 'Generation',
10189: inststatus => 'Affiliation',
10190: );
10191: return %fieldtitles;
10192: }
10193:
10194: sub sorted_inst_types {
10195: my ($dom) = @_;
10196: my ($usertypes,$order);
10197: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10198: if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10199: $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10200: $order = $domdefaults{'inststatus'}{'inststatusorder'};
10201: } else {
10202: ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10203: }
10204: my $othertitle = &mt('All users');
10205: if ($env{'request.course.id'}) {
10206: $othertitle = &mt('Any users');
10207: }
10208: my @types;
10209: if (ref($order) eq 'ARRAY') {
10210: @types = @{$order};
10211: }
10212: if (@types == 0) {
10213: if (ref($usertypes) eq 'HASH') {
10214: @types = sort(keys(%{$usertypes}));
10215: }
10216: }
10217: if (keys(%{$usertypes}) > 0) {
10218: $othertitle = &mt('Other users');
10219: }
10220: return ($othertitle,$usertypes,\@types);
10221: }
10222:
10223: sub get_institutional_codes {
10224: my ($settings,$allcourses,$LC_code) = @_;
10225: # Get complete list of course sections to update
10226: my @currsections = ();
10227: my @currxlists = ();
10228: my $coursecode = $$settings{'internal.coursecode'};
10229:
10230: if ($$settings{'internal.sectionnums'} ne '') {
10231: @currsections = split(/,/,$$settings{'internal.sectionnums'});
10232: }
10233:
10234: if ($$settings{'internal.crosslistings'} ne '') {
10235: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10236: }
10237:
10238: if (@currxlists > 0) {
10239: foreach (@currxlists) {
10240: if (m/^([^:]+):(\w*)$/) {
10241: unless (grep/^$1$/,@{$allcourses}) {
10242: push(@{$allcourses},$1);
10243: $$LC_code{$1} = $2;
10244: }
10245: }
10246: }
10247: }
10248:
10249: if (@currsections > 0) {
10250: foreach (@currsections) {
10251: if (m/^(\w+):(\w*)$/) {
10252: my $sec = $coursecode.$1;
10253: my $lc_sec = $2;
10254: unless (grep/^$sec$/,@{$allcourses}) {
10255: push(@{$allcourses},$sec);
10256: $$LC_code{$sec} = $lc_sec;
10257: }
10258: }
10259: }
10260: }
10261: return;
10262: }
10263:
10264: sub get_standard_codeitems {
10265: return ('Year','Semester','Department','Number','Section');
10266: }
10267:
10268: =pod
10269:
10270: =head1 Slot Helpers
10271:
10272: =over 4
10273:
10274: =item * sorted_slots()
10275:
10276: Sorts an array of slot names in order of an optional sort key,
10277: default sort is by slot start time (earliest first).
10278:
10279: Inputs:
10280:
10281: =over 4
10282:
10283: slotsarr - Reference to array of unsorted slot names.
10284:
10285: slots - Reference to hash of hash, where outer hash keys are slot names.
10286:
10287: sortkey - Name of key in inner hash to be sorted on (e.g., starttime).
10288:
10289: =back
10290:
10291: Returns:
10292:
10293: =over 4
10294:
10295: sorted - An array of slot names sorted by a specified sort key
10296: (default sort key is start time of the slot).
10297:
10298: =back
10299:
10300: =cut
10301:
10302:
10303: sub sorted_slots {
10304: my ($slotsarr,$slots,$sortkey) = @_;
10305: if ($sortkey eq '') {
10306: $sortkey = 'starttime';
10307: }
10308: my @sorted;
10309: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10310: @sorted =
10311: sort {
10312: if (ref($slots->{$a}) && ref($slots->{$b})) {
10313: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10314: }
10315: if (ref($slots->{$a})) { return -1;}
10316: if (ref($slots->{$b})) { return 1;}
10317: return 0;
10318: } @{$slotsarr};
10319: }
10320: return @sorted;
10321: }
10322:
10323: =pod
10324:
10325: =item * get_future_slots()
10326:
10327: Inputs:
10328:
10329: =over 4
10330:
10331: cnum - course number
10332:
10333: cdom - course domain
10334:
10335: now - current UNIX time
10336:
10337: symb - optional symb
10338:
10339: =back
10340:
10341: Returns:
10342:
10343: =over 4
10344:
10345: sorted_reservable - ref to array of student_schedulable slots currently
10346: reservable, ordered by end date of reservation period.
10347:
10348: reservable_now - ref to hash of student_schedulable slots currently
10349: reservable.
10350:
10351: Keys in inner hash are:
10352: (a) symb: either blank or symb to which slot use is restricted.
10353: (b) endreserve: end date of reservation period.
10354: (c) uniqueperiod: start,end dates when slot is to be uniquely
10355: selected.
10356:
10357: sorted_future - ref to array of student_schedulable slots reservable in
10358: the future, ordered by start date of reservation period.
10359:
10360: future_reservable - ref to hash of student_schedulable slots reservable
10361: in the future.
10362:
10363: Keys in inner hash are:
10364: (a) symb: either blank or symb to which slot use is restricted.
10365: (b) startreserve: start date of reservation period.
10366: (c) uniqueperiod: start,end dates when slot is to be uniquely
10367: selected.
10368:
10369: =back
10370:
10371: =cut
10372:
10373: sub get_future_slots {
10374: my ($cnum,$cdom,$now,$symb) = @_;
10375: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10376: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10377: foreach my $slot (keys(%slots)) {
10378: next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10379: if ($symb) {
10380: next if (($slots{$slot}->{'symb'} ne '') &&
10381: ($slots{$slot}->{'symb'} ne $symb));
10382: }
10383: if (($slots{$slot}->{'starttime'} > $now) &&
10384: ($slots{$slot}->{'endtime'} > $now)) {
10385: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10386: my $userallowed = 0;
10387: if ($slots{$slot}->{'allowedsections'}) {
10388: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10389: if (!defined($env{'request.role.sec'})
10390: && grep(/^No section assigned$/,@allowed_sec)) {
10391: $userallowed=1;
10392: } else {
10393: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10394: $userallowed=1;
10395: }
10396: }
10397: unless ($userallowed) {
10398: if (defined($env{'request.course.groups'})) {
10399: my @groups = split(/:/,$env{'request.course.groups'});
10400: foreach my $group (@groups) {
10401: if (grep(/^\Q$group\E$/,@allowed_sec)) {
10402: $userallowed=1;
10403: last;
10404: }
10405: }
10406: }
10407: }
10408: }
10409: if ($slots{$slot}->{'allowedusers'}) {
10410: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10411: my $user = $env{'user.name'}.':'.$env{'user.domain'};
10412: if (grep(/^\Q$user\E$/,@allowed_users)) {
10413: $userallowed = 1;
10414: }
10415: }
10416: next unless($userallowed);
10417: }
10418: my $startreserve = $slots{$slot}->{'startreserve'};
10419: my $endreserve = $slots{$slot}->{'endreserve'};
10420: my $symb = $slots{$slot}->{'symb'};
10421: my $uniqueperiod;
10422: if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
10423: $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
10424: }
10425: if (($startreserve < $now) &&
10426: (!$endreserve || $endreserve > $now)) {
10427: my $lastres = $endreserve;
10428: if (!$lastres) {
10429: $lastres = $slots{$slot}->{'starttime'};
10430: }
10431: $reservable_now{$slot} = {
10432: symb => $symb,
10433: endreserve => $lastres,
10434: uniqueperiod => $uniqueperiod,
10435: };
10436: } elsif (($startreserve > $now) &&
10437: (!$endreserve || $endreserve > $startreserve)) {
10438: $future_reservable{$slot} = {
10439: symb => $symb,
10440: startreserve => $startreserve,
10441: uniqueperiod => $uniqueperiod,
10442: };
10443: }
10444: }
10445: }
10446: my @unsorted_reservable = keys(%reservable_now);
10447: if (@unsorted_reservable > 0) {
10448: @sorted_reservable =
10449: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10450: }
10451: my @unsorted_future = keys(%future_reservable);
10452: if (@unsorted_future > 0) {
10453: @sorted_future =
10454: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10455: }
10456: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10457: }
10458:
10459: =pod
10460:
10461: =back
10462:
10463: =head1 HTTP Helpers
10464:
10465: =over 4
10466:
10467: =item * &get_unprocessed_cgi($query,$possible_names)
10468:
10469: Modify the %env hash to contain unprocessed CGI form parameters held in
10470: $query. The parameters listed in $possible_names (an array reference),
10471: will be set in $env{'form.name'} if they do not already exist.
10472:
10473: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
10474: $possible_names is an ref to an array of form element names. As an example:
10475: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10476: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10477:
10478: =cut
10479:
10480: sub get_unprocessed_cgi {
10481: my ($query,$possible_names)= @_;
10482: # $Apache::lonxml::debug=1;
10483: foreach my $pair (split(/&/,$query)) {
10484: my ($name, $value) = split(/=/,$pair);
10485: $name = &unescape($name);
10486: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10487: $value =~ tr/+/ /;
10488: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10489: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10490: }
10491: }
10492: }
10493:
10494: =pod
10495:
10496: =item * &cacheheader()
10497:
10498: returns cache-controlling header code
10499:
10500: =cut
10501:
10502: sub cacheheader {
10503: unless ($env{'request.method'} eq 'GET') { return ''; }
10504: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10505: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10506: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10507: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10508: return $output;
10509: }
10510:
10511: =pod
10512:
10513: =item * &no_cache($r)
10514:
10515: specifies header code to not have cache
10516:
10517: =cut
10518:
10519: sub no_cache {
10520: my ($r) = @_;
10521: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10522: $env{'request.method'} ne 'GET') { return ''; }
10523: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10524: $r->no_cache(1);
10525: $r->header_out("Expires" => $date);
10526: $r->header_out("Pragma" => "no-cache");
10527: }
10528:
10529: sub content_type {
10530: my ($r,$type,$charset) = @_;
10531: if ($r) {
10532: # Note that printout.pl calls this with undef for $r.
10533: &no_cache($r);
10534: }
10535: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10536: unless ($charset) {
10537: $charset=&Apache::lonlocal::current_encoding;
10538: }
10539: if ($charset) { $type.='; charset='.$charset; }
10540: if ($r) {
10541: $r->content_type($type);
10542: } else {
10543: print("Content-type: $type\n\n");
10544: }
10545: }
10546:
10547: =pod
10548:
10549: =item * &add_to_env($name,$value)
10550:
10551: adds $name to the %env hash with value
10552: $value, if $name already exists, the entry is converted to an array
10553: reference and $value is added to the array.
10554:
10555: =cut
10556:
10557: sub add_to_env {
10558: my ($name,$value)=@_;
10559: if (defined($env{$name})) {
10560: if (ref($env{$name})) {
10561: #already have multiple values
10562: push(@{ $env{$name} },$value);
10563: } else {
10564: #first time seeing multiple values, convert hash entry to an arrayref
10565: my $first=$env{$name};
10566: undef($env{$name});
10567: push(@{ $env{$name} },$first,$value);
10568: }
10569: } else {
10570: $env{$name}=$value;
10571: }
10572: }
10573:
10574: =pod
10575:
10576: =item * &get_env_multiple($name)
10577:
10578: gets $name from the %env hash, it seemlessly handles the cases where multiple
10579: values may be defined and end up as an array ref.
10580:
10581: returns an array of values
10582:
10583: =cut
10584:
10585: sub get_env_multiple {
10586: my ($name) = @_;
10587: my @values;
10588: if (defined($env{$name})) {
10589: # exists is it an array
10590: if (ref($env{$name})) {
10591: @values=@{ $env{$name} };
10592: } else {
10593: $values[0]=$env{$name};
10594: }
10595: }
10596: return(@values);
10597: }
10598:
10599: sub ask_for_embedded_content {
10600: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
10601: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
10602: %currsubfile,%unused,$rem);
10603: my $counter = 0;
10604: my $numnew = 0;
10605: my $numremref = 0;
10606: my $numinvalid = 0;
10607: my $numpathchg = 0;
10608: my $numexisting = 0;
10609: my $numunused = 0;
10610: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10611: $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10612: my $heading = &mt('Upload embedded files');
10613: my $buttontext = &mt('Upload');
10614:
10615: if ($env{'request.course.id'}) {
10616: if ($actionurl eq '/adm/dependencies') {
10617: $navmap = Apache::lonnavmaps::navmap->new();
10618: }
10619: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10620: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10621: }
10622: if (($actionurl eq '/adm/portfolio') ||
10623: ($actionurl eq '/adm/coursegrp_portfolio')) {
10624: my $current_path='/';
10625: if ($env{'form.currentpath'}) {
10626: $current_path = $env{'form.currentpath'};
10627: }
10628: if ($actionurl eq '/adm/coursegrp_portfolio') {
10629: $udom = $cdom;
10630: $uname = $cnum;
10631: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10632: } else {
10633: $udom = $env{'user.domain'};
10634: $uname = $env{'user.name'};
10635: $url = '/userfiles/portfolio';
10636: }
10637: $toplevel = $url.'/';
10638: $url .= $current_path;
10639: $getpropath = 1;
10640: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10641: ($actionurl eq '/adm/imsimport')) {
10642: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
10643: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
10644: $toplevel = $url;
10645: if ($rest ne '') {
10646: $url .= $rest;
10647: }
10648: } elsif ($actionurl eq '/adm/coursedocs') {
10649: if (ref($args) eq 'HASH') {
10650: $url = $args->{'docs_url'};
10651: $toplevel = $url;
10652: if ($args->{'context'} eq 'paste') {
10653: ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
10654: ($path) =
10655: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10656: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10657: $fileloc =~ s{^/}{};
10658: }
10659: }
10660: } elsif ($actionurl eq '/adm/dependencies') {
10661: if ($env{'request.course.id'} ne '') {
10662: if (ref($args) eq 'HASH') {
10663: $url = $args->{'docs_url'};
10664: $title = $args->{'docs_title'};
10665: $toplevel = $url;
10666: unless ($toplevel =~ m{^/}) {
10667: $toplevel = "/$url";
10668: }
10669: ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
10670: if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
10671: $path = $1;
10672: } else {
10673: ($path) =
10674: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10675: }
10676: if ($toplevel=~/^\/*(uploaded|editupload)/) {
10677: $fileloc = $toplevel;
10678: $fileloc=~ s/^\s*(\S+)\s*$/$1/;
10679: my ($udom,$uname,$fname) =
10680: ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
10681: $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
10682: } else {
10683: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10684: }
10685: $fileloc =~ s{^/}{};
10686: ($filename) = ($fileloc =~ m{.+/([^/]+)$});
10687: $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
10688: }
10689: }
10690: } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10691: $udom = $cdom;
10692: $uname = $cnum;
10693: $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
10694: $toplevel = $url;
10695: $path = $url;
10696: $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
10697: $fileloc =~ s{^/}{};
10698: }
10699: foreach my $file (keys(%{$allfiles})) {
10700: my $embed_file;
10701: if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
10702: $embed_file = $1;
10703: } else {
10704: $embed_file = $file;
10705: }
10706: my ($absolutepath,$cleaned_file);
10707: if ($embed_file =~ m{^\w+://}) {
10708: $cleaned_file = $embed_file;
10709: $newfiles{$cleaned_file} = 1;
10710: $mapping{$cleaned_file} = $embed_file;
10711: } else {
10712: $cleaned_file = &clean_path($embed_file);
10713: if ($embed_file =~ m{^/}) {
10714: $absolutepath = $embed_file;
10715: }
10716: if ($cleaned_file =~ m{/}) {
10717: my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
10718: $path = &check_for_traversal($path,$url,$toplevel);
10719: my $item = $fname;
10720: if ($path ne '') {
10721: $item = $path.'/'.$fname;
10722: $subdependencies{$path}{$fname} = 1;
10723: } else {
10724: $dependencies{$item} = 1;
10725: }
10726: if ($absolutepath) {
10727: $mapping{$item} = $absolutepath;
10728: } else {
10729: $mapping{$item} = $embed_file;
10730: }
10731: } else {
10732: $dependencies{$embed_file} = 1;
10733: if ($absolutepath) {
10734: $mapping{$cleaned_file} = $absolutepath;
10735: } else {
10736: $mapping{$cleaned_file} = $embed_file;
10737: }
10738: }
10739: }
10740: }
10741: my $dirptr = 16384;
10742: foreach my $path (keys(%subdependencies)) {
10743: $currsubfile{$path} = {};
10744: if (($actionurl eq '/adm/portfolio') ||
10745: ($actionurl eq '/adm/coursegrp_portfolio')) {
10746: my ($sublistref,$listerror) =
10747: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
10748: if (ref($sublistref) eq 'ARRAY') {
10749: foreach my $line (@{$sublistref}) {
10750: my ($file_name,$rest) = split(/\&/,$line,2);
10751: $currsubfile{$path}{$file_name} = 1;
10752: }
10753: }
10754: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10755: if (opendir(my $dir,$url.'/'.$path)) {
10756: my @subdir_list = grep(!/^\./,readdir($dir));
10757: map {$currsubfile{$path}{$_} = 1;} @subdir_list;
10758: }
10759: } elsif (($actionurl eq '/adm/dependencies') ||
10760: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10761: ($args->{'context'} eq 'paste')) ||
10762: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10763: if ($env{'request.course.id'} ne '') {
10764: my $dir;
10765: if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10766: $dir = $fileloc;
10767: } else {
10768: ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10769: }
10770: if ($dir ne '') {
10771: my ($sublistref,$listerror) =
10772: &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
10773: if (ref($sublistref) eq 'ARRAY') {
10774: foreach my $line (@{$sublistref}) {
10775: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
10776: undef,$mtime)=split(/\&/,$line,12);
10777: unless (($testdir&$dirptr) ||
10778: ($file_name =~ /^\.\.?$/)) {
10779: $currsubfile{$path}{$file_name} = [$size,$mtime];
10780: }
10781: }
10782: }
10783: }
10784: }
10785: }
10786: foreach my $file (keys(%{$subdependencies{$path}})) {
10787: if (exists($currsubfile{$path}{$file})) {
10788: my $item = $path.'/'.$file;
10789: unless ($mapping{$item} eq $item) {
10790: $pathchanges{$item} = 1;
10791: }
10792: $existing{$item} = 1;
10793: $numexisting ++;
10794: } else {
10795: $newfiles{$path.'/'.$file} = 1;
10796: }
10797: }
10798: if ($actionurl eq '/adm/dependencies') {
10799: foreach my $path (keys(%currsubfile)) {
10800: if (ref($currsubfile{$path}) eq 'HASH') {
10801: foreach my $file (keys(%{$currsubfile{$path}})) {
10802: unless ($subdependencies{$path}{$file}) {
10803: next if (($rem ne '') &&
10804: (($env{"httpref.$rem"."$path/$file"} ne '') ||
10805: (ref($navmap) &&
10806: (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10807: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10808: ($navmap->getResourceByUrl($rem."$path/$1")))))));
10809: $unused{$path.'/'.$file} = 1;
10810: }
10811: }
10812: }
10813: }
10814: }
10815: }
10816: my %currfile;
10817: if (($actionurl eq '/adm/portfolio') ||
10818: ($actionurl eq '/adm/coursegrp_portfolio')) {
10819: my ($dirlistref,$listerror) =
10820: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10821: if (ref($dirlistref) eq 'ARRAY') {
10822: foreach my $line (@{$dirlistref}) {
10823: my ($file_name,$rest) = split(/\&/,$line,2);
10824: $currfile{$file_name} = 1;
10825: }
10826: }
10827: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10828: if (opendir(my $dir,$url)) {
10829: my @dir_list = grep(!/^\./,readdir($dir));
10830: map {$currfile{$_} = 1;} @dir_list;
10831: }
10832: } elsif (($actionurl eq '/adm/dependencies') ||
10833: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10834: ($args->{'context'} eq 'paste')) ||
10835: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10836: if ($env{'request.course.id'} ne '') {
10837: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10838: if ($dir ne '') {
10839: my ($dirlistref,$listerror) =
10840: &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10841: if (ref($dirlistref) eq 'ARRAY') {
10842: foreach my $line (@{$dirlistref}) {
10843: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10844: $size,undef,$mtime)=split(/\&/,$line,12);
10845: unless (($testdir&$dirptr) ||
10846: ($file_name =~ /^\.\.?$/)) {
10847: $currfile{$file_name} = [$size,$mtime];
10848: }
10849: }
10850: }
10851: }
10852: }
10853: }
10854: foreach my $file (keys(%dependencies)) {
10855: if (exists($currfile{$file})) {
10856: unless ($mapping{$file} eq $file) {
10857: $pathchanges{$file} = 1;
10858: }
10859: $existing{$file} = 1;
10860: $numexisting ++;
10861: } else {
10862: $newfiles{$file} = 1;
10863: }
10864: }
10865: foreach my $file (keys(%currfile)) {
10866: unless (($file eq $filename) ||
10867: ($file eq $filename.'.bak') ||
10868: ($dependencies{$file})) {
10869: if ($actionurl eq '/adm/dependencies') {
10870: unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10871: next if (($rem ne '') &&
10872: (($env{"httpref.$rem".$file} ne '') ||
10873: (ref($navmap) &&
10874: (($navmap->getResourceByUrl($rem.$file) ne '') ||
10875: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10876: ($navmap->getResourceByUrl($rem.$1)))))));
10877: }
10878: }
10879: $unused{$file} = 1;
10880: }
10881: }
10882: if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10883: ($args->{'context'} eq 'paste')) {
10884: $counter = scalar(keys(%existing));
10885: $numpathchg = scalar(keys(%pathchanges));
10886: return ($output,$counter,$numpathchg,\%existing);
10887: } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
10888: (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10889: $counter = scalar(keys(%existing));
10890: $numpathchg = scalar(keys(%pathchanges));
10891: return ($output,$counter,$numpathchg,\%existing,\%mapping);
10892: }
10893: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10894: if ($actionurl eq '/adm/dependencies') {
10895: next if ($embed_file =~ m{^\w+://});
10896: }
10897: $upload_output .= &start_data_table_row().
10898: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
10899: '<span class="LC_filename">'.$embed_file.'</span>';
10900: unless ($mapping{$embed_file} eq $embed_file) {
10901: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10902: &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10903: }
10904: $upload_output .= '</td>';
10905: if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) {
10906: $upload_output.='<td align="right">'.
10907: '<span class="LC_info LC_fontsize_medium">'.
10908: &mt("URL points to web address").'</span>';
10909: $numremref++;
10910: } elsif ($args->{'error_on_invalid_names'}
10911: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10912: $upload_output.='<td align="right"><span class="LC_warning">'.
10913: &mt('Invalid characters').'</span>';
10914: $numinvalid++;
10915: } else {
10916: $upload_output .= '<td>'.
10917: &embedded_file_element('upload_embedded',$counter,
10918: $embed_file,\%mapping,
10919: $allfiles,$codebase,'upload');
10920: $counter ++;
10921: $numnew ++;
10922: }
10923: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10924: }
10925: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10926: if ($actionurl eq '/adm/dependencies') {
10927: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10928: $modify_output .= &start_data_table_row().
10929: '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10930: '<img src="'.&icon($embed_file).'" border="0" />'.
10931: ' <span class="LC_filename">'.$embed_file.'</span></a></td>'.
10932: '<td>'.$size.'</td>'.
10933: '<td>'.$mtime.'</td>'.
10934: '<td><label><input type="checkbox" name="mod_upload_dep" '.
10935: 'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10936: $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10937: '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10938: &embedded_file_element('upload_embedded',$counter,
10939: $embed_file,\%mapping,
10940: $allfiles,$codebase,'modify').
10941: '</div></td>'.
10942: &end_data_table_row()."\n";
10943: $counter ++;
10944: } else {
10945: $upload_output .= &start_data_table_row().
10946: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
10947: '<span class="LC_filename">'.$embed_file.'</span></td>'.
10948: '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10949: &Apache::loncommon::end_data_table_row()."\n";
10950: }
10951: }
10952: my $delidx = $counter;
10953: foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10954: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10955: $delete_output .= &start_data_table_row().
10956: '<td><img src="'.&icon($oldfile).'" />'.
10957: ' <span class="LC_filename">'.$oldfile.'</span></td>'.
10958: '<td>'.$size.'</td>'.
10959: '<td>'.$mtime.'</td>'.
10960: '<td><label><input type="checkbox" name="del_upload_dep" '.
10961: ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10962: &embedded_file_element('upload_embedded',$delidx,
10963: $oldfile,\%mapping,$allfiles,
10964: $codebase,'delete').'</td>'.
10965: &end_data_table_row()."\n";
10966: $numunused ++;
10967: $delidx ++;
10968: }
10969: if ($upload_output) {
10970: $upload_output = &start_data_table().
10971: $upload_output.
10972: &end_data_table()."\n";
10973: }
10974: if ($modify_output) {
10975: $modify_output = &start_data_table().
10976: &start_data_table_header_row().
10977: '<th>'.&mt('File').'</th>'.
10978: '<th>'.&mt('Size (KB)').'</th>'.
10979: '<th>'.&mt('Modified').'</th>'.
10980: '<th>'.&mt('Upload replacement?').'</th>'.
10981: &end_data_table_header_row().
10982: $modify_output.
10983: &end_data_table()."\n";
10984: }
10985: if ($delete_output) {
10986: $delete_output = &start_data_table().
10987: &start_data_table_header_row().
10988: '<th>'.&mt('File').'</th>'.
10989: '<th>'.&mt('Size (KB)').'</th>'.
10990: '<th>'.&mt('Modified').'</th>'.
10991: '<th>'.&mt('Delete?').'</th>'.
10992: &end_data_table_header_row().
10993: $delete_output.
10994: &end_data_table()."\n";
10995: }
10996: my $applies = 0;
10997: if ($numremref) {
10998: $applies ++;
10999: }
11000: if ($numinvalid) {
11001: $applies ++;
11002: }
11003: if ($numexisting) {
11004: $applies ++;
11005: }
11006: if ($counter || $numunused) {
11007: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11008: ' method="post" enctype="multipart/form-data">'."\n".
11009: $state.'<h3>'.$heading.'</h3>';
11010: if ($actionurl eq '/adm/dependencies') {
11011: if ($numnew) {
11012: $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11013: '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11014: $upload_output.'<br />'."\n";
11015: }
11016: if ($numexisting) {
11017: $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11018: '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11019: $modify_output.'<br />'."\n";
11020: $buttontext = &mt('Save changes');
11021: }
11022: if ($numunused) {
11023: $output .= '<h4>'.&mt('Unused files').'</h4>'.
11024: '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11025: $delete_output.'<br />'."\n";
11026: $buttontext = &mt('Save changes');
11027: }
11028: } else {
11029: $output .= $upload_output.'<br />'."\n";
11030: }
11031: $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11032: $counter.'" />'."\n";
11033: if ($actionurl eq '/adm/dependencies') {
11034: $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11035: $numnew.'" />'."\n";
11036: } elsif ($actionurl eq '') {
11037: $output .= '<input type="hidden" name="phase" value="three" />';
11038: }
11039: } elsif ($applies) {
11040: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11041: if ($applies > 1) {
11042: $output .=
11043: &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11044: if ($numremref) {
11045: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11046: }
11047: if ($numinvalid) {
11048: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11049: }
11050: if ($numexisting) {
11051: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11052: }
11053: $output .= '</ul><br />';
11054: } elsif ($numremref) {
11055: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11056: } elsif ($numinvalid) {
11057: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11058: } elsif ($numexisting) {
11059: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11060: }
11061: $output .= $upload_output.'<br />';
11062: }
11063: my ($pathchange_output,$chgcount);
11064: $chgcount = $counter;
11065: if (keys(%pathchanges) > 0) {
11066: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11067: if ($counter) {
11068: $output .= &embedded_file_element('pathchange',$chgcount,
11069: $embed_file,\%mapping,
11070: $allfiles,$codebase,'change');
11071: } else {
11072: $pathchange_output .=
11073: &start_data_table_row().
11074: '<td><input type ="checkbox" name="namechange" value="'.
11075: $chgcount.'" checked="checked" /></td>'.
11076: '<td>'.$mapping{$embed_file}.'</td>'.
11077: '<td>'.$embed_file.
11078: &embedded_file_element('pathchange',$numpathchg,$embed_file,
11079: \%mapping,$allfiles,$codebase,'change').
11080: '</td>'.&end_data_table_row();
11081: }
11082: $numpathchg ++;
11083: $chgcount ++;
11084: }
11085: }
11086: if (($counter) || ($numunused)) {
11087: if ($numpathchg) {
11088: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11089: $numpathchg.'" />'."\n";
11090: }
11091: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11092: ($actionurl eq '/adm/imsimport')) {
11093: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11094: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11095: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11096: } elsif ($actionurl eq '/adm/dependencies') {
11097: $output .= '<input type="hidden" name="action" value="process_changes" />';
11098: }
11099: $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11100: } elsif ($numpathchg) {
11101: my %pathchange = ();
11102: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11103: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11104: $output .= '<p>'.&mt('or').'</p>';
11105: }
11106: }
11107: return ($output,$counter,$numpathchg);
11108: }
11109:
11110: =pod
11111:
11112: =item * clean_path($name)
11113:
11114: Performs clean-up of directories, subdirectories and filename in an
11115: embedded object, referenced in an HTML file which is being uploaded
11116: to a course or portfolio, where
11117: "Upload embedded images/multimedia files if HTML file" checkbox was
11118: checked.
11119:
11120: Clean-up is similar to replacements in lonnet::clean_filename()
11121: except each / between sub-directory and next level is preserved.
11122:
11123: =cut
11124:
11125: sub clean_path {
11126: my ($embed_file) = @_;
11127: $embed_file =~s{^/+}{};
11128: my @contents;
11129: if ($embed_file =~ m{/}) {
11130: @contents = split(/\//,$embed_file);
11131: } else {
11132: @contents = ($embed_file);
11133: }
11134: my $lastidx = scalar(@contents)-1;
11135: for (my $i=0; $i<=$lastidx; $i++) {
11136: $contents[$i]=~s{\\}{/}g;
11137: $contents[$i]=~s/\s+/\_/g;
11138: $contents[$i]=~s{[^/\w\.\-]}{}g;
11139: if ($i == $lastidx) {
11140: $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11141: }
11142: }
11143: if ($lastidx > 0) {
11144: return join('/',@contents);
11145: } else {
11146: return $contents[0];
11147: }
11148: }
11149:
11150: sub embedded_file_element {
11151: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11152: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11153: (ref($codebase) eq 'HASH'));
11154: my $output;
11155: if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11156: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11157: }
11158: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11159: &escape($embed_file).'" />';
11160: unless (($context eq 'upload_embedded') &&
11161: ($mapping->{$embed_file} eq $embed_file)) {
11162: $output .='
11163: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11164: }
11165: my $attrib;
11166: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11167: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11168: }
11169: $output .=
11170: "\n\t\t".
11171: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11172: $attrib.'" />';
11173: if (exists($codebase->{$mapping->{$embed_file}})) {
11174: $output .=
11175: "\n\t\t".
11176: '<input name="codebase_'.$num.'" type="hidden" value="'.
11177: &escape($codebase->{$mapping->{$embed_file}}).'" />';
11178: }
11179: return $output;
11180: }
11181:
11182: sub get_dependency_details {
11183: my ($currfile,$currsubfile,$embed_file) = @_;
11184: my ($size,$mtime,$showsize,$showmtime);
11185: if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11186: if ($embed_file =~ m{/}) {
11187: my ($path,$fname) = split(/\//,$embed_file);
11188: if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11189: ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11190: }
11191: } else {
11192: if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11193: ($size,$mtime) = @{$currfile->{$embed_file}};
11194: }
11195: }
11196: $showsize = $size/1024.0;
11197: $showsize = sprintf("%.1f",$showsize);
11198: if ($mtime > 0) {
11199: $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11200: }
11201: }
11202: return ($showsize,$showmtime);
11203: }
11204:
11205: sub ask_embedded_js {
11206: return <<"END";
11207: <script type="text/javascript"">
11208: // <![CDATA[
11209: function toggleBrowse(counter) {
11210: var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11211: var fileid = document.getElementById('embedded_item_'+counter);
11212: var uploaddivid = document.getElementById('moduploaddep_'+counter);
11213: if (chkboxid.checked == true) {
11214: uploaddivid.style.display='block';
11215: } else {
11216: uploaddivid.style.display='none';
11217: fileid.value = '';
11218: }
11219: }
11220: // ]]>
11221: </script>
11222:
11223: END
11224: }
11225:
11226: sub upload_embedded {
11227: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11228: $current_disk_usage,$hiddenstate,$actionurl) = @_;
11229: my (%pathchange,$output,$modifyform,$footer,$returnflag);
11230: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11231: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11232: my $orig_uploaded_filename =
11233: $env{'form.embedded_item_'.$i.'.filename'};
11234: foreach my $type ('orig','ref','attrib','codebase') {
11235: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11236: $env{'form.embedded_'.$type.'_'.$i} =
11237: &unescape($env{'form.embedded_'.$type.'_'.$i});
11238: }
11239: }
11240: my ($path,$fname) =
11241: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11242: # no path, whole string is fname
11243: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11244: $fname = &Apache::lonnet::clean_filename($fname);
11245: # See if there is anything left
11246: next if ($fname eq '');
11247:
11248: # Check if file already exists as a file or directory.
11249: my ($state,$msg);
11250: if ($context eq 'portfolio') {
11251: my $port_path = $dirpath;
11252: if ($group ne '') {
11253: $port_path = "groups/$group/$port_path";
11254: }
11255: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11256: $fname,$group,'embedded_item_'.$i,
11257: $dir_root,$port_path,$disk_quota,
11258: $current_disk_usage,$uname,$udom);
11259: if ($state eq 'will_exceed_quota'
11260: || $state eq 'file_locked') {
11261: $output .= $msg;
11262: next;
11263: }
11264: } elsif (($context eq 'author') || ($context eq 'testbank')) {
11265: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11266: if ($state eq 'exists') {
11267: $output .= $msg;
11268: next;
11269: }
11270: }
11271: # Check if extension is valid
11272: if (($fname =~ /\.(\w+)$/) &&
11273: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11274: $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11275: .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11276: next;
11277: } elsif (($fname =~ /\.(\w+)$/) &&
11278: (!defined(&Apache::loncommon::fileembstyle($1)))) {
11279: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11280: next;
11281: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11282: $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11283: next;
11284: }
11285: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11286: my $subdir = $path;
11287: $subdir =~ s{/+$}{};
11288: if ($context eq 'portfolio') {
11289: my $result;
11290: if ($state eq 'existingfile') {
11291: $result=
11292: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11293: $dirpath.$env{'form.currentpath'}.$subdir);
11294: } else {
11295: $result=
11296: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11297: $dirpath.
11298: $env{'form.currentpath'}.$subdir);
11299: if ($result !~ m|^/uploaded/|) {
11300: $output .= '<span class="LC_error">'
11301: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11302: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11303: .'</span><br />';
11304: next;
11305: } else {
11306: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11307: $path.$fname.'</span>').'<br />';
11308: }
11309: }
11310: } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11311: my $extendedsubdir = $dirpath.'/'.$subdir;
11312: $extendedsubdir =~ s{/+$}{};
11313: my $result =
11314: &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11315: if ($result !~ m|^/uploaded/|) {
11316: $output .= '<span class="LC_error">'
11317: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11318: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11319: .'</span><br />';
11320: next;
11321: } else {
11322: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11323: $path.$fname.'</span>').'<br />';
11324: if ($context eq 'syllabus') {
11325: &Apache::lonnet::make_public_indefinitely($result);
11326: }
11327: }
11328: } else {
11329: # Save the file
11330: my $target = $env{'form.embedded_item_'.$i};
11331: my $fullpath = $dir_root.$dirpath.'/'.$path;
11332: my $dest = $fullpath.$fname;
11333: my $url = $url_root.$dirpath.'/'.$path.$fname;
11334: my @parts=split(/\//,"$dirpath/$path");
11335: my $count;
11336: my $filepath = $dir_root;
11337: foreach my $subdir (@parts) {
11338: $filepath .= "/$subdir";
11339: if (!-e $filepath) {
11340: mkdir($filepath,0770);
11341: }
11342: }
11343: my $fh;
11344: if (!open($fh,'>'.$dest)) {
11345: &Apache::lonnet::logthis('Failed to create '.$dest);
11346: $output .= '<span class="LC_error">'.
11347: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11348: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11349: '</span><br />';
11350: } else {
11351: if (!print $fh $env{'form.embedded_item_'.$i}) {
11352: &Apache::lonnet::logthis('Failed to write to '.$dest);
11353: $output .= '<span class="LC_error">'.
11354: &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11355: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11356: '</span><br />';
11357: } else {
11358: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11359: $url.'</span>').'<br />';
11360: unless ($context eq 'testbank') {
11361: $footer .= &mt('View embedded file: [_1]',
11362: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11363: }
11364: }
11365: close($fh);
11366: }
11367: }
11368: if ($env{'form.embedded_ref_'.$i}) {
11369: $pathchange{$i} = 1;
11370: }
11371: }
11372: if ($output) {
11373: $output = '<p>'.$output.'</p>';
11374: }
11375: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11376: $returnflag = 'ok';
11377: my $numpathchgs = scalar(keys(%pathchange));
11378: if ($numpathchgs > 0) {
11379: if ($context eq 'portfolio') {
11380: $output .= '<p>'.&mt('or').'</p>';
11381: } elsif ($context eq 'testbank') {
11382: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11383: '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11384: $returnflag = 'modify_orightml';
11385: }
11386: }
11387: return ($output.$footer,$returnflag,$numpathchgs);
11388: }
11389:
11390: sub modify_html_form {
11391: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11392: my $end = 0;
11393: my $modifyform;
11394: if ($context eq 'upload_embedded') {
11395: return unless (ref($pathchange) eq 'HASH');
11396: if ($env{'form.number_embedded_items'}) {
11397: $end += $env{'form.number_embedded_items'};
11398: }
11399: if ($env{'form.number_pathchange_items'}) {
11400: $end += $env{'form.number_pathchange_items'};
11401: }
11402: if ($end) {
11403: for (my $i=0; $i<$end; $i++) {
11404: if ($i < $env{'form.number_embedded_items'}) {
11405: next unless($pathchange->{$i});
11406: }
11407: $modifyform .=
11408: &start_data_table_row().
11409: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11410: 'checked="checked" /></td>'.
11411: '<td>'.$env{'form.embedded_ref_'.$i}.
11412: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11413: &escape($env{'form.embedded_ref_'.$i}).'" />'.
11414: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11415: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11416: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11417: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11418: '<td>'.$env{'form.embedded_orig_'.$i}.
11419: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11420: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11421: &end_data_table_row();
11422: }
11423: }
11424: } else {
11425: $modifyform = $pathchgtable;
11426: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11427: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11428: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11429: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11430: }
11431: }
11432: if ($modifyform) {
11433: if ($actionurl eq '/adm/dependencies') {
11434: $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11435: }
11436: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11437: '<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".
11438: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11439: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11440: '</ol></p>'."\n".'<p>'.
11441: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11442: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11443: &start_data_table()."\n".
11444: &start_data_table_header_row().
11445: '<th>'.&mt('Change?').'</th>'.
11446: '<th>'.&mt('Current reference').'</th>'.
11447: '<th>'.&mt('Required reference').'</th>'.
11448: &end_data_table_header_row()."\n".
11449: $modifyform.
11450: &end_data_table().'<br />'."\n".$hiddenstate.
11451: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11452: '</form>'."\n";
11453: }
11454: return;
11455: }
11456:
11457: sub modify_html_refs {
11458: my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11459: my $container;
11460: if ($context eq 'portfolio') {
11461: $container = $env{'form.container'};
11462: } elsif ($context eq 'coursedoc') {
11463: $container = $env{'form.primaryurl'};
11464: } elsif ($context eq 'manage_dependencies') {
11465: (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11466: $container = "/$container";
11467: } elsif ($context eq 'syllabus') {
11468: $container = $url;
11469: } else {
11470: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11471: }
11472: my (%allfiles,%codebase,$output,$content);
11473: my @changes = &get_env_multiple('form.namechange');
11474: unless ((@changes > 0) || ($context eq 'syllabus')) {
11475: if (wantarray) {
11476: return ('',0,0);
11477: } else {
11478: return;
11479: }
11480: }
11481: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
11482: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11483: unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11484: if (wantarray) {
11485: return ('',0,0);
11486: } else {
11487: return;
11488: }
11489: }
11490: $content = &Apache::lonnet::getfile($container);
11491: if ($content eq '-1') {
11492: if (wantarray) {
11493: return ('',0,0);
11494: } else {
11495: return;
11496: }
11497: }
11498: } else {
11499: unless ($container =~ /^\Q$dir_root\E/) {
11500: if (wantarray) {
11501: return ('',0,0);
11502: } else {
11503: return;
11504: }
11505: }
11506: if (open(my $fh,"<$container")) {
11507: $content = join('', <$fh>);
11508: close($fh);
11509: } else {
11510: if (wantarray) {
11511: return ('',0,0);
11512: } else {
11513: return;
11514: }
11515: }
11516: }
11517: my ($count,$codebasecount) = (0,0);
11518: my $mm = new File::MMagic;
11519: my $mime_type = $mm->checktype_contents($content);
11520: if ($mime_type eq 'text/html') {
11521: my $parse_result =
11522: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11523: \%codebase,\$content);
11524: if ($parse_result eq 'ok') {
11525: foreach my $i (@changes) {
11526: my $orig = &unescape($env{'form.embedded_orig_'.$i});
11527: my $ref = &unescape($env{'form.embedded_ref_'.$i});
11528: if ($allfiles{$ref}) {
11529: my $newname = $orig;
11530: my ($attrib_regexp,$codebase);
11531: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11532: if ($attrib_regexp =~ /:/) {
11533: $attrib_regexp =~ s/\:/|/g;
11534: }
11535: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11536: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11537: $count += $numchg;
11538: $allfiles{$newname} = $allfiles{$ref};
11539: delete($allfiles{$ref});
11540: }
11541: if ($env{'form.embedded_codebase_'.$i} ne '') {
11542: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11543: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
11544: $codebasecount ++;
11545: }
11546: }
11547: }
11548: my $skiprewrites;
11549: if ($count || $codebasecount) {
11550: my $saveresult;
11551: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
11552: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11553: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11554: if ($url eq $container) {
11555: my ($fname) = ($container =~ m{/([^/]+)$});
11556: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11557: $count,'<span class="LC_filename">'.
11558: $fname.'</span>').'</p>';
11559: } else {
11560: $output = '<p class="LC_error">'.
11561: &mt('Error: update failed for: [_1].',
11562: '<span class="LC_filename">'.
11563: $container.'</span>').'</p>';
11564: }
11565: if ($context eq 'syllabus') {
11566: unless ($saveresult eq 'ok') {
11567: $skiprewrites = 1;
11568: }
11569: }
11570: } else {
11571: if (open(my $fh,">$container")) {
11572: print $fh $content;
11573: close($fh);
11574: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11575: $count,'<span class="LC_filename">'.
11576: $container.'</span>').'</p>';
11577: } else {
11578: $output = '<p class="LC_error">'.
11579: &mt('Error: could not update [_1].',
11580: '<span class="LC_filename">'.
11581: $container.'</span>').'</p>';
11582: }
11583: }
11584: }
11585: if (($context eq 'syllabus') && (!$skiprewrites)) {
11586: my ($actionurl,$state);
11587: $actionurl = "/public/$udom/$uname/syllabus";
11588: my ($ignore,$num,$numpathchanges,$existing,$mapping) =
11589: &ask_for_embedded_content($actionurl,$state,\%allfiles,
11590: \%codebase,
11591: {'context' => 'rewrites',
11592: 'ignore_remote_references' => 1,});
11593: if (ref($mapping) eq 'HASH') {
11594: my $rewrites = 0;
11595: foreach my $key (keys(%{$mapping})) {
11596: next if ($key =~ m{^https?://});
11597: my $ref = $mapping->{$key};
11598: my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
11599: my $attrib;
11600: if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
11601: $attrib = join('|',@{$allfiles{$mapping->{$key}}});
11602: }
11603: if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11604: my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11605: $rewrites += $numchg;
11606: }
11607: }
11608: if ($rewrites) {
11609: my $saveresult;
11610: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11611: if ($url eq $container) {
11612: my ($fname) = ($container =~ m{/([^/]+)$});
11613: $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11614: $count,'<span class="LC_filename">'.
11615: $fname.'</span>').'</p>';
11616: } else {
11617: $output .= '<p class="LC_error">'.
11618: &mt('Error: could not update links in [_1].',
11619: '<span class="LC_filename">'.
11620: $container.'</span>').'</p>';
11621:
11622: }
11623: }
11624: }
11625: }
11626: } else {
11627: &logthis('Failed to parse '.$container.
11628: ' to modify references: '.$parse_result);
11629: }
11630: }
11631: if (wantarray) {
11632: return ($output,$count,$codebasecount);
11633: } else {
11634: return $output;
11635: }
11636: }
11637:
11638: sub check_for_existing {
11639: my ($path,$fname,$element) = @_;
11640: my ($state,$msg);
11641: if (-d $path.'/'.$fname) {
11642: $state = 'exists';
11643: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11644: } elsif (-e $path.'/'.$fname) {
11645: $state = 'exists';
11646: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11647: }
11648: if ($state eq 'exists') {
11649: $msg = '<span class="LC_error">'.$msg.'</span><br />';
11650: }
11651: return ($state,$msg);
11652: }
11653:
11654: sub check_for_upload {
11655: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
11656: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
11657: my $filesize = length($env{'form.'.$element});
11658: if (!$filesize) {
11659: my $msg = '<span class="LC_error">'.
11660: &mt('Unable to upload [_1]. (size = [_2] bytes)',
11661: '<span class="LC_filename">'.$fname.'</span>',
11662: $filesize).'<br />'.
11663: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
11664: '</span>';
11665: return ('zero_bytes',$msg);
11666: }
11667: $filesize = $filesize/1000; #express in k (1024?)
11668: my $getpropath = 1;
11669: my ($dirlistref,$listerror) =
11670: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
11671: my $found_file = 0;
11672: my $locked_file = 0;
11673: my @lockers;
11674: my $navmap;
11675: if ($env{'request.course.id'}) {
11676: $navmap = Apache::lonnavmaps::navmap->new();
11677: }
11678: if (ref($dirlistref) eq 'ARRAY') {
11679: foreach my $line (@{$dirlistref}) {
11680: my ($file_name,$rest)=split(/\&/,$line,2);
11681: if ($file_name eq $fname){
11682: $file_name = $path.$file_name;
11683: if ($group ne '') {
11684: $file_name = $group.$file_name;
11685: }
11686: $found_file = 1;
11687: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
11688: foreach my $lock (@lockers) {
11689: if (ref($lock) eq 'ARRAY') {
11690: my ($symb,$crsid) = @{$lock};
11691: if ($crsid eq $env{'request.course.id'}) {
11692: if (ref($navmap)) {
11693: my $res = $navmap->getBySymb($symb);
11694: foreach my $part (@{$res->parts()}) {
11695: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
11696: unless (($slot_status == $res->RESERVED) ||
11697: ($slot_status == $res->RESERVED_LOCATION)) {
11698: $locked_file = 1;
11699: }
11700: }
11701: } else {
11702: $locked_file = 1;
11703: }
11704: } else {
11705: $locked_file = 1;
11706: }
11707: }
11708: }
11709: } else {
11710: my @info = split(/\&/,$rest);
11711: my $currsize = $info[6]/1000;
11712: if ($currsize < $filesize) {
11713: my $extra = $filesize - $currsize;
11714: if (($current_disk_usage + $extra) > $disk_quota) {
11715: my $msg = '<p class="LC_warning">'.
11716: &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.',
11717: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
11718: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11719: $disk_quota,$current_disk_usage).'</p>';
11720: return ('will_exceed_quota',$msg);
11721: }
11722: }
11723: }
11724: }
11725: }
11726: }
11727: if (($current_disk_usage + $filesize) > $disk_quota){
11728: my $msg = '<p class="LC_warning">'.
11729: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
11730: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
11731: return ('will_exceed_quota',$msg);
11732: } elsif ($found_file) {
11733: if ($locked_file) {
11734: my $msg = '<p class="LC_warning">';
11735: $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>');
11736: $msg .= '</p>';
11737: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
11738: return ('file_locked',$msg);
11739: } else {
11740: my $msg = '<p class="LC_error">';
11741: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
11742: $msg .= '</p>';
11743: return ('existingfile',$msg);
11744: }
11745: }
11746: }
11747:
11748: sub check_for_traversal {
11749: my ($path,$url,$toplevel) = @_;
11750: my @parts=split(/\//,$path);
11751: my $cleanpath;
11752: my $fullpath = $url;
11753: for (my $i=0;$i<@parts;$i++) {
11754: next if ($parts[$i] eq '.');
11755: if ($parts[$i] eq '..') {
11756: $fullpath =~ s{([^/]+/)$}{};
11757: } else {
11758: $fullpath .= $parts[$i].'/';
11759: }
11760: }
11761: if ($fullpath =~ /^\Q$url\E(.*)$/) {
11762: $cleanpath = $1;
11763: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
11764: my $curr_toprel = $1;
11765: my @parts = split(/\//,$curr_toprel);
11766: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
11767: my @urlparts = split(/\//,$url_toprel);
11768: my $doubledots;
11769: my $startdiff = -1;
11770: for (my $i=0; $i<@urlparts; $i++) {
11771: if ($startdiff == -1) {
11772: unless ($urlparts[$i] eq $parts[$i]) {
11773: $startdiff = $i;
11774: $doubledots .= '../';
11775: }
11776: } else {
11777: $doubledots .= '../';
11778: }
11779: }
11780: if ($startdiff > -1) {
11781: $cleanpath = $doubledots;
11782: for (my $i=$startdiff; $i<@parts; $i++) {
11783: $cleanpath .= $parts[$i].'/';
11784: }
11785: }
11786: }
11787: $cleanpath =~ s{(/)$}{};
11788: return $cleanpath;
11789: }
11790:
11791: sub is_archive_file {
11792: my ($mimetype) = @_;
11793: if (($mimetype eq 'application/octet-stream') ||
11794: ($mimetype eq 'application/x-stuffit') ||
11795: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
11796: return 1;
11797: }
11798: return;
11799: }
11800:
11801: sub decompress_form {
11802: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11803: my %lt = &Apache::lonlocal::texthash (
11804: this => 'This file is an archive file.',
11805: camt => 'This file is a Camtasia archive file.',
11806: itsc => 'Its contents are as follows:',
11807: youm => 'You may wish to extract its contents.',
11808: extr => 'Extract contents',
11809: auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11810: proa => 'Process automatically?',
11811: yes => 'Yes',
11812: no => 'No',
11813: fold => 'Title for folder containing movie',
11814: movi => 'Title for page containing embedded movie',
11815: );
11816: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11817: my ($is_camtasia,$topdir,%toplevel,@paths);
11818: my $info = &list_archive_contents($fileloc,\@paths);
11819: if (@paths) {
11820: foreach my $path (@paths) {
11821: $path =~ s{^/}{};
11822: if ($path =~ m{^([^/]+)/$}) {
11823: $topdir = $1;
11824: }
11825: if ($path =~ m{^([^/]+)/}) {
11826: $toplevel{$1} = $path;
11827: } else {
11828: $toplevel{$path} = $path;
11829: }
11830: }
11831: }
11832: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11833: my @camtasia6 = ("$topdir/","$topdir/index.html",
11834: "$topdir/media/",
11835: "$topdir/media/$topdir.mp4",
11836: "$topdir/media/FirstFrame.png",
11837: "$topdir/media/player.swf",
11838: "$topdir/media/swfobject.js",
11839: "$topdir/media/expressInstall.swf");
11840: my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
11841: "$topdir/$topdir.mp4",
11842: "$topdir/$topdir\_config.xml",
11843: "$topdir/$topdir\_controller.swf",
11844: "$topdir/$topdir\_embed.css",
11845: "$topdir/$topdir\_First_Frame.png",
11846: "$topdir/$topdir\_player.html",
11847: "$topdir/$topdir\_Thumbnails.png",
11848: "$topdir/playerProductInstall.swf",
11849: "$topdir/scripts/",
11850: "$topdir/scripts/config_xml.js",
11851: "$topdir/scripts/handlebars.js",
11852: "$topdir/scripts/jquery-1.7.1.min.js",
11853: "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11854: "$topdir/scripts/modernizr.js",
11855: "$topdir/scripts/player-min.js",
11856: "$topdir/scripts/swfobject.js",
11857: "$topdir/skins/",
11858: "$topdir/skins/configuration_express.xml",
11859: "$topdir/skins/express_show/",
11860: "$topdir/skins/express_show/player-min.css",
11861: "$topdir/skins/express_show/spritesheet.png");
11862: my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
11863: "$topdir/$topdir.mp4",
11864: "$topdir/$topdir\_config.xml",
11865: "$topdir/$topdir\_controller.swf",
11866: "$topdir/$topdir\_embed.css",
11867: "$topdir/$topdir\_First_Frame.png",
11868: "$topdir/$topdir\_player.html",
11869: "$topdir/$topdir\_Thumbnails.png",
11870: "$topdir/playerProductInstall.swf",
11871: "$topdir/scripts/",
11872: "$topdir/scripts/config_xml.js",
11873: "$topdir/scripts/techsmith-smart-player.min.js",
11874: "$topdir/skins/",
11875: "$topdir/skins/configuration_express.xml",
11876: "$topdir/skins/express_show/",
11877: "$topdir/skins/express_show/spritesheet.min.css",
11878: "$topdir/skins/express_show/spritesheet.png",
11879: "$topdir/skins/express_show/techsmith-smart-player.min.css");
11880: my @diffs = &compare_arrays(\@paths,\@camtasia6);
11881: if (@diffs == 0) {
11882: $is_camtasia = 6;
11883: } else {
11884: @diffs = &compare_arrays(\@paths,\@camtasia8_1);
11885: if (@diffs == 0) {
11886: $is_camtasia = 8;
11887: } else {
11888: @diffs = &compare_arrays(\@paths,\@camtasia8_4);
11889: if (@diffs == 0) {
11890: $is_camtasia = 8;
11891: }
11892: }
11893: }
11894: }
11895: my $output;
11896: if ($is_camtasia) {
11897: $output = <<"ENDCAM";
11898: <script type="text/javascript" language="Javascript">
11899: // <![CDATA[
11900:
11901: function camtasiaToggle() {
11902: for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11903: if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11904: if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11905: document.getElementById('camtasia_titles').style.display='block';
11906: } else {
11907: document.getElementById('camtasia_titles').style.display='none';
11908: }
11909: }
11910: }
11911: return;
11912: }
11913:
11914: // ]]>
11915: </script>
11916: <p>$lt{'camt'}</p>
11917: ENDCAM
11918: } else {
11919: $output = '<p>'.$lt{'this'};
11920: if ($info eq '') {
11921: $output .= ' '.$lt{'youm'}.'</p>'."\n";
11922: } else {
11923: $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11924: '<div><pre>'.$info.'</pre></div>';
11925: }
11926: }
11927: $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11928: my $duplicates;
11929: my $num = 0;
11930: if (ref($dirlist) eq 'ARRAY') {
11931: foreach my $item (@{$dirlist}) {
11932: if (ref($item) eq 'ARRAY') {
11933: if (exists($toplevel{$item->[0]})) {
11934: $duplicates .=
11935: &start_data_table_row().
11936: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11937: 'value="0" checked="checked" />'.&mt('No').'</label>'.
11938: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '.
11939: 'value="1" />'.&mt('Yes').'</label>'.
11940: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11941: '<td>'.$item->[0].'</td>';
11942: if ($item->[2]) {
11943: $duplicates .= '<td>'.&mt('Directory').'</td>';
11944: } else {
11945: $duplicates .= '<td>'.&mt('File').'</td>';
11946: }
11947: $duplicates .= '<td>'.$item->[3].'</td>'.
11948: '<td>'.
11949: &Apache::lonlocal::locallocaltime($item->[4]).
11950: '</td>'.
11951: &end_data_table_row();
11952: $num ++;
11953: }
11954: }
11955: }
11956: }
11957: my $itemcount;
11958: if (@paths > 0) {
11959: $itemcount = scalar(@paths);
11960: } else {
11961: $itemcount = 1;
11962: }
11963: if ($is_camtasia) {
11964: $output .= $lt{'auto'}.'<br />'.
11965: '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11966: '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11967: $lt{'yes'}.'</label> <label>'.
11968: '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11969: $lt{'no'}.'</label></span><br />'.
11970: '<div id="camtasia_titles" style="display:block">'.
11971: &Apache::lonhtmlcommon::start_pick_box().
11972: &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11973: '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11974: &Apache::lonhtmlcommon::row_closure().
11975: &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11976: '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11977: &Apache::lonhtmlcommon::row_closure(1).
11978: &Apache::lonhtmlcommon::end_pick_box().
11979: '</div>';
11980: }
11981: $output .=
11982: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11983: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11984: "\n";
11985: if ($duplicates ne '') {
11986: $output .= '<p><span class="LC_warning">'.
11987: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.
11988: &start_data_table().
11989: &start_data_table_header_row().
11990: '<th>'.&mt('Overwrite?').'</th>'.
11991: '<th>'.&mt('Name').'</th>'.
11992: '<th>'.&mt('Type').'</th>'.
11993: '<th>'.&mt('Size').'</th>'.
11994: '<th>'.&mt('Last modified').'</th>'.
11995: &end_data_table_header_row().
11996: $duplicates.
11997: &end_data_table().
11998: '</p>';
11999: }
12000: $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12001: if (ref($hiddenelements) eq 'HASH') {
12002: foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12003: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12004: }
12005: }
12006: $output .= <<"END";
12007: <br />
12008: <input type="submit" name="decompress" value="$lt{'extr'}" />
12009: </form>
12010: $noextract
12011: END
12012: return $output;
12013: }
12014:
12015: sub decompression_utility {
12016: my ($program) = @_;
12017: my @utilities = ('tar','gunzip','bunzip2','unzip');
12018: my $location;
12019: if (grep(/^\Q$program\E$/,@utilities)) {
12020: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12021: '/usr/sbin/') {
12022: if (-x $dir.$program) {
12023: $location = $dir.$program;
12024: last;
12025: }
12026: }
12027: }
12028: return $location;
12029: }
12030:
12031: sub list_archive_contents {
12032: my ($file,$pathsref) = @_;
12033: my (@cmd,$output);
12034: my $needsregexp;
12035: if ($file =~ /\.zip$/) {
12036: @cmd = (&decompression_utility('unzip'),"-l");
12037: $needsregexp = 1;
12038: } elsif (($file =~ m/\.tar\.gz$/) ||
12039: ($file =~ /\.tgz$/)) {
12040: @cmd = (&decompression_utility('tar'),"-ztf");
12041: } elsif ($file =~ /\.tar\.bz2$/) {
12042: @cmd = (&decompression_utility('tar'),"-jtf");
12043: } elsif ($file =~ m|\.tar$|) {
12044: @cmd = (&decompression_utility('tar'),"-tf");
12045: }
12046: if (@cmd) {
12047: undef($!);
12048: undef($@);
12049: if (open(my $fh,"-|", @cmd, $file)) {
12050: while (my $line = <$fh>) {
12051: $output .= $line;
12052: chomp($line);
12053: my $item;
12054: if ($needsregexp) {
12055: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/);
12056: } else {
12057: $item = $line;
12058: }
12059: if ($item ne '') {
12060: unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12061: push(@{$pathsref},$item);
12062: }
12063: }
12064: }
12065: close($fh);
12066: }
12067: }
12068: return $output;
12069: }
12070:
12071: sub decompress_uploaded_file {
12072: my ($file,$dir) = @_;
12073: &Apache::lonnet::appenv({'cgi.file' => $file});
12074: &Apache::lonnet::appenv({'cgi.dir' => $dir});
12075: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12076: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12077: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12078: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12079: my $decompressed = $env{'cgi.decompressed'};
12080: &Apache::lonnet::delenv('cgi.file');
12081: &Apache::lonnet::delenv('cgi.dir');
12082: &Apache::lonnet::delenv('cgi.decompressed');
12083: return ($decompressed,$result);
12084: }
12085:
12086: sub process_decompression {
12087: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12088: unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
12089: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12090: &mt('Unexpected file path.').'</p>'."\n";
12091: }
12092: unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
12093: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12094: &mt('Unexpected course context.').'</p>'."\n";
12095: }
12096: unless ($file eq &Apache::lonnet::clean_filename($file)) {
12097: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12098: &mt('Filename contained unexpected characters.').'</p>'."\n";
12099: }
12100: my ($dir,$error,$warning,$output);
12101: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12102: $error = &mt('Filename not a supported archive file type.').
12103: '<br />'.&mt('Filename should end with one of: [_1].',
12104: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12105: } else {
12106: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12107: if ($docuhome eq 'no_host') {
12108: $error = &mt('Could not determine home server for course.');
12109: } else {
12110: my @ids=&Apache::lonnet::current_machine_ids();
12111: my $currdir = "$dir_root/$destination";
12112: if (grep(/^\Q$docuhome\E$/,@ids)) {
12113: $dir = &LONCAPA::propath($docudom,$docuname).
12114: "$dir_root/$destination";
12115: } else {
12116: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12117: "$dir_root/$docudom/$docuname/$destination";
12118: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12119: $error = &mt('Archive file not found.');
12120: }
12121: }
12122: my (@to_overwrite,@to_skip);
12123: if ($env{'form.archive_overwrite_total'} > 0) {
12124: my $total = $env{'form.archive_overwrite_total'};
12125: for (my $i=0; $i<$total; $i++) {
12126: if ($env{'form.archive_overwrite_'.$i} == 1) {
12127: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12128: } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12129: push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12130: }
12131: }
12132: }
12133: my $numskip = scalar(@to_skip);
12134: my $numoverwrite = scalar(@to_overwrite);
12135: if (($numskip) && (!$numoverwrite)) {
12136: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');
12137: } elsif ($dir eq '') {
12138: $error = &mt('Directory containing archive file unavailable.');
12139: } elsif (!$error) {
12140: my ($decompressed,$display);
12141: if (($numskip) || ($numoverwrite)) {
12142: my $tempdir = time.'_'.$$.int(rand(10000));
12143: mkdir("$dir/$tempdir",0755);
12144: if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
12145: ($decompressed,$display) =
12146: &decompress_uploaded_file($file,"$dir/$tempdir");
12147: foreach my $item (@to_skip) {
12148: if (($item ne '') && ($item !~ /\.\./)) {
12149: if (-f "$dir/$tempdir/$item") {
12150: unlink("$dir/$tempdir/$item");
12151: } elsif (-d "$dir/$tempdir/$item") {
12152: &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
12153: }
12154: }
12155: }
12156: foreach my $item (@to_overwrite) {
12157: if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
12158: if (($item ne '') && ($item !~ /\.\./)) {
12159: if (-f "$dir/$item") {
12160: unlink("$dir/$item");
12161: } elsif (-d "$dir/$item") {
12162: &File::Path::remove_tree("$dir/$item",{ safe => 1 });
12163: }
12164: &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
12165: }
12166: }
12167: }
12168: if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
12169: &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
12170: }
12171: }
12172: } else {
12173: ($decompressed,$display) =
12174: &decompress_uploaded_file($file,$dir);
12175: }
12176: if ($decompressed eq 'ok') {
12177: $output = '<p class="LC_info">'.
12178: &mt('Files extracted successfully from archive.').
12179: '</p>'."\n";
12180: my ($warning,$result,@contents);
12181: my ($newdirlistref,$newlisterror) =
12182: &Apache::lonnet::dirlist($currdir,$docudom,
12183: $docuname,1);
12184: my (%is_dir,%changes,@newitems);
12185: my $dirptr = 16384;
12186: if (ref($newdirlistref) eq 'ARRAY') {
12187: foreach my $dir_line (@{$newdirlistref}) {
12188: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12189: unless (($item =~ /^\.+$/) || ($item eq $file) ||
12190: ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
12191: push(@newitems,$item);
12192: if ($dirptr&$testdir) {
12193: $is_dir{$item} = 1;
12194: }
12195: $changes{$item} = 1;
12196: }
12197: }
12198: }
12199: if (keys(%changes) > 0) {
12200: foreach my $item (sort(@newitems)) {
12201: if ($changes{$item}) {
12202: push(@contents,$item);
12203: }
12204: }
12205: }
12206: if (@contents > 0) {
12207: my $wantform;
12208: unless ($env{'form.autoextract_camtasia'}) {
12209: $wantform = 1;
12210: }
12211: my (%children,%parent,%dirorder,%titles);
12212: my ($count,$datatable) = &get_extracted($docudom,$docuname,
12213: $currdir,\%is_dir,
12214: \%children,\%parent,
12215: \@contents,\%dirorder,
12216: \%titles,$wantform);
12217: if ($datatable ne '') {
12218: $output .= &archive_options_form('decompressed',$datatable,
12219: $count,$hiddenelem);
12220: my $startcount = 6;
12221: $output .= &archive_javascript($startcount,$count,
12222: \%titles,\%children);
12223: }
12224: if ($env{'form.autoextract_camtasia'}) {
12225: my $version = $env{'form.autoextract_camtasia'};
12226: my %displayed;
12227: my $total = 1;
12228: $env{'form.archive_directory'} = [];
12229: foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12230: my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12231: $path =~ s{/$}{};
12232: my $item;
12233: if ($path ne '') {
12234: $item = "$path/$titles{$i}";
12235: } else {
12236: $item = $titles{$i};
12237: }
12238: $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12239: if ($item eq $contents[0]) {
12240: push(@{$env{'form.archive_directory'}},$i);
12241: $env{'form.archive_'.$i} = 'display';
12242: $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12243: $displayed{'folder'} = $i;
12244: } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12245: (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
12246: $env{'form.archive_'.$i} = 'display';
12247: $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12248: $displayed{'web'} = $i;
12249: } else {
12250: if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12251: ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12252: ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12253: push(@{$env{'form.archive_directory'}},$i);
12254: }
12255: $env{'form.archive_'.$i} = 'dependency';
12256: }
12257: $total ++;
12258: }
12259: for (my $i=1; $i<$total; $i++) {
12260: next if ($i == $displayed{'web'});
12261: next if ($i == $displayed{'folder'});
12262: $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12263: }
12264: $env{'form.phase'} = 'decompress_cleanup';
12265: $env{'form.archivedelete'} = 1;
12266: $env{'form.archive_count'} = $total-1;
12267: $output .=
12268: &process_extracted_files('coursedocs',$docudom,
12269: $docuname,$destination,
12270: $dir_root,$hiddenelem);
12271: }
12272: } else {
12273: $warning = &mt('No new items extracted from archive file.');
12274: }
12275: } else {
12276: $output = $display;
12277: $error = &mt('An error occurred during extraction from the archive file.');
12278: }
12279: }
12280: }
12281: }
12282: if ($error) {
12283: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12284: $error.'</p>'."\n";
12285: }
12286: if ($warning) {
12287: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12288: }
12289: return $output;
12290: }
12291:
12292: sub get_extracted {
12293: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12294: $titles,$wantform) = @_;
12295: my $count = 0;
12296: my $depth = 0;
12297: my $datatable;
12298: my @hierarchy;
12299: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12300: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12301: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12302: foreach my $item (@{$contents}) {
12303: $count ++;
12304: @{$dirorder->{$count}} = @hierarchy;
12305: $titles->{$count} = $item;
12306: &archive_hierarchy($depth,$count,$parent,$children);
12307: if ($wantform) {
12308: $datatable .= &archive_row($is_dir->{$item},$item,
12309: $currdir,$depth,$count);
12310: }
12311: if ($is_dir->{$item}) {
12312: $depth ++;
12313: push(@hierarchy,$count);
12314: $parent->{$depth} = $count;
12315: $datatable .=
12316: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12317: \$depth,\$count,\@hierarchy,$dirorder,
12318: $children,$parent,$titles,$wantform);
12319: $depth --;
12320: pop(@hierarchy);
12321: }
12322: }
12323: return ($count,$datatable);
12324: }
12325:
12326: sub recurse_extracted_archive {
12327: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12328: $children,$parent,$titles,$wantform) = @_;
12329: my $result='';
12330: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12331: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12332: (ref($dirorder) eq 'HASH')) {
12333: return $result;
12334: }
12335: my $dirptr = 16384;
12336: my ($newdirlistref,$newlisterror) =
12337: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12338: if (ref($newdirlistref) eq 'ARRAY') {
12339: foreach my $dir_line (@{$newdirlistref}) {
12340: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12341: unless ($item =~ /^\.+$/) {
12342: $$count ++;
12343: @{$dirorder->{$$count}} = @{$hierarchy};
12344: $titles->{$$count} = $item;
12345: &archive_hierarchy($$depth,$$count,$parent,$children);
12346:
12347: my $is_dir;
12348: if ($dirptr&$testdir) {
12349: $is_dir = 1;
12350: }
12351: if ($wantform) {
12352: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12353: }
12354: if ($is_dir) {
12355: $$depth ++;
12356: push(@{$hierarchy},$$count);
12357: $parent->{$$depth} = $$count;
12358: $result .=
12359: &recurse_extracted_archive("$currdir/$item",$docudom,
12360: $docuname,$depth,$count,
12361: $hierarchy,$dirorder,$children,
12362: $parent,$titles,$wantform);
12363: $$depth --;
12364: pop(@{$hierarchy});
12365: }
12366: }
12367: }
12368: }
12369: return $result;
12370: }
12371:
12372: sub archive_hierarchy {
12373: my ($depth,$count,$parent,$children) =@_;
12374: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12375: if (exists($parent->{$depth})) {
12376: $children->{$parent->{$depth}} .= $count.':';
12377: }
12378: }
12379: return;
12380: }
12381:
12382: sub archive_row {
12383: my ($is_dir,$item,$currdir,$depth,$count) = @_;
12384: my ($name) = ($item =~ m{([^/]+)$});
12385: my %choices = &Apache::lonlocal::texthash (
12386: 'display' => 'Add as file',
12387: 'dependency' => 'Include as dependency',
12388: 'discard' => 'Discard',
12389: );
12390: if ($is_dir) {
12391: $choices{'display'} = &mt('Add as folder');
12392: }
12393: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12394: my $offset = 0;
12395: foreach my $action ('display','dependency','discard') {
12396: $offset ++;
12397: if ($action ne 'display') {
12398: $offset ++;
12399: }
12400: $output .= '<td><span class="LC_nobreak">'.
12401: '<label><input type="radio" name="archive_'.$count.
12402: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12403: my $text = $choices{$action};
12404: if ($is_dir) {
12405: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12406: if ($action eq 'display') {
12407: $text = &mt('Add as folder');
12408: }
12409: } else {
12410: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12411:
12412: }
12413: $output .= ' /> '.$choices{$action}.'</label></span>';
12414: if ($action eq 'dependency') {
12415: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12416: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '.
12417: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12418: '<option value=""></option>'."\n".
12419: '</select>'."\n".
12420: '</div>';
12421: } elsif ($action eq 'display') {
12422: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12423: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12424: '</div>';
12425: }
12426: $output .= '</td>';
12427: }
12428: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12429: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2);
12430: for (my $i=0; $i<$depth; $i++) {
12431: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12432: }
12433: if ($is_dir) {
12434: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n".
12435: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12436: } else {
12437: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12438: }
12439: $output .= ' '.$name.'</td>'."\n".
12440: &end_data_table_row();
12441: return $output;
12442: }
12443:
12444: sub archive_options_form {
12445: my ($form,$display,$count,$hiddenelem) = @_;
12446: my %lt = &Apache::lonlocal::texthash(
12447: perm => 'Permanently remove archive file?',
12448: hows => 'How should each extracted item be incorporated in the course?',
12449: cont => 'Content actions for all',
12450: addf => 'Add as folder/file',
12451: incd => 'Include as dependency for a displayed file',
12452: disc => 'Discard',
12453: no => 'No',
12454: yes => 'Yes',
12455: save => 'Save',
12456: );
12457: my $output = <<"END";
12458: <form name="$form" method="post" action="">
12459: <p><span class="LC_nobreak">$lt{'perm'}
12460: <label>
12461: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12462: </label>
12463:
12464: <label>
12465: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12466: </span>
12467: </p>
12468: <input type="hidden" name="phase" value="decompress_cleanup" />
12469: <br />$lt{'hows'}
12470: <div class="LC_columnSection">
12471: <fieldset>
12472: <legend>$lt{'cont'}</legend>
12473: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" />
12474: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12475: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12476: </fieldset>
12477: </div>
12478: END
12479: return $output.
12480: &start_data_table()."\n".
12481: $display."\n".
12482: &end_data_table()."\n".
12483: '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12484: $hiddenelem.
12485: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12486: '</form>';
12487: }
12488:
12489: sub archive_javascript {
12490: my ($startcount,$numitems,$titles,$children) = @_;
12491: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12492: my $maintitle = $env{'form.comment'};
12493: my $scripttag = <<START;
12494: <script type="text/javascript">
12495: // <![CDATA[
12496:
12497: function checkAll(form,prefix) {
12498: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$");
12499: for (var i=0; i < form.elements.length; i++) {
12500: var id = form.elements[i].id;
12501: if ((id != '') && (id != undefined)) {
12502: if (idstr.test(id)) {
12503: if (form.elements[i].type == 'radio') {
12504: form.elements[i].checked = true;
12505: var nostart = i-$startcount;
12506: var offset = nostart%7;
12507: var count = (nostart-offset)/7;
12508: dependencyCheck(form,count,offset);
12509: }
12510: }
12511: }
12512: }
12513: }
12514:
12515: function propagateCheck(form,count) {
12516: if (count > 0) {
12517: var startelement = $startcount + ((count-1) * 7);
12518: for (var j=1; j<6; j++) {
12519: if ((j != 2) && (j != 4)) {
12520: var item = startelement + j;
12521: if (form.elements[item].type == 'radio') {
12522: if (form.elements[item].checked) {
12523: containerCheck(form,count,j);
12524: break;
12525: }
12526: }
12527: }
12528: }
12529: }
12530: }
12531:
12532: numitems = $numitems
12533: var titles = new Array(numitems);
12534: var parents = new Array(numitems);
12535: for (var i=0; i<numitems; i++) {
12536: parents[i] = new Array;
12537: }
12538: var maintitle = '$maintitle';
12539:
12540: START
12541:
12542: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12543: my @contents = split(/:/,$children->{$container});
12544: for (my $i=0; $i<@contents; $i ++) {
12545: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12546: }
12547: }
12548:
12549: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12550: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12551: }
12552:
12553: $scripttag .= <<END;
12554:
12555: function containerCheck(form,count,offset) {
12556: if (count > 0) {
12557: dependencyCheck(form,count,offset);
12558: var item = (offset+$startcount)+7*(count-1);
12559: form.elements[item].checked = true;
12560: if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12561: if (parents[count].length > 0) {
12562: for (var j=0; j<parents[count].length; j++) {
12563: containerCheck(form,parents[count][j],offset);
12564: }
12565: }
12566: }
12567: }
12568: }
12569:
12570: function dependencyCheck(form,count,offset) {
12571: if (count > 0) {
12572: var chosen = (offset+$startcount)+7*(count-1);
12573: var depitem = $startcount + ((count-1) * 7) + 4;
12574: var currtype = form.elements[depitem].type;
12575: if (form.elements[chosen].value == 'dependency') {
12576: document.getElementById('arc_depon_'+count).style.display='block';
12577: form.elements[depitem].options.length = 0;
12578: form.elements[depitem].options[0] = new Option('Select','',true,true);
12579: for (var i=1; i<=numitems; i++) {
12580: if (i == count) {
12581: continue;
12582: }
12583: var startelement = $startcount + (i-1) * 7;
12584: for (var j=1; j<6; j++) {
12585: if ((j != 2) && (j!= 4)) {
12586: var item = startelement + j;
12587: if (form.elements[item].type == 'radio') {
12588: if (form.elements[item].checked) {
12589: if (form.elements[item].value == 'display') {
12590: var n = form.elements[depitem].options.length;
12591: form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
12592: }
12593: }
12594: }
12595: }
12596: }
12597: }
12598: } else {
12599: document.getElementById('arc_depon_'+count).style.display='none';
12600: form.elements[depitem].options.length = 0;
12601: form.elements[depitem].options[0] = new Option('Select','',true,true);
12602: }
12603: titleCheck(form,count,offset);
12604: }
12605: }
12606:
12607: function propagateSelect(form,count,offset) {
12608: if (count > 0) {
12609: var item = (1+offset+$startcount)+7*(count-1);
12610: var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
12611: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12612: if (parents[count].length > 0) {
12613: for (var j=0; j<parents[count].length; j++) {
12614: containerSelect(form,parents[count][j],offset,picked);
12615: }
12616: }
12617: }
12618: }
12619: }
12620:
12621: function containerSelect(form,count,offset,picked) {
12622: if (count > 0) {
12623: var item = (offset+$startcount)+7*(count-1);
12624: if (form.elements[item].type == 'radio') {
12625: if (form.elements[item].value == 'dependency') {
12626: if (form.elements[item+1].type == 'select-one') {
12627: for (var i=0; i<form.elements[item+1].options.length; i++) {
12628: if (form.elements[item+1].options[i].value == picked) {
12629: form.elements[item+1].selectedIndex = i;
12630: break;
12631: }
12632: }
12633: }
12634: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12635: if (parents[count].length > 0) {
12636: for (var j=0; j<parents[count].length; j++) {
12637: containerSelect(form,parents[count][j],offset,picked);
12638: }
12639: }
12640: }
12641: }
12642: }
12643: }
12644: }
12645:
12646: function titleCheck(form,count,offset) {
12647: if (count > 0) {
12648: var chosen = (offset+$startcount)+7*(count-1);
12649: var depitem = $startcount + ((count-1) * 7) + 2;
12650: var currtype = form.elements[depitem].type;
12651: if (form.elements[chosen].value == 'display') {
12652: document.getElementById('arc_title_'+count).style.display='block';
12653: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
12654: document.getElementById('archive_title_'+count).value=maintitle;
12655: }
12656: } else {
12657: document.getElementById('arc_title_'+count).style.display='none';
12658: if (currtype == 'text') {
12659: document.getElementById('archive_title_'+count).value='';
12660: }
12661: }
12662: }
12663: return;
12664: }
12665:
12666: // ]]>
12667: </script>
12668: END
12669: return $scripttag;
12670: }
12671:
12672: sub process_extracted_files {
12673: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
12674: my $numitems = $env{'form.archive_count'};
12675: return if ((!$numitems) || ($numitems =~ /\D/));
12676: my @ids=&Apache::lonnet::current_machine_ids();
12677: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
12678: %folders,%containers,%mapinner,%prompttofetch);
12679: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12680: if (grep(/^\Q$docuhome\E$/,@ids)) {
12681: $prefix = &LONCAPA::propath($docudom,$docuname);
12682: $pathtocheck = "$dir_root/$destination";
12683: $dir = $dir_root;
12684: $ishome = 1;
12685: } else {
12686: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
12687: $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
12688: $dir = "$dir_root/$docudom/$docuname";
12689: }
12690: my $currdir = "$dir_root/$destination";
12691: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
12692: if ($env{'form.folderpath'}) {
12693: my @items = split('&',$env{'form.folderpath'});
12694: $folders{'0'} = $items[-2];
12695: if ($env{'form.folderpath'} =~ /\:1$/) {
12696: $containers{'0'}='page';
12697: } else {
12698: $containers{'0'}='sequence';
12699: }
12700: }
12701: my @archdirs = &get_env_multiple('form.archive_directory');
12702: if ($numitems) {
12703: for (my $i=1; $i<=$numitems; $i++) {
12704: my $path = $env{'form.archive_content_'.$i};
12705: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
12706: my $item = $1;
12707: $toplevelitems{$item} = $i;
12708: if (grep(/^\Q$i\E$/,@archdirs)) {
12709: $is_dir{$item} = 1;
12710: }
12711: }
12712: }
12713: }
12714: my ($output,%children,%parent,%titles,%dirorder,$result);
12715: if (keys(%toplevelitems) > 0) {
12716: my @contents = sort(keys(%toplevelitems));
12717: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
12718: \%parent,\@contents,\%dirorder,\%titles);
12719: }
12720: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
12721: if ($numitems) {
12722: for (my $i=1; $i<=$numitems; $i++) {
12723: next if ($env{'form.archive_'.$i} eq 'dependency');
12724: my $path = $env{'form.archive_content_'.$i};
12725: if ($path =~ /^\Q$pathtocheck\E/) {
12726: if ($env{'form.archive_'.$i} eq 'discard') {
12727: if ($prefix ne '' && $path ne '') {
12728: if (-e $prefix.$path) {
12729: if ((@archdirs > 0) &&
12730: (grep(/^\Q$i\E$/,@archdirs))) {
12731: $todeletedir{$prefix.$path} = 1;
12732: } else {
12733: $todelete{$prefix.$path} = 1;
12734: }
12735: }
12736: }
12737: } elsif ($env{'form.archive_'.$i} eq 'display') {
12738: my ($docstitle,$title,$url,$outer);
12739: ($title) = ($path =~ m{/([^/]+)$});
12740: $docstitle = $env{'form.archive_title_'.$i};
12741: if ($docstitle eq '') {
12742: $docstitle = $title;
12743: }
12744: $outer = 0;
12745: if (ref($dirorder{$i}) eq 'ARRAY') {
12746: if (@{$dirorder{$i}} > 0) {
12747: foreach my $item (reverse(@{$dirorder{$i}})) {
12748: if ($env{'form.archive_'.$item} eq 'display') {
12749: $outer = $item;
12750: last;
12751: }
12752: }
12753: }
12754: }
12755: my ($errtext,$fatal) =
12756: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
12757: '/'.$folders{$outer}.'.'.
12758: $containers{$outer});
12759: next if ($fatal);
12760: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
12761: if ($context eq 'coursedocs') {
12762: $mapinner{$i} = time;
12763: $folders{$i} = 'default_'.$mapinner{$i};
12764: $containers{$i} = 'sequence';
12765: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12766: $folders{$i}.'.'.$containers{$i};
12767: my $newidx = &LONCAPA::map::getresidx();
12768: $LONCAPA::map::resources[$newidx]=
12769: $docstitle.':'.$url.':false:normal:res';
12770: push(@LONCAPA::map::order,$newidx);
12771: my ($outtext,$errtext) =
12772: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12773: $docuname.'/'.$folders{$outer}.
12774: '.'.$containers{$outer},1,1);
12775: $newseqid{$i} = $newidx;
12776: unless ($errtext) {
12777: $result .= '<li>'.&mt('Folder: [_1] added to course',
12778: &HTML::Entities::encode($docstitle,'<>&"')).
12779: '</li>'."\n";
12780: }
12781: }
12782: } else {
12783: if ($context eq 'coursedocs') {
12784: my $newidx=&LONCAPA::map::getresidx();
12785: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12786: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
12787: $title;
12788: if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
12789: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
12790: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
12791: }
12792: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12793: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
12794: }
12795: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12796: if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
12797: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
12798: unless ($ishome) {
12799: my $fetch = "$newdest{$i}/$title";
12800: $fetch =~ s/^\Q$prefix$dir\E//;
12801: $prompttofetch{$fetch} = 1;
12802: }
12803: }
12804: }
12805: $LONCAPA::map::resources[$newidx]=
12806: $docstitle.':'.$url.':false:normal:res';
12807: push(@LONCAPA::map::order, $newidx);
12808: my ($outtext,$errtext)=
12809: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12810: $docuname.'/'.$folders{$outer}.
12811: '.'.$containers{$outer},1,1);
12812: unless ($errtext) {
12813: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
12814: $result .= '<li>'.&mt('File: [_1] added to course',
12815: &HTML::Entities::encode($docstitle,'<>&"')).
12816: '</li>'."\n";
12817: }
12818: }
12819: } else {
12820: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12821: &HTML::Entities::encode($path,'<>&"')).'<br />';
12822: }
12823: }
12824: }
12825: }
12826: } else {
12827: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12828: &HTML::Entities::encode($path,'<>&"')).'<br />';
12829: }
12830: }
12831: for (my $i=1; $i<=$numitems; $i++) {
12832: next unless ($env{'form.archive_'.$i} eq 'dependency');
12833: my $path = $env{'form.archive_content_'.$i};
12834: if ($path =~ /^\Q$pathtocheck\E/) {
12835: my ($title) = ($path =~ m{/([^/]+)$});
12836: $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
12837: if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
12838: if (ref($dirorder{$i}) eq 'ARRAY') {
12839: my ($itemidx,$fullpath,$relpath);
12840: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
12841: my $container = $dirorder{$referrer{$i}}->[-1];
12842: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
12843: if ($dirorder{$i}->[$j] eq $container) {
12844: $itemidx = $j;
12845: }
12846: }
12847: }
12848: if ($itemidx eq '') {
12849: $itemidx = 0;
12850: }
12851: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
12852: if ($mapinner{$referrer{$i}}) {
12853: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
12854: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12855: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12856: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12857: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12858: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12859: if (!-e $fullpath) {
12860: mkdir($fullpath,0755);
12861: }
12862: }
12863: } else {
12864: last;
12865: }
12866: }
12867: }
12868: } elsif ($newdest{$referrer{$i}}) {
12869: $fullpath = $newdest{$referrer{$i}};
12870: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12871: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12872: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12873: last;
12874: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12875: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12876: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12877: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12878: if (!-e $fullpath) {
12879: mkdir($fullpath,0755);
12880: }
12881: }
12882: } else {
12883: last;
12884: }
12885: }
12886: }
12887: if ($fullpath ne '') {
12888: if (-e "$prefix$path") {
12889: unless (rename("$prefix$path","$fullpath/$title")) {
12890: $warning .= &mt('Failed to rename dependency').'<br />';
12891: }
12892: }
12893: if (-e "$fullpath/$title") {
12894: my $showpath;
12895: if ($relpath ne '') {
12896: $showpath = "$relpath/$title";
12897: } else {
12898: $showpath = "/$title";
12899: }
12900: $result .= '<li>'.&mt('[_1] included as a dependency',
12901: &HTML::Entities::encode($showpath,'<>&"')).
12902: '</li>'."\n";
12903: }
12904: unless ($ishome) {
12905: my $fetch = "$fullpath/$title";
12906: $fetch =~ s/^\Q$prefix$dir\E//;
12907: $prompttofetch{$fetch} = 1;
12908: }
12909: }
12910: }
12911: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12912: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12913: &HTML::Entities::encode($path,'<>&"'),
12914: &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
12915: '<br />';
12916: }
12917: } else {
12918: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12919: &HTML::Entities::encode($path)).'<br />';
12920: }
12921: }
12922: if (keys(%todelete)) {
12923: foreach my $key (keys(%todelete)) {
12924: unlink($key);
12925: }
12926: }
12927: if (keys(%todeletedir)) {
12928: foreach my $key (keys(%todeletedir)) {
12929: rmdir($key);
12930: }
12931: }
12932: foreach my $dir (sort(keys(%is_dir))) {
12933: if (($pathtocheck ne '') && ($dir ne '')) {
12934: &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12935: }
12936: }
12937: if ($result ne '') {
12938: $output .= '<ul>'."\n".
12939: $result."\n".
12940: '</ul>';
12941: }
12942: unless ($ishome) {
12943: my $replicationfail;
12944: foreach my $item (keys(%prompttofetch)) {
12945: my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12946: unless ($fetchresult eq 'ok') {
12947: $replicationfail .= '<li>'.$item.'</li>'."\n";
12948: }
12949: }
12950: if ($replicationfail) {
12951: $output .= '<p class="LC_error">'.
12952: &mt('Course home server failed to retrieve:').'<ul>'.
12953: $replicationfail.
12954: '</ul></p>';
12955: }
12956: }
12957: } else {
12958: $warning = &mt('No items found in archive.');
12959: }
12960: if ($error) {
12961: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12962: $error.'</p>'."\n";
12963: }
12964: if ($warning) {
12965: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12966: }
12967: return $output;
12968: }
12969:
12970: sub cleanup_empty_dirs {
12971: my ($path) = @_;
12972: if (($path ne '') && (-d $path)) {
12973: if (opendir(my $dirh,$path)) {
12974: my @dircontents = grep(!/^\./,readdir($dirh));
12975: my $numitems = 0;
12976: foreach my $item (@dircontents) {
12977: if (-d "$path/$item") {
12978: &cleanup_empty_dirs("$path/$item");
12979: if (-e "$path/$item") {
12980: $numitems ++;
12981: }
12982: } else {
12983: $numitems ++;
12984: }
12985: }
12986: if ($numitems == 0) {
12987: rmdir($path);
12988: }
12989: closedir($dirh);
12990: }
12991: }
12992: return;
12993: }
12994:
12995: =pod
12996:
12997: =item * &get_folder_hierarchy()
12998:
12999: Provides hierarchy of names of folders/sub-folders containing the current
13000: item,
13001:
13002: Inputs: 3
13003: - $navmap - navmaps object
13004:
13005: - $map - url for map (either the trigger itself, or map containing
13006: the resource, which is the trigger).
13007:
13008: - $showitem - 1 => show title for map itself; 0 => do not show.
13009:
13010: Outputs: 1 @pathitems - array of folder/subfolder names.
13011:
13012: =cut
13013:
13014: sub get_folder_hierarchy {
13015: my ($navmap,$map,$showitem) = @_;
13016: my @pathitems;
13017: if (ref($navmap)) {
13018: my $mapres = $navmap->getResourceByUrl($map);
13019: if (ref($mapres)) {
13020: my $pcslist = $mapres->map_hierarchy();
13021: if ($pcslist ne '') {
13022: my @pcs = split(/,/,$pcslist);
13023: foreach my $pc (@pcs) {
13024: if ($pc == 1) {
13025: push(@pathitems,&mt('Main Content'));
13026: } else {
13027: my $res = $navmap->getByMapPc($pc);
13028: if (ref($res)) {
13029: my $title = $res->compTitle();
13030: $title =~ s/\W+/_/g;
13031: if ($title ne '') {
13032: push(@pathitems,$title);
13033: }
13034: }
13035: }
13036: }
13037: }
13038: if ($showitem) {
13039: if ($mapres->{ID} eq '0.0') {
13040: push(@pathitems,&mt('Main Content'));
13041: } else {
13042: my $maptitle = $mapres->compTitle();
13043: $maptitle =~ s/\W+/_/g;
13044: if ($maptitle ne '') {
13045: push(@pathitems,$maptitle);
13046: }
13047: }
13048: }
13049: }
13050: }
13051: return @pathitems;
13052: }
13053:
13054: =pod
13055:
13056: =item * &get_turnedin_filepath()
13057:
13058: Determines path in a user's portfolio file for storage of files uploaded
13059: to a specific essayresponse or dropbox item.
13060:
13061: Inputs: 3 required + 1 optional.
13062: $symb is symb for resource, $uname and $udom are for current user (required).
13063: $caller is optional (can be "submission", if routine is called when storing
13064: an upoaded file when "Submit Answer" button was pressed).
13065:
13066: Returns array containing $path and $multiresp.
13067: $path is path in portfolio. $multiresp is 1 if this resource contains more
13068: than one file upload item. Callers of routine should append partid as a
13069: subdirectory to $path in cases where $multiresp is 1.
13070:
13071: Called by: homework/essayresponse.pm and homework/structuretags.pm
13072:
13073: =cut
13074:
13075: sub get_turnedin_filepath {
13076: my ($symb,$uname,$udom,$caller) = @_;
13077: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13078: my $turnindir;
13079: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13080: $turnindir = $userhash{'turnindir'};
13081: my ($path,$multiresp);
13082: if ($turnindir eq '') {
13083: if ($caller eq 'submission') {
13084: $turnindir = &mt('turned in');
13085: $turnindir =~ s/\W+/_/g;
13086: my %newhash = (
13087: 'turnindir' => $turnindir,
13088: );
13089: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13090: }
13091: }
13092: if ($turnindir ne '') {
13093: $path = '/'.$turnindir.'/';
13094: my ($multipart,$turnin,@pathitems);
13095: my $navmap = Apache::lonnavmaps::navmap->new();
13096: if (defined($navmap)) {
13097: my $mapres = $navmap->getResourceByUrl($map);
13098: if (ref($mapres)) {
13099: my $pcslist = $mapres->map_hierarchy();
13100: if ($pcslist ne '') {
13101: foreach my $pc (split(/,/,$pcslist)) {
13102: my $res = $navmap->getByMapPc($pc);
13103: if (ref($res)) {
13104: my $title = $res->compTitle();
13105: $title =~ s/\W+/_/g;
13106: if ($title ne '') {
13107: if (($pc > 1) && (length($title) > 12)) {
13108: $title = substr($title,0,12);
13109: }
13110: push(@pathitems,$title);
13111: }
13112: }
13113: }
13114: }
13115: my $maptitle = $mapres->compTitle();
13116: $maptitle =~ s/\W+/_/g;
13117: if ($maptitle ne '') {
13118: if (length($maptitle) > 12) {
13119: $maptitle = substr($maptitle,0,12);
13120: }
13121: push(@pathitems,$maptitle);
13122: }
13123: unless ($env{'request.state'} eq 'construct') {
13124: my $res = $navmap->getBySymb($symb);
13125: if (ref($res)) {
13126: my $partlist = $res->parts();
13127: my $totaluploads = 0;
13128: if (ref($partlist) eq 'ARRAY') {
13129: foreach my $part (@{$partlist}) {
13130: my @types = $res->responseType($part);
13131: my @ids = $res->responseIds($part);
13132: for (my $i=0; $i < scalar(@ids); $i++) {
13133: if ($types[$i] eq 'essay') {
13134: my $partid = $part.'_'.$ids[$i];
13135: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13136: $totaluploads ++;
13137: }
13138: }
13139: }
13140: }
13141: if ($totaluploads > 1) {
13142: $multiresp = 1;
13143: }
13144: }
13145: }
13146: }
13147: } else {
13148: return;
13149: }
13150: } else {
13151: return;
13152: }
13153: my $restitle=&Apache::lonnet::gettitle($symb);
13154: $restitle =~ s/\W+/_/g;
13155: if ($restitle eq '') {
13156: $restitle = ($resurl =~ m{/[^/]+$});
13157: if ($restitle eq '') {
13158: $restitle = time;
13159: }
13160: }
13161: if (length($restitle) > 12) {
13162: $restitle = substr($restitle,0,12);
13163: }
13164: push(@pathitems,$restitle);
13165: $path .= join('/',@pathitems);
13166: }
13167: return ($path,$multiresp);
13168: }
13169:
13170: =pod
13171:
13172: =back
13173:
13174: =head1 CSV Upload/Handling functions
13175:
13176: =over 4
13177:
13178: =item * &upfile_store($r)
13179:
13180: Store uploaded file, $r should be the HTTP Request object,
13181: needs $env{'form.upfile'}
13182: returns $datatoken to be put into hidden field
13183:
13184: =cut
13185:
13186: sub upfile_store {
13187: my $r=shift;
13188: $env{'form.upfile'}=~s/\r/\n/gs;
13189: $env{'form.upfile'}=~s/\f/\n/gs;
13190: $env{'form.upfile'}=~s/\n+/\n/gs;
13191: $env{'form.upfile'}=~s/\n+$//gs;
13192:
13193: my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
13194: '_enroll_'.$env{'request.course.id'}.'_'.
13195: time.'_'.$$);
13196: return if ($datatoken eq '');
13197: {
13198: my $datafile = $r->dir_config('lonDaemons').
13199: '/tmp/'.$datatoken.'.tmp';
13200: if ( open(my $fh,">$datafile") ) {
13201: print $fh $env{'form.upfile'};
13202: close($fh);
13203: }
13204: }
13205: return $datatoken;
13206: }
13207:
13208: =pod
13209:
13210: =item * &load_tmp_file($r,$datatoken)
13211:
13212: Load uploaded file from tmp, $r should be the HTTP Request object,
13213: $datatoken is the name to assign to the temporary file.
13214: sets $env{'form.upfile'} to the contents of the file
13215:
13216: =cut
13217:
13218: sub load_tmp_file {
13219: my ($r,$datatoken) = @_;
13220: return if ($datatoken eq '');
13221: my @studentdata=();
13222: {
13223: my $studentfile = $r->dir_config('lonDaemons').
13224: '/tmp/'.$datatoken.'.tmp';
13225: if ( open(my $fh,"<$studentfile") ) {
13226: @studentdata=<$fh>;
13227: close($fh);
13228: }
13229: }
13230: $env{'form.upfile'}=join('',@studentdata);
13231: }
13232:
13233: sub valid_datatoken {
13234: my ($datatoken) = @_;
13235: if ($datatoken =~ /^$match_username\_$match_domain\_enroll_$match_domain\_$match_courseid\_\d+_\d+$/) {
13236: return $datatoken;
13237: }
13238: return;
13239: }
13240:
13241: =pod
13242:
13243: =item * &upfile_record_sep()
13244:
13245: Separate uploaded file into records
13246: returns array of records,
13247: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13248:
13249: =cut
13250:
13251: sub upfile_record_sep {
13252: if ($env{'form.upfiletype'} eq 'xml') {
13253: } else {
13254: my @records;
13255: foreach my $line (split(/\n/,$env{'form.upfile'})) {
13256: if ($line=~/^\s*$/) { next; }
13257: push(@records,$line);
13258: }
13259: return @records;
13260: }
13261: }
13262:
13263: =pod
13264:
13265: =item * &record_sep($record)
13266:
13267: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13268:
13269: =cut
13270:
13271: sub takeleft {
13272: my $index=shift;
13273: return substr('0000'.$index,-4,4);
13274: }
13275:
13276: sub record_sep {
13277: my $record=shift;
13278: my %components=();
13279: if ($env{'form.upfiletype'} eq 'xml') {
13280: } elsif ($env{'form.upfiletype'} eq 'space') {
13281: my $i=0;
13282: foreach my $field (split(/\s+/,$record)) {
13283: $field=~s/^(\"|\')//;
13284: $field=~s/(\"|\')$//;
13285: $components{&takeleft($i)}=$field;
13286: $i++;
13287: }
13288: } elsif ($env{'form.upfiletype'} eq 'tab') {
13289: my $i=0;
13290: foreach my $field (split(/\t/,$record)) {
13291: $field=~s/^(\"|\')//;
13292: $field=~s/(\"|\')$//;
13293: $components{&takeleft($i)}=$field;
13294: $i++;
13295: }
13296: } else {
13297: my $separator=',';
13298: if ($env{'form.upfiletype'} eq 'semisv') {
13299: $separator=';';
13300: }
13301: my $i=0;
13302: # the character we are looking for to indicate the end of a quote or a record
13303: my $looking_for=$separator;
13304: # do not add the characters to the fields
13305: my $ignore=0;
13306: # we just encountered a separator (or the beginning of the record)
13307: my $just_found_separator=1;
13308: # store the field we are working on here
13309: my $field='';
13310: # work our way through all characters in record
13311: foreach my $character ($record=~/(.)/g) {
13312: if ($character eq $looking_for) {
13313: if ($character ne $separator) {
13314: # Found the end of a quote, again looking for separator
13315: $looking_for=$separator;
13316: $ignore=1;
13317: } else {
13318: # Found a separator, store away what we got
13319: $components{&takeleft($i)}=$field;
13320: $i++;
13321: $just_found_separator=1;
13322: $ignore=0;
13323: $field='';
13324: }
13325: next;
13326: }
13327: # single or double quotation marks after a separator indicate beginning of a quote
13328: # we are now looking for the end of the quote and need to ignore separators
13329: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
13330: $looking_for=$character;
13331: next;
13332: }
13333: # ignore would be true after we reached the end of a quote
13334: if ($ignore) { next; }
13335: if (($just_found_separator) && ($character=~/\s/)) { next; }
13336: $field.=$character;
13337: $just_found_separator=0;
13338: }
13339: # catch the very last entry, since we never encountered the separator
13340: $components{&takeleft($i)}=$field;
13341: }
13342: return %components;
13343: }
13344:
13345: ######################################################
13346: ######################################################
13347:
13348: =pod
13349:
13350: =item * &upfile_select_html()
13351:
13352: Return HTML code to select a file from the users machine and specify
13353: the file type.
13354:
13355: =cut
13356:
13357: ######################################################
13358: ######################################################
13359: sub upfile_select_html {
13360: my %Types = (
13361: csv => &mt('CSV (comma separated values, spreadsheet)'),
13362: semisv => &mt('Semicolon separated values'),
13363: space => &mt('Space separated'),
13364: tab => &mt('Tabulator separated'),
13365: # xml => &mt('HTML/XML'),
13366: );
13367: my $Str = '<input type="file" name="upfile" size="50" />'.
13368: '<br />'.&mt('Type').': <select name="upfiletype">';
13369: foreach my $type (sort(keys(%Types))) {
13370: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13371: }
13372: $Str .= "</select>\n";
13373: return $Str;
13374: }
13375:
13376: sub get_samples {
13377: my ($records,$toget) = @_;
13378: my @samples=({});
13379: my $got=0;
13380: foreach my $rec (@$records) {
13381: my %temp = &record_sep($rec);
13382: if (! grep(/\S/, values(%temp))) { next; }
13383: if (%temp) {
13384: $samples[$got]=\%temp;
13385: $got++;
13386: if ($got == $toget) { last; }
13387: }
13388: }
13389: return \@samples;
13390: }
13391:
13392: ######################################################
13393: ######################################################
13394:
13395: =pod
13396:
13397: =item * &csv_print_samples($r,$records)
13398:
13399: Prints a table of sample values from each column uploaded $r is an
13400: Apache Request ref, $records is an arrayref from
13401: &Apache::loncommon::upfile_record_sep
13402:
13403: =cut
13404:
13405: ######################################################
13406: ######################################################
13407: sub csv_print_samples {
13408: my ($r,$records) = @_;
13409: my $samples = &get_samples($records,5);
13410:
13411: $r->print(&mt('Samples').'<br />'.&start_data_table().
13412: &start_data_table_header_row());
13413: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13414: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13415: $r->print(&end_data_table_header_row());
13416: foreach my $hash (@$samples) {
13417: $r->print(&start_data_table_row());
13418: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13419: $r->print('<td>');
13420: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13421: $r->print('</td>');
13422: }
13423: $r->print(&end_data_table_row());
13424: }
13425: $r->print(&end_data_table().'<br />'."\n");
13426: }
13427:
13428: ######################################################
13429: ######################################################
13430:
13431: =pod
13432:
13433: =item * &csv_print_select_table($r,$records,$d)
13434:
13435: Prints a table to create associations between values and table columns.
13436:
13437: $r is an Apache Request ref,
13438: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13439: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13440:
13441: =cut
13442:
13443: ######################################################
13444: ######################################################
13445: sub csv_print_select_table {
13446: my ($r,$records,$d) = @_;
13447: my $i=0;
13448: my $samples = &get_samples($records,1);
13449: $r->print(&mt('Associate columns with student attributes.')."\n".
13450: &start_data_table().&start_data_table_header_row().
13451: '<th>'.&mt('Attribute').'</th>'.
13452: '<th>'.&mt('Column').'</th>'.
13453: &end_data_table_header_row()."\n");
13454: foreach my $array_ref (@$d) {
13455: my ($value,$display,$defaultcol)=@{ $array_ref };
13456: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
13457:
13458: $r->print('<td><select name="f'.$i.'"'.
13459: ' onchange="javascript:flip(this.form,'.$i.');">');
13460: $r->print('<option value="none"></option>');
13461: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13462: $r->print('<option value="'.$sample.'"'.
13463: ($sample eq $defaultcol ? ' selected="selected" ' : '').
13464: '>'.&mt('Column [_1]',($sample+1)).'</option>');
13465: }
13466: $r->print('</select></td>'.&end_data_table_row()."\n");
13467: $i++;
13468: }
13469: $r->print(&end_data_table());
13470: $i--;
13471: return $i;
13472: }
13473:
13474: ######################################################
13475: ######################################################
13476:
13477: =pod
13478:
13479: =item * &csv_samples_select_table($r,$records,$d)
13480:
13481: Prints a table of sample values from the upload and can make associate samples to internal names.
13482:
13483: $r is an Apache Request ref,
13484: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13485: $d is an array of 2 element arrays (internal name, displayed name)
13486:
13487: =cut
13488:
13489: ######################################################
13490: ######################################################
13491: sub csv_samples_select_table {
13492: my ($r,$records,$d) = @_;
13493: my $i=0;
13494: #
13495: my $max_samples = 5;
13496: my $samples = &get_samples($records,$max_samples);
13497: $r->print(&start_data_table().
13498: &start_data_table_header_row().'<th>'.
13499: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13500: &end_data_table_header_row());
13501:
13502: foreach my $key (sort(keys(%{ $samples->[0] }))) {
13503: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13504: ' onchange="javascript:flip(this.form,'.$i.');">');
13505: foreach my $option (@$d) {
13506: my ($value,$display,$defaultcol)=@{ $option };
13507: $r->print('<option value="'.$value.'"'.
13508: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13509: $display.'</option>');
13510: }
13511: $r->print('</select></td><td>');
13512: foreach my $line (0..($max_samples-1)) {
13513: if (defined($samples->[$line]{$key})) {
13514: $r->print($samples->[$line]{$key}."<br />\n");
13515: }
13516: }
13517: $r->print('</td>'.&end_data_table_row());
13518: $i++;
13519: }
13520: $r->print(&end_data_table());
13521: $i--;
13522: return($i);
13523: }
13524:
13525: ######################################################
13526: ######################################################
13527:
13528: =pod
13529:
13530: =item * &clean_excel_name($name)
13531:
13532: Returns a replacement for $name which does not contain any illegal characters.
13533:
13534: =cut
13535:
13536: ######################################################
13537: ######################################################
13538: sub clean_excel_name {
13539: my ($name) = @_;
13540: $name =~ s/[:\*\?\/\\]//g;
13541: if (length($name) > 31) {
13542: $name = substr($name,0,31);
13543: }
13544: return $name;
13545: }
13546:
13547: =pod
13548:
13549: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13550:
13551: Returns either 1 or undef
13552:
13553: 1 if the part is to be hidden, undef if it is to be shown
13554:
13555: Arguments are:
13556:
13557: $id the id of the part to be checked
13558: $symb, optional the symb of the resource to check
13559: $udom, optional the domain of the user to check for
13560: $uname, optional the username of the user to check for
13561:
13562: =cut
13563:
13564: sub check_if_partid_hidden {
13565: my ($id,$symb,$udom,$uname) = @_;
13566: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13567: $symb,$udom,$uname);
13568: my $truth=1;
13569: #if the string starts with !, then the list is the list to show not hide
13570: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13571: my @hiddenlist=split(/,/,$hiddenparts);
13572: foreach my $checkid (@hiddenlist) {
13573: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13574: }
13575: return !$truth;
13576: }
13577:
13578:
13579: ############################################################
13580: ############################################################
13581:
13582: =pod
13583:
13584: =back
13585:
13586: =head1 cgi-bin script and graphing routines
13587:
13588: =over 4
13589:
13590: =item * &get_cgi_id()
13591:
13592: Inputs: none
13593:
13594: Returns an id which can be used to pass environment variables
13595: to various cgi-bin scripts. These environment variables will
13596: be removed from the users environment after a given time by
13597: the routine &Apache::lonnet::transfer_profile_to_env.
13598:
13599: =cut
13600:
13601: ############################################################
13602: ############################################################
13603: my $uniq=0;
13604: sub get_cgi_id {
13605: $uniq=($uniq+1)%100000;
13606: return (time.'_'.$$.'_'.$uniq);
13607: }
13608:
13609: ############################################################
13610: ############################################################
13611:
13612: =pod
13613:
13614: =item * &DrawBarGraph()
13615:
13616: Facilitates the plotting of data in a (stacked) bar graph.
13617: Puts plot definition data into the users environment in order for
13618: graph.png to plot it. Returns an <img> tag for the plot.
13619: The bars on the plot are labeled '1','2',...,'n'.
13620:
13621: Inputs:
13622:
13623: =over 4
13624:
13625: =item $Title: string, the title of the plot
13626:
13627: =item $xlabel: string, text describing the X-axis of the plot
13628:
13629: =item $ylabel: string, text describing the Y-axis of the plot
13630:
13631: =item $Max: scalar, the maximum Y value to use in the plot
13632: If $Max is < any data point, the graph will not be rendered.
13633:
13634: =item $colors: array ref holding the colors to be used for the data sets when
13635: they are plotted. If undefined, default values will be used.
13636:
13637: =item $labels: array ref holding the labels to use on the x-axis for the bars.
13638:
13639: =item @Values: An array of array references. Each array reference holds data
13640: to be plotted in a stacked bar chart.
13641:
13642: =item If the final element of @Values is a hash reference the key/value
13643: pairs will be added to the graph definition.
13644:
13645: =back
13646:
13647: Returns:
13648:
13649: An <img> tag which references graph.png and the appropriate identifying
13650: information for the plot.
13651:
13652: =cut
13653:
13654: ############################################################
13655: ############################################################
13656: sub DrawBarGraph {
13657: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
13658: #
13659: if (! defined($colors)) {
13660: $colors = ['#33ff00',
13661: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
13662: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
13663: ];
13664: }
13665: my $extra_settings = {};
13666: if (ref($Values[-1]) eq 'HASH') {
13667: $extra_settings = pop(@Values);
13668: }
13669: #
13670: my $identifier = &get_cgi_id();
13671: my $id = 'cgi.'.$identifier;
13672: if (! @Values || ref($Values[0]) ne 'ARRAY') {
13673: return '';
13674: }
13675: #
13676: my @Labels;
13677: if (defined($labels)) {
13678: @Labels = @$labels;
13679: } else {
13680: for (my $i=0;$i<@{$Values[0]};$i++) {
13681: push(@Labels,$i+1);
13682: }
13683: }
13684: #
13685: my $NumBars = scalar(@{$Values[0]});
13686: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
13687: my %ValuesHash;
13688: my $NumSets=1;
13689: foreach my $array (@Values) {
13690: next if (! ref($array));
13691: $ValuesHash{$id.'.data.'.$NumSets++} =
13692: join(',',@$array);
13693: }
13694: #
13695: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
13696: if ($NumBars < 3) {
13697: $width = 120+$NumBars*32;
13698: $xskip = 1;
13699: $bar_width = 30;
13700: } elsif ($NumBars < 5) {
13701: $width = 120+$NumBars*20;
13702: $xskip = 1;
13703: $bar_width = 20;
13704: } elsif ($NumBars < 10) {
13705: $width = 120+$NumBars*15;
13706: $xskip = 1;
13707: $bar_width = 15;
13708: } elsif ($NumBars <= 25) {
13709: $width = 120+$NumBars*11;
13710: $xskip = 5;
13711: $bar_width = 8;
13712: } elsif ($NumBars <= 50) {
13713: $width = 120+$NumBars*8;
13714: $xskip = 5;
13715: $bar_width = 4;
13716: } else {
13717: $width = 120+$NumBars*8;
13718: $xskip = 5;
13719: $bar_width = 4;
13720: }
13721: #
13722: $Max = 1 if ($Max < 1);
13723: if ( int($Max) < $Max ) {
13724: $Max++;
13725: $Max = int($Max);
13726: }
13727: $Title = '' if (! defined($Title));
13728: $xlabel = '' if (! defined($xlabel));
13729: $ylabel = '' if (! defined($ylabel));
13730: $ValuesHash{$id.'.title'} = &escape($Title);
13731: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
13732: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
13733: $ValuesHash{$id.'.y_max_value'} = $Max;
13734: $ValuesHash{$id.'.NumBars'} = $NumBars;
13735: $ValuesHash{$id.'.NumSets'} = $NumSets;
13736: $ValuesHash{$id.'.PlotType'} = 'bar';
13737: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
13738: $ValuesHash{$id.'.height'} = $height;
13739: $ValuesHash{$id.'.width'} = $width;
13740: $ValuesHash{$id.'.xskip'} = $xskip;
13741: $ValuesHash{$id.'.bar_width'} = $bar_width;
13742: $ValuesHash{$id.'.labels'} = join(',',@Labels);
13743: #
13744: # Deal with other parameters
13745: while (my ($key,$value) = each(%$extra_settings)) {
13746: $ValuesHash{$id.'.'.$key} = $value;
13747: }
13748: #
13749: &Apache::lonnet::appenv(\%ValuesHash);
13750: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13751: }
13752:
13753: ############################################################
13754: ############################################################
13755:
13756: =pod
13757:
13758: =item * &DrawXYGraph()
13759:
13760: Facilitates the plotting of data in an XY graph.
13761: Puts plot definition data into the users environment in order for
13762: graph.png to plot it. Returns an <img> tag for the plot.
13763:
13764: Inputs:
13765:
13766: =over 4
13767:
13768: =item $Title: string, the title of the plot
13769:
13770: =item $xlabel: string, text describing the X-axis of the plot
13771:
13772: =item $ylabel: string, text describing the Y-axis of the plot
13773:
13774: =item $Max: scalar, the maximum Y value to use in the plot
13775: If $Max is < any data point, the graph will not be rendered.
13776:
13777: =item $colors: Array ref containing the hex color codes for the data to be
13778: plotted in. If undefined, default values will be used.
13779:
13780: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13781:
13782: =item $Ydata: Array ref containing Array refs.
13783: Each of the contained arrays will be plotted as a separate curve.
13784:
13785: =item %Values: hash indicating or overriding any default values which are
13786: passed to graph.png.
13787: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13788:
13789: =back
13790:
13791: Returns:
13792:
13793: An <img> tag which references graph.png and the appropriate identifying
13794: information for the plot.
13795:
13796: =cut
13797:
13798: ############################################################
13799: ############################################################
13800: sub DrawXYGraph {
13801: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
13802: #
13803: # Create the identifier for the graph
13804: my $identifier = &get_cgi_id();
13805: my $id = 'cgi.'.$identifier;
13806: #
13807: $Title = '' if (! defined($Title));
13808: $xlabel = '' if (! defined($xlabel));
13809: $ylabel = '' if (! defined($ylabel));
13810: my %ValuesHash =
13811: (
13812: $id.'.title' => &escape($Title),
13813: $id.'.xlabel' => &escape($xlabel),
13814: $id.'.ylabel' => &escape($ylabel),
13815: $id.'.y_max_value'=> $Max,
13816: $id.'.labels' => join(',',@$Xlabels),
13817: $id.'.PlotType' => 'XY',
13818: );
13819: #
13820: if (defined($colors) && ref($colors) eq 'ARRAY') {
13821: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
13822: }
13823: #
13824: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
13825: return '';
13826: }
13827: my $NumSets=1;
13828: foreach my $array (@{$Ydata}){
13829: next if (! ref($array));
13830: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13831: }
13832: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
13833: #
13834: # Deal with other parameters
13835: while (my ($key,$value) = each(%Values)) {
13836: $ValuesHash{$id.'.'.$key} = $value;
13837: }
13838: #
13839: &Apache::lonnet::appenv(\%ValuesHash);
13840: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13841: }
13842:
13843: ############################################################
13844: ############################################################
13845:
13846: =pod
13847:
13848: =item * &DrawXYYGraph()
13849:
13850: Facilitates the plotting of data in an XY graph with two Y axes.
13851: Puts plot definition data into the users environment in order for
13852: graph.png to plot it. Returns an <img> tag for the plot.
13853:
13854: Inputs:
13855:
13856: =over 4
13857:
13858: =item $Title: string, the title of the plot
13859:
13860: =item $xlabel: string, text describing the X-axis of the plot
13861:
13862: =item $ylabel: string, text describing the Y-axis of the plot
13863:
13864: =item $colors: Array ref containing the hex color codes for the data to be
13865: plotted in. If undefined, default values will be used.
13866:
13867: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13868:
13869: =item $Ydata1: The first data set
13870:
13871: =item $Min1: The minimum value of the left Y-axis
13872:
13873: =item $Max1: The maximum value of the left Y-axis
13874:
13875: =item $Ydata2: The second data set
13876:
13877: =item $Min2: The minimum value of the right Y-axis
13878:
13879: =item $Max2: The maximum value of the left Y-axis
13880:
13881: =item %Values: hash indicating or overriding any default values which are
13882: passed to graph.png.
13883: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13884:
13885: =back
13886:
13887: Returns:
13888:
13889: An <img> tag which references graph.png and the appropriate identifying
13890: information for the plot.
13891:
13892: =cut
13893:
13894: ############################################################
13895: ############################################################
13896: sub DrawXYYGraph {
13897: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13898: $Ydata2,$Min2,$Max2,%Values)=@_;
13899: #
13900: # Create the identifier for the graph
13901: my $identifier = &get_cgi_id();
13902: my $id = 'cgi.'.$identifier;
13903: #
13904: $Title = '' if (! defined($Title));
13905: $xlabel = '' if (! defined($xlabel));
13906: $ylabel = '' if (! defined($ylabel));
13907: my %ValuesHash =
13908: (
13909: $id.'.title' => &escape($Title),
13910: $id.'.xlabel' => &escape($xlabel),
13911: $id.'.ylabel' => &escape($ylabel),
13912: $id.'.labels' => join(',',@$Xlabels),
13913: $id.'.PlotType' => 'XY',
13914: $id.'.NumSets' => 2,
13915: $id.'.two_axes' => 1,
13916: $id.'.y1_max_value' => $Max1,
13917: $id.'.y1_min_value' => $Min1,
13918: $id.'.y2_max_value' => $Max2,
13919: $id.'.y2_min_value' => $Min2,
13920: );
13921: #
13922: if (defined($colors) && ref($colors) eq 'ARRAY') {
13923: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
13924: }
13925: #
13926: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13927: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13928: return '';
13929: }
13930: my $NumSets=1;
13931: foreach my $array ($Ydata1,$Ydata2){
13932: next if (! ref($array));
13933: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13934: }
13935: #
13936: # Deal with other parameters
13937: while (my ($key,$value) = each(%Values)) {
13938: $ValuesHash{$id.'.'.$key} = $value;
13939: }
13940: #
13941: &Apache::lonnet::appenv(\%ValuesHash);
13942: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13943: }
13944:
13945: ############################################################
13946: ############################################################
13947:
13948: =pod
13949:
13950: =back
13951:
13952: =head1 Statistics helper routines?
13953:
13954: Bad place for them but what the hell.
13955:
13956: =over 4
13957:
13958: =item * &chartlink()
13959:
13960: Returns a link to the chart for a specific student.
13961:
13962: Inputs:
13963:
13964: =over 4
13965:
13966: =item $linktext: The text of the link
13967:
13968: =item $sname: The students username
13969:
13970: =item $sdomain: The students domain
13971:
13972: =back
13973:
13974: =back
13975:
13976: =cut
13977:
13978: ############################################################
13979: ############################################################
13980: sub chartlink {
13981: my ($linktext, $sname, $sdomain) = @_;
13982: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13983: '&SelectedStudent='.&escape($sname.':'.$sdomain).
13984: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
13985: '">'.$linktext.'</a>';
13986: }
13987:
13988: #######################################################
13989: #######################################################
13990:
13991: =pod
13992:
13993: =head1 Course Environment Routines
13994:
13995: =over 4
13996:
13997: =item * &restore_course_settings()
13998:
13999: =item * &store_course_settings()
14000:
14001: Restores/Store indicated form parameters from the course environment.
14002: Will not overwrite existing values of the form parameters.
14003:
14004: Inputs:
14005: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14006:
14007: a hash ref describing the data to be stored. For example:
14008:
14009: %Save_Parameters = ('Status' => 'scalar',
14010: 'chartoutputmode' => 'scalar',
14011: 'chartoutputdata' => 'scalar',
14012: 'Section' => 'array',
14013: 'Group' => 'array',
14014: 'StudentData' => 'array',
14015: 'Maps' => 'array');
14016:
14017: Returns: both routines return nothing
14018:
14019: =back
14020:
14021: =cut
14022:
14023: #######################################################
14024: #######################################################
14025: sub store_course_settings {
14026: return &store_settings($env{'request.course.id'},@_);
14027: }
14028:
14029: sub store_settings {
14030: # save to the environment
14031: # appenv the same items, just to be safe
14032: my $udom = $env{'user.domain'};
14033: my $uname = $env{'user.name'};
14034: my ($context,$prefix,$Settings) = @_;
14035: my %SaveHash;
14036: my %AppHash;
14037: while (my ($setting,$type) = each(%$Settings)) {
14038: my $basename = join('.','internal',$context,$prefix,$setting);
14039: my $envname = 'environment.'.$basename;
14040: if (exists($env{'form.'.$setting})) {
14041: # Save this value away
14042: if ($type eq 'scalar' &&
14043: (! exists($env{$envname}) ||
14044: $env{$envname} ne $env{'form.'.$setting})) {
14045: $SaveHash{$basename} = $env{'form.'.$setting};
14046: $AppHash{$envname} = $env{'form.'.$setting};
14047: } elsif ($type eq 'array') {
14048: my $stored_form;
14049: if (ref($env{'form.'.$setting})) {
14050: $stored_form = join(',',
14051: map {
14052: &escape($_);
14053: } sort(@{$env{'form.'.$setting}}));
14054: } else {
14055: $stored_form =
14056: &escape($env{'form.'.$setting});
14057: }
14058: # Determine if the array contents are the same.
14059: if ($stored_form ne $env{$envname}) {
14060: $SaveHash{$basename} = $stored_form;
14061: $AppHash{$envname} = $stored_form;
14062: }
14063: }
14064: }
14065: }
14066: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14067: $udom,$uname);
14068: if ($put_result !~ /^(ok|delayed)/) {
14069: &Apache::lonnet::logthis('unable to save form parameters, '.
14070: 'got error:'.$put_result);
14071: }
14072: # Make sure these settings stick around in this session, too
14073: &Apache::lonnet::appenv(\%AppHash);
14074: return;
14075: }
14076:
14077: sub restore_course_settings {
14078: return &restore_settings($env{'request.course.id'},@_);
14079: }
14080:
14081: sub restore_settings {
14082: my ($context,$prefix,$Settings) = @_;
14083: while (my ($setting,$type) = each(%$Settings)) {
14084: next if (exists($env{'form.'.$setting}));
14085: my $envname = 'environment.internal.'.$context.'.'.$prefix.
14086: '.'.$setting;
14087: if (exists($env{$envname})) {
14088: if ($type eq 'scalar') {
14089: $env{'form.'.$setting} = $env{$envname};
14090: } elsif ($type eq 'array') {
14091: $env{'form.'.$setting} = [
14092: map {
14093: &unescape($_);
14094: } split(',',$env{$envname})
14095: ];
14096: }
14097: }
14098: }
14099: }
14100:
14101: #######################################################
14102: #######################################################
14103:
14104: =pod
14105:
14106: =head1 Domain E-mail Routines
14107:
14108: =over 4
14109:
14110: =item * &build_recipient_list()
14111:
14112: Build recipient lists for following types of e-mail:
14113: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14114: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14115: module change checking, student/employee ID conflict checks, as
14116: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14117: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14118:
14119: Inputs:
14120: defmail (scalar - email address of default recipient),
14121: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14122: requestsmail, updatesmail, or idconflictsmail).
14123:
14124: defdom (domain for which to retrieve configuration settings),
14125:
14126: origmail (scalar - email address of recipient from loncapa.conf,
14127: i.e., predates configuration by DC via domainprefs.pm
14128:
14129: $requname username of requester (if mailing type is helpdeskmail)
14130:
14131: $requdom domain of requester (if mailing type is helpdeskmail)
14132:
14133: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
14134:
14135:
14136: Returns: comma separated list of addresses to which to send e-mail.
14137:
14138: =back
14139:
14140: =cut
14141:
14142: ############################################################
14143: ############################################################
14144: sub build_recipient_list {
14145: my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
14146: my @recipients;
14147: my ($otheremails,$lastresort,$allbcc,$addtext);
14148: my %domconfig =
14149: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14150: if (ref($domconfig{'contacts'}) eq 'HASH') {
14151: if (exists($domconfig{'contacts'}{$mailing})) {
14152: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14153: my @contacts = ('adminemail','supportemail');
14154: foreach my $item (@contacts) {
14155: if ($domconfig{'contacts'}{$mailing}{$item}) {
14156: my $addr = $domconfig{'contacts'}{$item};
14157: if (!grep(/^\Q$addr\E$/,@recipients)) {
14158: push(@recipients,$addr);
14159: }
14160: }
14161: }
14162: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14163: if ($mailing eq 'helpdeskmail') {
14164: if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
14165: my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
14166: my @ok_bccs;
14167: foreach my $bcc (@bccs) {
14168: $bcc =~ s/^\s+//g;
14169: $bcc =~ s/\s+$//g;
14170: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14171: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14172: push(@ok_bccs,$bcc);
14173: }
14174: }
14175: }
14176: if (@ok_bccs > 0) {
14177: $allbcc = join(', ',@ok_bccs);
14178: }
14179: }
14180: $addtext = $domconfig{'contacts'}{$mailing}{'include'};
14181: }
14182: }
14183: } elsif ($origmail ne '') {
14184: $lastresort = $origmail;
14185: }
14186: if ($mailing eq 'helpdeskmail') {
14187: if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
14188: (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
14189: my ($inststatus,$inststatus_checked);
14190: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
14191: ($env{'user.domain'} ne 'public')) {
14192: $inststatus_checked = 1;
14193: $inststatus = $env{'environment.inststatus'};
14194: }
14195: unless ($inststatus_checked) {
14196: if (($requname ne '') && ($requdom ne '')) {
14197: if (($requname =~ /^$match_username$/) &&
14198: ($requdom =~ /^$match_domain$/) &&
14199: (&Apache::lonnet::domain($requdom))) {
14200: my $requhome = &Apache::lonnet::homeserver($requname,
14201: $requdom);
14202: unless ($requhome eq 'no_host') {
14203: my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
14204: $inststatus = $userenv{'inststatus'};
14205: $inststatus_checked = 1;
14206: }
14207: }
14208: }
14209: }
14210: unless ($inststatus_checked) {
14211: if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
14212: my %srch = (srchby => 'email',
14213: srchdomain => $defdom,
14214: srchterm => $reqemail,
14215: srchtype => 'exact');
14216: my %srch_results = &Apache::lonnet::usersearch(\%srch);
14217: foreach my $uname (keys(%srch_results)) {
14218: if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14219: $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14220: $inststatus_checked = 1;
14221: last;
14222: }
14223: }
14224: unless ($inststatus_checked) {
14225: my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
14226: if ($dirsrchres eq 'ok') {
14227: foreach my $uname (keys(%srch_results)) {
14228: if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14229: $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14230: $inststatus_checked = 1;
14231: last;
14232: }
14233: }
14234: }
14235: }
14236: }
14237: }
14238: if ($inststatus ne '') {
14239: foreach my $status (split(/\:/,$inststatus)) {
14240: if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
14241: my @contacts = ('adminemail','supportemail');
14242: foreach my $item (@contacts) {
14243: if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
14244: my $addr = $domconfig{'contacts'}{'overrides'}{$status};
14245: if (!grep(/^\Q$addr\E$/,@recipients)) {
14246: push(@recipients,$addr);
14247: }
14248: }
14249: }
14250: $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
14251: if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
14252: my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
14253: my @ok_bccs;
14254: foreach my $bcc (@bccs) {
14255: $bcc =~ s/^\s+//g;
14256: $bcc =~ s/\s+$//g;
14257: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14258: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14259: push(@ok_bccs,$bcc);
14260: }
14261: }
14262: }
14263: if (@ok_bccs > 0) {
14264: $allbcc = join(', ',@ok_bccs);
14265: }
14266: }
14267: $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
14268: last;
14269: }
14270: }
14271: }
14272: }
14273: }
14274: } elsif ($origmail ne '') {
14275: $lastresort = $origmail;
14276: }
14277:
14278: if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
14279: unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
14280: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
14281: my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
14282: my %what = (
14283: perlvar => 1,
14284: );
14285: my $primary = &Apache::lonnet::domain($defdom,'primary');
14286: if ($primary) {
14287: my $gotaddr;
14288: my ($result,$returnhash) =
14289: &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
14290: if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
14291: if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
14292: $lastresort = $returnhash->{'lonSupportEMail'};
14293: $gotaddr = 1;
14294: }
14295: }
14296: unless ($gotaddr) {
14297: my $uintdom = &Apache::lonnet::internet_dom($primary);
14298: my $intdom = &Apache::lonnet::internet_dom($lonhost);
14299: unless ($uintdom eq $intdom) {
14300: my %domconfig =
14301: &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
14302: if (ref($domconfig{'contacts'}) eq 'HASH') {
14303: if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
14304: my @contacts = ('adminemail','supportemail');
14305: foreach my $item (@contacts) {
14306: if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
14307: my $addr = $domconfig{'contacts'}{$item};
14308: if (!grep(/^\Q$addr\E$/,@recipients)) {
14309: push(@recipients,$addr);
14310: }
14311: }
14312: }
14313: if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
14314: $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
14315: }
14316: if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
14317: my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
14318: my @ok_bccs;
14319: foreach my $bcc (@bccs) {
14320: $bcc =~ s/^\s+//g;
14321: $bcc =~ s/\s+$//g;
14322: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14323: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14324: push(@ok_bccs,$bcc);
14325: }
14326: }
14327: }
14328: if (@ok_bccs > 0) {
14329: $allbcc = join(', ',@ok_bccs);
14330: }
14331: }
14332: $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
14333: }
14334: }
14335: }
14336: }
14337: }
14338: }
14339: }
14340: if (defined($defmail)) {
14341: if ($defmail ne '') {
14342: push(@recipients,$defmail);
14343: }
14344: }
14345: if ($otheremails) {
14346: my @others;
14347: if ($otheremails =~ /,/) {
14348: @others = split(/,/,$otheremails);
14349: } else {
14350: push(@others,$otheremails);
14351: }
14352: foreach my $addr (@others) {
14353: if (!grep(/^\Q$addr\E$/,@recipients)) {
14354: push(@recipients,$addr);
14355: }
14356: }
14357: }
14358: if ($mailing eq 'helpdeskmail') {
14359: if ((!@recipients) && ($lastresort ne '')) {
14360: push(@recipients,$lastresort);
14361: }
14362: } elsif ($lastresort ne '') {
14363: if (!grep(/^\Q$lastresort\E$/,@recipients)) {
14364: push(@recipients,$lastresort);
14365: }
14366: }
14367: my $recipientlist = join(',',@recipients);
14368: if (wantarray) {
14369: return ($recipientlist,$allbcc,$addtext);
14370: } else {
14371: return $recipientlist;
14372: }
14373: }
14374:
14375: ############################################################
14376: ############################################################
14377:
14378: =pod
14379:
14380: =head1 Course Catalog Routines
14381:
14382: =over 4
14383:
14384: =item * &gather_categories()
14385:
14386: Converts category definitions - keys of categories hash stored in
14387: coursecategories in configuration.db on the primary library server in a
14388: domain - to an array. Also generates javascript and idx hash used to
14389: generate Domain Coordinator interface for editing Course Categories.
14390:
14391: Inputs:
14392:
14393: categories (reference to hash of category definitions).
14394:
14395: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14396: categories and subcategories).
14397:
14398: idx (reference to hash of counters used in Domain Coordinator interface for
14399: editing Course Categories).
14400:
14401: jsarray (reference to array of categories used to create Javascript arrays for
14402: Domain Coordinator interface for editing Course Categories).
14403:
14404: Returns: nothing
14405:
14406: Side effects: populates cats, idx and jsarray.
14407:
14408: =cut
14409:
14410: sub gather_categories {
14411: my ($categories,$cats,$idx,$jsarray) = @_;
14412: my %counters;
14413: my $num = 0;
14414: foreach my $item (keys(%{$categories})) {
14415: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
14416: if ($container eq '' && $depth == 0) {
14417: $cats->[$depth][$categories->{$item}] = $cat;
14418: } else {
14419: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
14420: }
14421: my ($escitem,$tail) = split(/:/,$item,2);
14422: if ($counters{$tail} eq '') {
14423: $counters{$tail} = $num;
14424: $num ++;
14425: }
14426: if (ref($idx) eq 'HASH') {
14427: $idx->{$item} = $counters{$tail};
14428: }
14429: if (ref($jsarray) eq 'ARRAY') {
14430: push(@{$jsarray->[$counters{$tail}]},$item);
14431: }
14432: }
14433: return;
14434: }
14435:
14436: =pod
14437:
14438: =item * &extract_categories()
14439:
14440: Used to generate breadcrumb trails for course categories.
14441:
14442: Inputs:
14443:
14444: categories (reference to hash of category definitions).
14445:
14446: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14447: categories and subcategories).
14448:
14449: trails (reference to array of breacrumb trails for each category).
14450:
14451: allitems (reference to hash - key is category key
14452: (format: escaped(name):escaped(parent category):depth in hierarchy).
14453:
14454: idx (reference to hash of counters used in Domain Coordinator interface for
14455: editing Course Categories).
14456:
14457: jsarray (reference to array of categories used to create Javascript arrays for
14458: Domain Coordinator interface for editing Course Categories).
14459:
14460: subcats (reference to hash of arrays containing all subcategories within each
14461: category, -recursive)
14462:
14463: Returns: nothing
14464:
14465: Side effects: populates trails and allitems hash references.
14466:
14467: =cut
14468:
14469: sub extract_categories {
14470: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
14471: if (ref($categories) eq 'HASH') {
14472: &gather_categories($categories,$cats,$idx,$jsarray);
14473: if (ref($cats->[0]) eq 'ARRAY') {
14474: for (my $i=0; $i<@{$cats->[0]}; $i++) {
14475: my $name = $cats->[0][$i];
14476: my $item = &escape($name).'::0';
14477: my $trailstr;
14478: if ($name eq 'instcode') {
14479: $trailstr = &mt('Official courses (with institutional codes)');
14480: } elsif ($name eq 'communities') {
14481: $trailstr = &mt('Communities');
14482: } else {
14483: $trailstr = $name;
14484: }
14485: if ($allitems->{$item} eq '') {
14486: push(@{$trails},$trailstr);
14487: $allitems->{$item} = scalar(@{$trails})-1;
14488: }
14489: my @parents = ($name);
14490: if (ref($cats->[1]{$name}) eq 'ARRAY') {
14491: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
14492: my $category = $cats->[1]{$name}[$j];
14493: if (ref($subcats) eq 'HASH') {
14494: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
14495: }
14496: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
14497: }
14498: } else {
14499: if (ref($subcats) eq 'HASH') {
14500: $subcats->{$item} = [];
14501: }
14502: }
14503: }
14504: }
14505: }
14506: return;
14507: }
14508:
14509: =pod
14510:
14511: =item * &recurse_categories()
14512:
14513: Recursively used to generate breadcrumb trails for course categories.
14514:
14515: Inputs:
14516:
14517: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14518: categories and subcategories).
14519:
14520: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
14521:
14522: category (current course category, for which breadcrumb trail is being generated).
14523:
14524: trails (reference to array of breadcrumb trails for each category).
14525:
14526: allitems (reference to hash - key is category key
14527: (format: escaped(name):escaped(parent category):depth in hierarchy).
14528:
14529: parents (array containing containers directories for current category,
14530: back to top level).
14531:
14532: Returns: nothing
14533:
14534: Side effects: populates trails and allitems hash references
14535:
14536: =cut
14537:
14538: sub recurse_categories {
14539: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
14540: my $shallower = $depth - 1;
14541: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
14542: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
14543: my $name = $cats->[$depth]{$category}[$k];
14544: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14545: my $trailstr = join(' -> ',(@{$parents},$category));
14546: if ($allitems->{$item} eq '') {
14547: push(@{$trails},$trailstr);
14548: $allitems->{$item} = scalar(@{$trails})-1;
14549: }
14550: my $deeper = $depth+1;
14551: push(@{$parents},$category);
14552: if (ref($subcats) eq 'HASH') {
14553: my $subcat = &escape($name).':'.$category.':'.$depth;
14554: for (my $j=@{$parents}; $j>=0; $j--) {
14555: my $higher;
14556: if ($j > 0) {
14557: $higher = &escape($parents->[$j]).':'.
14558: &escape($parents->[$j-1]).':'.$j;
14559: } else {
14560: $higher = &escape($parents->[$j]).'::'.$j;
14561: }
14562: push(@{$subcats->{$higher}},$subcat);
14563: }
14564: }
14565: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14566: $subcats);
14567: pop(@{$parents});
14568: }
14569: } else {
14570: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14571: my $trailstr = join(' -> ',(@{$parents},$category));
14572: if ($allitems->{$item} eq '') {
14573: push(@{$trails},$trailstr);
14574: $allitems->{$item} = scalar(@{$trails})-1;
14575: }
14576: }
14577: return;
14578: }
14579:
14580: =pod
14581:
14582: =item * &assign_categories_table()
14583:
14584: Create a datatable for display of hierarchical categories in a domain,
14585: with checkboxes to allow a course to be categorized.
14586:
14587: Inputs:
14588:
14589: cathash - reference to hash of categories defined for the domain (from
14590: configuration.db)
14591:
14592: currcat - scalar with an & separated list of categories assigned to a course.
14593:
14594: type - scalar contains course type (Course or Community).
14595:
14596: disabled - scalar (optional) contains disabled="disabled" if input elements are
14597: to be readonly (e.g., Domain Helpdesk role viewing course settings).
14598:
14599: Returns: $output (markup to be displayed)
14600:
14601: =cut
14602:
14603: sub assign_categories_table {
14604: my ($cathash,$currcat,$type,$disabled) = @_;
14605: my $output;
14606: if (ref($cathash) eq 'HASH') {
14607: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
14608: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
14609: $maxdepth = scalar(@cats);
14610: if (@cats > 0) {
14611: my $itemcount = 0;
14612: if (ref($cats[0]) eq 'ARRAY') {
14613: my @currcategories;
14614: if ($currcat ne '') {
14615: @currcategories = split('&',$currcat);
14616: }
14617: my $table;
14618: for (my $i=0; $i<@{$cats[0]}; $i++) {
14619: my $parent = $cats[0][$i];
14620: next if ($parent eq 'instcode');
14621: if ($type eq 'Community') {
14622: next unless ($parent eq 'communities');
14623: } else {
14624: next if ($parent eq 'communities');
14625: }
14626: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14627: my $item = &escape($parent).'::0';
14628: my $checked = '';
14629: if (@currcategories > 0) {
14630: if (grep(/^\Q$item\E$/,@currcategories)) {
14631: $checked = ' checked="checked"';
14632: }
14633: }
14634: my $parent_title = $parent;
14635: if ($parent eq 'communities') {
14636: $parent_title = &mt('Communities');
14637: }
14638: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
14639: '<input type="checkbox" name="usecategory" value="'.
14640: $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
14641: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
14642: my $depth = 1;
14643: push(@path,$parent);
14644: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
14645: pop(@path);
14646: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
14647: $itemcount ++;
14648: }
14649: if ($itemcount) {
14650: $output = &Apache::loncommon::start_data_table().
14651: $table.
14652: &Apache::loncommon::end_data_table();
14653: }
14654: }
14655: }
14656: }
14657: return $output;
14658: }
14659:
14660: =pod
14661:
14662: =item * &assign_category_rows()
14663:
14664: Create a datatable row for display of nested categories in a domain,
14665: with checkboxes to allow a course to be categorized,called recursively.
14666:
14667: Inputs:
14668:
14669: itemcount - track row number for alternating colors
14670:
14671: cats - reference to array of arrays/hashes which encapsulates hierarchy of
14672: categories and subcategories.
14673:
14674: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
14675:
14676: parent - parent of current category item
14677:
14678: path - Array containing all categories back up through the hierarchy from the
14679: current category to the top level.
14680:
14681: currcategories - reference to array of current categories assigned to the course
14682:
14683: disabled - scalar (optional) contains disabled="disabled" if input elements are
14684: to be readonly (e.g., Domain Helpdesk role viewing course settings).
14685:
14686: Returns: $output (markup to be displayed).
14687:
14688: =cut
14689:
14690: sub assign_category_rows {
14691: my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
14692: my ($text,$name,$item,$chgstr);
14693: if (ref($cats) eq 'ARRAY') {
14694: my $maxdepth = scalar(@{$cats});
14695: if (ref($cats->[$depth]) eq 'HASH') {
14696: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
14697: my $numchildren = @{$cats->[$depth]{$parent}};
14698: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14699: $text .= '<td><table class="LC_data_table">';
14700: for (my $j=0; $j<$numchildren; $j++) {
14701: $name = $cats->[$depth]{$parent}[$j];
14702: $item = &escape($name).':'.&escape($parent).':'.$depth;
14703: my $deeper = $depth+1;
14704: my $checked = '';
14705: if (ref($currcategories) eq 'ARRAY') {
14706: if (@{$currcategories} > 0) {
14707: if (grep(/^\Q$item\E$/,@{$currcategories})) {
14708: $checked = ' checked="checked"';
14709: }
14710: }
14711: }
14712: $text .= '<tr><td><span class="LC_nobreak"><label>'.
14713: '<input type="checkbox" name="usecategory" value="'.
14714: $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
14715: '<input type="hidden" name="catname" value="'.$name.'" />'.
14716: '</td><td>';
14717: if (ref($path) eq 'ARRAY') {
14718: push(@{$path},$name);
14719: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
14720: pop(@{$path});
14721: }
14722: $text .= '</td></tr>';
14723: }
14724: $text .= '</table></td>';
14725: }
14726: }
14727: }
14728: return $text;
14729: }
14730:
14731: =pod
14732:
14733: =back
14734:
14735: =cut
14736:
14737: ############################################################
14738: ############################################################
14739:
14740:
14741: sub commit_customrole {
14742: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
14743: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
14744: ($start?', '.&mt('starting').' '.localtime($start):'').
14745: ($end?', ending '.localtime($end):'').': <b>'.
14746: &Apache::lonnet::assigncustomrole(
14747: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
14748: '</b><br />';
14749: return $output;
14750: }
14751:
14752: sub commit_standardrole {
14753: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
14754: my ($output,$logmsg,$linefeed);
14755: if ($context eq 'auto') {
14756: $linefeed = "\n";
14757: } else {
14758: $linefeed = "<br />\n";
14759: }
14760: if ($three eq 'st') {
14761: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
14762: $one,$two,$sec,$context,$credits);
14763: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
14764: ($result eq 'unknown_course') || ($result eq 'refused')) {
14765: $output = $logmsg.' '.&mt('Error: ').$result."\n";
14766: } else {
14767: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
14768: ($start?', '.&mt('starting').' '.localtime($start):'').
14769: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14770: if ($context eq 'auto') {
14771: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
14772: } else {
14773: $output .= '<b>'.$result.'</b>'.$linefeed.
14774: &mt('Add to classlist').': <b>ok</b>';
14775: }
14776: $output .= $linefeed;
14777: }
14778: } else {
14779: $output = &mt('Assigning').' '.$three.' in '.$url.
14780: ($start?', '.&mt('starting').' '.localtime($start):'').
14781: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14782: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
14783: if ($context eq 'auto') {
14784: $output .= $result.$linefeed;
14785: } else {
14786: $output .= '<b>'.$result.'</b>'.$linefeed;
14787: }
14788: }
14789: return $output;
14790: }
14791:
14792: sub commit_studentrole {
14793: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
14794: $credits) = @_;
14795: my ($result,$linefeed,$oldsecurl,$newsecurl);
14796: if ($context eq 'auto') {
14797: $linefeed = "\n";
14798: } else {
14799: $linefeed = '<br />'."\n";
14800: }
14801: if (defined($one) && defined($two)) {
14802: my $cid=$one.'_'.$two;
14803: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
14804: my $secchange = 0;
14805: my $expire_role_result;
14806: my $modify_section_result;
14807: if ($oldsec ne '-1') {
14808: if ($oldsec ne $sec) {
14809: $secchange = 1;
14810: my $now = time;
14811: my $uurl='/'.$cid;
14812: $uurl=~s/\_/\//g;
14813: if ($oldsec) {
14814: $uurl.='/'.$oldsec;
14815: }
14816: $oldsecurl = $uurl;
14817: $expire_role_result =
14818: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
14819: if ($env{'request.course.sec'} ne '') {
14820: if ($expire_role_result eq 'refused') {
14821: my @roles = ('st');
14822: my @statuses = ('previous');
14823: my @roledoms = ($one);
14824: my $withsec = 1;
14825: my %roleshash =
14826: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
14827: \@statuses,\@roles,\@roledoms,$withsec);
14828: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
14829: my ($oldstart,$oldend) =
14830: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
14831: if ($oldend > 0 && $oldend <= $now) {
14832: $expire_role_result = 'ok';
14833: }
14834: }
14835: }
14836: }
14837: $result = $expire_role_result;
14838: }
14839: }
14840: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
14841: $modify_section_result =
14842: &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
14843: undef,undef,undef,$sec,
14844: $end,$start,'','',$cid,
14845: '',$context,$credits);
14846: if ($modify_section_result =~ /^ok/) {
14847: if ($secchange == 1) {
14848: if ($sec eq '') {
14849: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
14850: } else {
14851: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
14852: }
14853: } elsif ($oldsec eq '-1') {
14854: if ($sec eq '') {
14855: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
14856: } else {
14857: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14858: }
14859: } else {
14860: if ($sec eq '') {
14861: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
14862: } else {
14863: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14864: }
14865: }
14866: } else {
14867: if ($secchange) {
14868: $$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;
14869: } else {
14870: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
14871: }
14872: }
14873: $result = $modify_section_result;
14874: } elsif ($secchange == 1) {
14875: if ($oldsec eq '') {
14876: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
14877: } else {
14878: $$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;
14879: }
14880: if ($expire_role_result eq 'refused') {
14881: my $newsecurl = '/'.$cid;
14882: $newsecurl =~ s/\_/\//g;
14883: if ($sec ne '') {
14884: $newsecurl.='/'.$sec;
14885: }
14886: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
14887: if ($sec eq '') {
14888: $$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;
14889: } else {
14890: $$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;
14891: }
14892: }
14893: }
14894: }
14895: } else {
14896: $$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;
14897: $result = "error: incomplete course id\n";
14898: }
14899: return $result;
14900: }
14901:
14902: sub show_role_extent {
14903: my ($scope,$context,$role) = @_;
14904: $scope =~ s{^/}{};
14905: my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
14906: push(@courseroles,'co');
14907: my @authorroles = &Apache::lonuserutils::roles_by_context('author');
14908: if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
14909: $scope =~ s{/}{_};
14910: return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
14911: } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
14912: my ($audom,$auname) = split(/\//,$scope);
14913: return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
14914: &Apache::loncommon::plainname($auname,$audom).'</span>');
14915: } else {
14916: $scope =~ s{/$}{};
14917: return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
14918: &Apache::lonnet::domain($scope,'description').'</span>');
14919: }
14920: }
14921:
14922: ############################################################
14923: ############################################################
14924:
14925: sub check_clone {
14926: my ($args,$linefeed) = @_;
14927: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
14928: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
14929: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
14930: my $clonemsg;
14931: my $can_clone = 0;
14932: my $lctype = lc($args->{'crstype'});
14933: if ($lctype ne 'community') {
14934: $lctype = 'course';
14935: }
14936: if ($clonehome eq 'no_host') {
14937: if ($args->{'crstype'} eq 'Community') {
14938: $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'});
14939: } else {
14940: $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'});
14941: }
14942: } else {
14943: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
14944: if ($args->{'crstype'} eq 'Community') {
14945: if ($clonedesc{'type'} ne 'Community') {
14946: $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'});
14947: return ($can_clone, $clonemsg, $cloneid, $clonehome);
14948: }
14949: }
14950: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
14951: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
14952: $can_clone = 1;
14953: } else {
14954: my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
14955: $args->{'clonedomain'},$args->{'clonecourse'});
14956: if ($clonehash{'cloners'} eq '') {
14957: my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
14958: if ($domdefs{'canclone'}) {
14959: unless ($domdefs{'canclone'} eq 'none') {
14960: if ($domdefs{'canclone'} eq 'domain') {
14961: if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
14962: $can_clone = 1;
14963: }
14964: } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
14965: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
14966: if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
14967: $clonehash{'internal.coursecode'},$args->{'crscode'})) {
14968: $can_clone = 1;
14969: }
14970: }
14971: }
14972: }
14973: } else {
14974: my @cloners = split(/,/,$clonehash{'cloners'});
14975: if (grep(/^\*$/,@cloners)) {
14976: $can_clone = 1;
14977: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14978: $can_clone = 1;
14979: } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14980: $can_clone = 1;
14981: }
14982: unless ($can_clone) {
14983: if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
14984: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
14985: my (%gotdomdefaults,%gotcodedefaults);
14986: foreach my $cloner (@cloners) {
14987: if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
14988: ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
14989: my (%codedefaults,@code_order);
14990: if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
14991: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
14992: %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
14993: }
14994: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
14995: @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
14996: }
14997: } else {
14998: &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
14999: \%codedefaults,
15000: \@code_order);
15001: $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15002: $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15003: }
15004: if (@code_order > 0) {
15005: if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15006: $cloner,$clonehash{'internal.coursecode'},
15007: $args->{'crscode'})) {
15008: $can_clone = 1;
15009: last;
15010: }
15011: }
15012: }
15013: }
15014: }
15015: }
15016: }
15017: unless ($can_clone) {
15018: my $ccrole = 'cc';
15019: if ($args->{'crstype'} eq 'Community') {
15020: $ccrole = 'co';
15021: }
15022: my %roleshash =
15023: &Apache::lonnet::get_my_roles($args->{'ccuname'},
15024: $args->{'ccdomain'},
15025: 'userroles',['active'],[$ccrole],
15026: [$args->{'clonedomain'}]);
15027: if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15028: $can_clone = 1;
15029: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15030: $args->{'ccuname'},$args->{'ccdomain'})) {
15031: $can_clone = 1;
15032: }
15033: }
15034: unless ($can_clone) {
15035: if ($args->{'crstype'} eq 'Community') {
15036: $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'});
15037: } else {
15038: $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'});
15039: }
15040: }
15041: }
15042: }
15043: return ($can_clone, $clonemsg, $cloneid, $clonehome);
15044: }
15045:
15046: sub construct_course {
15047: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
15048: $cnum,$category,$coderef) = @_;
15049: my $outcome;
15050: my $linefeed = '<br />'."\n";
15051: if ($context eq 'auto') {
15052: $linefeed = "\n";
15053: }
15054:
15055: #
15056: # Are we cloning?
15057: #
15058: my ($can_clone, $clonemsg, $cloneid, $clonehome);
15059: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
15060: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
15061: if ($context ne 'auto') {
15062: if ($clonemsg ne '') {
15063: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
15064: }
15065: }
15066: $outcome .= $clonemsg.$linefeed;
15067:
15068: if (!$can_clone) {
15069: return (0,$outcome);
15070: }
15071: }
15072:
15073: #
15074: # Open course
15075: #
15076: my $crstype = lc($args->{'crstype'});
15077: my %cenv=();
15078: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
15079: $args->{'cdescr'},
15080: $args->{'curl'},
15081: $args->{'course_home'},
15082: $args->{'nonstandard'},
15083: $args->{'crscode'},
15084: $args->{'ccuname'}.':'.
15085: $args->{'ccdomain'},
15086: $args->{'crstype'},
15087: $cnum,$context,$category);
15088:
15089: # Note: The testing routines depend on this being output; see
15090: # Utils::Course. This needs to at least be output as a comment
15091: # if anyone ever decides to not show this, and Utils::Course::new
15092: # will need to be suitably modified.
15093: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
15094: if ($$courseid =~ /^error:/) {
15095: return (0,$outcome);
15096: }
15097:
15098: #
15099: # Check if created correctly
15100: #
15101: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
15102: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
15103: if ($crsuhome eq 'no_host') {
15104: $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
15105: return (0,$outcome);
15106: }
15107: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
15108:
15109: #
15110: # Do the cloning
15111: #
15112: if ($can_clone && $cloneid) {
15113: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
15114: if ($context ne 'auto') {
15115: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
15116: }
15117: $outcome .= $clonemsg.$linefeed;
15118: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
15119: # Copy all files
15120: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
15121: # Restore URL
15122: $cenv{'url'}=$oldcenv{'url'};
15123: # Restore title
15124: $cenv{'description'}=$oldcenv{'description'};
15125: # Restore creation date, creator and creation context.
15126: $cenv{'internal.created'}=$oldcenv{'internal.created'};
15127: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
15128: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
15129: # Mark as cloned
15130: $cenv{'clonedfrom'}=$cloneid;
15131: # Need to clone grading mode
15132: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
15133: $cenv{'grading'}=$newenv{'grading'};
15134: # Do not clone these environment entries
15135: &Apache::lonnet::del('environment',
15136: ['default_enrollment_start_date',
15137: 'default_enrollment_end_date',
15138: 'question.email',
15139: 'policy.email',
15140: 'comment.email',
15141: 'pch.users.denied',
15142: 'plc.users.denied',
15143: 'hidefromcat',
15144: 'checkforpriv',
15145: 'categories',
15146: 'internal.uniquecode'],
15147: $$crsudom,$$crsunum);
15148: if ($args->{'textbook'}) {
15149: $cenv{'internal.textbook'} = $args->{'textbook'};
15150: }
15151: }
15152:
15153: #
15154: # Set environment (will override cloned, if existing)
15155: #
15156: my @sections = ();
15157: my @xlists = ();
15158: if ($args->{'crstype'}) {
15159: $cenv{'type'}=$args->{'crstype'};
15160: }
15161: if ($args->{'crsid'}) {
15162: $cenv{'courseid'}=$args->{'crsid'};
15163: }
15164: if ($args->{'crscode'}) {
15165: $cenv{'internal.coursecode'}=$args->{'crscode'};
15166: }
15167: if ($args->{'crsquota'} ne '') {
15168: $cenv{'internal.coursequota'}=$args->{'crsquota'};
15169: } else {
15170: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
15171: }
15172: if ($args->{'ccuname'}) {
15173: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
15174: ':'.$args->{'ccdomain'};
15175: } else {
15176: $cenv{'internal.courseowner'} = $args->{'curruser'};
15177: }
15178: if ($args->{'defaultcredits'}) {
15179: $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
15180: }
15181: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
15182: if ($args->{'crssections'}) {
15183: $cenv{'internal.sectionnums'} = '';
15184: if ($args->{'crssections'} =~ m/,/) {
15185: @sections = split/,/,$args->{'crssections'};
15186: } else {
15187: $sections[0] = $args->{'crssections'};
15188: }
15189: if (@sections > 0) {
15190: foreach my $item (@sections) {
15191: my ($sec,$gp) = split/:/,$item;
15192: my $class = $args->{'crscode'}.$sec;
15193: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
15194: $cenv{'internal.sectionnums'} .= $item.',';
15195: unless ($addcheck eq 'ok') {
15196: push(@badclasses,$class);
15197: }
15198: }
15199: $cenv{'internal.sectionnums'} =~ s/,$//;
15200: }
15201: }
15202: # do not hide course coordinator from staff listing,
15203: # even if privileged
15204: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15205: # add course coordinator's domain to domains to check for privileged users
15206: # if different to course domain
15207: if ($$crsudom ne $args->{'ccdomain'}) {
15208: $cenv{'checkforpriv'} = $args->{'ccdomain'};
15209: }
15210: # add crosslistings
15211: if ($args->{'crsxlist'}) {
15212: $cenv{'internal.crosslistings'}='';
15213: if ($args->{'crsxlist'} =~ m/,/) {
15214: @xlists = split/,/,$args->{'crsxlist'};
15215: } else {
15216: $xlists[0] = $args->{'crsxlist'};
15217: }
15218: if (@xlists > 0) {
15219: foreach my $item (@xlists) {
15220: my ($xl,$gp) = split/:/,$item;
15221: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15222: $cenv{'internal.crosslistings'} .= $item.',';
15223: unless ($addcheck eq 'ok') {
15224: push(@badclasses,$xl);
15225: }
15226: }
15227: $cenv{'internal.crosslistings'} =~ s/,$//;
15228: }
15229: }
15230: if ($args->{'autoadds'}) {
15231: $cenv{'internal.autoadds'}=$args->{'autoadds'};
15232: }
15233: if ($args->{'autodrops'}) {
15234: $cenv{'internal.autodrops'}=$args->{'autodrops'};
15235: }
15236: # check for notification of enrollment changes
15237: my @notified = ();
15238: if ($args->{'notify_owner'}) {
15239: if ($args->{'ccuname'} ne '') {
15240: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15241: }
15242: }
15243: if ($args->{'notify_dc'}) {
15244: if ($uname ne '') {
15245: push(@notified,$uname.':'.$udom);
15246: }
15247: }
15248: if (@notified > 0) {
15249: my $notifylist;
15250: if (@notified > 1) {
15251: $notifylist = join(',',@notified);
15252: } else {
15253: $notifylist = $notified[0];
15254: }
15255: $cenv{'internal.notifylist'} = $notifylist;
15256: }
15257: if (@badclasses > 0) {
15258: my %lt=&Apache::lonlocal::texthash(
15259: 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
15260: 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
15261: 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
15262: );
15263: my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
15264: &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'};
15265: if ($context eq 'auto') {
15266: $outcome .= $badclass_msg.$linefeed;
15267: } else {
15268: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15269: }
15270: foreach my $item (@badclasses) {
15271: if ($context eq 'auto') {
15272: $outcome .= " - $item\n";
15273: } else {
15274: $outcome .= "<li>$item</li>\n";
15275: }
15276: }
15277: if ($context eq 'auto') {
15278: $outcome .= $linefeed;
15279: } else {
15280: $outcome .= "</ul><br /><br /></div>\n";
15281: }
15282: }
15283: if ($args->{'no_end_date'}) {
15284: $args->{'endaccess'} = 0;
15285: }
15286: $cenv{'internal.autostart'}=$args->{'enrollstart'};
15287: $cenv{'internal.autoend'}=$args->{'enrollend'};
15288: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15289: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15290: if ($args->{'showphotos'}) {
15291: $cenv{'internal.showphotos'}=$args->{'showphotos'};
15292: }
15293: $cenv{'internal.authtype'} = $args->{'authtype'};
15294: $cenv{'internal.autharg'} = $args->{'autharg'};
15295: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15296: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
15297: 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');
15298: if ($context eq 'auto') {
15299: $outcome .= $krb_msg;
15300: } else {
15301: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15302: }
15303: $outcome .= $linefeed;
15304: }
15305: }
15306: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15307: if ($args->{'setpolicy'}) {
15308: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15309: }
15310: if ($args->{'setcontent'}) {
15311: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15312: }
15313: if ($args->{'setcomment'}) {
15314: $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15315: }
15316: }
15317: if ($args->{'reshome'}) {
15318: $cenv{'reshome'}=$args->{'reshome'}.'/';
15319: $cenv{'reshome'}=~s/\/+$/\//;
15320: }
15321: #
15322: # course has keyed access
15323: #
15324: if ($args->{'setkeys'}) {
15325: $cenv{'keyaccess'}='yes';
15326: }
15327: # if specified, key authority is not course, but user
15328: # only active if keyaccess is yes
15329: if ($args->{'keyauth'}) {
15330: my ($user,$domain) = split(':',$args->{'keyauth'});
15331: $user = &LONCAPA::clean_username($user);
15332: $domain = &LONCAPA::clean_username($domain);
15333: if ($user ne '' && $domain ne '') {
15334: $cenv{'keyauth'}=$user.':'.$domain;
15335: }
15336: }
15337:
15338: #
15339: # generate and store uniquecode (available to course requester), if course should have one.
15340: #
15341: if ($args->{'uniquecode'}) {
15342: my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
15343: if ($code) {
15344: $cenv{'internal.uniquecode'} = $code;
15345: my %crsinfo =
15346: &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
15347: if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
15348: $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
15349: my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
15350: }
15351: if (ref($coderef)) {
15352: $$coderef = $code;
15353: }
15354: }
15355: }
15356:
15357: if ($args->{'disresdis'}) {
15358: $cenv{'pch.roles.denied'}='st';
15359: }
15360: if ($args->{'disablechat'}) {
15361: $cenv{'plc.roles.denied'}='st';
15362: }
15363:
15364: # Record we've not yet viewed the Course Initialization Helper for this
15365: # course
15366: $cenv{'course.helper.not.run'} = 1;
15367: #
15368: # Use new Randomseed
15369: #
15370: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
15371: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
15372: #
15373: # The encryption code and receipt prefix for this course
15374: #
15375: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
15376: $cenv{'internal.encpref'}=100+int(9*rand(99));
15377: #
15378: # By default, use standard grading
15379: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
15380:
15381: $outcome .= $linefeed.&mt('Setting environment').': '.
15382: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
15383: #
15384: # Open all assignments
15385: #
15386: if ($args->{'openall'}) {
15387: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
15388: my %storecontent = ($storeunder => time,
15389: $storeunder.'.type' => 'date_start');
15390:
15391: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
15392: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
15393: }
15394: #
15395: # Set first page
15396: #
15397: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
15398: || ($cloneid)) {
15399: use LONCAPA::map;
15400: $outcome .= &mt('Setting first resource').': ';
15401:
15402: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
15403: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
15404:
15405: $outcome .= ($fatal?$errtext:'read ok').' - ';
15406: my $title; my $url;
15407: if ($args->{'firstres'} eq 'syl') {
15408: $title=&mt('Syllabus');
15409: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
15410: } else {
15411: $title=&mt('Table of Contents');
15412: $url='/adm/navmaps';
15413: }
15414:
15415: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
15416: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
15417:
15418: if ($errtext) { $fatal=2; }
15419: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
15420: }
15421:
15422: return (1,$outcome);
15423: }
15424:
15425: sub make_unique_code {
15426: my ($cdom,$cnum) = @_;
15427: # get lock on uniquecodes db
15428: my $lockhash = {
15429: $cnum."\0".'uniquecodes' => $env{'user.name'}.
15430: ':'.$env{'user.domain'},
15431: };
15432: my $tries = 0;
15433: my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15434: my ($code,$error);
15435:
15436: while (($gotlock ne 'ok') && ($tries<3)) {
15437: $tries ++;
15438: sleep 1;
15439: $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15440: }
15441: if ($gotlock eq 'ok') {
15442: my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
15443: my $gotcode;
15444: my $attempts = 0;
15445: while ((!$gotcode) && ($attempts < 100)) {
15446: $code = &generate_code();
15447: if (!exists($currcodes{$code})) {
15448: $gotcode = 1;
15449: unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
15450: $error = 'nostore';
15451: }
15452: }
15453: $attempts ++;
15454: }
15455: my @del_lock = ($cnum."\0".'uniquecodes');
15456: my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
15457: } else {
15458: $error = 'nolock';
15459: }
15460: return ($code,$error);
15461: }
15462:
15463: sub generate_code {
15464: my $code;
15465: my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
15466: for (my $i=0; $i<6; $i++) {
15467: my $lettnum = int (rand 2);
15468: my $item = '';
15469: if ($lettnum) {
15470: $item = $letts[int( rand(18) )];
15471: } else {
15472: $item = 1+int( rand(8) );
15473: }
15474: $code .= $item;
15475: }
15476: return $code;
15477: }
15478:
15479: ############################################################
15480: ############################################################
15481:
15482: #SD
15483: # only Community and Course, or anything else?
15484: sub course_type {
15485: my ($cid) = @_;
15486: if (!defined($cid)) {
15487: $cid = $env{'request.course.id'};
15488: }
15489: if (defined($env{'course.'.$cid.'.type'})) {
15490: return $env{'course.'.$cid.'.type'};
15491: } else {
15492: return 'Course';
15493: }
15494: }
15495:
15496: sub group_term {
15497: my $crstype = &course_type();
15498: my %names = (
15499: 'Course' => 'group',
15500: 'Community' => 'group',
15501: );
15502: return $names{$crstype};
15503: }
15504:
15505: sub course_types {
15506: my @types = ('official','unofficial','community','textbook');
15507: my %typename = (
15508: official => 'Official course',
15509: unofficial => 'Unofficial course',
15510: community => 'Community',
15511: textbook => 'Textbook course',
15512: );
15513: return (\@types,\%typename);
15514: }
15515:
15516: sub icon {
15517: my ($file)=@_;
15518: my $curfext = lc((split(/\./,$file))[-1]);
15519: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
15520: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
15521: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
15522: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
15523: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15524: $curfext.".gif") {
15525: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15526: $curfext.".gif";
15527: }
15528: }
15529: return &lonhttpdurl($iconname);
15530: }
15531:
15532: sub lonhttpdurl {
15533: #
15534: # Had been used for "small fry" static images on separate port 8080.
15535: # Modify here if lightweight http functionality desired again.
15536: # Currently eliminated due to increasing firewall issues.
15537: #
15538: my ($url)=@_;
15539: return $url;
15540: }
15541:
15542: sub connection_aborted {
15543: my ($r)=@_;
15544: $r->print(" ");$r->rflush();
15545: my $c = $r->connection;
15546: return $c->aborted();
15547: }
15548:
15549: # Escapes strings that may have embedded 's that will be put into
15550: # strings as 'strings'.
15551: sub escape_single {
15552: my ($input) = @_;
15553: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
15554: $input =~ s/\'/\\\'/g; # Esacpe the 's....
15555: return $input;
15556: }
15557:
15558: # Same as escape_single, but escape's "'s This
15559: # can be used for "strings"
15560: sub escape_double {
15561: my ($input) = @_;
15562: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
15563: $input =~ s/\"/\\\"/g; # Esacpe the "s....
15564: return $input;
15565: }
15566:
15567: # Escapes the last element of a full URL.
15568: sub escape_url {
15569: my ($url) = @_;
15570: my @urlslices = split(/\//, $url,-1);
15571: my $lastitem = &escape(pop(@urlslices));
15572: return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
15573: }
15574:
15575: sub compare_arrays {
15576: my ($arrayref1,$arrayref2) = @_;
15577: my (@difference,%count);
15578: @difference = ();
15579: %count = ();
15580: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
15581: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
15582: foreach my $element (keys(%count)) {
15583: if ($count{$element} == 1) {
15584: push(@difference,$element);
15585: }
15586: }
15587: }
15588: return @difference;
15589: }
15590:
15591: # -------------------------------------------------------- Initialize user login
15592: sub init_user_environment {
15593: my ($r, $username, $domain, $authhost, $form, $args) = @_;
15594: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
15595:
15596: my $public=($username eq 'public' && $domain eq 'public');
15597:
15598: # See if old ID present, if so, remove
15599:
15600: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
15601: my $now=time;
15602:
15603: if ($public) {
15604: my $max_public=100;
15605: my $oldest;
15606: my $oldest_time=0;
15607: for(my $next=1;$next<=$max_public;$next++) {
15608: if (-e $lonids."/publicuser_$next.id") {
15609: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
15610: if ($mtime<$oldest_time || !$oldest_time) {
15611: $oldest_time=$mtime;
15612: $oldest=$next;
15613: }
15614: } else {
15615: $cookie="publicuser_$next";
15616: last;
15617: }
15618: }
15619: if (!$cookie) { $cookie="publicuser_$oldest"; }
15620: } else {
15621: # if this isn't a robot, kill any existing non-robot sessions
15622: if (!$args->{'robot'}) {
15623: opendir(DIR,$lonids);
15624: while ($filename=readdir(DIR)) {
15625: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
15626: unlink($lonids.'/'.$filename);
15627: }
15628: }
15629: closedir(DIR);
15630: # If there is a undeleted lockfile for the user's paste buffer remove it.
15631: my $namespace = 'nohist_courseeditor';
15632: my $lockingkey = 'paste'."\0".'locked_num';
15633: my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
15634: $domain,$username);
15635: if (exists($lockhash{$lockingkey})) {
15636: my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
15637: unless ($delresult eq 'ok') {
15638: &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
15639: }
15640: }
15641: }
15642: # Give them a new cookie
15643: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
15644: : $now.$$.int(rand(10000)));
15645: $cookie="$username\_$id\_$domain\_$authhost";
15646:
15647: # Initialize roles
15648:
15649: ($userroles,$firstaccenv,$timerintenv) =
15650: &Apache::lonnet::rolesinit($domain,$username,$authhost);
15651: }
15652: # ------------------------------------ Check browser type and MathML capability
15653:
15654: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
15655: $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
15656:
15657: # ------------------------------------------------------------- Get environment
15658:
15659: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
15660: my ($tmp) = keys(%userenv);
15661: if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
15662: undef(%userenv);
15663: }
15664: if (($userenv{'interface'}) && (!$form->{'interface'})) {
15665: $form->{'interface'}=$userenv{'interface'};
15666: }
15667: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
15668:
15669: # --------------- Do not trust query string to be put directly into environment
15670: foreach my $option ('interface','localpath','localres') {
15671: $form->{$option}=~s/[\n\r\=]//gs;
15672: }
15673: # --------------------------------------------------------- Write first profile
15674:
15675: {
15676: my %initial_env =
15677: ("user.name" => $username,
15678: "user.domain" => $domain,
15679: "user.home" => $authhost,
15680: "browser.type" => $clientbrowser,
15681: "browser.version" => $clientversion,
15682: "browser.mathml" => $clientmathml,
15683: "browser.unicode" => $clientunicode,
15684: "browser.os" => $clientos,
15685: "browser.mobile" => $clientmobile,
15686: "browser.info" => $clientinfo,
15687: "browser.osversion" => $clientosversion,
15688: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
15689: "request.course.fn" => '',
15690: "request.course.uri" => '',
15691: "request.course.sec" => '',
15692: "request.role" => 'cm',
15693: "request.role.adv" => $env{'user.adv'},
15694: "request.host" => $ENV{'REMOTE_ADDR'},);
15695:
15696: if ($form->{'localpath'}) {
15697: $initial_env{"browser.localpath"} = $form->{'localpath'};
15698: $initial_env{"browser.localres"} = $form->{'localres'};
15699: }
15700:
15701: if ($form->{'interface'}) {
15702: $form->{'interface'}=~s/\W//gs;
15703: $initial_env{"browser.interface"} = $form->{'interface'};
15704: $env{'browser.interface'}=$form->{'interface'};
15705: }
15706:
15707: if ($form->{'iptoken'}) {
15708: my $lonhost = $r->dir_config('lonHostID');
15709: $initial_env{"user.noloadbalance"} = $lonhost;
15710: $env{'user.noloadbalance'} = $lonhost;
15711: }
15712:
15713: if ($form->{'noloadbalance'}) {
15714: my @hosts = &Apache::lonnet::current_machine_ids();
15715: my $hosthere = $form->{'noloadbalance'};
15716: if (grep(/^\Q$hosthere\E$/,@hosts)) {
15717: $initial_env{"user.noloadbalance"} = $hosthere;
15718: $env{'user.noloadbalance'} = $hosthere;
15719: }
15720: }
15721:
15722: unless ($domain eq 'public') {
15723: my %is_adv = ( is_adv => $env{'user.adv'} );
15724: my %domdef = &Apache::lonnet::get_domain_defaults($domain);
15725:
15726: foreach my $tool ('aboutme','blog','webdav','portfolio') {
15727: $userenv{'availabletools.'.$tool} =
15728: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
15729: undef,\%userenv,\%domdef,\%is_adv);
15730: }
15731:
15732: foreach my $crstype ('official','unofficial','community','textbook') {
15733: $userenv{'canrequest.'.$crstype} =
15734: &Apache::lonnet::usertools_access($username,$domain,$crstype,
15735: 'reload','requestcourses',
15736: \%userenv,\%domdef,\%is_adv);
15737: }
15738:
15739: $userenv{'canrequest.author'} =
15740: &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
15741: 'reload','requestauthor',
15742: \%userenv,\%domdef,\%is_adv);
15743: my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
15744: $domain,$username);
15745: my $reqstatus = $reqauthor{'author_status'};
15746: if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
15747: if (ref($reqauthor{'author'}) eq 'HASH') {
15748: $userenv{'requestauthorqueued'} = $reqstatus.':'.
15749: $reqauthor{'author'}{'timestamp'};
15750: }
15751: }
15752: }
15753:
15754: $env{'user.environment'} = "$lonids/$cookie.id";
15755:
15756: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
15757: &GDBM_WRCREAT(),0640)) {
15758: &_add_to_env(\%disk_env,\%initial_env);
15759: &_add_to_env(\%disk_env,\%userenv,'environment.');
15760: &_add_to_env(\%disk_env,$userroles);
15761: if (ref($firstaccenv) eq 'HASH') {
15762: &_add_to_env(\%disk_env,$firstaccenv);
15763: }
15764: if (ref($timerintenv) eq 'HASH') {
15765: &_add_to_env(\%disk_env,$timerintenv);
15766: }
15767: if (ref($args->{'extra_env'})) {
15768: &_add_to_env(\%disk_env,$args->{'extra_env'});
15769: }
15770: untie(%disk_env);
15771: } else {
15772: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
15773: 'Could not create environment storage in lonauth: '.$!.'</span>');
15774: return 'error: '.$!;
15775: }
15776: }
15777: $env{'request.role'}='cm';
15778: $env{'request.role.adv'}=$env{'user.adv'};
15779: $env{'browser.type'}=$clientbrowser;
15780:
15781: return $cookie;
15782:
15783: }
15784:
15785: sub _add_to_env {
15786: my ($idf,$env_data,$prefix) = @_;
15787: if (ref($env_data) eq 'HASH') {
15788: while (my ($key,$value) = each(%$env_data)) {
15789: $idf->{$prefix.$key} = $value;
15790: $env{$prefix.$key} = $value;
15791: }
15792: }
15793: }
15794:
15795: # --- Get the symbolic name of a problem and the url
15796: sub get_symb {
15797: my ($request,$silent) = @_;
15798: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
15799: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
15800: if ($symb eq '') {
15801: if (!$silent) {
15802: if (ref($request)) {
15803: $request->print("Unable to handle ambiguous references:$url:.");
15804: }
15805: return ();
15806: }
15807: }
15808: &Apache::lonenc::check_decrypt(\$symb);
15809: return ($symb);
15810: }
15811:
15812: # --------------------------------------------------------------Get annotation
15813:
15814: sub get_annotation {
15815: my ($symb,$enc) = @_;
15816:
15817: my $key = $symb;
15818: if (!$enc) {
15819: $key =
15820: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
15821: }
15822: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
15823: return $annotation{$key};
15824: }
15825:
15826: sub clean_symb {
15827: my ($symb,$delete_enc) = @_;
15828:
15829: &Apache::lonenc::check_decrypt(\$symb);
15830: my $enc = $env{'request.enc'};
15831: if ($delete_enc) {
15832: delete($env{'request.enc'});
15833: }
15834:
15835: return ($symb,$enc);
15836: }
15837:
15838: ############################################################
15839: ############################################################
15840:
15841: =pod
15842:
15843: =head1 Routines for building display used to search for courses
15844:
15845:
15846: =over 4
15847:
15848: =item * &build_filters()
15849:
15850: Create markup for a table used to set filters to use when selecting
15851: courses in a domain. Used by lonpickcourse.pm, lonmodifycourse.pm
15852: and quotacheck.pl
15853:
15854:
15855: Inputs:
15856:
15857: filterlist - anonymous array of fields to include as potential filters
15858:
15859: crstype - course type
15860:
15861: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
15862: to pop-open a course selector (will contain "extra element").
15863:
15864: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
15865:
15866: filter - anonymous hash of criteria and their values
15867:
15868: action - form action
15869:
15870: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
15871:
15872: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
15873:
15874: cloneruname - username of owner of new course who wants to clone
15875:
15876: clonerudom - domain of owner of new course who wants to clone
15877:
15878: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
15879:
15880: codetitlesref - reference to array of titles of components in institutional codes (official courses)
15881:
15882: codedom - domain
15883:
15884: formname - value of form element named "form".
15885:
15886: fixeddom - domain, if fixed.
15887:
15888: prevphase - value to assign to form element named "phase" when going back to the previous screen
15889:
15890: cnameelement - name of form element in form on opener page which will receive title of selected course
15891:
15892: cnumelement - name of form element in form on opener page which will receive courseID of selected course
15893:
15894: cdomelement - name of form element in form on opener page which will receive domain of selected course
15895:
15896: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
15897:
15898: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
15899:
15900: clonewarning - warning message about missing information for intended course owner when DC creates a course
15901:
15902:
15903: Returns: $output - HTML for display of search criteria, and hidden form elements.
15904:
15905:
15906: Side Effects: None
15907:
15908: =cut
15909:
15910: # ---------------------------------------------- search for courses based on last activity etc.
15911:
15912: sub build_filters {
15913: my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
15914: $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
15915: $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
15916: $cnameelement,$cnumelement,$cdomelement,$setroles,
15917: $clonetext,$clonewarning) = @_;
15918: my ($list,$jscript);
15919: my $onchange = 'javascript:updateFilters(this)';
15920: my ($domainselectform,$sincefilterform,$createdfilterform,
15921: $ownerdomselectform,$persondomselectform,$instcodeform,
15922: $typeselectform,$instcodetitle);
15923: if ($formname eq '') {
15924: $formname = $caller;
15925: }
15926: foreach my $item (@{$filterlist}) {
15927: unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
15928: ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
15929: if ($item eq 'domainfilter') {
15930: $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
15931: } elsif ($item eq 'coursefilter') {
15932: $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
15933: } elsif ($item eq 'ownerfilter') {
15934: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15935: } elsif ($item eq 'ownerdomfilter') {
15936: $filter->{'ownerdomfilter'} =
15937: &LONCAPA::clean_domain($filter->{$item});
15938: $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
15939: 'ownerdomfilter',1);
15940: } elsif ($item eq 'personfilter') {
15941: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15942: } elsif ($item eq 'persondomfilter') {
15943: $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
15944: 'persondomfilter',1);
15945: } else {
15946: $filter->{$item} =~ s/\W//g;
15947: }
15948: if (!$filter->{$item}) {
15949: $filter->{$item} = '';
15950: }
15951: }
15952: if ($item eq 'domainfilter') {
15953: my $allow_blank = 1;
15954: if ($formname eq 'portform') {
15955: $allow_blank=0;
15956: } elsif ($formname eq 'studentform') {
15957: $allow_blank=0;
15958: }
15959: if ($fixeddom) {
15960: $domainselectform = '<input type="hidden" name="domainfilter"'.
15961: ' value="'.$codedom.'" />'.
15962: &Apache::lonnet::domain($codedom,'description');
15963: } else {
15964: $domainselectform = &select_dom_form($filter->{$item},
15965: 'domainfilter',
15966: $allow_blank,'',$onchange);
15967: }
15968: } else {
15969: $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
15970: }
15971: }
15972:
15973: # last course activity filter and selection
15974: $sincefilterform = &timebased_select_form('sincefilter',$filter);
15975:
15976: # course created filter and selection
15977: if (exists($filter->{'createdfilter'})) {
15978: $createdfilterform = &timebased_select_form('createdfilter',$filter);
15979: }
15980:
15981: my %lt = &Apache::lonlocal::texthash(
15982: 'cac' => "$crstype Activity",
15983: 'ccr' => "$crstype Created",
15984: 'cde' => "$crstype Title",
15985: 'cdo' => "$crstype Domain",
15986: 'ins' => 'Institutional Code',
15987: 'inc' => 'Institutional Categorization',
15988: 'cow' => "$crstype Owner/Co-owner",
15989: 'cop' => "$crstype Personnel Includes",
15990: 'cog' => 'Type',
15991: );
15992:
15993: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15994: my $typeval = 'Course';
15995: if ($crstype eq 'Community') {
15996: $typeval = 'Community';
15997: }
15998: $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
15999: } else {
16000: $typeselectform = '<select name="type" size="1"';
16001: if ($onchange) {
16002: $typeselectform .= ' onchange="'.$onchange.'"';
16003: }
16004: $typeselectform .= '>'."\n";
16005: foreach my $posstype ('Course','Community') {
16006: $typeselectform.='<option value="'.$posstype.'"'.
16007: ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
16008: }
16009: $typeselectform.="</select>";
16010: }
16011:
16012: my ($cloneableonlyform,$cloneabletitle);
16013: if (exists($filter->{'cloneableonly'})) {
16014: my $cloneableon = '';
16015: my $cloneableoff = ' checked="checked"';
16016: if ($filter->{'cloneableonly'}) {
16017: $cloneableon = $cloneableoff;
16018: $cloneableoff = '';
16019: }
16020: $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>';
16021: if ($formname eq 'ccrs') {
16022: $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
16023: } else {
16024: $cloneabletitle = &mt('Cloneable by you');
16025: }
16026: }
16027: my $officialjs;
16028: if ($crstype eq 'Course') {
16029: if (exists($filter->{'instcodefilter'})) {
16030: # if (($fixeddom) || ($formname eq 'requestcrs') ||
16031: # ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
16032: if ($codedom) {
16033: $officialjs = 1;
16034: ($instcodeform,$jscript,$$numtitlesref) =
16035: &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
16036: $officialjs,$codetitlesref);
16037: if ($jscript) {
16038: $jscript = '<script type="text/javascript">'."\n".
16039: '// <![CDATA['."\n".
16040: $jscript."\n".
16041: '// ]]>'."\n".
16042: '</script>'."\n";
16043: }
16044: }
16045: if ($instcodeform eq '') {
16046: $instcodeform =
16047: '<input type="text" name="instcodefilter" size="10" value="'.
16048: $list->{'instcodefilter'}.'" />';
16049: $instcodetitle = $lt{'ins'};
16050: } else {
16051: $instcodetitle = $lt{'inc'};
16052: }
16053: if ($fixeddom) {
16054: $instcodetitle .= '<br />('.$codedom.')';
16055: }
16056: }
16057: }
16058: my $output = qq|
16059: <form method="post" name="filterpicker" action="$action">
16060: <input type="hidden" name="form" value="$formname" />
16061: |;
16062: if ($formname eq 'modifycourse') {
16063: $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
16064: '<input type="hidden" name="prevphase" value="'.
16065: $prevphase.'" />'."\n";
16066: } elsif ($formname eq 'quotacheck') {
16067: $output .= qq|
16068: <input type="hidden" name="sortby" value="" />
16069: <input type="hidden" name="sortorder" value="" />
16070: |;
16071: } else {
16072: my $name_input;
16073: if ($cnameelement ne '') {
16074: $name_input = '<input type="hidden" name="cnameelement" value="'.
16075: $cnameelement.'" />';
16076: }
16077: $output .= qq|
16078: <input type="hidden" name="cnumelement" value="$cnumelement" />
16079: <input type="hidden" name="cdomelement" value="$cdomelement" />
16080: $name_input
16081: $roleelement
16082: $multelement
16083: $typeelement
16084: |;
16085: if ($formname eq 'portform') {
16086: $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
16087: }
16088: }
16089: if ($fixeddom) {
16090: $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
16091: }
16092: $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
16093: if ($sincefilterform) {
16094: $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
16095: .$sincefilterform
16096: .&Apache::lonhtmlcommon::row_closure();
16097: }
16098: if ($createdfilterform) {
16099: $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
16100: .$createdfilterform
16101: .&Apache::lonhtmlcommon::row_closure();
16102: }
16103: if ($domainselectform) {
16104: $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
16105: .$domainselectform
16106: .&Apache::lonhtmlcommon::row_closure();
16107: }
16108: if ($typeselectform) {
16109: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16110: $output .= $typeselectform;
16111: } else {
16112: $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
16113: .$typeselectform
16114: .&Apache::lonhtmlcommon::row_closure();
16115: }
16116: }
16117: if ($instcodeform) {
16118: $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
16119: .$instcodeform
16120: .&Apache::lonhtmlcommon::row_closure();
16121: }
16122: if (exists($filter->{'ownerfilter'})) {
16123: $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
16124: '<table><tr><td>'.&mt('Username').'<br />'.
16125: '<input type="text" name="ownerfilter" size="20" value="'.
16126: $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16127: $ownerdomselectform.'</td></tr></table>'.
16128: &Apache::lonhtmlcommon::row_closure();
16129: }
16130: if (exists($filter->{'personfilter'})) {
16131: $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
16132: '<table><tr><td>'.&mt('Username').'<br />'.
16133: '<input type="text" name="personfilter" size="20" value="'.
16134: $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16135: $persondomselectform.'</td></tr></table>'.
16136: &Apache::lonhtmlcommon::row_closure();
16137: }
16138: if (exists($filter->{'coursefilter'})) {
16139: $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
16140: .'<input type="text" name="coursefilter" size="25" value="'
16141: .$list->{'coursefilter'}.'" />'
16142: .&Apache::lonhtmlcommon::row_closure();
16143: }
16144: if ($cloneableonlyform) {
16145: $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
16146: $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
16147: }
16148: if (exists($filter->{'descriptfilter'})) {
16149: $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
16150: .'<input type="text" name="descriptfilter" size="40" value="'
16151: .$list->{'descriptfilter'}.'" />'
16152: .&Apache::lonhtmlcommon::row_closure(1);
16153: }
16154: $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
16155: '<input type="hidden" name="updater" value="" />'."\n".
16156: '<input type="submit" name="gosearch" value="'.
16157: &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
16158: return $jscript.$clonewarning.$output;
16159: }
16160:
16161: =pod
16162:
16163: =item * &timebased_select_form()
16164:
16165: Create markup for a dropdown list used to select a time-based
16166: filter e.g., Course Activity, Course Created, when searching for courses
16167: or communities
16168:
16169: Inputs:
16170:
16171: item - name of form element (sincefilter or createdfilter)
16172:
16173: filter - anonymous hash of criteria and their values
16174:
16175: Returns: HTML for a select box contained a blank, then six time selections,
16176: with value set in incoming form variables currently selected.
16177:
16178: Side Effects: None
16179:
16180: =cut
16181:
16182: sub timebased_select_form {
16183: my ($item,$filter) = @_;
16184: if (ref($filter) eq 'HASH') {
16185: $filter->{$item} =~ s/[^\d-]//g;
16186: if (!$filter->{$item}) { $filter->{$item}=-1; }
16187: return &select_form(
16188: $filter->{$item},
16189: $item,
16190: { '-1' => '',
16191: '86400' => &mt('today'),
16192: '604800' => &mt('last week'),
16193: '2592000' => &mt('last month'),
16194: '7776000' => &mt('last three months'),
16195: '15552000' => &mt('last six months'),
16196: '31104000' => &mt('last year'),
16197: 'select_form_order' =>
16198: ['-1','86400','604800','2592000','7776000',
16199: '15552000','31104000']});
16200: }
16201: }
16202:
16203: =pod
16204:
16205: =item * &js_changer()
16206:
16207: Create script tag containing Javascript used to submit course search form
16208: when course type or domain is changed, and also to hide 'Searching ...' on
16209: page load completion for page showing search result.
16210:
16211: Inputs: None
16212:
16213: Returns: markup containing updateFilters() and hideSearching() javascript functions.
16214:
16215: Side Effects: None
16216:
16217: =cut
16218:
16219: sub js_changer {
16220: return <<ENDJS;
16221: <script type="text/javascript">
16222: // <![CDATA[
16223: function updateFilters(caller) {
16224: if (typeof(caller) != "undefined") {
16225: document.filterpicker.updater.value = caller.name;
16226: }
16227: document.filterpicker.submit();
16228: }
16229:
16230: function hideSearching() {
16231: if (document.getElementById('searching')) {
16232: document.getElementById('searching').style.display = 'none';
16233: }
16234: return;
16235: }
16236:
16237: // ]]>
16238: </script>
16239:
16240: ENDJS
16241: }
16242:
16243: =pod
16244:
16245: =item * &search_courses()
16246:
16247: Process selected filters form course search form and pass to lonnet::courseiddump
16248: to retrieve a hash for which keys are courseIDs which match the selected filters.
16249:
16250: Inputs:
16251:
16252: dom - domain being searched
16253:
16254: type - course type ('Course' or 'Community' or '.' if any).
16255:
16256: filter - anonymous hash of criteria and their values
16257:
16258: numtitles - for institutional codes - number of categories
16259:
16260: cloneruname - optional username of new course owner
16261:
16262: clonerudom - optional domain of new course owner
16263:
16264: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
16265: (used when DC is using course creation form)
16266:
16267: codetitles - reference to array of titles of components in institutional codes (official courses).
16268:
16269: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16270: (and so can clone automatically)
16271:
16272: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16273:
16274: reqinstcode - institutional code of new course, where search_courses is used to identify potential
16275: courses to clone
16276:
16277: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
16278:
16279:
16280: Side Effects: None
16281:
16282: =cut
16283:
16284:
16285: sub search_courses {
16286: my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
16287: $cc_clone,$reqcrsdom,$reqinstcode) = @_;
16288: my (%courses,%showcourses,$cloner);
16289: if (($filter->{'ownerfilter'} ne '') ||
16290: ($filter->{'ownerdomfilter'} ne '')) {
16291: $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
16292: $filter->{'ownerdomfilter'};
16293: }
16294: foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
16295: if (!$filter->{$item}) {
16296: $filter->{$item}='.';
16297: }
16298: }
16299: my $now = time;
16300: my $timefilter =
16301: ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
16302: my ($createdbefore,$createdafter);
16303: if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
16304: $createdbefore = $now;
16305: $createdafter = $now-$filter->{'createdfilter'};
16306: }
16307: my ($instcodefilter,$regexpok);
16308: if ($numtitles) {
16309: if ($env{'form.official'} eq 'on') {
16310: $instcodefilter =
16311: &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16312: $regexpok = 1;
16313: } elsif ($env{'form.official'} eq 'off') {
16314: $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16315: unless ($instcodefilter eq '') {
16316: $regexpok = -1;
16317: }
16318: }
16319: } else {
16320: $instcodefilter = $filter->{'instcodefilter'};
16321: }
16322: if ($instcodefilter eq '') { $instcodefilter = '.'; }
16323: if ($type eq '') { $type = '.'; }
16324:
16325: if (($clonerudom ne '') && ($cloneruname ne '')) {
16326: $cloner = $cloneruname.':'.$clonerudom;
16327: }
16328: %courses = &Apache::lonnet::courseiddump($dom,
16329: $filter->{'descriptfilter'},
16330: $timefilter,
16331: $instcodefilter,
16332: $filter->{'combownerfilter'},
16333: $filter->{'coursefilter'},
16334: undef,undef,$type,$regexpok,undef,undef,
16335: undef,undef,$cloner,$cc_clone,
16336: $filter->{'cloneableonly'},
16337: $createdbefore,$createdafter,undef,
16338: $domcloner,undef,$reqcrsdom,$reqinstcode);
16339: if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
16340: my $ccrole;
16341: if ($type eq 'Community') {
16342: $ccrole = 'co';
16343: } else {
16344: $ccrole = 'cc';
16345: }
16346: my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
16347: $filter->{'persondomfilter'},
16348: 'userroles',undef,
16349: [$ccrole,'in','ad','ep','ta','cr'],
16350: $dom);
16351: foreach my $role (keys(%rolehash)) {
16352: my ($cnum,$cdom,$courserole) = split(':',$role);
16353: my $cid = $cdom.'_'.$cnum;
16354: if (exists($courses{$cid})) {
16355: if (ref($courses{$cid}) eq 'HASH') {
16356: if (ref($courses{$cid}{roles}) eq 'ARRAY') {
16357: if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
16358: push(@{$courses{$cid}{roles}},$courserole);
16359: }
16360: } else {
16361: $courses{$cid}{roles} = [$courserole];
16362: }
16363: $showcourses{$cid} = $courses{$cid};
16364: }
16365: }
16366: }
16367: %courses = %showcourses;
16368: }
16369: return %courses;
16370: }
16371:
16372: =pod
16373:
16374: =back
16375:
16376: =head1 Routines for version requirements for current course.
16377:
16378: =over 4
16379:
16380: =item * &check_release_required()
16381:
16382: Compares required LON-CAPA version with version on server, and
16383: if required version is newer looks for a server with the required version.
16384:
16385: Looks first at servers in user's owen domain; if none suitable, looks at
16386: servers in course's domain are permitted to host sessions for user's domain.
16387:
16388: Inputs:
16389:
16390: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16391:
16392: $courseid - Course ID of current course
16393:
16394: $rolecode - User's current role in course (for switchserver query string).
16395:
16396: $required - LON-CAPA version needed by course (format: Major.Minor).
16397:
16398:
16399: Returns:
16400:
16401: $switchserver - query string tp append to /adm/switchserver call (if
16402: current server's LON-CAPA version is too old.
16403:
16404: $warning - Message is displayed if no suitable server could be found.
16405:
16406: =cut
16407:
16408: sub check_release_required {
16409: my ($loncaparev,$courseid,$rolecode,$required) = @_;
16410: my ($switchserver,$warning);
16411: if ($required ne '') {
16412: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
16413: my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16414: if ($reqdmajor ne '' && $reqdminor ne '') {
16415: my $otherserver;
16416: if (($major eq '' && $minor eq '') ||
16417: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
16418: my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
16419: my $switchlcrev =
16420: &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
16421: $userdomserver);
16422: my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16423: if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
16424: (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
16425: my $cdom = $env{'course.'.$courseid.'.domain'};
16426: if ($cdom ne $env{'user.domain'}) {
16427: my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
16428: my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
16429: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16430: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
16431: my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
16432: my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
16433: my $canhost =
16434: &Apache::lonnet::can_host_session($env{'user.domain'},
16435: $coursedomserver,
16436: $remoterev,
16437: $udomdefaults{'remotesessions'},
16438: $defdomdefaults{'hostedsessions'});
16439:
16440: if ($canhost) {
16441: $otherserver = $coursedomserver;
16442: } else {
16443: $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.");
16444: }
16445: } else {
16446: $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).");
16447: }
16448: } else {
16449: $otherserver = $userdomserver;
16450: }
16451: }
16452: if ($otherserver ne '') {
16453: $switchserver = 'otherserver='.$otherserver.'&role='.$rolecode;
16454: }
16455: }
16456: }
16457: return ($switchserver,$warning);
16458: }
16459:
16460: =pod
16461:
16462: =item * &check_release_result()
16463:
16464: Inputs:
16465:
16466: $switchwarning - Warning message if no suitable server found to host session.
16467:
16468: $switchserver - query string to append to /adm/switchserver containing lonHostID
16469: and current role.
16470:
16471: Returns: HTML to display with information about requirement to switch server.
16472: Either displaying warning with link to Roles/Courses screen or
16473: display link to switchserver.
16474:
16475: =cut
16476:
16477: sub check_release_result {
16478: my ($switchwarning,$switchserver) = @_;
16479: my $output = &start_page('Selected course unavailable on this server').
16480: '<p class="LC_warning">';
16481: if ($switchwarning) {
16482: $output .= $switchwarning.'<br /><a href="/adm/roles">';
16483: if (&show_course()) {
16484: $output .= &mt('Display courses');
16485: } else {
16486: $output .= &mt('Display roles');
16487: }
16488: $output .= '</a>';
16489: } elsif ($switchserver) {
16490: $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
16491: '<br />'.
16492: '<a href="/adm/switchserver?'.$switchserver.'">'.
16493: &mt('Switch Server').
16494: '</a>';
16495: }
16496: $output .= '</p>'.&end_page();
16497: return $output;
16498: }
16499:
16500: =pod
16501:
16502: =item * &needs_coursereinit()
16503:
16504: Determine if course contents stored for user's session needs to be
16505: refreshed, because content has changed since "Big Hash" last tied.
16506:
16507: Check for change is made if time last checked is more than 10 minutes ago
16508: (by default).
16509:
16510: Inputs:
16511:
16512: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16513:
16514: $interval (optional) - Time which may elapse (in s) between last check for content
16515: change in current course. (default: 600 s).
16516:
16517: Returns: an array; first element is:
16518:
16519: =over 4
16520:
16521: 'switch' - if content updates mean user's session
16522: needs to be switched to a server running a newer LON-CAPA version
16523:
16524: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
16525: on current server hosting user's session
16526:
16527: '' - if no action required.
16528:
16529: =back
16530:
16531: If first item element is 'switch':
16532:
16533: second item is $switchwarning - Warning message if no suitable server found to host session.
16534:
16535: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
16536: and current role.
16537:
16538: otherwise: no other elements returned.
16539:
16540: =back
16541:
16542: =cut
16543:
16544: sub needs_coursereinit {
16545: my ($loncaparev,$interval) = @_;
16546: return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
16547: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
16548: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
16549: my $now = time;
16550: if ($interval eq '') {
16551: $interval = 600;
16552: }
16553: if (($now-$env{'request.course.timechecked'})>$interval) {
16554: my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
16555: &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
16556: if ($lastchange > $env{'request.course.tied'}) {
16557: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16558: if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
16559: my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
16560: if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
16561: &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
16562: $curr_reqd_hash{'internal.releaserequired'}});
16563: my ($switchserver,$switchwarning) =
16564: &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
16565: $curr_reqd_hash{'internal.releaserequired'});
16566: if ($switchwarning ne '' || $switchserver ne '') {
16567: return ('switch',$switchwarning,$switchserver);
16568: }
16569: }
16570: }
16571: return ('update');
16572: }
16573: }
16574: return ();
16575: }
16576:
16577: sub update_content_constraints {
16578: my ($cdom,$cnum,$chome,$cid) = @_;
16579: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16580: my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
16581: my %checkresponsetypes;
16582: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
16583: my ($item,$name,$value) = split(/:/,$key);
16584: if ($item eq 'resourcetag') {
16585: if ($name eq 'responsetype') {
16586: $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
16587: }
16588: }
16589: }
16590: my $navmap = Apache::lonnavmaps::navmap->new();
16591: if (defined($navmap)) {
16592: my %allresponses;
16593: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
16594: my %responses = $res->responseTypes();
16595: foreach my $key (keys(%responses)) {
16596: next unless(exists($checkresponsetypes{$key}));
16597: $allresponses{$key} += $responses{$key};
16598: }
16599: }
16600: foreach my $key (keys(%allresponses)) {
16601: my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
16602: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
16603: ($reqdmajor,$reqdminor) = ($major,$minor);
16604: }
16605: }
16606: undef($navmap);
16607: }
16608: unless (($reqdmajor eq '') && ($reqdminor eq '')) {
16609: &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
16610: }
16611: return;
16612: }
16613:
16614: sub allmaps_incourse {
16615: my ($cdom,$cnum,$chome,$cid) = @_;
16616: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
16617: $cid = $env{'request.course.id'};
16618: $cdom = $env{'course.'.$cid.'.domain'};
16619: $cnum = $env{'course.'.$cid.'.num'};
16620: $chome = $env{'course.'.$cid.'.home'};
16621: }
16622: my %allmaps = ();
16623: my $lastchange =
16624: &Apache::lonnet::get_coursechange($cdom,$cnum);
16625: if ($lastchange > $env{'request.course.tied'}) {
16626: my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
16627: unless ($ferr) {
16628: &update_content_constraints($cdom,$cnum,$chome,$cid);
16629: }
16630: }
16631: my $navmap = Apache::lonnavmaps::navmap->new();
16632: if (defined($navmap)) {
16633: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
16634: $allmaps{$res->src()} = 1;
16635: }
16636: }
16637: return \%allmaps;
16638: }
16639:
16640: sub parse_supplemental_title {
16641: my ($title) = @_;
16642:
16643: my ($foldertitle,$renametitle);
16644: if ($title =~ /&&&/) {
16645: $title = &HTML::Entites::decode($title);
16646: }
16647: if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
16648: $renametitle=$4;
16649: my ($time,$uname,$udom) = ($1,$2,$3);
16650: $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
16651: my $name = &plainname($uname,$udom);
16652: $name = &HTML::Entities::encode($name,'"<>&\'');
16653: $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
16654: $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
16655: $name.': <br />'.$foldertitle;
16656: }
16657: if (wantarray) {
16658: return ($title,$foldertitle,$renametitle);
16659: }
16660: return $title;
16661: }
16662:
16663: sub recurse_supplemental {
16664: my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
16665: if ($suppmap) {
16666: my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
16667: if ($fatal) {
16668: $errors ++;
16669: } else {
16670: if ($#LONCAPA::map::resources > 0) {
16671: foreach my $res (@LONCAPA::map::resources) {
16672: my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
16673: if (($src ne '') && ($status eq 'res')) {
16674: if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
16675: ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
16676: } else {
16677: $numfiles ++;
16678: }
16679: }
16680: }
16681: }
16682: }
16683: }
16684: return ($numfiles,$errors);
16685: }
16686:
16687: sub symb_to_docspath {
16688: my ($symb,$navmapref) = @_;
16689: return unless ($symb && ref($navmapref));
16690: my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
16691: if ($resurl=~/\.(sequence|page)$/) {
16692: $mapurl=$resurl;
16693: } elsif ($resurl eq 'adm/navmaps') {
16694: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
16695: }
16696: my $mapresobj;
16697: unless (ref($$navmapref)) {
16698: $$navmapref = Apache::lonnavmaps::navmap->new();
16699: }
16700: if (ref($$navmapref)) {
16701: $mapresobj = $$navmapref->getResourceByUrl($mapurl);
16702: }
16703: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
16704: my $type=$2;
16705: my $path;
16706: if (ref($mapresobj)) {
16707: my $pcslist = $mapresobj->map_hierarchy();
16708: if ($pcslist ne '') {
16709: foreach my $pc (split(/,/,$pcslist)) {
16710: next if ($pc <= 1);
16711: my $res = $$navmapref->getByMapPc($pc);
16712: if (ref($res)) {
16713: my $thisurl = $res->src();
16714: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
16715: my $thistitle = $res->title();
16716: $path .= '&'.
16717: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
16718: &escape($thistitle).
16719: ':'.$res->randompick().
16720: ':'.$res->randomout().
16721: ':'.$res->encrypted().
16722: ':'.$res->randomorder().
16723: ':'.$res->is_page();
16724: }
16725: }
16726: }
16727: $path =~ s/^\&//;
16728: my $maptitle = $mapresobj->title();
16729: if ($mapurl eq 'default') {
16730: $maptitle = 'Main Content';
16731: }
16732: $path .= (($path ne '')? '&' : '').
16733: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16734: &escape($maptitle).
16735: ':'.$mapresobj->randompick().
16736: ':'.$mapresobj->randomout().
16737: ':'.$mapresobj->encrypted().
16738: ':'.$mapresobj->randomorder().
16739: ':'.$mapresobj->is_page();
16740: } else {
16741: my $maptitle = &Apache::lonnet::gettitle($mapurl);
16742: my $ispage = (($type eq 'page')? 1 : '');
16743: if ($mapurl eq 'default') {
16744: $maptitle = 'Main Content';
16745: }
16746: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16747: &escape($maptitle).':::::'.$ispage;
16748: }
16749: unless ($mapurl eq 'default') {
16750: $path = 'default&'.
16751: &escape('Main Content').
16752: ':::::&'.$path;
16753: }
16754: return $path;
16755: }
16756:
16757: sub captcha_display {
16758: my ($context,$lonhost) = @_;
16759: my ($output,$error);
16760: my ($captcha,$pubkey,$privkey,$version) =
16761: &get_captcha_config($context,$lonhost);
16762: if ($captcha eq 'original') {
16763: $output = &create_captcha();
16764: unless ($output) {
16765: $error = 'captcha';
16766: }
16767: } elsif ($captcha eq 'recaptcha') {
16768: $output = &create_recaptcha($pubkey,$version);
16769: unless ($output) {
16770: $error = 'recaptcha';
16771: }
16772: }
16773: return ($output,$error,$captcha,$version);
16774: }
16775:
16776: sub captcha_response {
16777: my ($context,$lonhost) = @_;
16778: my ($captcha_chk,$captcha_error);
16779: my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
16780: if ($captcha eq 'original') {
16781: ($captcha_chk,$captcha_error) = &check_captcha();
16782: } elsif ($captcha eq 'recaptcha') {
16783: $captcha_chk = &check_recaptcha($privkey,$version);
16784: } else {
16785: $captcha_chk = 1;
16786: }
16787: return ($captcha_chk,$captcha_error);
16788: }
16789:
16790: sub get_captcha_config {
16791: my ($context,$lonhost) = @_;
16792: my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
16793: my $hostname = &Apache::lonnet::hostname($lonhost);
16794: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
16795: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16796: if ($context eq 'usercreation') {
16797: my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
16798: if (ref($domconfig{$context}) eq 'HASH') {
16799: $hashtocheck = $domconfig{$context}{'cancreate'};
16800: if (ref($hashtocheck) eq 'HASH') {
16801: if ($hashtocheck->{'captcha'} eq 'recaptcha') {
16802: if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
16803: $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
16804: $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
16805: }
16806: if ($privkey && $pubkey) {
16807: $captcha = 'recaptcha';
16808: $version = $hashtocheck->{'recaptchaversion'};
16809: if ($version ne '2') {
16810: $version = 1;
16811: }
16812: } else {
16813: $captcha = 'original';
16814: }
16815: } elsif ($hashtocheck->{'captcha'} ne 'notused') {
16816: $captcha = 'original';
16817: }
16818: }
16819: } else {
16820: $captcha = 'captcha';
16821: }
16822: } elsif ($context eq 'login') {
16823: my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
16824: if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
16825: $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
16826: $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
16827: if ($privkey && $pubkey) {
16828: $captcha = 'recaptcha';
16829: $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
16830: if ($version ne '2') {
16831: $version = 1;
16832: }
16833: } else {
16834: $captcha = 'original';
16835: }
16836: } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
16837: $captcha = 'original';
16838: }
16839: }
16840: return ($captcha,$pubkey,$privkey,$version);
16841: }
16842:
16843: sub create_captcha {
16844: my %captcha_params = &captcha_settings();
16845: my ($output,$maxtries,$tries) = ('',10,0);
16846: while ($tries < $maxtries) {
16847: $tries ++;
16848: my $captcha = Authen::Captcha->new (
16849: output_folder => $captcha_params{'output_dir'},
16850: data_folder => $captcha_params{'db_dir'},
16851: );
16852: my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
16853:
16854: if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
16855: $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
16856: &mt('Type in the letters/numbers shown below').' '.
16857: '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
16858: '<br />'.
16859: '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
16860: last;
16861: }
16862: }
16863: return $output;
16864: }
16865:
16866: sub captcha_settings {
16867: my %captcha_params = (
16868: output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'},
16869: www_output_dir => "/captchaspool",
16870: db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'},
16871: numchars => '5',
16872: );
16873: return %captcha_params;
16874: }
16875:
16876: sub check_captcha {
16877: my ($captcha_chk,$captcha_error);
16878: my $code = $env{'form.code'};
16879: my $md5sum = $env{'form.crypt'};
16880: my %captcha_params = &captcha_settings();
16881: my $captcha = Authen::Captcha->new(
16882: output_folder => $captcha_params{'output_dir'},
16883: data_folder => $captcha_params{'db_dir'},
16884: );
16885: $captcha_chk = $captcha->check_code($code,$md5sum);
16886: my %captcha_hash = (
16887: 0 => 'Code not checked (file error)',
16888: -1 => 'Failed: code expired',
16889: -2 => 'Failed: invalid code (not in database)',
16890: -3 => 'Failed: invalid code (code does not match crypt)',
16891: );
16892: if ($captcha_chk != 1) {
16893: $captcha_error = $captcha_hash{$captcha_chk}
16894: }
16895: return ($captcha_chk,$captcha_error);
16896: }
16897:
16898: sub create_recaptcha {
16899: my ($pubkey,$version) = @_;
16900: if ($version >= 2) {
16901: return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
16902: } else {
16903: my $use_ssl;
16904: if ($ENV{'SERVER_PORT'} == 443) {
16905: $use_ssl = 1;
16906: }
16907: my $captcha = Captcha::reCAPTCHA->new;
16908: return $captcha->get_options_setter({theme => 'white'})."\n".
16909: $captcha->get_html($pubkey,undef,$use_ssl).
16910: &mt('If the text is hard to read, [_1] will replace them.',
16911: '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
16912: '<br /><br />';
16913: }
16914: }
16915:
16916: sub check_recaptcha {
16917: my ($privkey,$version) = @_;
16918: my $captcha_chk;
16919: if ($version >= 2) {
16920: my $ua = LWP::UserAgent->new;
16921: $ua->timeout(10);
16922: my %info = (
16923: secret => $privkey,
16924: response => $env{'form.g-recaptcha-response'},
16925: remoteip => $ENV{'REMOTE_ADDR'},
16926: );
16927: my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
16928: if ($response->is_success) {
16929: my $data = JSON::DWIW->from_json($response->decoded_content);
16930: if (ref($data) eq 'HASH') {
16931: if ($data->{'success'}) {
16932: $captcha_chk = 1;
16933: }
16934: }
16935: }
16936: } else {
16937: my $captcha = Captcha::reCAPTCHA->new;
16938: my $captcha_result =
16939: $captcha->check_answer(
16940: $privkey,
16941: $ENV{'REMOTE_ADDR'},
16942: $env{'form.recaptcha_challenge_field'},
16943: $env{'form.recaptcha_response_field'},
16944: );
16945: if ($captcha_result->{is_valid}) {
16946: $captcha_chk = 1;
16947: }
16948: }
16949: return $captcha_chk;
16950: }
16951:
16952: sub emailusername_info {
16953: my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
16954: my %titles = &Apache::lonlocal::texthash (
16955: lastname => 'Last Name',
16956: firstname => 'First Name',
16957: institution => 'School/college/university',
16958: location => "School's city, state/province, country",
16959: web => "School's web address",
16960: officialemail => 'E-mail address at institution (if different)',
16961: id => 'Student/Employee ID',
16962: );
16963: return (\@fields,\%titles);
16964: }
16965:
16966: sub cleanup_html {
16967: my ($incoming) = @_;
16968: my $outgoing;
16969: if ($incoming ne '') {
16970: $outgoing = $incoming;
16971: $outgoing =~ s/;/;/g;
16972: $outgoing =~ s/\#/#/g;
16973: $outgoing =~ s/\&/&/g;
16974: $outgoing =~ s/</</g;
16975: $outgoing =~ s/>/>/g;
16976: $outgoing =~ s/\(/(/g;
16977: $outgoing =~ s/\)/)/g;
16978: $outgoing =~ s/"/"/g;
16979: $outgoing =~ s/'/'/g;
16980: $outgoing =~ s/\$/$/g;
16981: $outgoing =~ s{/}{/}g;
16982: $outgoing =~ s/=/=/g;
16983: $outgoing =~ s/\\/\/g
16984: }
16985: return $outgoing;
16986: }
16987:
16988: # Checks for critical messages and returns a redirect url if one exists.
16989: # $interval indicates how often to check for messages.
16990: sub critical_redirect {
16991: my ($interval) = @_;
16992: if ((time-$env{'user.criticalcheck.time'})>$interval) {
16993: my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
16994: $env{'user.name'});
16995: &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
16996: my $redirecturl;
16997: if ($what[0]) {
16998: if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
16999: $redirecturl='/adm/email?critical=display';
17000: my $url=&Apache::lonnet::absolute_url().$redirecturl;
17001: return (1, $url);
17002: }
17003: }
17004: }
17005: return ();
17006: }
17007:
17008: # Use:
17009: # my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
17010: #
17011: ##################################################
17012: # password associated functions #
17013: ##################################################
17014: sub des_keys {
17015: # Make a new key for DES encryption.
17016: # Each key has two parts which are returned separately.
17017: # Please note: Each key must be passed through the &hex function
17018: # before it is output to the web browser. The hex versions cannot
17019: # be used to decrypt.
17020: my @hexstr=('0','1','2','3','4','5','6','7',
17021: '8','9','a','b','c','d','e','f');
17022: my $lkey='';
17023: for (0..7) {
17024: $lkey.=$hexstr[rand(15)];
17025: }
17026: my $ukey='';
17027: for (0..7) {
17028: $ukey.=$hexstr[rand(15)];
17029: }
17030: return ($lkey,$ukey);
17031: }
17032:
17033: sub des_decrypt {
17034: my ($key,$cyphertext) = @_;
17035: my $keybin=pack("H16",$key);
17036: my $cypher;
17037: if ($Crypt::DES::VERSION>=2.03) {
17038: $cypher=new Crypt::DES $keybin;
17039: } else {
17040: $cypher=new DES $keybin;
17041: }
17042: my $plaintext='';
17043: my $cypherlength = length($cyphertext);
17044: my $numchunks = int($cypherlength/32);
17045: for (my $j=0; $j<$numchunks; $j++) {
17046: my $start = $j*32;
17047: my $cypherblock = substr($cyphertext,$start,32);
17048: my $chunk =
17049: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
17050: $chunk .=
17051: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
17052: $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
17053: $plaintext .= $chunk;
17054: }
17055: return $plaintext;
17056: }
17057:
17058: 1;
17059: __END__;
17060:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>