File:
[LON-CAPA] /
loncom /
interface /
loncommon.pm
Revision
1.1313:
download - view:
text,
annotated -
select for diffs
Sun Apr 15 00:28:07 2018 UTC (6 years, 5 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Bug 6754 LON-CAPA as LTI Provider
- If original LTI launch of LON-CAPA specified display in an iframe, display
Authoring Space directory in same iframe, when accessed via Edit in
Functions menu.
1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1313 2018/04/15 00:28:07 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: # Makes a table out of the previous attempts
30: # Inputs result_from_symbread, user, domain, course_id
31: # Reads in non-network-related .tab files
32:
33: # POD header:
34:
35: =pod
36:
37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
45:
46: =head1 OVERVIEW
47:
48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
55: package Apache::loncommon;
56:
57: use strict;
58: use Apache::lonnet;
59: use GDBM_File;
60: use POSIX qw(strftime mktime);
61: use Apache::lonmenu();
62: use Apache::lonenc();
63: use Apache::lonlocal;
64: use Apache::lonnet();
65: use HTML::Entities;
66: use Apache::lonhtmlcommon();
67: use Apache::loncoursedata();
68: use Apache::lontexconvert();
69: use Apache::lonclonecourse();
70: use Apache::lonuserutils();
71: use Apache::lonuserstate();
72: use Apache::courseclassifier();
73: use LONCAPA qw(:DEFAULT :match);
74: use LONCAPA::LWPReq;
75: use DateTime::TimeZone;
76: use DateTime::Locale;
77: use Encode();
78: use Text::Aspell;
79: use Authen::Captcha;
80: use Captcha::reCAPTCHA;
81: use JSON::DWIW;
82: use LWP::UserAgent;
83: use Crypt::DES;
84: use DynaLoader; # for Crypt::DES version
85: use MIME::Lite;
86: use MIME::Types;
87: use File::Copy();
88: use File::Path();
89: use String::CRC32();
90: use Short::URL();
91:
92: # ---------------------------------------------- Designs
93: use vars qw(%defaultdesign);
94:
95: my $readit;
96:
97:
98: ##
99: ## Global Variables
100: ##
101:
102:
103: # ----------------------------------------------- SSI with retries:
104: #
105:
106: =pod
107:
108: =head1 Server Side include with retries:
109:
110: =over 4
111:
112: =item * &ssi_with_retries(resource,retries form)
113:
114: Performs an ssi with some number of retries. Retries continue either
115: until the result is ok or until the retry count supplied by the
116: caller is exhausted.
117:
118: Inputs:
119:
120: =over 4
121:
122: resource - Identifies the resource to insert.
123:
124: retries - Count of the number of retries allowed.
125:
126: form - Hash that identifies the rendering options.
127:
128: =back
129:
130: Returns:
131:
132: =over 4
133:
134: content - The content of the response. If retries were exhausted this is empty.
135:
136: response - The response from the last attempt (which may or may not have been successful.
137:
138: =back
139:
140: =back
141:
142: =cut
143:
144: sub ssi_with_retries {
145: my ($resource, $retries, %form) = @_;
146:
147:
148: my $ok = 0; # True if we got a good response.
149: my $content;
150: my $response;
151:
152: # Try to get the ssi done. within the retries count:
153:
154: do {
155: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
156: $ok = $response->is_success;
157: if (!$ok) {
158: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
159: }
160: $retries--;
161: } while (!$ok && ($retries > 0));
162:
163: if (!$ok) {
164: $content = ''; # On error return an empty content.
165: }
166: return ($content, $response);
167:
168: }
169:
170:
171:
172: # ----------------------------------------------- Filetypes/Languages/Copyright
173: my %language;
174: my %supported_language;
175: my %supported_codes;
176: my %latex_language; # For choosing hyphenation in <transl..>
177: my %latex_language_bykey; # for choosing hyphenation from metadata
178: my %cprtag;
179: my %scprtag;
180: my %fe; my %fd; my %fm;
181: my %category_extensions;
182:
183: # ---------------------------------------------- Thesaurus variables
184: #
185: # %Keywords:
186: # A hash used by &keyword to determine if a word is considered a keyword.
187: # $thesaurus_db_file
188: # Scalar containing the full path to the thesaurus database.
189:
190: my %Keywords;
191: my $thesaurus_db_file;
192:
193: #
194: # Initialize values from language.tab, copyright.tab, filetypes.tab,
195: # thesaurus.tab, and filecategories.tab.
196: #
197: BEGIN {
198: # Variable initialization
199: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
200: #
201: unless ($readit) {
202: # ------------------------------------------------------------------- languages
203: {
204: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
205: '/language.tab';
206: if ( open(my $fh,"<$langtabfile") ) {
207: while (my $line = <$fh>) {
208: next if ($line=~/^\#/);
209: chomp($line);
210: my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
211: $language{$key}=$val.' - '.$enc;
212: if ($sup) {
213: $supported_language{$key}=$sup;
214: $supported_codes{$key} = $code;
215: }
216: if ($latex) {
217: $latex_language_bykey{$key} = $latex;
218: $latex_language{$code} = $latex;
219: }
220: }
221: close($fh);
222: }
223: }
224: # ------------------------------------------------------------------ copyrights
225: {
226: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
227: '/copyright.tab';
228: if ( open (my $fh,"<$copyrightfile") ) {
229: while (my $line = <$fh>) {
230: next if ($line=~/^\#/);
231: chomp($line);
232: my ($key,$val)=(split(/\s+/,$line,2));
233: $cprtag{$key}=$val;
234: }
235: close($fh);
236: }
237: }
238: # ----------------------------------------------------------- source copyrights
239: {
240: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
241: '/source_copyright.tab';
242: if ( open (my $fh,"<$sourcecopyrightfile") ) {
243: while (my $line = <$fh>) {
244: next if ($line =~ /^\#/);
245: chomp($line);
246: my ($key,$val)=(split(/\s+/,$line,2));
247: $scprtag{$key}=$val;
248: }
249: close($fh);
250: }
251: }
252:
253: # -------------------------------------------------------------- default domain designs
254: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
255: my $designfile = $designdir.'/default.tab';
256: if ( open (my $fh,"<$designfile") ) {
257: while (my $line = <$fh>) {
258: next if ($line =~ /^\#/);
259: chomp($line);
260: my ($key,$val)=(split(/\=/,$line));
261: if ($val) { $defaultdesign{$key}=$val; }
262: }
263: close($fh);
264: }
265:
266: # ------------------------------------------------------------- file categories
267: {
268: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
269: '/filecategories.tab';
270: if ( open (my $fh,"<$categoryfile") ) {
271: while (my $line = <$fh>) {
272: next if ($line =~ /^\#/);
273: chomp($line);
274: my ($extension,$category)=(split(/\s+/,$line,2));
275: push(@{$category_extensions{lc($category)}},$extension);
276: }
277: close($fh);
278: }
279:
280: }
281: # ------------------------------------------------------------------ file types
282: {
283: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
284: '/filetypes.tab';
285: if ( open (my $fh,"<$typesfile") ) {
286: while (my $line = <$fh>) {
287: next if ($line =~ /^\#/);
288: chomp($line);
289: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
290: if ($descr ne '') {
291: $fe{$ending}=lc($emb);
292: $fd{$ending}=$descr;
293: if ($mime ne 'unk') { $fm{$ending}=$mime; }
294: }
295: }
296: close($fh);
297: }
298: }
299: &Apache::lonnet::logthis(
300: "<span style='color:yellow;'>INFO: Read file types</span>");
301: $readit=1;
302: } # end of unless($readit)
303:
304: }
305:
306: ###############################################################
307: ## HTML and Javascript Helper Functions ##
308: ###############################################################
309:
310: =pod
311:
312: =head1 HTML and Javascript Functions
313:
314: =over 4
315:
316: =item * &browser_and_searcher_javascript()
317:
318: X<browsing, javascript>X<searching, javascript>Returns a string
319: containing javascript with two functions, C<openbrowser> and
320: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
321: tags.
322:
323: =item * &openbrowser(formname,elementname,only,omit) [javascript]
324:
325: inputs: formname, elementname, only, omit
326:
327: formname and elementname indicate the name of the html form and name of
328: the element that the results of the browsing selection are to be placed in.
329:
330: Specifying 'only' will restrict the browser to displaying only files
331: with the given extension. Can be a comma separated list.
332:
333: Specifying 'omit' will restrict the browser to NOT displaying files
334: with the given extension. Can be a comma separated list.
335:
336: =item * &opensearcher(formname,elementname) [javascript]
337:
338: Inputs: formname, elementname
339:
340: formname and elementname specify the name of the html form and the name
341: of the element the selection from the search results will be placed in.
342:
343: =cut
344:
345: sub browser_and_searcher_javascript {
346: my ($mode)=@_;
347: if (!defined($mode)) { $mode='edit'; }
348: my $resurl=&escape_single(&lastresurl());
349: return <<END;
350: // <!-- BEGIN LON-CAPA Internal
351: var editbrowser = null;
352: function openbrowser(formname,elementname,only,omit,titleelement) {
353: var url = '$resurl/?';
354: if (editbrowser == null) {
355: url += 'launch=1&';
356: }
357: url += 'catalogmode=interactive&';
358: url += 'mode=$mode&';
359: url += 'inhibitmenu=yes&';
360: url += 'form=' + formname + '&';
361: if (only != null) {
362: url += 'only=' + only + '&';
363: } else {
364: url += 'only=&';
365: }
366: if (omit != null) {
367: url += 'omit=' + omit + '&';
368: } else {
369: url += 'omit=&';
370: }
371: if (titleelement != null) {
372: url += 'titleelement=' + titleelement + '&';
373: } else {
374: url += 'titleelement=&';
375: }
376: url += 'element=' + elementname + '';
377: var title = 'Browser';
378: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
379: options += ',width=700,height=600';
380: editbrowser = open(url,title,options,'1');
381: editbrowser.focus();
382: }
383: var editsearcher;
384: function opensearcher(formname,elementname,titleelement) {
385: var url = '/adm/searchcat?';
386: if (editsearcher == null) {
387: url += 'launch=1&';
388: }
389: url += 'catalogmode=interactive&';
390: url += 'mode=$mode&';
391: url += 'form=' + formname + '&';
392: if (titleelement != null) {
393: url += 'titleelement=' + titleelement + '&';
394: } else {
395: url += 'titleelement=&';
396: }
397: url += 'element=' + elementname + '';
398: var title = 'Search';
399: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
400: options += ',width=700,height=600';
401: editsearcher = open(url,title,options,'1');
402: editsearcher.focus();
403: }
404: // END LON-CAPA Internal -->
405: END
406: }
407:
408: sub lastresurl {
409: if ($env{'environment.lastresurl'}) {
410: return $env{'environment.lastresurl'}
411: } else {
412: return '/res';
413: }
414: }
415:
416: sub storeresurl {
417: my $resurl=&Apache::lonnet::clutter(shift);
418: unless ($resurl=~/^\/res/) { return 0; }
419: $resurl=~s/\/$//;
420: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
421: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
422: return 1;
423: }
424:
425: sub studentbrowser_javascript {
426: unless (
427: (($env{'request.course.id'}) &&
428: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
429: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
430: '/'.$env{'request.course.sec'})
431: ))
432: || ($env{'request.role'}=~/^(au|dc|su)/)
433: ) { return ''; }
434: return (<<'ENDSTDBRW');
435: <script type="text/javascript" language="Javascript">
436: // <![CDATA[
437: var stdeditbrowser;
438: function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
439: var url = '/adm/pickstudent?';
440: var filter;
441: if (!ignorefilter) {
442: eval('filter=document.'+formname+'.'+uname+'.value;');
443: }
444: if (filter != null) {
445: if (filter != '') {
446: url += 'filter='+filter+'&';
447: }
448: }
449: url += 'form=' + formname + '&unameelement='+uname+
450: '&udomelement='+udom+
451: '&clicker='+clicker;
452: if (roleflag) { url+="&roles=1"; }
453: if (courseadvonly) { url+="&courseadvonly=1"; }
454: var title = 'Student_Browser';
455: var options = 'scrollbars=1,resizable=1,menubar=0';
456: options += ',width=700,height=600';
457: stdeditbrowser = open(url,title,options,'1');
458: stdeditbrowser.focus();
459: }
460: // ]]>
461: </script>
462: ENDSTDBRW
463: }
464:
465: sub resourcebrowser_javascript {
466: unless ($env{'request.course.id'}) { return ''; }
467: return (<<'ENDRESBRW');
468: <script type="text/javascript" language="Javascript">
469: // <![CDATA[
470: var reseditbrowser;
471: function openresbrowser(formname,reslink) {
472: var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
473: var title = 'Resource_Browser';
474: var options = 'scrollbars=1,resizable=1,menubar=0';
475: options += ',width=700,height=500';
476: reseditbrowser = open(url,title,options,'1');
477: reseditbrowser.focus();
478: }
479: // ]]>
480: </script>
481: ENDRESBRW
482: }
483:
484: sub selectstudent_link {
485: my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
486: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
487: &Apache::lonhtmlcommon::entity_encode($unameele)."','".
488: &Apache::lonhtmlcommon::entity_encode($udomele)."'";
489: if ($env{'request.course.id'}) {
490: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
491: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
492: '/'.$env{'request.course.sec'})) {
493: return '';
494: }
495: $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
496: if ($courseadvonly) {
497: $callargs .= ",'',1,1";
498: }
499: return '<span class="LC_nobreak">'.
500: '<a href="javascript:openstdbrowser('.$callargs.');">'.
501: &mt('Select User').'</a></span>';
502: }
503: if ($env{'request.role'}=~/^(au|dc|su)/) {
504: $callargs .= ",'',1";
505: return '<span class="LC_nobreak">'.
506: '<a href="javascript:openstdbrowser('.$callargs.');">'.
507: &mt('Select User').'</a></span>';
508: }
509: return '';
510: }
511:
512: sub selectresource_link {
513: my ($form,$reslink,$arg)=@_;
514:
515: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
516: &Apache::lonhtmlcommon::entity_encode($reslink)."'";
517: unless ($env{'request.course.id'}) { return $arg; }
518: return '<span class="LC_nobreak">'.
519: '<a href="javascript:openresbrowser('.$callargs.');">'.
520: $arg.'</a></span>';
521: }
522:
523:
524:
525: sub authorbrowser_javascript {
526: return <<"ENDAUTHORBRW";
527: <script type="text/javascript" language="JavaScript">
528: // <![CDATA[
529: var stdeditbrowser;
530:
531: function openauthorbrowser(formname,udom) {
532: var url = '/adm/pickauthor?';
533: url += 'form='+formname+'&roledom='+udom;
534: var title = 'Author_Browser';
535: var options = 'scrollbars=1,resizable=1,menubar=0';
536: options += ',width=700,height=600';
537: stdeditbrowser = open(url,title,options,'1');
538: stdeditbrowser.focus();
539: }
540:
541: // ]]>
542: </script>
543: ENDAUTHORBRW
544: }
545:
546: sub coursebrowser_javascript {
547: my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
548: $credits_element,$instcode) = @_;
549: my $wintitle = 'Course_Browser';
550: if ($crstype eq 'Community') {
551: $wintitle = 'Community_Browser';
552: }
553: my $id_functions = &javascript_index_functions();
554: my $output = '
555: <script type="text/javascript" language="JavaScript">
556: // <![CDATA[
557: var stdeditbrowser;'."\n";
558:
559: $output .= <<"ENDSTDBRW";
560: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
561: var url = '/adm/pickcourse?';
562: var formid = getFormIdByName(formname);
563: var domainfilter = getDomainFromSelectbox(formname,udom);
564: if (domainfilter != null) {
565: if (domainfilter != '') {
566: url += 'domainfilter='+domainfilter+'&';
567: }
568: }
569: url += 'form=' + formname + '&cnumelement='+uname+
570: '&cdomelement='+udom+
571: '&cnameelement='+desc;
572: if (extra_element !=null && extra_element != '') {
573: if (formname == 'rolechoice' || formname == 'studentform') {
574: url += '&roleelement='+extra_element;
575: if (domainfilter == null || domainfilter == '') {
576: url += '&domainfilter='+extra_element;
577: }
578: }
579: else {
580: if (formname == 'portform') {
581: url += '&setroles='+extra_element;
582: } else {
583: if (formname == 'rules') {
584: url += '&fixeddom='+extra_element;
585: }
586: }
587: }
588: }
589: if (type != null && type != '') {
590: url += '&type='+type;
591: }
592: if (type_elem != null && type_elem != '') {
593: url += '&typeelement='+type_elem;
594: }
595: if (formname == 'ccrs') {
596: var ownername = document.forms[formid].ccuname.value;
597: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
598: url += '&cloner='+ownername+':'+ownerdom;
599: if (type == 'Course') {
600: url += '&crscode='+document.forms[formid].crscode.value;
601: }
602: }
603: if (formname == 'requestcrs') {
604: url += '&crsdom=$domainfilter&crscode=$instcode';
605: }
606: if (multflag !=null && multflag != '') {
607: url += '&multiple='+multflag;
608: }
609: var title = '$wintitle';
610: var options = 'scrollbars=1,resizable=1,menubar=0';
611: options += ',width=700,height=600';
612: stdeditbrowser = open(url,title,options,'1');
613: stdeditbrowser.focus();
614: }
615: $id_functions
616: ENDSTDBRW
617: if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
618: $output .= &setsec_javascript($sec_element,$formname,$role_element,
619: $credits_element);
620: }
621: $output .= '
622: // ]]>
623: </script>';
624: return $output;
625: }
626:
627: sub javascript_index_functions {
628: return <<"ENDJS";
629:
630: function getFormIdByName(formname) {
631: for (var i=0;i<document.forms.length;i++) {
632: if (document.forms[i].name == formname) {
633: return i;
634: }
635: }
636: return -1;
637: }
638:
639: function getIndexByName(formid,item) {
640: for (var i=0;i<document.forms[formid].elements.length;i++) {
641: if (document.forms[formid].elements[i].name == item) {
642: return i;
643: }
644: }
645: return -1;
646: }
647:
648: function getDomainFromSelectbox(formname,udom) {
649: var userdom;
650: var formid = getFormIdByName(formname);
651: if (formid > -1) {
652: var domid = getIndexByName(formid,udom);
653: if (domid > -1) {
654: if (document.forms[formid].elements[domid].type == 'select-one') {
655: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
656: }
657: if (document.forms[formid].elements[domid].type == 'hidden') {
658: userdom=document.forms[formid].elements[domid].value;
659: }
660: }
661: }
662: return userdom;
663: }
664:
665: ENDJS
666:
667: }
668:
669: sub javascript_array_indexof {
670: return <<ENDJS;
671: <script type="text/javascript" language="JavaScript">
672: // <![CDATA[
673:
674: if (!Array.prototype.indexOf) {
675: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
676: "use strict";
677: if (this === void 0 || this === null) {
678: throw new TypeError();
679: }
680: var t = Object(this);
681: var len = t.length >>> 0;
682: if (len === 0) {
683: return -1;
684: }
685: var n = 0;
686: if (arguments.length > 0) {
687: n = Number(arguments[1]);
688: if (n !== n) { // shortcut for verifying if it is NaN
689: n = 0;
690: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
691: n = (n > 0 || -1) * Math.floor(Math.abs(n));
692: }
693: }
694: if (n >= len) {
695: return -1;
696: }
697: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
698: for (; k < len; k++) {
699: if (k in t && t[k] === searchElement) {
700: return k;
701: }
702: }
703: return -1;
704: }
705: }
706:
707: // ]]>
708: </script>
709:
710: ENDJS
711:
712: }
713:
714: sub userbrowser_javascript {
715: my $id_functions = &javascript_index_functions();
716: return <<"ENDUSERBRW";
717:
718: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
719: var url = '/adm/pickuser?';
720: var userdom = getDomainFromSelectbox(formname,udom);
721: if (userdom != null) {
722: if (userdom != '') {
723: url += 'srchdom='+userdom+'&';
724: }
725: }
726: url += 'form=' + formname + '&unameelement='+uname+
727: '&udomelement='+udom+
728: '&ulastelement='+ulast+
729: '&ufirstelement='+ufirst+
730: '&uemailelement='+uemail+
731: '&hideudomelement='+hideudom+
732: '&coursedom='+crsdom;
733: if ((caller != null) && (caller != undefined)) {
734: url += '&caller='+caller;
735: }
736: var title = 'User_Browser';
737: var options = 'scrollbars=1,resizable=1,menubar=0';
738: options += ',width=700,height=600';
739: var stdeditbrowser = open(url,title,options,'1');
740: stdeditbrowser.focus();
741: }
742:
743: function fix_domain (formname,udom,origdom,uname) {
744: var formid = getFormIdByName(formname);
745: if (formid > -1) {
746: var unameid = getIndexByName(formid,uname);
747: var domid = getIndexByName(formid,udom);
748: var hidedomid = getIndexByName(formid,origdom);
749: if (hidedomid > -1) {
750: var fixeddom = document.forms[formid].elements[hidedomid].value;
751: var unameval = document.forms[formid].elements[unameid].value;
752: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
753: if (domid > -1) {
754: var slct = document.forms[formid].elements[domid];
755: if (slct.type == 'select-one') {
756: var i;
757: for (i=0;i<slct.length;i++) {
758: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
759: }
760: }
761: if (slct.type == 'hidden') {
762: slct.value = fixeddom;
763: }
764: }
765: }
766: }
767: }
768: return;
769: }
770:
771: $id_functions
772: ENDUSERBRW
773: }
774:
775: sub setsec_javascript {
776: my ($sec_element,$formname,$role_element,$credits_element) = @_;
777: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
778: $communityrolestr);
779: if ($role_element ne '') {
780: my @allroles = ('st','ta','ep','in','ad');
781: foreach my $crstype ('Course','Community') {
782: if ($crstype eq 'Community') {
783: foreach my $role (@allroles) {
784: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
785: }
786: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
787: } else {
788: foreach my $role (@allroles) {
789: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
790: }
791: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
792: }
793: }
794: $rolestr = '"'.join('","',@allroles).'"';
795: $courserolestr = '"'.join('","',@courserolenames).'"';
796: $communityrolestr = '"'.join('","',@communityrolenames).'"';
797: }
798: my $setsections = qq|
799: function setSect(sectionlist) {
800: var sectionsArray = new Array();
801: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
802: sectionsArray = sectionlist.split(",");
803: }
804: var numSections = sectionsArray.length;
805: document.$formname.$sec_element.length = 0;
806: if (numSections == 0) {
807: document.$formname.$sec_element.multiple=false;
808: document.$formname.$sec_element.size=1;
809: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
810: } else {
811: if (numSections == 1) {
812: document.$formname.$sec_element.multiple=false;
813: document.$formname.$sec_element.size=1;
814: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
815: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
816: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
817: } else {
818: for (var i=0; i<numSections; i++) {
819: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
820: }
821: document.$formname.$sec_element.multiple=true
822: if (numSections < 3) {
823: document.$formname.$sec_element.size=numSections;
824: } else {
825: document.$formname.$sec_element.size=3;
826: }
827: document.$formname.$sec_element.options[0].selected = false
828: }
829: }
830: }
831:
832: function setRole(crstype) {
833: |;
834: if ($role_element eq '') {
835: $setsections .= ' return;
836: }
837: ';
838: } else {
839: $setsections .= qq|
840: var elementLength = document.$formname.$role_element.length;
841: var allroles = Array($rolestr);
842: var courserolenames = Array($courserolestr);
843: var communityrolenames = Array($communityrolestr);
844: if (elementLength != undefined) {
845: if (document.$formname.$role_element.options[5].value == 'cc') {
846: if (crstype == 'Course') {
847: return;
848: } else {
849: allroles[5] = 'co';
850: for (var i=0; i<6; i++) {
851: document.$formname.$role_element.options[i].value = allroles[i];
852: document.$formname.$role_element.options[i].text = communityrolenames[i];
853: }
854: }
855: } else {
856: if (crstype == 'Community') {
857: return;
858: } else {
859: allroles[5] = 'cc';
860: for (var i=0; i<6; i++) {
861: document.$formname.$role_element.options[i].value = allroles[i];
862: document.$formname.$role_element.options[i].text = courserolenames[i];
863: }
864: }
865: }
866: }
867: return;
868: }
869: |;
870: }
871: if ($credits_element) {
872: $setsections .= qq|
873: function setCredits(defaultcredits) {
874: document.$formname.$credits_element.value = defaultcredits;
875: return;
876: }
877: |;
878: }
879: return $setsections;
880: }
881:
882: sub selectcourse_link {
883: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
884: $typeelement) = @_;
885: my $type = $selecttype;
886: my $linktext = &mt('Select Course');
887: if ($selecttype eq 'Community') {
888: $linktext = &mt('Select Community');
889: } elsif ($selecttype eq 'Placement') {
890: $linktext = &mt('Select Placement Test');
891: } elsif ($selecttype eq 'Course/Community') {
892: $linktext = &mt('Select Course/Community');
893: $type = '';
894: } elsif ($selecttype eq 'Select') {
895: $linktext = &mt('Select');
896: $type = '';
897: }
898: return '<span class="LC_nobreak">'
899: ."<a href='"
900: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
901: .'","'.$udomele.'","'.$desc.'","'.$extra_element
902: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
903: ."'>".$linktext.'</a>'
904: .'</span>';
905: }
906:
907: sub selectauthor_link {
908: my ($form,$udom)=@_;
909: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
910: &mt('Select Author').'</a>';
911: }
912:
913: sub selectuser_link {
914: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
915: $coursedom,$linktext,$caller) = @_;
916: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
917: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
918: ');">'.$linktext.'</a>';
919: }
920:
921: sub check_uncheck_jscript {
922: my $jscript = <<"ENDSCRT";
923: function checkAll(field) {
924: if (field.length > 0) {
925: for (i = 0; i < field.length; i++) {
926: if (!field[i].disabled) {
927: field[i].checked = true;
928: }
929: }
930: } else {
931: if (!field.disabled) {
932: field.checked = true;
933: }
934: }
935: }
936:
937: function uncheckAll(field) {
938: if (field.length > 0) {
939: for (i = 0; i < field.length; i++) {
940: field[i].checked = false ;
941: }
942: } else {
943: field.checked = false ;
944: }
945: }
946: ENDSCRT
947: return $jscript;
948: }
949:
950: sub select_timezone {
951: my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
952: my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
953: if ($includeempty) {
954: $output .= '<option value=""';
955: if (($selected eq '') || ($selected eq 'local')) {
956: $output .= ' selected="selected" ';
957: }
958: $output .= '> </option>';
959: }
960: my @timezones = DateTime::TimeZone->all_names;
961: foreach my $tzone (@timezones) {
962: $output.= '<option value="'.$tzone.'"';
963: if ($tzone eq $selected) {
964: $output.=' selected="selected"';
965: }
966: $output.=">$tzone</option>\n";
967: }
968: $output.="</select>";
969: return $output;
970: }
971:
972: sub select_datelocale {
973: my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
974: my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
975: if ($includeempty) {
976: $output .= '<option value=""';
977: if ($selected eq '') {
978: $output .= ' selected="selected" ';
979: }
980: $output .= '> </option>';
981: }
982: my @languages = &Apache::lonlocal::preferred_languages();
983: my (@possibles,%locale_names);
984: my @locales = DateTime::Locale->ids();
985: foreach my $id (@locales) {
986: if ($id ne '') {
987: my ($en_terr,$native_terr);
988: my $loc = DateTime::Locale->load($id);
989: if (ref($loc)) {
990: $en_terr = $loc->name();
991: $native_terr = $loc->native_name();
992: if (grep(/^en$/,@languages) || !@languages) {
993: if ($en_terr ne '') {
994: $locale_names{$id} = '('.$en_terr.')';
995: } elsif ($native_terr ne '') {
996: $locale_names{$id} = $native_terr;
997: }
998: } else {
999: if ($native_terr ne '') {
1000: $locale_names{$id} = $native_terr.' ';
1001: } elsif ($en_terr ne '') {
1002: $locale_names{$id} = '('.$en_terr.')';
1003: }
1004: }
1005: $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1006: push(@possibles,$id);
1007: }
1008: }
1009: }
1010: foreach my $item (sort(@possibles)) {
1011: $output.= '<option value="'.$item.'"';
1012: if ($item eq $selected) {
1013: $output.=' selected="selected"';
1014: }
1015: $output.=">$item";
1016: if ($locale_names{$item} ne '') {
1017: $output.=' '.$locale_names{$item};
1018: }
1019: $output.="</option>\n";
1020: }
1021: $output.="</select>";
1022: return $output;
1023: }
1024:
1025: sub select_language {
1026: my ($name,$selected,$includeempty,$noedit) = @_;
1027: my %langchoices;
1028: if ($includeempty) {
1029: %langchoices = ('' => 'No language preference');
1030: }
1031: foreach my $id (&languageids()) {
1032: my $code = &supportedlanguagecode($id);
1033: if ($code) {
1034: $langchoices{$code} = &plainlanguagedescription($id);
1035: }
1036: }
1037: %langchoices = &Apache::lonlocal::texthash(%langchoices);
1038: return &select_form($selected,$name,\%langchoices,undef,$noedit);
1039: }
1040:
1041: =pod
1042:
1043:
1044: =item * &list_languages()
1045:
1046: Returns an array reference that is suitable for use in language prompters.
1047: Each array element is itself a two element array. The first element
1048: is the language code. The second element a descsriptiuon of the
1049: language itself. This is suitable for use in e.g.
1050: &Apache::edit::select_arg (once dereferenced that is).
1051:
1052: =cut
1053:
1054: sub list_languages {
1055: my @lang_choices;
1056:
1057: foreach my $id (&languageids()) {
1058: my $code = &supportedlanguagecode($id);
1059: if ($code) {
1060: my $selector = $supported_codes{$id};
1061: my $description = &plainlanguagedescription($id);
1062: push(@lang_choices, [$selector, $description]);
1063: }
1064: }
1065: return \@lang_choices;
1066: }
1067:
1068: =pod
1069:
1070: =item * &linked_select_forms(...)
1071:
1072: linked_select_forms returns a string containing a <script></script> block
1073: and html for two <select> menus. The select menus will be linked in that
1074: changing the value of the first menu will result in new values being placed
1075: in the second menu. The values in the select menu will appear in alphabetical
1076: order unless a defined order is provided.
1077:
1078: linked_select_forms takes the following ordered inputs:
1079:
1080: =over 4
1081:
1082: =item * $formname, the name of the <form> tag
1083:
1084: =item * $middletext, the text which appears between the <select> tags
1085:
1086: =item * $firstdefault, the default value for the first menu
1087:
1088: =item * $firstselectname, the name of the first <select> tag
1089:
1090: =item * $secondselectname, the name of the second <select> tag
1091:
1092: =item * $hashref, a reference to a hash containing the data for the menus.
1093:
1094: =item * $menuorder, the order of values in the first menu
1095:
1096: =item * $onchangefirst, additional javascript call to execute for an onchange
1097: event for the first <select> tag
1098:
1099: =item * $onchangesecond, additional javascript call to execute for an onchange
1100: event for the second <select> tag
1101:
1102: =item * $suffix, to differentiate separate uses of select2data javascript
1103: objects in a page.
1104:
1105: =back
1106:
1107: Below is an example of such a hash. Only the 'text', 'default', and
1108: 'select2' keys must appear as stated. keys(%menu) are the possible
1109: values for the first select menu. The text that coincides with the
1110: first menu value is given in $menu{$choice1}->{'text'}. The values
1111: and text for the second menu are given in the hash pointed to by
1112: $menu{$choice1}->{'select2'}.
1113:
1114: my %menu = ( A1 => { text =>"Choice A1" ,
1115: default => "B3",
1116: select2 => {
1117: B1 => "Choice B1",
1118: B2 => "Choice B2",
1119: B3 => "Choice B3",
1120: B4 => "Choice B4"
1121: },
1122: order => ['B4','B3','B1','B2'],
1123: },
1124: A2 => { text =>"Choice A2" ,
1125: default => "C2",
1126: select2 => {
1127: C1 => "Choice C1",
1128: C2 => "Choice C2",
1129: C3 => "Choice C3"
1130: },
1131: order => ['C2','C1','C3'],
1132: },
1133: A3 => { text =>"Choice A3" ,
1134: default => "D6",
1135: select2 => {
1136: D1 => "Choice D1",
1137: D2 => "Choice D2",
1138: D3 => "Choice D3",
1139: D4 => "Choice D4",
1140: D5 => "Choice D5",
1141: D6 => "Choice D6",
1142: D7 => "Choice D7"
1143: },
1144: order => ['D4','D3','D2','D1','D7','D6','D5'],
1145: }
1146: );
1147:
1148: =cut
1149:
1150: sub linked_select_forms {
1151: my ($formname,
1152: $middletext,
1153: $firstdefault,
1154: $firstselectname,
1155: $secondselectname,
1156: $hashref,
1157: $menuorder,
1158: $onchangefirst,
1159: $onchangesecond,
1160: $suffix
1161: ) = @_;
1162: my $second = "document.$formname.$secondselectname";
1163: my $first = "document.$formname.$firstselectname";
1164: # output the javascript to do the changing
1165: my $result = '';
1166: $result.='<script type="text/javascript" language="JavaScript">'."\n";
1167: $result.="// <![CDATA[\n";
1168: $result.="var select2data${suffix} = new Object();\n";
1169: $" = '","';
1170: my $debug = '';
1171: foreach my $s1 (sort(keys(%$hashref))) {
1172: $result.="select2data${suffix}['d_$s1'] = new Object();\n";
1173: $result.="select2data${suffix}['d_$s1'].def = new String('".
1174: $hashref->{$s1}->{'default'}."');\n";
1175: $result.="select2data${suffix}['d_$s1'].values = new Array(";
1176: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1177: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1178: @s2values = @{$hashref->{$s1}->{'order'}};
1179: }
1180: $result.="\"@s2values\");\n";
1181: $result.="select2data${suffix}['d_$s1'].texts = new Array(";
1182: my @s2texts;
1183: foreach my $value (@s2values) {
1184: push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1185: }
1186: $result.="\"@s2texts\");\n";
1187: }
1188: $"=' ';
1189: $result.= <<"END";
1190:
1191: function select1${suffix}_changed() {
1192: // Determine new choice
1193: var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1194: // update select2
1195: var values = select2data${suffix}[newvalue].values;
1196: var texts = select2data${suffix}[newvalue].texts;
1197: var select2def = select2data${suffix}[newvalue].def;
1198: var i;
1199: // out with the old
1200: $second.options.length = 0;
1201: // in with the new
1202: for (i=0;i<values.length; i++) {
1203: $second.options[i] = new Option(values[i]);
1204: $second.options[i].value = values[i];
1205: $second.options[i].text = texts[i];
1206: if (values[i] == select2def) {
1207: $second.options[i].selected = true;
1208: }
1209: }
1210: }
1211: // ]]>
1212: </script>
1213: END
1214: # output the initial values for the selection lists
1215: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1216: my @order = sort(keys(%{$hashref}));
1217: if (ref($menuorder) eq 'ARRAY') {
1218: @order = @{$menuorder};
1219: }
1220: foreach my $value (@order) {
1221: $result.=" <option value=\"$value\" ";
1222: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1223: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1224: }
1225: $result .= "</select>\n";
1226: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1227: $result .= $middletext;
1228: $result .= "<select size=\"1\" name=\"$secondselectname\"";
1229: if ($onchangesecond) {
1230: $result .= ' onchange="'.$onchangesecond.'"';
1231: }
1232: $result .= ">\n";
1233: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1234:
1235: my @secondorder = sort(keys(%select2));
1236: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1237: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1238: }
1239: foreach my $value (@secondorder) {
1240: $result.=" <option value=\"$value\" ";
1241: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1242: $result.=">".&mt($select2{$value})."</option>\n";
1243: }
1244: $result .= "</select>\n";
1245: # return $debug;
1246: return $result;
1247: } # end of sub linked_select_forms {
1248:
1249: =pod
1250:
1251: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1252:
1253: Returns a string corresponding to an HTML link to the given help
1254: $topic, where $topic corresponds to the name of a .tex file in
1255: /home/httpd/html/adm/help/tex, with underscores replaced by
1256: spaces.
1257:
1258: $text will optionally be linked to the same topic, allowing you to
1259: link text in addition to the graphic. If you do not want to link
1260: text, but wish to specify one of the later parameters, pass an
1261: empty string.
1262:
1263: $stayOnPage is a value that will be interpreted as a boolean. If true,
1264: the link will not open a new window. If false, the link will open
1265: a new window using Javascript. (Default is false.)
1266:
1267: $width and $height are optional numerical parameters that will
1268: override the width and height of the popped up window, which may
1269: be useful for certain help topics with big pictures included.
1270:
1271: $imgid is the id of the img tag used for the help icon. This may be
1272: used in a javascript call to switch the image src. See
1273: lonhtmlcommon::htmlareaselectactive() for an example.
1274:
1275: =cut
1276:
1277: sub help_open_topic {
1278: my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1279: $text = "" if (not defined $text);
1280: $stayOnPage = 0 if (not defined $stayOnPage);
1281: $width = 500 if (not defined $width);
1282: $height = 400 if (not defined $height);
1283: my $filename = $topic;
1284: $filename =~ s/ /_/g;
1285:
1286: my $template = "";
1287: my $link;
1288:
1289: $topic=~s/\W/\_/g;
1290:
1291: if (!$stayOnPage) {
1292: $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1293: } elsif ($stayOnPage eq 'popup') {
1294: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1295: } else {
1296: $link = "/adm/help/${filename}.hlp";
1297: }
1298:
1299: # Add the text
1300: if ($text ne "") {
1301: $template.='<span class="LC_help_open_topic">'
1302: .'<a target="_top" href="'.$link.'">'
1303: .$text.'</a>';
1304: }
1305:
1306: # (Always) Add the graphic
1307: my $title = &mt('Online Help');
1308: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1309: if ($imgid ne '') {
1310: $imgid = ' id="'.$imgid.'"';
1311: }
1312: $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
1313: .'<img src="'.$helpicon.'" border="0"'
1314: .' alt="'.&mt('Help: [_1]',$topic).'"'
1315: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
1316: .' /></a>';
1317: if ($text ne "") {
1318: $template.='</span>';
1319: }
1320: return $template;
1321:
1322: }
1323:
1324: # This is a quicky function for Latex cheatsheet editing, since it
1325: # appears in at least four places
1326: sub helpLatexCheatsheet {
1327: my ($topic,$text,$not_author,$stayOnPage) = @_;
1328: my $out;
1329: my $addOther = '';
1330: if ($topic) {
1331: $addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1332: }
1333: $out = '<span>' # Start cheatsheet
1334: .$addOther
1335: .'<span>'
1336: .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1337: .'</span> <span>'
1338: .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1339: .'</span>';
1340: unless ($not_author) {
1341: $out .= '<span>'
1342: .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1343: .'</span> <span>'
1344: .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1345: .'</span>';
1346: }
1347: $out .= '</span>'; # End cheatsheet
1348: return $out;
1349: }
1350:
1351: sub general_help {
1352: my $helptopic='Student_Intro';
1353: if ($env{'request.role'}=~/^(ca|au)/) {
1354: $helptopic='Authoring_Intro';
1355: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1356: $helptopic='Course_Coordination_Intro';
1357: } elsif ($env{'request.role'}=~/^dc/) {
1358: $helptopic='Domain_Coordination_Intro';
1359: }
1360: return $helptopic;
1361: }
1362:
1363: sub update_help_link {
1364: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1365: my $origurl = $ENV{'REQUEST_URI'};
1366: $origurl=~s|^/~|/priv/|;
1367: my $timestamp = time;
1368: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1369: $$datum = &escape($$datum);
1370: }
1371:
1372: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1373: my $output .= <<"ENDOUTPUT";
1374: <script type="text/javascript">
1375: // <![CDATA[
1376: banner_link = '$banner_link';
1377: // ]]>
1378: </script>
1379: ENDOUTPUT
1380: return $output;
1381: }
1382:
1383: # now just updates the help link and generates a blue icon
1384: sub help_open_menu {
1385: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
1386: = @_;
1387: $stayOnPage = 1;
1388: my $output;
1389: if ($component_help) {
1390: if (!$text) {
1391: $output=&help_open_topic($component_help,undef,$stayOnPage,
1392: $width,$height);
1393: } else {
1394: my $help_text;
1395: $help_text=&unescape($topic);
1396: $output='<table><tr><td>'.
1397: &help_open_topic($component_help,$help_text,$stayOnPage,
1398: $width,$height).'</td></tr></table>';
1399: }
1400: }
1401: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1402: return $output.$banner_link;
1403: }
1404:
1405: sub top_nav_help {
1406: my ($text) = @_;
1407: $text = &mt($text);
1408: my $stay_on_page = 1;
1409:
1410: my ($link,$banner_link);
1411: unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
1412: $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1413: : "javascript:helpMenu('open')";
1414: $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1415: }
1416: my $title = &mt('Get help');
1417: if ($link) {
1418: return <<"END";
1419: $banner_link
1420: <a href="$link" title="$title">$text</a>
1421: END
1422: } else {
1423: return ' '.$text.' ';
1424: }
1425: }
1426:
1427: sub help_menu_js {
1428: my ($httphost) = @_;
1429: my $stayOnPage = 1;
1430: my $width = 620;
1431: my $height = 600;
1432: my $helptopic=&general_help();
1433: my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1434: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1435: my $start_page =
1436: &Apache::loncommon::start_page('Help Menu', undef,
1437: {'frameset' => 1,
1438: 'js_ready' => 1,
1439: 'use_absolute' => $httphost,
1440: 'add_entries' => {
1441: 'border' => '0',
1442: 'rows' => "110,*",},});
1443: my $end_page =
1444: &Apache::loncommon::end_page({'frameset' => 1,
1445: 'js_ready' => 1,});
1446:
1447: my $template .= <<"ENDTEMPLATE";
1448: <script type="text/javascript">
1449: // <![CDATA[
1450: // <!-- BEGIN LON-CAPA Internal
1451: var banner_link = '';
1452: function helpMenu(target) {
1453: var caller = this;
1454: if (target == 'open') {
1455: var newWindow = null;
1456: try {
1457: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1458: }
1459: catch(error) {
1460: writeHelp(caller);
1461: return;
1462: }
1463: if (newWindow) {
1464: caller = newWindow;
1465: }
1466: }
1467: writeHelp(caller);
1468: return;
1469: }
1470: function writeHelp(caller) {
1471: caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
1472: caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
1473: caller.document.close();
1474: caller.focus();
1475: }
1476: // END LON-CAPA Internal -->
1477: // ]]>
1478: </script>
1479: ENDTEMPLATE
1480: return $template;
1481: }
1482:
1483: sub help_open_bug {
1484: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1485: unless ($env{'user.adv'}) { return ''; }
1486: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1487: $text = "" if (not defined $text);
1488: $stayOnPage=1;
1489: $width = 600 if (not defined $width);
1490: $height = 600 if (not defined $height);
1491:
1492: $topic=~s/\W+/\+/g;
1493: my $link='';
1494: my $template='';
1495: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1496: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1497: if (!$stayOnPage)
1498: {
1499: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1500: }
1501: else
1502: {
1503: $link = $url;
1504: }
1505: # Add the text
1506: if ($text ne "")
1507: {
1508: $template .=
1509: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1510: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1511: }
1512:
1513: # Add the graphic
1514: my $title = &mt('Report a Bug');
1515: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1516: $template .= <<"ENDTEMPLATE";
1517: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1518: ENDTEMPLATE
1519: if ($text ne '') { $template.='</td></tr></table>' };
1520: return $template;
1521:
1522: }
1523:
1524: sub help_open_faq {
1525: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1526: unless ($env{'user.adv'}) { return ''; }
1527: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1528: $text = "" if (not defined $text);
1529: $stayOnPage=1;
1530: $width = 350 if (not defined $width);
1531: $height = 400 if (not defined $height);
1532:
1533: $topic=~s/\W+/\+/g;
1534: my $link='';
1535: my $template='';
1536: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1537: if (!$stayOnPage)
1538: {
1539: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1540: }
1541: else
1542: {
1543: $link = $url;
1544: }
1545:
1546: # Add the text
1547: if ($text ne "")
1548: {
1549: $template .=
1550: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1551: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1552: }
1553:
1554: # Add the graphic
1555: my $title = &mt('View the FAQ');
1556: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1557: $template .= <<"ENDTEMPLATE";
1558: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1559: ENDTEMPLATE
1560: if ($text ne '') { $template.='</td></tr></table>' };
1561: return $template;
1562:
1563: }
1564:
1565: ###############################################################
1566: ###############################################################
1567:
1568: =pod
1569:
1570: =item * &change_content_javascript():
1571:
1572: This and the next function allow you to create small sections of an
1573: otherwise static HTML page that you can update on the fly with
1574: Javascript, even in Netscape 4.
1575:
1576: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1577: must be written to the HTML page once. It will prove the Javascript
1578: function "change(name, content)". Calling the change function with the
1579: name of the section
1580: you want to update, matching the name passed to C<changable_area>, and
1581: the new content you want to put in there, will put the content into
1582: that area.
1583:
1584: B<Note>: Netscape 4 only reserves enough space for the changable area
1585: to contain room for the original contents. You need to "make space"
1586: for whatever changes you wish to make, and be B<sure> to check your
1587: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1588: it's adequate for updating a one-line status display, but little more.
1589: This script will set the space to 100% width, so you only need to
1590: worry about height in Netscape 4.
1591:
1592: Modern browsers are much less limiting, and if you can commit to the
1593: user not using Netscape 4, this feature may be used freely with
1594: pretty much any HTML.
1595:
1596: =cut
1597:
1598: sub change_content_javascript {
1599: # If we're on Netscape 4, we need to use Layer-based code
1600: if ($env{'browser.type'} eq 'netscape' &&
1601: $env{'browser.version'} =~ /^4\./) {
1602: return (<<NETSCAPE4);
1603: function change(name, content) {
1604: doc = document.layers[name+"___escape"].layers[0].document;
1605: doc.open();
1606: doc.write(content);
1607: doc.close();
1608: }
1609: NETSCAPE4
1610: } else {
1611: # Otherwise, we need to use semi-standards-compliant code
1612: # (technically, "innerHTML" isn't standard but the equivalent
1613: # is really scary, and every useful browser supports it
1614: return (<<DOMBASED);
1615: function change(name, content) {
1616: element = document.getElementById(name);
1617: element.innerHTML = content;
1618: }
1619: DOMBASED
1620: }
1621: }
1622:
1623: =pod
1624:
1625: =item * &changable_area($name,$origContent):
1626:
1627: This provides a "changable area" that can be modified on the fly via
1628: the Javascript code provided in C<change_content_javascript>. $name is
1629: the name you will use to reference the area later; do not repeat the
1630: same name on a given HTML page more then once. $origContent is what
1631: the area will originally contain, which can be left blank.
1632:
1633: =cut
1634:
1635: sub changable_area {
1636: my ($name, $origContent) = @_;
1637:
1638: if ($env{'browser.type'} eq 'netscape' &&
1639: $env{'browser.version'} =~ /^4\./) {
1640: # If this is netscape 4, we need to use the Layer tag
1641: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1642: } else {
1643: return "<span id='$name'>$origContent</span>";
1644: }
1645: }
1646:
1647: =pod
1648:
1649: =item * &viewport_geometry_js
1650:
1651: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1652:
1653: =cut
1654:
1655:
1656: sub viewport_geometry_js {
1657: return <<"GEOMETRY";
1658: var Geometry = {};
1659: function init_geometry() {
1660: if (Geometry.init) { return };
1661: Geometry.init=1;
1662: if (window.innerHeight) {
1663: Geometry.getViewportHeight = function() { return window.innerHeight; };
1664: Geometry.getViewportWidth = function() { return window.innerWidth; };
1665: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1666: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1667: }
1668: else if (document.documentElement && document.documentElement.clientHeight) {
1669: Geometry.getViewportHeight =
1670: function() { return document.documentElement.clientHeight; };
1671: Geometry.getViewportWidth =
1672: function() { return document.documentElement.clientWidth; };
1673:
1674: Geometry.getHorizontalScroll =
1675: function() { return document.documentElement.scrollLeft; };
1676: Geometry.getVerticalScroll =
1677: function() { return document.documentElement.scrollTop; };
1678: }
1679: else if (document.body.clientHeight) {
1680: Geometry.getViewportHeight =
1681: function() { return document.body.clientHeight; };
1682: Geometry.getViewportWidth =
1683: function() { return document.body.clientWidth; };
1684: Geometry.getHorizontalScroll =
1685: function() { return document.body.scrollLeft; };
1686: Geometry.getVerticalScroll =
1687: function() { return document.body.scrollTop; };
1688: }
1689: }
1690:
1691: GEOMETRY
1692: }
1693:
1694: =pod
1695:
1696: =item * &viewport_size_js()
1697:
1698: 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.
1699:
1700: =cut
1701:
1702: sub viewport_size_js {
1703: my $geometry = &viewport_geometry_js();
1704: return <<"DIMS";
1705:
1706: $geometry
1707:
1708: function getViewportDims(width,height) {
1709: init_geometry();
1710: width.value = Geometry.getViewportWidth();
1711: height.value = Geometry.getViewportHeight();
1712: return;
1713: }
1714:
1715: DIMS
1716: }
1717:
1718: =pod
1719:
1720: =item * &resize_textarea_js()
1721:
1722: emits the needed javascript to resize a textarea to be as big as possible
1723:
1724: creates a function resize_textrea that takes two IDs first should be
1725: the id of the element to resize, second should be the id of a div that
1726: surrounds everything that comes after the textarea, this routine needs
1727: to be attached to the <body> for the onload and onresize events.
1728:
1729: =back
1730:
1731: =cut
1732:
1733: sub resize_textarea_js {
1734: my $geometry = &viewport_geometry_js();
1735: return <<"RESIZE";
1736: <script type="text/javascript">
1737: // <![CDATA[
1738: $geometry
1739:
1740: function getX(element) {
1741: var x = 0;
1742: while (element) {
1743: x += element.offsetLeft;
1744: element = element.offsetParent;
1745: }
1746: return x;
1747: }
1748: function getY(element) {
1749: var y = 0;
1750: while (element) {
1751: y += element.offsetTop;
1752: element = element.offsetParent;
1753: }
1754: return y;
1755: }
1756:
1757:
1758: function resize_textarea(textarea_id,bottom_id) {
1759: init_geometry();
1760: var textarea = document.getElementById(textarea_id);
1761: //alert(textarea);
1762:
1763: var textarea_top = getY(textarea);
1764: var textarea_height = textarea.offsetHeight;
1765: var bottom = document.getElementById(bottom_id);
1766: var bottom_top = getY(bottom);
1767: var bottom_height = bottom.offsetHeight;
1768: var window_height = Geometry.getViewportHeight();
1769: var fudge = 23;
1770: var new_height = window_height-fudge-textarea_top-bottom_height;
1771: if (new_height < 300) {
1772: new_height = 300;
1773: }
1774: textarea.style.height=new_height+'px';
1775: }
1776: // ]]>
1777: </script>
1778: RESIZE
1779:
1780: }
1781:
1782: sub colorfuleditor_js {
1783: my $browse_or_search;
1784: my $respath;
1785: my ($cnum,$cdom) = &crsauthor_url();
1786: if ($cnum) {
1787: $respath = "/res/$cdom/$cnum/";
1788: my %js_lt = &Apache::lonlocal::texthash(
1789: sunm => 'Sub-directory name',
1790: save => 'Save page to make this permanent',
1791: );
1792: &js_escape(\%js_lt);
1793: $browse_or_search = <<"END";
1794:
1795: function toggleChooser(form,element,titleid,only,search) {
1796: var disp = 'none';
1797: if (document.getElementById('chooser_'+element)) {
1798: var curr = document.getElementById('chooser_'+element).style.display;
1799: if (curr == 'none') {
1800: disp='inline';
1801: if (form.elements['chooser_'+element].length) {
1802: for (var i=0; i<form.elements['chooser_'+element].length; i++) {
1803: form.elements['chooser_'+element][i].checked = false;
1804: }
1805: }
1806: toggleResImport(form,element);
1807: }
1808: document.getElementById('chooser_'+element).style.display = disp;
1809: }
1810: }
1811:
1812: function toggleCrsFile(form,element,numdirs) {
1813: if (document.getElementById('chooser_'+element+'_crsres')) {
1814: var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
1815: if (curr == 'none') {
1816: if (numdirs) {
1817: form.elements['coursepath_'+element].selectedIndex = 0;
1818: if (numdirs > 1) {
1819: window['select1'+element+'_changed']();
1820: }
1821: }
1822: }
1823: document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
1824:
1825: }
1826: if (document.getElementById('chooser_'+element+'_upload')) {
1827: document.getElementById('chooser_'+element+'_upload').style.display = 'none';
1828: if (document.getElementById('uploadcrsres_'+element)) {
1829: document.getElementById('uploadcrsres_'+element).value = '';
1830: }
1831: }
1832: return;
1833: }
1834:
1835: function toggleCrsUpload(form,element,numcrsdirs) {
1836: if (document.getElementById('chooser_'+element+'_crsres')) {
1837: document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
1838: }
1839: if (document.getElementById('chooser_'+element+'_upload')) {
1840: var curr = document.getElementById('chooser_'+element+'_upload').style.display;
1841: if (curr == 'none') {
1842: if (numcrsdirs) {
1843: form.elements['crsauthorpath_'+element].selectedIndex = 0;
1844: form.elements['newsubdir_'+element][0].checked = true;
1845: toggleNewsubdir(form,element);
1846: }
1847: }
1848: document.getElementById('chooser_'+element+'_upload').style.display = 'block';
1849: }
1850: return;
1851: }
1852:
1853: function toggleResImport(form,element) {
1854: var choices = new Array('crsres','upload');
1855: for (var i=0; i<choices.length; i++) {
1856: if (document.getElementById('chooser_'+element+'_'+choices[i])) {
1857: document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
1858: }
1859: }
1860: }
1861:
1862: function toggleNewsubdir(form,element) {
1863: var newsub = form.elements['newsubdir_'+element];
1864: if (newsub) {
1865: if (newsub.length) {
1866: for (var j=0; j<newsub.length; j++) {
1867: if (newsub[j].checked) {
1868: if (document.getElementById('newsubdirname_'+element)) {
1869: if (newsub[j].value == '1') {
1870: document.getElementById('newsubdirname_'+element).type = "text";
1871: if (document.getElementById('newsubdir_'+element)) {
1872: document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
1873: }
1874: } else {
1875: document.getElementById('newsubdirname_'+element).type = "hidden";
1876: document.getElementById('newsubdirname_'+element).value = "";
1877: document.getElementById('newsubdir_'+element).innerHTML = "";
1878: }
1879: }
1880: break;
1881: }
1882: }
1883: }
1884: }
1885: }
1886:
1887: function updateCrsFile(form,element) {
1888: var directory = form.elements['coursepath_'+element];
1889: var filename = form.elements['coursefile_'+element];
1890: var path = directory.options[directory.selectedIndex].value;
1891: var file = filename.options[filename.selectedIndex].value;
1892: form.elements[element].value = '$respath';
1893: if (path == '/') {
1894: form.elements[element].value += file;
1895: } else {
1896: form.elements[element].value += path+'/'+file;
1897: }
1898: unClean();
1899: if (document.getElementById('previewimg_'+element)) {
1900: document.getElementById('previewimg_'+element).src = form.elements[element].value;
1901: var newsrc = document.getElementById('previewimg_'+element).src;
1902: }
1903: if (document.getElementById('showimg_'+element)) {
1904: document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
1905: }
1906: toggleChooser(form,element);
1907: return;
1908: }
1909:
1910: function uploadDone(suffix,name) {
1911: if (name) {
1912: document.forms["lonhomework"].elements[suffix].value = name;
1913: unClean();
1914: toggleChooser(document.forms["lonhomework"],suffix);
1915: }
1916: }
1917:
1918: \$(document).ready(function(){
1919:
1920: \$(document).delegate('form :submit', 'click', function( event ) {
1921: if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
1922: var buttonId = this.id;
1923: var suffix = buttonId.toString();
1924: suffix = suffix.replace(/^crsupload_/,'');
1925: event.preventDefault();
1926: document.lonhomework.target = 'crsupload_target_'+suffix;
1927: document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
1928: \$(this.form).submit();
1929: document.lonhomework.target = '';
1930: if (document.getElementById('crsuploadto_'+suffix)) {
1931: document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
1932: }
1933: return false;
1934: }
1935: });
1936: });
1937: END
1938: }
1939: return <<"COLORFULEDIT"
1940: <script type="text/javascript">
1941: // <![CDATA[>
1942: function fold_box(curDepth, lastresource){
1943:
1944: // we need a list because there can be several blocks you need to fold in one tag
1945: var block = document.getElementsByName('foldblock_'+curDepth);
1946: // but there is only one folding button per tag
1947: var foldbutton = document.getElementById('folding_btn_'+curDepth);
1948:
1949: if(block.item(0).style.display == 'none'){
1950:
1951: foldbutton.value = '@{[&mt("Hide")]}';
1952: for (i = 0; i < block.length; i++){
1953: block.item(i).style.display = '';
1954: }
1955: }else{
1956:
1957: foldbutton.value = '@{[&mt("Show")]}';
1958: for (i = 0; i < block.length; i++){
1959: // block.item(i).style.visibility = 'collapse';
1960: block.item(i).style.display = 'none';
1961: }
1962: };
1963: saveState(lastresource);
1964: }
1965:
1966: function saveState (lastresource) {
1967:
1968: var tag_list = getTagList();
1969: if(tag_list != null){
1970: var timestamp = new Date().getTime();
1971: var key = lastresource;
1972:
1973: // the value pattern is: 'time;key1,value1;key2,value2; ... '
1974: // starting with timestamp
1975: var value = timestamp+';';
1976:
1977: // building the list of key-value pairs
1978: for(var i = 0; i < tag_list.length; i++){
1979: value += tag_list[i]+',';
1980: value += document.getElementsByName(tag_list[i])[0].style.display+';';
1981: }
1982:
1983: // only iterate whole storage if nothing to override
1984: if(localStorage.getItem(key) == null){
1985:
1986: // prevent storage from growing large
1987: if(localStorage.length > 50){
1988: var regex_getTimestamp = /^(?:\d)+;/;
1989: var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
1990: var oldest_key;
1991:
1992: for(var i = 1; i < localStorage.length; i++){
1993: if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
1994: oldest_key = localStorage.key(i);
1995: oldest_timestamp = regex_getTimestamp.exec(oldest_key);
1996: }
1997: }
1998: localStorage.removeItem(oldest_key);
1999: }
2000: }
2001: localStorage.setItem(key,value);
2002: }
2003: }
2004:
2005: // restore folding status of blocks (on page load)
2006: function restoreState (lastresource) {
2007: if(localStorage.getItem(lastresource) != null){
2008: var key = lastresource;
2009: var value = localStorage.getItem(key);
2010: var regex_delTimestamp = /^\d+;/;
2011:
2012: value.replace(regex_delTimestamp, '');
2013:
2014: var valueArr = value.split(';');
2015: var pairs;
2016: var elements;
2017: for (var i = 0; i < valueArr.length; i++){
2018: pairs = valueArr[i].split(',');
2019: elements = document.getElementsByName(pairs[0]);
2020:
2021: for (var j = 0; j < elements.length; j++){
2022: elements[j].style.display = pairs[1];
2023: if (pairs[1] == "none"){
2024: var regex_id = /([_\\d]+)\$/;
2025: regex_id.exec(pairs[0]);
2026: document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
2027: }
2028: }
2029: }
2030: }
2031: }
2032:
2033: function getTagList () {
2034:
2035: var stringToSearch = document.lonhomework.innerHTML;
2036:
2037: var ret = new Array();
2038: var regex_findBlock = /(foldblock_.*?)"/g;
2039: var tag_list = stringToSearch.match(regex_findBlock);
2040:
2041: if(tag_list != null){
2042: for(var i = 0; i < tag_list.length; i++){
2043: ret.push(tag_list[i].replace(/"/, ''));
2044: }
2045: }
2046: return ret;
2047: }
2048:
2049: function saveScrollPosition (resource) {
2050: var tag_list = getTagList();
2051:
2052: // we dont always want to jump to the first block
2053: // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
2054: if(\$(window).scrollTop() > 170){
2055: if(tag_list != null){
2056: var result;
2057: for(var i = 0; i < tag_list.length; i++){
2058: if(isElementInViewport(tag_list[i])){
2059: result += tag_list[i]+';';
2060: }
2061: }
2062: sessionStorage.setItem('anchor_'+resource, result);
2063: }
2064: } else {
2065: // we dont need to save zero, just delete the item to leave everything tidy
2066: sessionStorage.removeItem('anchor_'+resource);
2067: }
2068: }
2069:
2070: function restoreScrollPosition(resource){
2071:
2072: var elem = sessionStorage.getItem('anchor_'+resource);
2073: if(elem != null){
2074: var tag_list = elem.split(';');
2075: var elem_list;
2076:
2077: for(var i = 0; i < tag_list.length; i++){
2078: elem_list = document.getElementsByName(tag_list[i]);
2079:
2080: if(elem_list.length > 0){
2081: elem = elem_list[0];
2082: break;
2083: }
2084: }
2085: elem.scrollIntoView();
2086: }
2087: }
2088:
2089: function isElementInViewport(el) {
2090:
2091: // change to last element instead of first
2092: var elem = document.getElementsByName(el);
2093: var rect = elem[0].getBoundingClientRect();
2094:
2095: return (
2096: rect.top >= 0 &&
2097: rect.left >= 0 &&
2098: rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
2099: rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
2100: );
2101: }
2102:
2103: function autosize(depth){
2104: var cmInst = window['cm'+depth];
2105: var fitsizeButton = document.getElementById('fitsize'+depth);
2106:
2107: // is fixed size, switching to dynamic
2108: if (sessionStorage.getItem("autosized_"+depth) == null) {
2109: cmInst.setSize("","auto");
2110: fitsizeButton.value = "@{[&mt('Fixed size')]}";
2111: sessionStorage.setItem("autosized_"+depth, "yes");
2112:
2113: // is dynamic size, switching to fixed
2114: } else {
2115: cmInst.setSize("","300px");
2116: fitsizeButton.value = "@{[&mt('Dynamic size')]}";
2117: sessionStorage.removeItem("autosized_"+depth);
2118: }
2119: }
2120:
2121: $browse_or_search
2122:
2123: // ]]>
2124: </script>
2125: COLORFULEDIT
2126: }
2127:
2128: sub xmleditor_js {
2129: return <<XMLEDIT
2130: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
2131: <script type="text/javascript">
2132: // <![CDATA[>
2133:
2134: function saveScrollPosition (resource) {
2135:
2136: var scrollPos = \$(window).scrollTop();
2137: sessionStorage.setItem(resource,scrollPos);
2138: }
2139:
2140: function restoreScrollPosition(resource){
2141:
2142: var scrollPos = sessionStorage.getItem(resource);
2143: \$(window).scrollTop(scrollPos);
2144: }
2145:
2146: // unless internet explorer
2147: if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
2148:
2149: \$(document).ready(function() {
2150: \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
2151: });
2152: }
2153:
2154: // inserts text at cursor position into codemirror (xml editor only)
2155: function insertText(text){
2156: cm.focus();
2157: var curPos = cm.getCursor();
2158: cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
2159: }
2160: // ]]>
2161: </script>
2162: XMLEDIT
2163: }
2164:
2165: sub insert_folding_button {
2166: my $curDepth = $Apache::lonxml::curdepth;
2167: my $lastresource = $env{'request.ambiguous'};
2168:
2169: return "<input type=\"button\" id=\"folding_btn_$curDepth\"
2170: value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
2171: }
2172:
2173: sub crsauthor_url {
2174: my ($url) = @_;
2175: if ($url eq '') {
2176: $url = $ENV{'REQUEST_URI'};
2177: }
2178: my ($cnum,$cdom);
2179: if ($env{'request.course.id'}) {
2180: my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
2181: if ($audom ne '' && $auname ne '') {
2182: if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
2183: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
2184: $cnum = $auname;
2185: $cdom = $audom;
2186: }
2187: }
2188: }
2189: return ($cnum,$cdom);
2190: }
2191:
2192: sub import_crsauthor_form {
2193: my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix,$disabled) = @_;
2194: return (0) unless ($env{'request.course.id'});
2195: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2196: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2197: my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
2198: return (0) unless (($cnum ne '') && ($cdom ne ''));
2199: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
2200: my @ids=&Apache::lonnet::current_machine_ids();
2201: my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
2202:
2203: if (grep(/^\Q$crshome\E$/,@ids)) {
2204: $is_home = 1;
2205: }
2206: $relpath = "/priv/$cdom/$cnum";
2207: &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
2208: my %lt = &Apache::lonlocal::texthash (
2209: fnam => 'Filename',
2210: dire => 'Directory',
2211: );
2212: my $numdirs = scalar(keys(%files));
2213: my (%possexts,$singledir,@singledirfiles);
2214: if ($only) {
2215: map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
2216: }
2217: my (%nonemptydirs,$possdirs);
2218: if ($numdirs > 1) {
2219: my @order;
2220: foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
2221: if (ref($files{$key}) eq 'HASH') {
2222: my $shown = $key;
2223: if ($key eq '') {
2224: $shown = '/';
2225: }
2226: my @ordered = ();
2227: foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
2228: if ($only) {
2229: my ($ext) = ($file =~ /\.([^.]+)$/);
2230: unless ($possexts{lc($ext)}) {
2231: next;
2232: }
2233: }
2234: $selimport_menus{$key}->{'select2'}->{$file} = $file;
2235: push(@ordered,$file);
2236: }
2237: if (@ordered) {
2238: push(@order,$key);
2239: $nonemptydirs{$key} = 1;
2240: $selimport_menus{$key}->{'text'} = $shown;
2241: $selimport_menus{$key}->{'default'} = '';
2242: $selimport_menus{$key}->{'select2'}->{''} = '';
2243: $selimport_menus{$key}->{'order'} = \@ordered;
2244: }
2245: }
2246: }
2247: $possdirs = scalar(keys(%nonemptydirs));
2248: if ($possdirs > 1) {
2249: my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
2250: $output = $lt{'dire'}.
2251: &linked_select_forms($form,'<br />'.
2252: $lt{'fnam'},'',
2253: $firstselectname,$secondselectname,
2254: \%selimport_menus,\@order,
2255: $onchangefirst,'',$suffix).'<br />';
2256: } elsif ($possdirs == 1) {
2257: $singledir = (keys(%nonemptydirs))[0];
2258: if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
2259: @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
2260: }
2261: delete($selimport_menus{$singledir});
2262: }
2263: } elsif ($numdirs == 1) {
2264: $singledir = (keys(%files))[0];
2265: foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
2266: if ($only) {
2267: my ($ext) = ($file =~ /\.([^.]+)$/);
2268: unless ($possexts{lc($ext)}) {
2269: next;
2270: }
2271: }
2272: push(@singledirfiles,$file);
2273: }
2274: if (@singledirfiles) {
2275: $possdirs == 1;
2276: }
2277: }
2278: if (($possdirs == 1) && (@singledirfiles)) {
2279: my $showdir = $singledir;
2280: if ($singledir eq '') {
2281: $showdir = '/';
2282: }
2283: $output = $lt{'dire'}.
2284: '<select name="'.$firstselectname.'">'.
2285: '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
2286: '</select><br />'.
2287: $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
2288: '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
2289: foreach my $file (@singledirfiles) {
2290: $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
2291: }
2292: $output .= '</select><br />'."\n";
2293: }
2294: return ($possdirs,$output);
2295: }
2296:
2297: =pod
2298:
2299: =head1 Excel and CSV file utility routines
2300:
2301: =cut
2302:
2303: ###############################################################
2304: ###############################################################
2305:
2306: =pod
2307:
2308: =over 4
2309:
2310: =item * &csv_translate($text)
2311:
2312: Translate $text to allow it to be output as a 'comma separated values'
2313: format.
2314:
2315: =cut
2316:
2317: ###############################################################
2318: ###############################################################
2319: sub csv_translate {
2320: my $text = shift;
2321: $text =~ s/\"/\"\"/g;
2322: $text =~ s/\n/ /g;
2323: return $text;
2324: }
2325:
2326: ###############################################################
2327: ###############################################################
2328:
2329: =pod
2330:
2331: =item * &define_excel_formats()
2332:
2333: Define some commonly used Excel cell formats.
2334:
2335: Currently supported formats:
2336:
2337: =over 4
2338:
2339: =item header
2340:
2341: =item bold
2342:
2343: =item h1
2344:
2345: =item h2
2346:
2347: =item h3
2348:
2349: =item h4
2350:
2351: =item i
2352:
2353: =item date
2354:
2355: =back
2356:
2357: Inputs: $workbook
2358:
2359: Returns: $format, a hash reference.
2360:
2361:
2362: =cut
2363:
2364: ###############################################################
2365: ###############################################################
2366: sub define_excel_formats {
2367: my ($workbook) = @_;
2368: my $format;
2369: $format->{'header'} = $workbook->add_format(bold => 1,
2370: bottom => 1,
2371: align => 'center');
2372: $format->{'bold'} = $workbook->add_format(bold=>1);
2373: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
2374: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
2375: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
2376: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
2377: $format->{'i'} = $workbook->add_format(italic=>1);
2378: $format->{'date'} = $workbook->add_format(num_format=>
2379: 'mm/dd/yyyy hh:mm:ss');
2380: return $format;
2381: }
2382:
2383: ###############################################################
2384: ###############################################################
2385:
2386: =pod
2387:
2388: =item * &create_workbook()
2389:
2390: Create an Excel worksheet. If it fails, output message on the
2391: request object and return undefs.
2392:
2393: Inputs: Apache request object
2394:
2395: Returns (undef) on failure,
2396: Excel worksheet object, scalar with filename, and formats
2397: from &Apache::loncommon::define_excel_formats on success
2398:
2399: =cut
2400:
2401: ###############################################################
2402: ###############################################################
2403: sub create_workbook {
2404: my ($r) = @_;
2405: #
2406: # Create the excel spreadsheet
2407: my $filename = '/prtspool/'.
2408: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2409: time.'_'.rand(1000000000).'.xls';
2410: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
2411: if (! defined($workbook)) {
2412: $r->log_error("Error creating excel spreadsheet $filename: $!");
2413: $r->print(
2414: '<p class="LC_error">'
2415: .&mt('Problems occurred in creating the new Excel file.')
2416: .' '.&mt('This error has been logged.')
2417: .' '.&mt('Please alert your LON-CAPA administrator.')
2418: .'</p>'
2419: );
2420: return (undef);
2421: }
2422: #
2423: $workbook->set_tempdir(LONCAPA::tempdir());
2424: #
2425: my $format = &Apache::loncommon::define_excel_formats($workbook);
2426: return ($workbook,$filename,$format);
2427: }
2428:
2429: ###############################################################
2430: ###############################################################
2431:
2432: =pod
2433:
2434: =item * &create_text_file()
2435:
2436: Create a file to write to and eventually make available to the user.
2437: If file creation fails, outputs an error message on the request object and
2438: return undefs.
2439:
2440: Inputs: Apache request object, and file suffix
2441:
2442: Returns (undef) on failure,
2443: Filehandle and filename on success.
2444:
2445: =cut
2446:
2447: ###############################################################
2448: ###############################################################
2449: sub create_text_file {
2450: my ($r,$suffix) = @_;
2451: if (! defined($suffix)) { $suffix = 'txt'; };
2452: my $fh;
2453: my $filename = '/prtspool/'.
2454: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2455: time.'_'.rand(1000000000).'.'.$suffix;
2456: $fh = Apache::File->new('>/home/httpd'.$filename);
2457: if (! defined($fh)) {
2458: $r->log_error("Couldn't open $filename for output $!");
2459: $r->print(
2460: '<p class="LC_error">'
2461: .&mt('Problems occurred in creating the output file.')
2462: .' '.&mt('This error has been logged.')
2463: .' '.&mt('Please alert your LON-CAPA administrator.')
2464: .'</p>'
2465: );
2466: }
2467: return ($fh,$filename)
2468: }
2469:
2470:
2471: =pod
2472:
2473: =back
2474:
2475: =cut
2476:
2477: ###############################################################
2478: ## Home server <option> list generating code ##
2479: ###############################################################
2480:
2481: # ------------------------------------------
2482:
2483: sub domain_select {
2484: my ($name,$value,$multiple,$incdoms,$excdoms)=@_;
2485: my @possdoms;
2486: if (ref($incdoms) eq 'ARRAY') {
2487: @possdoms = @{$incdoms};
2488: } else {
2489: @possdoms = &Apache::lonnet::all_domains();
2490: }
2491:
2492: my %domains=map {
2493: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
2494: } @possdoms;
2495:
2496: if ((ref($excdoms) eq 'ARRAY') && (@{$excdoms} > 0)) {
2497: foreach my $dom (@{$excdoms}) {
2498: delete($domains{$dom});
2499: }
2500: }
2501:
2502: if ($multiple) {
2503: $domains{''}=&mt('Any domain');
2504: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2505: return &multiple_select_form($name,$value,4,\%domains);
2506: } else {
2507: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2508: return &select_form($name,$value,\%domains);
2509: }
2510: }
2511:
2512: #-------------------------------------------
2513:
2514: =pod
2515:
2516: =head1 Routines for form select boxes
2517:
2518: =over 4
2519:
2520: =item * &multiple_select_form($name,$value,$size,$hash,$order)
2521:
2522: Returns a string containing a <select> element int multiple mode
2523:
2524:
2525: Args:
2526: $name - name of the <select> element
2527: $value - scalar or array ref of values that should already be selected
2528: $size - number of rows long the select element is
2529: $hash - the elements should be 'option' => 'shown text'
2530: (shown text should already have been &mt())
2531: $order - (optional) array ref of the order to show the elements in
2532:
2533: =cut
2534:
2535: #-------------------------------------------
2536: sub multiple_select_form {
2537: my ($name,$value,$size,$hash,$order)=@_;
2538: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
2539: my $output='';
2540: if (! defined($size)) {
2541: $size = 4;
2542: if (scalar(keys(%$hash))<4) {
2543: $size = scalar(keys(%$hash));
2544: }
2545: }
2546: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
2547: my @order;
2548: if (ref($order) eq 'ARRAY') {
2549: @order = @{$order};
2550: } else {
2551: @order = sort(keys(%$hash));
2552: }
2553: if (exists($$hash{'select_form_order'})) {
2554: @order = @{$$hash{'select_form_order'}};
2555: }
2556:
2557: foreach my $key (@order) {
2558: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
2559: $output.='selected="selected" ' if ($selected{$key});
2560: $output.='>'.$hash->{$key}."</option>\n";
2561: }
2562: $output.="</select>\n";
2563: return $output;
2564: }
2565:
2566: #-------------------------------------------
2567:
2568: =pod
2569:
2570: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
2571:
2572: Returns a string containing a <select name='$name' size='1'> form to
2573: allow a user to select options from a ref to a hash containing:
2574: option_name => displayed text. An optional $onchange can include
2575: a javascript onchange item, e.g., onchange="this.form.submit();".
2576: An optional arg -- $readonly -- if true will cause the select form
2577: to be disabled, e.g., for the case where an instructor has a section-
2578: specific role, and is viewing/modifying parameters.
2579:
2580: See lonrights.pm for an example invocation and use.
2581:
2582: =cut
2583:
2584: #-------------------------------------------
2585: sub select_form {
2586: my ($def,$name,$hashref,$onchange,$readonly) = @_;
2587: return unless (ref($hashref) eq 'HASH');
2588: if ($onchange) {
2589: $onchange = ' onchange="'.$onchange.'"';
2590: }
2591: my $disabled;
2592: if ($readonly) {
2593: $disabled = ' disabled="disabled"';
2594: }
2595: my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2596: my @keys;
2597: if (exists($hashref->{'select_form_order'})) {
2598: @keys=@{$hashref->{'select_form_order'}};
2599: } else {
2600: @keys=sort(keys(%{$hashref}));
2601: }
2602: foreach my $key (@keys) {
2603: $selectform.=
2604: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
2605: ($key eq $def ? 'selected="selected" ' : '').
2606: ">".$hashref->{$key}."</option>\n";
2607: }
2608: $selectform.="</select>";
2609: return $selectform;
2610: }
2611:
2612: # For display filters
2613:
2614: sub display_filter {
2615: my ($context) = @_;
2616: if (!$env{'form.show'}) { $env{'form.show'}=10; }
2617: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
2618: my $phraseinput = 'hidden';
2619: my $includeinput = 'hidden';
2620: my ($checked,$includetypestext);
2621: if ($env{'form.displayfilter'} eq 'containing') {
2622: $phraseinput = 'text';
2623: if ($context eq 'parmslog') {
2624: $includeinput = 'checkbox';
2625: if ($env{'form.includetypes'}) {
2626: $checked = ' checked="checked"';
2627: }
2628: $includetypestext = &mt('Include parameter types');
2629: }
2630: } else {
2631: $includetypestext = ' ';
2632: }
2633: my ($additional,$secondid,$thirdid);
2634: if ($context eq 'parmslog') {
2635: $additional =
2636: '<label><input type="'.$includeinput.'" name="includetypes"'.
2637: $checked.' name="includetypes" value="1" id="includetypes" />'.
2638: ' <span id="includetypestext">'.$includetypestext.'</span>'.
2639: '</label>';
2640: $secondid = 'includetypes';
2641: $thirdid = 'includetypestext';
2642: }
2643: my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
2644: '$secondid','$thirdid')";
2645: return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
2646: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
2647: (&mt('all'),10,20,50,100,1000,10000))).
2648: '</label></span> <span class="LC_nobreak">'.
2649: &mt('Filter: [_1]',
2650: &select_form($env{'form.displayfilter'},
2651: 'displayfilter',
2652: {'currentfolder' => 'Current folder/page',
2653: 'containing' => 'Containing phrase',
2654: 'none' => 'None'},$onchange)).' '.
2655: '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
2656: &HTML::Entities::encode($env{'form.containingphrase'}).
2657: '" />'.$additional;
2658: }
2659:
2660: sub display_filter_js {
2661: my $includetext = &mt('Include parameter types');
2662: return <<"ENDJS";
2663:
2664: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
2665: var firstType = 'hidden';
2666: if (setter.options[setter.selectedIndex].value == 'containing') {
2667: firstType = 'text';
2668: }
2669: firstObject = document.getElementById(firstid);
2670: if (typeof(firstObject) == 'object') {
2671: if (firstObject.type != firstType) {
2672: changeInputType(firstObject,firstType);
2673: }
2674: }
2675: if (context == 'parmslog') {
2676: var secondType = 'hidden';
2677: if (firstType == 'text') {
2678: secondType = 'checkbox';
2679: }
2680: secondObject = document.getElementById(secondid);
2681: if (typeof(secondObject) == 'object') {
2682: if (secondObject.type != secondType) {
2683: changeInputType(secondObject,secondType);
2684: }
2685: }
2686: var textItem = document.getElementById(thirdid);
2687: var currtext = textItem.innerHTML;
2688: var newtext;
2689: if (firstType == 'text') {
2690: newtext = '$includetext';
2691: } else {
2692: newtext = ' ';
2693: }
2694: if (currtext != newtext) {
2695: textItem.innerHTML = newtext;
2696: }
2697: }
2698: return;
2699: }
2700:
2701: function changeInputType(oldObject,newType) {
2702: var newObject = document.createElement('input');
2703: newObject.type = newType;
2704: if (oldObject.size) {
2705: newObject.size = oldObject.size;
2706: }
2707: if (oldObject.value) {
2708: newObject.value = oldObject.value;
2709: }
2710: if (oldObject.name) {
2711: newObject.name = oldObject.name;
2712: }
2713: if (oldObject.id) {
2714: newObject.id = oldObject.id;
2715: }
2716: oldObject.parentNode.replaceChild(newObject,oldObject);
2717: return;
2718: }
2719:
2720: ENDJS
2721: }
2722:
2723: sub gradeleveldescription {
2724: my $gradelevel=shift;
2725: my %gradelevels=(0 => 'Not specified',
2726: 1 => 'Grade 1',
2727: 2 => 'Grade 2',
2728: 3 => 'Grade 3',
2729: 4 => 'Grade 4',
2730: 5 => 'Grade 5',
2731: 6 => 'Grade 6',
2732: 7 => 'Grade 7',
2733: 8 => 'Grade 8',
2734: 9 => 'Grade 9',
2735: 10 => 'Grade 10',
2736: 11 => 'Grade 11',
2737: 12 => 'Grade 12',
2738: 13 => 'Grade 13',
2739: 14 => '100 Level',
2740: 15 => '200 Level',
2741: 16 => '300 Level',
2742: 17 => '400 Level',
2743: 18 => 'Graduate Level');
2744: return &mt($gradelevels{$gradelevel});
2745: }
2746:
2747: sub select_level_form {
2748: my ($deflevel,$name)=@_;
2749: unless ($deflevel) { $deflevel=0; }
2750: my $selectform = "<select name=\"$name\" size=\"1\">\n";
2751: for (my $i=0; $i<=18; $i++) {
2752: $selectform.="<option value=\"$i\" ".
2753: ($i==$deflevel ? 'selected="selected" ' : '').
2754: ">".&gradeleveldescription($i)."</option>\n";
2755: }
2756: $selectform.="</select>";
2757: return $selectform;
2758: }
2759:
2760: #-------------------------------------------
2761:
2762: =pod
2763:
2764: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
2765:
2766: Returns a string containing a <select name='$name' size='1'> form to
2767: allow a user to select the domain to preform an operation in.
2768: See loncreateuser.pm for an example invocation and use.
2769:
2770: If the $includeempty flag is set, it also includes an empty choice ("no domain
2771: selected");
2772:
2773: If the $showdomdesc flag is set, the domain name is followed by the domain description.
2774:
2775: 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.
2776:
2777: The optional $incdoms is a reference to an array of domains which will be the only available options.
2778:
2779: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
2780:
2781: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
2782:
2783: =cut
2784:
2785: #-------------------------------------------
2786: sub select_dom_form {
2787: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
2788: if ($onchange) {
2789: $onchange = ' onchange="'.$onchange.'"';
2790: }
2791: if ($disabled) {
2792: $disabled = ' disabled="disabled"';
2793: }
2794: my (@domains,%exclude);
2795: if (ref($incdoms) eq 'ARRAY') {
2796: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
2797: } else {
2798: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
2799: }
2800: if ($includeempty) { @domains=('',@domains); }
2801: if (ref($excdoms) eq 'ARRAY') {
2802: map { $exclude{$_} = 1; } @{$excdoms};
2803: }
2804: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2805: foreach my $dom (@domains) {
2806: next if ($exclude{$dom});
2807: $selectdomain.="<option value=\"$dom\" ".
2808: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
2809: if ($showdomdesc) {
2810: if ($dom ne '') {
2811: my $domdesc = &Apache::lonnet::domain($dom,'description');
2812: if ($domdesc ne '') {
2813: $selectdomain .= ' ('.$domdesc.')';
2814: }
2815: }
2816: }
2817: $selectdomain .= "</option>\n";
2818: }
2819: $selectdomain.="</select>";
2820: return $selectdomain;
2821: }
2822:
2823: #-------------------------------------------
2824:
2825: =pod
2826:
2827: =item * &home_server_form_item($domain,$name,$defaultflag)
2828:
2829: input: 4 arguments (two required, two optional) -
2830: $domain - domain of new user
2831: $name - name of form element
2832: $default - Value of 'default' causes a default item to be first
2833: option, and selected by default.
2834: $hide - Value of 'hide' causes hiding of the name of the server,
2835: if 1 server found, or default, if 0 found.
2836: output: returns 2 items:
2837: (a) form element which contains either:
2838: (i) <select name="$name">
2839: <option value="$hostid1">$hostid $servers{$hostid}</option>
2840: <option value="$hostid2">$hostid $servers{$hostid}</option>
2841: </select>
2842: form item if there are multiple library servers in $domain, or
2843: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2844: if there is only one library server in $domain.
2845:
2846: (b) number of library servers found.
2847:
2848: See loncreateuser.pm for example of use.
2849:
2850: =cut
2851:
2852: #-------------------------------------------
2853: sub home_server_form_item {
2854: my ($domain,$name,$default,$hide) = @_;
2855: my %servers = &Apache::lonnet::get_servers($domain,'library');
2856: my $result;
2857: my $numlib = keys(%servers);
2858: if ($numlib > 1) {
2859: $result .= '<select name="'.$name.'" />'."\n";
2860: if ($default) {
2861: $result .= '<option value="default" selected="selected">'.&mt('default').
2862: '</option>'."\n";
2863: }
2864: foreach my $hostid (sort(keys(%servers))) {
2865: $result.= '<option value="'.$hostid.'">'.
2866: $hostid.' '.$servers{$hostid}."</option>\n";
2867: }
2868: $result .= '</select>'."\n";
2869: } elsif ($numlib == 1) {
2870: my $hostid;
2871: foreach my $item (keys(%servers)) {
2872: $hostid = $item;
2873: }
2874: $result .= '<input type="hidden" name="'.$name.'" value="'.
2875: $hostid.'" />';
2876: if (!$hide) {
2877: $result .= $hostid.' '.$servers{$hostid};
2878: }
2879: $result .= "\n";
2880: } elsif ($default) {
2881: $result .= '<input type="hidden" name="'.$name.
2882: '" value="default" />';
2883: if (!$hide) {
2884: $result .= &mt('default');
2885: }
2886: $result .= "\n";
2887: }
2888: return ($result,$numlib);
2889: }
2890:
2891: =pod
2892:
2893: =back
2894:
2895: =cut
2896:
2897: ###############################################################
2898: ## Decoding User Agent ##
2899: ###############################################################
2900:
2901: =pod
2902:
2903: =head1 Decoding the User Agent
2904:
2905: =over 4
2906:
2907: =item * &decode_user_agent()
2908:
2909: Inputs: $r
2910:
2911: Outputs:
2912:
2913: =over 4
2914:
2915: =item * $httpbrowser
2916:
2917: =item * $clientbrowser
2918:
2919: =item * $clientversion
2920:
2921: =item * $clientmathml
2922:
2923: =item * $clientunicode
2924:
2925: =item * $clientos
2926:
2927: =item * $clientmobile
2928:
2929: =item * $clientinfo
2930:
2931: =item * $clientosversion
2932:
2933: =back
2934:
2935: =back
2936:
2937: =cut
2938:
2939: ###############################################################
2940: ###############################################################
2941: sub decode_user_agent {
2942: my ($r)=@_;
2943: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
2944: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
2945: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
2946: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
2947: my $clientbrowser='unknown';
2948: my $clientversion='0';
2949: my $clientmathml='';
2950: my $clientunicode='0';
2951: my $clientmobile=0;
2952: my $clientosversion='';
2953: for (my $i=0;$i<=$#browsertype;$i++) {
2954: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
2955: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
2956: $clientbrowser=$bname;
2957: $httpbrowser=~/$vreg/i;
2958: $clientversion=$1;
2959: $clientmathml=($clientversion>=$minv);
2960: $clientunicode=($clientversion>=$univ);
2961: }
2962: }
2963: my $clientos='unknown';
2964: my $clientinfo;
2965: if (($httpbrowser=~/linux/i) ||
2966: ($httpbrowser=~/unix/i) ||
2967: ($httpbrowser=~/ux/i) ||
2968: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
2969: if (($httpbrowser=~/vax/i) ||
2970: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
2971: if ($httpbrowser=~/next/i) { $clientos='next'; }
2972: if (($httpbrowser=~/mac/i) ||
2973: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
2974: if ($httpbrowser=~/win/i) {
2975: $clientos='win';
2976: if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
2977: $clientosversion = $1;
2978: }
2979: }
2980: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
2981: if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
2982: $clientmobile=lc($1);
2983: }
2984: if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
2985: $clientinfo = 'firefox-'.$1;
2986: } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
2987: $clientinfo = 'chromeframe-'.$1;
2988: }
2989: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
2990: $clientunicode,$clientos,$clientmobile,$clientinfo,
2991: $clientosversion);
2992: }
2993:
2994: ###############################################################
2995: ## Authentication changing form generation subroutines ##
2996: ###############################################################
2997: ##
2998: ## All of the authform_xxxxxxx subroutines take their inputs in a
2999: ## hash, and have reasonable default values.
3000: ##
3001: ## formname = the name given in the <form> tag.
3002: #-------------------------------------------
3003:
3004: =pod
3005:
3006: =head1 Authentication Routines
3007:
3008: =over 4
3009:
3010: =item * &authform_xxxxxx()
3011:
3012: The authform_xxxxxx subroutines provide javascript and html forms which
3013: handle some of the conveniences required for authentication forms.
3014: This is not an optimal method, but it works.
3015:
3016: =over 4
3017:
3018: =item * authform_header
3019:
3020: =item * authform_authorwarning
3021:
3022: =item * authform_nochange
3023:
3024: =item * authform_kerberos
3025:
3026: =item * authform_internal
3027:
3028: =item * authform_filesystem
3029:
3030: =item * authform_lti
3031:
3032: =back
3033:
3034: See loncreateuser.pm for invocation and use examples.
3035:
3036: =cut
3037:
3038: #-------------------------------------------
3039: sub authform_header{
3040: my %in = (
3041: formname => 'cu',
3042: kerb_def_dom => '',
3043: @_,
3044: );
3045: $in{'formname'} = 'document.' . $in{'formname'};
3046: my $result='';
3047:
3048: #---------------------------------------------- Code for upper case translation
3049: my $Javascript_toUpperCase;
3050: unless ($in{kerb_def_dom}) {
3051: $Javascript_toUpperCase =<<"END";
3052: switch (choice) {
3053: case 'krb': currentform.elements[choicearg].value =
3054: currentform.elements[choicearg].value.toUpperCase();
3055: break;
3056: default:
3057: }
3058: END
3059: } else {
3060: $Javascript_toUpperCase = "";
3061: }
3062:
3063: my $radioval = "'nochange'";
3064: if (defined($in{'curr_authtype'})) {
3065: if ($in{'curr_authtype'} ne '') {
3066: $radioval = "'".$in{'curr_authtype'}."arg'";
3067: }
3068: }
3069: my $argfield = 'null';
3070: if (defined($in{'mode'})) {
3071: if ($in{'mode'} eq 'modifycourse') {
3072: if (defined($in{'curr_autharg'})) {
3073: if ($in{'curr_autharg'} ne '') {
3074: $argfield = "'$in{'curr_autharg'}'";
3075: }
3076: }
3077: }
3078: }
3079:
3080: $result.=<<"END";
3081: var current = new Object();
3082: current.radiovalue = $radioval;
3083: current.argfield = $argfield;
3084:
3085: function changed_radio(choice,currentform) {
3086: var choicearg = choice + 'arg';
3087: // If a radio button in changed, we need to change the argfield
3088: if (current.radiovalue != choice) {
3089: current.radiovalue = choice;
3090: if (current.argfield != null) {
3091: currentform.elements[current.argfield].value = '';
3092: }
3093: if (choice == 'nochange') {
3094: current.argfield = null;
3095: } else {
3096: current.argfield = choicearg;
3097: switch(choice) {
3098: case 'krb':
3099: currentform.elements[current.argfield].value =
3100: "$in{'kerb_def_dom'}";
3101: break;
3102: default:
3103: break;
3104: }
3105: }
3106: }
3107: return;
3108: }
3109:
3110: function changed_text(choice,currentform) {
3111: var choicearg = choice + 'arg';
3112: if (currentform.elements[choicearg].value !='') {
3113: $Javascript_toUpperCase
3114: // clear old field
3115: if ((current.argfield != choicearg) && (current.argfield != null)) {
3116: currentform.elements[current.argfield].value = '';
3117: }
3118: current.argfield = choicearg;
3119: }
3120: set_auth_radio_buttons(choice,currentform);
3121: return;
3122: }
3123:
3124: function set_auth_radio_buttons(newvalue,currentform) {
3125: var numauthchoices = currentform.login.length;
3126: if (typeof numauthchoices == "undefined") {
3127: return;
3128: }
3129: var i=0;
3130: while (i < numauthchoices) {
3131: if (currentform.login[i].value == newvalue) { break; }
3132: i++;
3133: }
3134: if (i == numauthchoices) {
3135: return;
3136: }
3137: current.radiovalue = newvalue;
3138: currentform.login[i].checked = true;
3139: return;
3140: }
3141: END
3142: return $result;
3143: }
3144:
3145: sub authform_authorwarning {
3146: my $result='';
3147: $result='<i>'.
3148: &mt('As a general rule, only authors or co-authors should be '.
3149: 'filesystem authenticated '.
3150: '(which allows access to the server filesystem).')."</i>\n";
3151: return $result;
3152: }
3153:
3154: sub authform_nochange {
3155: my %in = (
3156: formname => 'document.cu',
3157: kerb_def_dom => 'MSU.EDU',
3158: @_,
3159: );
3160: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3161: my $result;
3162: if (!$authnum) {
3163: $result = &mt('Under your current role you are not permitted to change login settings for this user');
3164: } else {
3165: $result = '<label>'.&mt('[_1] Do not change login data',
3166: '<input type="radio" name="login" value="nochange" '.
3167: 'checked="checked" onclick="'.
3168: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
3169: '</label>';
3170: }
3171: return $result;
3172: }
3173:
3174: sub authform_kerberos {
3175: my %in = (
3176: formname => 'document.cu',
3177: kerb_def_dom => 'MSU.EDU',
3178: kerb_def_auth => 'krb4',
3179: @_,
3180: );
3181: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
3182: $autharg,$jscall,$disabled);
3183: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3184: if ($in{'kerb_def_auth'} eq 'krb5') {
3185: $check5 = ' checked="checked"';
3186: } else {
3187: $check4 = ' checked="checked"';
3188: }
3189: if ($in{'readonly'}) {
3190: $disabled = ' disabled="disabled"';
3191: }
3192: $krbarg = $in{'kerb_def_dom'};
3193: if (defined($in{'curr_authtype'})) {
3194: if ($in{'curr_authtype'} eq 'krb') {
3195: $krbcheck = ' checked="checked"';
3196: if (defined($in{'mode'})) {
3197: if ($in{'mode'} eq 'modifyuser') {
3198: $krbcheck = '';
3199: }
3200: }
3201: if (defined($in{'curr_kerb_ver'})) {
3202: if ($in{'curr_krb_ver'} eq '5') {
3203: $check5 = ' checked="checked"';
3204: $check4 = '';
3205: } else {
3206: $check4 = ' checked="checked"';
3207: $check5 = '';
3208: }
3209: }
3210: if (defined($in{'curr_autharg'})) {
3211: $krbarg = $in{'curr_autharg'};
3212: }
3213: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
3214: if (defined($in{'curr_autharg'})) {
3215: $result =
3216: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
3217: $in{'curr_autharg'},$krbver);
3218: } else {
3219: $result =
3220: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
3221: }
3222: return $result;
3223: }
3224: }
3225: } else {
3226: if ($authnum == 1) {
3227: $authtype = '<input type="hidden" name="login" value="krb" />';
3228: }
3229: }
3230: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
3231: return;
3232: } elsif ($authtype eq '') {
3233: if (defined($in{'mode'})) {
3234: if ($in{'mode'} eq 'modifycourse') {
3235: if ($authnum == 1) {
3236: $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
3237: }
3238: }
3239: }
3240: }
3241: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
3242: if ($authtype eq '') {
3243: $authtype = '<input type="radio" name="login" value="krb" '.
3244: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
3245: $krbcheck.$disabled.' />';
3246: }
3247: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
3248: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
3249: $in{'curr_authtype'} eq 'krb5') ||
3250: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
3251: $in{'curr_authtype'} eq 'krb4')) {
3252: $result .= &mt
3253: ('[_1] Kerberos authenticated with domain [_2] '.
3254: '[_3] Version 4 [_4] Version 5 [_5]',
3255: '<label>'.$authtype,
3256: '</label><input type="text" size="10" name="krbarg" '.
3257: 'value="'.$krbarg.'" '.
3258: 'onchange="'.$jscall.'"'.$disabled.' />',
3259: '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
3260: '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
3261: '</label>');
3262: } elsif ($can_assign{'krb4'}) {
3263: $result .= &mt
3264: ('[_1] Kerberos authenticated with domain [_2] '.
3265: '[_3] Version 4 [_4]',
3266: '<label>'.$authtype,
3267: '</label><input type="text" size="10" name="krbarg" '.
3268: 'value="'.$krbarg.'" '.
3269: 'onchange="'.$jscall.'"'.$disabled.' />',
3270: '<label><input type="hidden" name="krbver" value="4" />',
3271: '</label>');
3272: } elsif ($can_assign{'krb5'}) {
3273: $result .= &mt
3274: ('[_1] Kerberos authenticated with domain [_2] '.
3275: '[_3] Version 5 [_4]',
3276: '<label>'.$authtype,
3277: '</label><input type="text" size="10" name="krbarg" '.
3278: 'value="'.$krbarg.'" '.
3279: 'onchange="'.$jscall.'"'.$disabled.' />',
3280: '<label><input type="hidden" name="krbver" value="5" />',
3281: '</label>');
3282: }
3283: return $result;
3284: }
3285:
3286: sub authform_internal {
3287: my %in = (
3288: formname => 'document.cu',
3289: kerb_def_dom => 'MSU.EDU',
3290: @_,
3291: );
3292: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
3293: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3294: if ($in{'readonly'}) {
3295: $disabled = ' disabled="disabled"';
3296: }
3297: if (defined($in{'curr_authtype'})) {
3298: if ($in{'curr_authtype'} eq 'int') {
3299: if ($can_assign{'int'}) {
3300: $intcheck = 'checked="checked" ';
3301: if (defined($in{'mode'})) {
3302: if ($in{'mode'} eq 'modifyuser') {
3303: $intcheck = '';
3304: }
3305: }
3306: if (defined($in{'curr_autharg'})) {
3307: $intarg = $in{'curr_autharg'};
3308: }
3309: } else {
3310: $result = &mt('Currently internally authenticated.');
3311: return $result;
3312: }
3313: }
3314: } else {
3315: if ($authnum == 1) {
3316: $authtype = '<input type="hidden" name="login" value="int" />';
3317: }
3318: }
3319: if (!$can_assign{'int'}) {
3320: return;
3321: } elsif ($authtype eq '') {
3322: if (defined($in{'mode'})) {
3323: if ($in{'mode'} eq 'modifycourse') {
3324: if ($authnum == 1) {
3325: $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
3326: }
3327: }
3328: }
3329: }
3330: $jscall = "javascript:changed_radio('int',$in{'formname'});";
3331: if ($authtype eq '') {
3332: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
3333: ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
3334: }
3335: $autharg = '<input type="password" size="10" name="intarg" value="'.
3336: $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3337: $result = &mt
3338: ('[_1] Internally authenticated (with initial password [_2])',
3339: '<label>'.$authtype,'</label>'.$autharg);
3340: $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>';
3341: return $result;
3342: }
3343:
3344: sub authform_local {
3345: my %in = (
3346: formname => 'document.cu',
3347: kerb_def_dom => 'MSU.EDU',
3348: @_,
3349: );
3350: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
3351: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3352: if ($in{'readonly'}) {
3353: $disabled = ' disabled="disabled"';
3354: }
3355: if (defined($in{'curr_authtype'})) {
3356: if ($in{'curr_authtype'} eq 'loc') {
3357: if ($can_assign{'loc'}) {
3358: $loccheck = 'checked="checked" ';
3359: if (defined($in{'mode'})) {
3360: if ($in{'mode'} eq 'modifyuser') {
3361: $loccheck = '';
3362: }
3363: }
3364: if (defined($in{'curr_autharg'})) {
3365: $locarg = $in{'curr_autharg'};
3366: }
3367: } else {
3368: $result = &mt('Currently using local (institutional) authentication.');
3369: return $result;
3370: }
3371: }
3372: } else {
3373: if ($authnum == 1) {
3374: $authtype = '<input type="hidden" name="login" value="loc" />';
3375: }
3376: }
3377: if (!$can_assign{'loc'}) {
3378: return;
3379: } elsif ($authtype eq '') {
3380: if (defined($in{'mode'})) {
3381: if ($in{'mode'} eq 'modifycourse') {
3382: if ($authnum == 1) {
3383: $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
3384: }
3385: }
3386: }
3387: }
3388: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
3389: if ($authtype eq '') {
3390: $authtype = '<input type="radio" name="login" value="loc" '.
3391: $loccheck.' onchange="'.$jscall.'" onclick="'.
3392: $jscall.'"'.$disabled.' />';
3393: }
3394: $autharg = '<input type="text" size="10" name="locarg" value="'.
3395: $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
3396: $result = &mt('[_1] Local Authentication with argument [_2]',
3397: '<label>'.$authtype,'</label>'.$autharg);
3398: return $result;
3399: }
3400:
3401: sub authform_filesystem {
3402: my %in = (
3403: formname => 'document.cu',
3404: kerb_def_dom => 'MSU.EDU',
3405: @_,
3406: );
3407: my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
3408: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3409: if ($in{'readonly'}) {
3410: $disabled = ' disabled="disabled"';
3411: }
3412: if (defined($in{'curr_authtype'})) {
3413: if ($in{'curr_authtype'} eq 'fsys') {
3414: if ($can_assign{'fsys'}) {
3415: $fsyscheck = 'checked="checked" ';
3416: if (defined($in{'mode'})) {
3417: if ($in{'mode'} eq 'modifyuser') {
3418: $fsyscheck = '';
3419: }
3420: }
3421: } else {
3422: $result = &mt('Currently Filesystem Authenticated.');
3423: return $result;
3424: }
3425: }
3426: } else {
3427: if ($authnum == 1) {
3428: $authtype = '<input type="hidden" name="login" value="fsys" />';
3429: }
3430: }
3431: if (!$can_assign{'fsys'}) {
3432: return;
3433: } elsif ($authtype eq '') {
3434: if (defined($in{'mode'})) {
3435: if ($in{'mode'} eq 'modifycourse') {
3436: if ($authnum == 1) {
3437: $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
3438: }
3439: }
3440: }
3441: }
3442: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
3443: if ($authtype eq '') {
3444: $authtype = '<input type="radio" name="login" value="fsys" '.
3445: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
3446: $jscall.'"'.$disabled.' />';
3447: }
3448: $autharg = '<input type="password" size="10" name="fsysarg" value=""'.
3449: ' onchange="'.$jscall.'"'.$disabled.' />';
3450: $result = &mt
3451: ('[_1] Filesystem Authenticated (with initial password [_2])',
3452: '<label>'.$authtype,'</label>'.$autharg);
3453: return $result;
3454: }
3455:
3456: sub authform_lti {
3457: my %in = (
3458: formname => 'document.cu',
3459: kerb_def_dom => 'MSU.EDU',
3460: @_,
3461: );
3462: my ($lticheck,$result,$authtype,$autharg,$jscall,$disabled);
3463: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3464: if ($in{'readonly'}) {
3465: $disabled = ' disabled="disabled"';
3466: }
3467: if (defined($in{'curr_authtype'})) {
3468: if ($in{'curr_authtype'} eq 'lti') {
3469: if ($can_assign{'lti'}) {
3470: $lticheck = 'checked="checked" ';
3471: if (defined($in{'mode'})) {
3472: if ($in{'mode'} eq 'modifyuser') {
3473: $lticheck = '';
3474: }
3475: }
3476: } else {
3477: $result = &mt('Currently LTI Authenticated.');
3478: return $result;
3479: }
3480: }
3481: } else {
3482: if ($authnum == 1) {
3483: $authtype = '<input type="hidden" name="login" value="lti" />';
3484: }
3485: }
3486: if (!$can_assign{'lti'}) {
3487: return;
3488: } elsif ($authtype eq '') {
3489: if (defined($in{'mode'})) {
3490: if ($in{'mode'} eq 'modifycourse') {
3491: if ($authnum == 1) {
3492: $authtype = '<input type="radio" name="login" value="lti"'.$disabled.' />';
3493: }
3494: }
3495: }
3496: }
3497: $jscall = "javascript:changed_radio('lti',$in{'formname'});";
3498: if (($authtype eq '') && (($in{'mode'} eq 'modifycourse') || ($in{'curr_authtype'} ne 'lti'))) {
3499: $authtype = '<input type="radio" name="login" value="lti" '.
3500: $lticheck.' onchange="'.$jscall.'" onclick="'.
3501: $jscall.'"'.$disabled.' />';
3502: }
3503: $autharg = '<input type="hidden" name="ltiarg" value="" />';
3504: if ($authtype) {
3505: $result = &mt('[_1] LTI Authenticated',
3506: '<label>'.$authtype.'</label>'.$autharg);
3507: } else {
3508: $result = '<b>'.&mt('LTI Authenticated').'</b>'.
3509: $autharg;
3510: }
3511: return $result;
3512: }
3513:
3514: sub get_assignable_auth {
3515: my ($dom) = @_;
3516: if ($dom eq '') {
3517: $dom = $env{'request.role.domain'};
3518: }
3519: my %can_assign = (
3520: krb4 => 1,
3521: krb5 => 1,
3522: int => 1,
3523: loc => 1,
3524: lti => 1,
3525: );
3526: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
3527: if (ref($domconfig{'usercreation'}) eq 'HASH') {
3528: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
3529: my $authhash = $domconfig{'usercreation'}{'authtypes'};
3530: my $context;
3531: if ($env{'request.role'} =~ /^au/) {
3532: $context = 'author';
3533: } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
3534: $context = 'domain';
3535: } elsif ($env{'request.course.id'}) {
3536: $context = 'course';
3537: }
3538: if ($context) {
3539: if (ref($authhash->{$context}) eq 'HASH') {
3540: %can_assign = %{$authhash->{$context}};
3541: }
3542: }
3543: }
3544: }
3545: my $authnum = 0;
3546: foreach my $key (keys(%can_assign)) {
3547: if ($can_assign{$key}) {
3548: $authnum ++;
3549: }
3550: }
3551: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
3552: $authnum --;
3553: }
3554: return ($authnum,%can_assign);
3555: }
3556:
3557: ###############################################################
3558: ## Get Kerberos Defaults for Domain ##
3559: ###############################################################
3560: ##
3561: ## Returns default kerberos version and an associated argument
3562: ## as listed in file domain.tab. If not listed, provides
3563: ## appropriate default domain and kerberos version.
3564: ##
3565: #-------------------------------------------
3566:
3567: =pod
3568:
3569: =item * &get_kerberos_defaults()
3570:
3571: get_kerberos_defaults($target_domain) returns the default kerberos
3572: version and domain. If not found, it defaults to version 4 and the
3573: domain of the server.
3574:
3575: =over 4
3576:
3577: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
3578:
3579: =back
3580:
3581: =back
3582:
3583: =cut
3584:
3585: #-------------------------------------------
3586: sub get_kerberos_defaults {
3587: my $domain=shift;
3588: my ($krbdef,$krbdefdom);
3589: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
3590: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
3591: $krbdef = $domdefaults{'auth_def'};
3592: $krbdefdom = $domdefaults{'auth_arg_def'};
3593: } else {
3594: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
3595: my $krbdefdom=$1;
3596: $krbdefdom=~tr/a-z/A-Z/;
3597: $krbdef = "krb4";
3598: }
3599: return ($krbdef,$krbdefdom);
3600: }
3601:
3602:
3603: ###############################################################
3604: ## Thesaurus Functions ##
3605: ###############################################################
3606:
3607: =pod
3608:
3609: =head1 Thesaurus Functions
3610:
3611: =over 4
3612:
3613: =item * &initialize_keywords()
3614:
3615: Initializes the package variable %Keywords if it is empty. Uses the
3616: package variable $thesaurus_db_file.
3617:
3618: =cut
3619:
3620: ###################################################
3621:
3622: sub initialize_keywords {
3623: return 1 if (scalar keys(%Keywords));
3624: # If we are here, %Keywords is empty, so fill it up
3625: # Make sure the file we need exists...
3626: if (! -e $thesaurus_db_file) {
3627: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
3628: " failed because it does not exist");
3629: return 0;
3630: }
3631: # Set up the hash as a database
3632: my %thesaurus_db;
3633: if (! tie(%thesaurus_db,'GDBM_File',
3634: $thesaurus_db_file,&GDBM_READER(),0640)){
3635: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
3636: $thesaurus_db_file);
3637: return 0;
3638: }
3639: # Get the average number of appearances of a word.
3640: my $avecount = $thesaurus_db{'average.count'};
3641: # Put keywords (those that appear > average) into %Keywords
3642: while (my ($word,$data)=each (%thesaurus_db)) {
3643: my ($count,undef) = split /:/,$data;
3644: $Keywords{$word}++ if ($count > $avecount);
3645: }
3646: untie %thesaurus_db;
3647: # Remove special values from %Keywords.
3648: foreach my $value ('total.count','average.count') {
3649: delete($Keywords{$value}) if (exists($Keywords{$value}));
3650: }
3651: return 1;
3652: }
3653:
3654: ###################################################
3655:
3656: =pod
3657:
3658: =item * &keyword($word)
3659:
3660: Returns true if $word is a keyword. A keyword is a word that appears more
3661: than the average number of times in the thesaurus database. Calls
3662: &initialize_keywords
3663:
3664: =cut
3665:
3666: ###################################################
3667:
3668: sub keyword {
3669: return if (!&initialize_keywords());
3670: my $word=lc(shift());
3671: $word=~s/\W//g;
3672: return exists($Keywords{$word});
3673: }
3674:
3675: ###############################################################
3676:
3677: =pod
3678:
3679: =item * &get_related_words()
3680:
3681: Look up a word in the thesaurus. Takes a scalar argument and returns
3682: an array of words. If the keyword is not in the thesaurus, an empty array
3683: will be returned. The order of the words returned is determined by the
3684: database which holds them.
3685:
3686: Uses global $thesaurus_db_file.
3687:
3688:
3689: =cut
3690:
3691: ###############################################################
3692: sub get_related_words {
3693: my $keyword = shift;
3694: my %thesaurus_db;
3695: if (! -e $thesaurus_db_file) {
3696: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
3697: "failed because the file does not exist");
3698: return ();
3699: }
3700: if (! tie(%thesaurus_db,'GDBM_File',
3701: $thesaurus_db_file,&GDBM_READER(),0640)){
3702: return ();
3703: }
3704: my @Words=();
3705: my $count=0;
3706: if (exists($thesaurus_db{$keyword})) {
3707: # The first element is the number of times
3708: # the word appears. We do not need it now.
3709: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
3710: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
3711: my $threshold=$mostfrequentcount/10;
3712: foreach my $possibleword (@RelatedWords) {
3713: my ($word,$wordcount)=split(/\,/,$possibleword);
3714: if ($wordcount>$threshold) {
3715: push(@Words,$word);
3716: $count++;
3717: if ($count>10) { last; }
3718: }
3719: }
3720: }
3721: untie %thesaurus_db;
3722: return @Words;
3723: }
3724: ###############################################################
3725: #
3726: # Spell checking
3727: #
3728:
3729: =pod
3730:
3731: =back
3732:
3733: =head1 Spell checking
3734:
3735: =over 4
3736:
3737: =item * &check_spelling($wordlist $language)
3738:
3739: Takes a string containing words and feeds it to an external
3740: spellcheck program via a pipeline. Returns a string containing
3741: them mis-spelled words.
3742:
3743: Parameters:
3744:
3745: =over 4
3746:
3747: =item - $wordlist
3748:
3749: String that will be fed into the spellcheck program.
3750:
3751: =item - $language
3752:
3753: Language string that specifies the language for which the spell
3754: check will be performed.
3755:
3756: =back
3757:
3758: =back
3759:
3760: Note: This sub assumes that aspell is installed.
3761:
3762:
3763: =cut
3764:
3765:
3766: sub check_spelling {
3767: my ($wordlist, $language) = @_;
3768: my @misspellings;
3769:
3770: # Generate the speller and set the langauge.
3771: # if explicitly selected:
3772:
3773: my $speller = Text::Aspell->new;
3774: if ($language) {
3775: $speller->set_option('lang', $language);
3776: }
3777:
3778: # Turn the word list into an array of words by splittingon whitespace
3779:
3780: my @words = split(/\s+/, $wordlist);
3781:
3782: foreach my $word (@words) {
3783: if(! $speller->check($word)) {
3784: push(@misspellings, $word);
3785: }
3786: }
3787: return join(' ', @misspellings);
3788:
3789: }
3790:
3791: # -------------------------------------------------------------- Plaintext name
3792: =pod
3793:
3794: =head1 User Name Functions
3795:
3796: =over 4
3797:
3798: =item * &plainname($uname,$udom,$first)
3799:
3800: Takes a users logon name and returns it as a string in
3801: "first middle last generation" form
3802: if $first is set to 'lastname' then it returns it as
3803: 'lastname generation, firstname middlename' if their is a lastname
3804:
3805: =cut
3806:
3807:
3808: ###############################################################
3809: sub plainname {
3810: my ($uname,$udom,$first)=@_;
3811: return if (!defined($uname) || !defined($udom));
3812: my %names=&getnames($uname,$udom);
3813: my $name=&Apache::lonnet::format_name($names{'firstname'},
3814: $names{'middlename'},
3815: $names{'lastname'},
3816: $names{'generation'},$first);
3817: $name=~s/^\s+//;
3818: $name=~s/\s+$//;
3819: $name=~s/\s+/ /g;
3820: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
3821: return $name;
3822: }
3823:
3824: # -------------------------------------------------------------------- Nickname
3825: =pod
3826:
3827: =item * &nickname($uname,$udom)
3828:
3829: Gets a users name and returns it as a string as
3830:
3831: ""nickname""
3832:
3833: if the user has a nickname or
3834:
3835: "first middle last generation"
3836:
3837: if the user does not
3838:
3839: =cut
3840:
3841: sub nickname {
3842: my ($uname,$udom)=@_;
3843: return if (!defined($uname) || !defined($udom));
3844: my %names=&getnames($uname,$udom);
3845: my $name=$names{'nickname'};
3846: if ($name) {
3847: $name='"'.$name.'"';
3848: } else {
3849: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
3850: $names{'lastname'}.' '.$names{'generation'};
3851: $name=~s/\s+$//;
3852: $name=~s/\s+/ /g;
3853: }
3854: return $name;
3855: }
3856:
3857: sub getnames {
3858: my ($uname,$udom)=@_;
3859: return if (!defined($uname) || !defined($udom));
3860: if ($udom eq 'public' && $uname eq 'public') {
3861: return ('lastname' => &mt('Public'));
3862: }
3863: my $id=$uname.':'.$udom;
3864: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
3865: if ($cached) {
3866: return %{$names};
3867: } else {
3868: my %loadnames=&Apache::lonnet::get('environment',
3869: ['firstname','middlename','lastname','generation','nickname'],
3870: $udom,$uname);
3871: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
3872: return %loadnames;
3873: }
3874: }
3875:
3876: # -------------------------------------------------------------------- getemails
3877:
3878: =pod
3879:
3880: =item * &getemails($uname,$udom)
3881:
3882: Gets a user's email information and returns it as a hash with keys:
3883: notification, critnotification, permanentemail
3884:
3885: For notification and critnotification, values are comma-separated lists
3886: of e-mail addresses; for permanentemail, value is a single e-mail address.
3887:
3888:
3889: =cut
3890:
3891:
3892: sub getemails {
3893: my ($uname,$udom)=@_;
3894: if ($udom eq 'public' && $uname eq 'public') {
3895: return;
3896: }
3897: if (!$udom) { $udom=$env{'user.domain'}; }
3898: if (!$uname) { $uname=$env{'user.name'}; }
3899: my $id=$uname.':'.$udom;
3900: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
3901: if ($cached) {
3902: return %{$names};
3903: } else {
3904: my %loadnames=&Apache::lonnet::get('environment',
3905: ['notification','critnotification',
3906: 'permanentemail'],
3907: $udom,$uname);
3908: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
3909: return %loadnames;
3910: }
3911: }
3912:
3913: sub flush_email_cache {
3914: my ($uname,$udom)=@_;
3915: if (!$udom) { $udom =$env{'user.domain'}; }
3916: if (!$uname) { $uname=$env{'user.name'}; }
3917: return if ($udom eq 'public' && $uname eq 'public');
3918: my $id=$uname.':'.$udom;
3919: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
3920: }
3921:
3922: # -------------------------------------------------------------------- getlangs
3923:
3924: =pod
3925:
3926: =item * &getlangs($uname,$udom)
3927:
3928: Gets a user's language preference and returns it as a hash with key:
3929: language.
3930:
3931: =cut
3932:
3933:
3934: sub getlangs {
3935: my ($uname,$udom) = @_;
3936: if (!$udom) { $udom =$env{'user.domain'}; }
3937: if (!$uname) { $uname=$env{'user.name'}; }
3938: my $id=$uname.':'.$udom;
3939: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
3940: if ($cached) {
3941: return %{$langs};
3942: } else {
3943: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
3944: $udom,$uname);
3945: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
3946: return %loadlangs;
3947: }
3948: }
3949:
3950: sub flush_langs_cache {
3951: my ($uname,$udom)=@_;
3952: if (!$udom) { $udom =$env{'user.domain'}; }
3953: if (!$uname) { $uname=$env{'user.name'}; }
3954: return if ($udom eq 'public' && $uname eq 'public');
3955: my $id=$uname.':'.$udom;
3956: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
3957: }
3958:
3959: # ------------------------------------------------------------------ Screenname
3960:
3961: =pod
3962:
3963: =item * &screenname($uname,$udom)
3964:
3965: Gets a users screenname and returns it as a string
3966:
3967: =cut
3968:
3969: sub screenname {
3970: my ($uname,$udom)=@_;
3971: if ($uname eq $env{'user.name'} &&
3972: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
3973: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
3974: return $names{'screenname'};
3975: }
3976:
3977:
3978: # ------------------------------------------------------------- Confirm Wrapper
3979: =pod
3980:
3981: =item * &confirmwrapper($message)
3982:
3983: Wrap messages about completion of operation in box
3984:
3985: =cut
3986:
3987: sub confirmwrapper {
3988: my ($message)=@_;
3989: if ($message) {
3990: return "\n".'<div class="LC_confirm_box">'."\n"
3991: .$message."\n"
3992: .'</div>'."\n";
3993: } else {
3994: return $message;
3995: }
3996: }
3997:
3998: # ------------------------------------------------------------- Message Wrapper
3999:
4000: sub messagewrapper {
4001: my ($link,$username,$domain,$subject,$text)=@_;
4002: return
4003: '<a href="/adm/email?compose=individual&'.
4004: 'recname='.$username.'&recdom='.$domain.
4005: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
4006: 'title="'.&mt('Send message').'">'.$link.'</a>';
4007: }
4008:
4009: # --------------------------------------------------------------- Notes Wrapper
4010:
4011: sub noteswrapper {
4012: my ($link,$un,$do)=@_;
4013: return
4014: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
4015: }
4016:
4017: # ------------------------------------------------------------- Aboutme Wrapper
4018:
4019: sub aboutmewrapper {
4020: my ($link,$username,$domain,$target,$class)=@_;
4021: if (!defined($username) && !defined($domain)) {
4022: return;
4023: }
4024: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
4025: ($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
4026: }
4027:
4028: # ------------------------------------------------------------ Syllabus Wrapper
4029:
4030: sub syllabuswrapper {
4031: my ($linktext,$coursedir,$domain)=@_;
4032: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
4033: }
4034:
4035: # -----------------------------------------------------------------------------
4036:
4037: sub track_student_link {
4038: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
4039: my $link ="/adm/trackstudent?";
4040: my $title = 'View recent activity';
4041: if (defined($sname) && $sname !~ /^\s*$/ &&
4042: defined($sdom) && $sdom !~ /^\s*$/) {
4043: $link .= "selected_student=$sname:$sdom";
4044: $title .= ' of this student';
4045: }
4046: if (defined($target) && $target !~ /^\s*$/) {
4047: $target = qq{target="$target"};
4048: } else {
4049: $target = '';
4050: }
4051: if ($start) { $link.='&start='.$start; }
4052: if ($only_body) { $link .= '&only_body=1'; }
4053: $title = &mt($title);
4054: $linktext = &mt($linktext);
4055: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
4056: &help_open_topic('View_recent_activity');
4057: }
4058:
4059: sub slot_reservations_link {
4060: my ($linktext,$sname,$sdom,$target) = @_;
4061: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
4062: my $title = 'View slot reservation history';
4063: if (defined($sname) && $sname !~ /^\s*$/ &&
4064: defined($sdom) && $sdom !~ /^\s*$/) {
4065: $link .= "&uname=$sname&udom=$sdom";
4066: $title .= ' of this student';
4067: }
4068: if (defined($target) && $target !~ /^\s*$/) {
4069: $target = qq{target="$target"};
4070: } else {
4071: $target = '';
4072: }
4073: $title = &mt($title);
4074: $linktext = &mt($linktext);
4075: return qq{<a href="$link" title="$title" $target>$linktext</a>};
4076: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
4077:
4078: }
4079:
4080: # ===================================================== Display a student photo
4081:
4082:
4083: sub student_image_tag {
4084: my ($domain,$user)=@_;
4085: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
4086: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
4087: return '<img src="'.$imgsrc.'" align="right" />';
4088: } else {
4089: return '';
4090: }
4091: }
4092:
4093: =pod
4094:
4095: =back
4096:
4097: =head1 Access .tab File Data
4098:
4099: =over 4
4100:
4101: =item * &languageids()
4102:
4103: returns list of all language ids
4104:
4105: =cut
4106:
4107: sub languageids {
4108: return sort(keys(%language));
4109: }
4110:
4111: =pod
4112:
4113: =item * &languagedescription()
4114:
4115: returns description of a specified language id
4116:
4117: =cut
4118:
4119: sub languagedescription {
4120: my $code=shift;
4121: return ($supported_language{$code}?'* ':'').
4122: $language{$code}.
4123: ($supported_language{$code}?' ('.&mt('interface available').')':'');
4124: }
4125:
4126: =pod
4127:
4128: =item * &plainlanguagedescription
4129:
4130: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
4131: and the language character encoding (e.g. ISO) separated by a ' - ' string.
4132:
4133: =cut
4134:
4135: sub plainlanguagedescription {
4136: my $code=shift;
4137: return $language{$code};
4138: }
4139:
4140: =pod
4141:
4142: =item * &supportedlanguagecode
4143:
4144: Returns the supported language code (e.g. sptutf maps to pt) given a language
4145: code.
4146:
4147: =cut
4148:
4149: sub supportedlanguagecode {
4150: my $code=shift;
4151: return $supported_language{$code};
4152: }
4153:
4154: =pod
4155:
4156: =item * &latexlanguage()
4157:
4158: Given a language key code returns the correspondnig language to use
4159: to select the correct hyphenation on LaTeX printouts. This is undef if there
4160: is no supported hyphenation for the language code.
4161:
4162: =cut
4163:
4164: sub latexlanguage {
4165: my $code = shift;
4166: return $latex_language{$code};
4167: }
4168:
4169: =pod
4170:
4171: =item * &latexhyphenation()
4172:
4173: Same as above but what's supplied is the language as it might be stored
4174: in the metadata.
4175:
4176: =cut
4177:
4178: sub latexhyphenation {
4179: my $key = shift;
4180: return $latex_language_bykey{$key};
4181: }
4182:
4183: =pod
4184:
4185: =item * ©rightids()
4186:
4187: returns list of all copyrights
4188:
4189: =cut
4190:
4191: sub copyrightids {
4192: return sort(keys(%cprtag));
4193: }
4194:
4195: =pod
4196:
4197: =item * ©rightdescription()
4198:
4199: returns description of a specified copyright id
4200:
4201: =cut
4202:
4203: sub copyrightdescription {
4204: return &mt($cprtag{shift(@_)});
4205: }
4206:
4207: =pod
4208:
4209: =item * &source_copyrightids()
4210:
4211: returns list of all source copyrights
4212:
4213: =cut
4214:
4215: sub source_copyrightids {
4216: return sort(keys(%scprtag));
4217: }
4218:
4219: =pod
4220:
4221: =item * &source_copyrightdescription()
4222:
4223: returns description of a specified source copyright id
4224:
4225: =cut
4226:
4227: sub source_copyrightdescription {
4228: return &mt($scprtag{shift(@_)});
4229: }
4230:
4231: =pod
4232:
4233: =item * &filecategories()
4234:
4235: returns list of all file categories
4236:
4237: =cut
4238:
4239: sub filecategories {
4240: return sort(keys(%category_extensions));
4241: }
4242:
4243: =pod
4244:
4245: =item * &filecategorytypes()
4246:
4247: returns list of file types belonging to a given file
4248: category
4249:
4250: =cut
4251:
4252: sub filecategorytypes {
4253: my ($cat) = @_;
4254: if (ref($category_extensions{lc($cat)}) eq 'ARRAY') {
4255: return @{$category_extensions{lc($cat)}};
4256: } else {
4257: return ();
4258: }
4259: }
4260:
4261: =pod
4262:
4263: =item * &fileembstyle()
4264:
4265: returns embedding style for a specified file type
4266:
4267: =cut
4268:
4269: sub fileembstyle {
4270: return $fe{lc(shift(@_))};
4271: }
4272:
4273: sub filemimetype {
4274: return $fm{lc(shift(@_))};
4275: }
4276:
4277:
4278: sub filecategoryselect {
4279: my ($name,$value)=@_;
4280: return &select_form($value,$name,
4281: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
4282: }
4283:
4284: =pod
4285:
4286: =item * &filedescription()
4287:
4288: returns description for a specified file type
4289:
4290: =cut
4291:
4292: sub filedescription {
4293: my $file_description = $fd{lc(shift())};
4294: $file_description =~ s:([\[\]]):~$1:g;
4295: return &mt($file_description);
4296: }
4297:
4298: =pod
4299:
4300: =item * &filedescriptionex()
4301:
4302: returns description for a specified file type with
4303: extra formatting
4304:
4305: =cut
4306:
4307: sub filedescriptionex {
4308: my $ex=shift;
4309: my $file_description = $fd{lc($ex)};
4310: $file_description =~ s:([\[\]]):~$1:g;
4311: return '.'.$ex.' '.&mt($file_description);
4312: }
4313:
4314: # End of .tab access
4315: =pod
4316:
4317: =back
4318:
4319: =cut
4320:
4321: # ------------------------------------------------------------------ File Types
4322: sub fileextensions {
4323: return sort(keys(%fe));
4324: }
4325:
4326: # ----------------------------------------------------------- Display Languages
4327: # returns a hash with all desired display languages
4328: #
4329:
4330: sub display_languages {
4331: my %languages=();
4332: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
4333: $languages{$lang}=1;
4334: }
4335: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
4336: if ($env{'form.displaylanguage'}) {
4337: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
4338: $languages{$lang}=1;
4339: }
4340: }
4341: return %languages;
4342: }
4343:
4344: sub languages {
4345: my ($possible_langs) = @_;
4346: my @preferred_langs = &Apache::lonlocal::preferred_languages();
4347: if (!ref($possible_langs)) {
4348: if( wantarray ) {
4349: return @preferred_langs;
4350: } else {
4351: return $preferred_langs[0];
4352: }
4353: }
4354: my %possibilities = map { $_ => 1 } (@$possible_langs);
4355: my @preferred_possibilities;
4356: foreach my $preferred_lang (@preferred_langs) {
4357: if (exists($possibilities{$preferred_lang})) {
4358: push(@preferred_possibilities, $preferred_lang);
4359: }
4360: }
4361: if( wantarray ) {
4362: return @preferred_possibilities;
4363: }
4364: return $preferred_possibilities[0];
4365: }
4366:
4367: sub user_lang {
4368: my ($touname,$toudom,$fromcid) = @_;
4369: my @userlangs;
4370: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
4371: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
4372: $env{'course.'.$fromcid.'.languages'}));
4373: } else {
4374: my %langhash = &getlangs($touname,$toudom);
4375: if ($langhash{'languages'} ne '') {
4376: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
4377: } else {
4378: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
4379: if ($domdefs{'lang_def'} ne '') {
4380: @userlangs = ($domdefs{'lang_def'});
4381: }
4382: }
4383: }
4384: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
4385: my $user_lh = Apache::localize->get_handle(@languages);
4386: return $user_lh;
4387: }
4388:
4389:
4390: ###############################################################
4391: ## Student Answer Attempts ##
4392: ###############################################################
4393:
4394: =pod
4395:
4396: =head1 Alternate Problem Views
4397:
4398: =over 4
4399:
4400: =item * &get_previous_attempt($symb, $username, $domain, $course,
4401: $getattempt, $regexp, $gradesub, $usec, $identifier)
4402:
4403: Return string with previous attempt on problem. Arguments:
4404:
4405: =over 4
4406:
4407: =item * $symb: Problem, including path
4408:
4409: =item * $username: username of the desired student
4410:
4411: =item * $domain: domain of the desired student
4412:
4413: =item * $course: Course ID
4414:
4415: =item * $getattempt: Leave blank for all attempts, otherwise put
4416: something
4417:
4418: =item * $regexp: if string matches this regexp, the string will be
4419: sent to $gradesub
4420:
4421: =item * $gradesub: routine that processes the string if it matches $regexp
4422:
4423: =item * $usec: section of the desired student
4424:
4425: =item * $identifier: counter for student (multiple students one problem) or
4426: problem (one student; whole sequence).
4427:
4428: =back
4429:
4430: The output string is a table containing all desired attempts, if any.
4431:
4432: =cut
4433:
4434: sub get_previous_attempt {
4435: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
4436: my $prevattempts='';
4437: no strict 'refs';
4438: if ($symb) {
4439: my (%returnhash)=
4440: &Apache::lonnet::restore($symb,$course,$domain,$username);
4441: if ($returnhash{'version'}) {
4442: my %lasthash=();
4443: my $version;
4444: for ($version=1;$version<=$returnhash{'version'};$version++) {
4445: foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
4446: if ($key =~ /\.rawrndseed$/) {
4447: my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
4448: $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
4449: } else {
4450: $lasthash{$key}=$returnhash{$version.':'.$key};
4451: }
4452: }
4453: }
4454: $prevattempts=&start_data_table().&start_data_table_header_row();
4455: $prevattempts.='<th>'.&mt('History').'</th>';
4456: my (%typeparts,%lasthidden,%regraded,%hidestatus);
4457: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
4458: foreach my $key (sort(keys(%lasthash))) {
4459: my ($ign,@parts) = split(/\./,$key);
4460: if ($#parts > 0) {
4461: my $data=$parts[-1];
4462: next if ($data eq 'foilorder');
4463: pop(@parts);
4464: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
4465: if ($data eq 'type') {
4466: unless ($showsurv) {
4467: my $id = join(',',@parts);
4468: $typeparts{$ign.'.'.$id} = $lasthash{$key};
4469: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
4470: $lasthidden{$ign.'.'.$id} = 1;
4471: }
4472: }
4473: if ($identifier ne '') {
4474: my $id = join(',',@parts);
4475: if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
4476: $domain,$username,$usec,undef,$course) =~ /^no/) {
4477: $hidestatus{$ign.'.'.$id} = 1;
4478: }
4479: }
4480: } elsif ($data eq 'regrader') {
4481: if (($identifier ne '') && (@parts)) {
4482: my $id = join(',',@parts);
4483: $regraded{$ign.'.'.$id} = 1;
4484: }
4485: }
4486: } else {
4487: if ($#parts == 0) {
4488: $prevattempts.='<th>'.$parts[0].'</th>';
4489: } else {
4490: $prevattempts.='<th>'.$ign.'</th>';
4491: }
4492: }
4493: }
4494: $prevattempts.=&end_data_table_header_row();
4495: if ($getattempt eq '') {
4496: my (%solved,%resets,%probstatus);
4497: if (($identifier ne '') && (keys(%regraded) > 0)) {
4498: for ($version=1;$version<=$returnhash{'version'};$version++) {
4499: foreach my $id (keys(%regraded)) {
4500: if (($returnhash{$version.':'.$id.'.regrader'}) &&
4501: ($returnhash{$version.':'.$id.'.tries'} eq '') &&
4502: ($returnhash{$version.':'.$id.'.award'} eq '')) {
4503: push(@{$resets{$id}},$version);
4504: }
4505: }
4506: }
4507: }
4508: for ($version=1;$version<=$returnhash{'version'};$version++) {
4509: my (@hidden,@unsolved);
4510: if (%typeparts) {
4511: foreach my $id (keys(%typeparts)) {
4512: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
4513: ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
4514: push(@hidden,$id);
4515: } elsif ($identifier ne '') {
4516: unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
4517: ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
4518: ($hidestatus{$id})) {
4519: next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
4520: if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
4521: push(@{$solved{$id}},$version);
4522: } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
4523: (ref($solved{$id}) eq 'ARRAY')) {
4524: my $skip;
4525: if (ref($resets{$id}) eq 'ARRAY') {
4526: foreach my $reset (@{$resets{$id}}) {
4527: if ($reset > $solved{$id}[-1]) {
4528: $skip=1;
4529: last;
4530: }
4531: }
4532: }
4533: unless ($skip) {
4534: my ($ign,$partslist) = split(/\./,$id,2);
4535: push(@unsolved,$partslist);
4536: }
4537: }
4538: }
4539: }
4540: }
4541: }
4542: $prevattempts.=&start_data_table_row().
4543: '<td>'.&mt('Transaction [_1]',$version);
4544: if (@unsolved) {
4545: $prevattempts .= '<span class="LC_nobreak"><label>'.
4546: '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
4547: &mt('Hide').'</label></span>';
4548: }
4549: $prevattempts .= '</td>';
4550: if (@hidden) {
4551: foreach my $key (sort(keys(%lasthash))) {
4552: next if ($key =~ /\.foilorder$/);
4553: my $hide;
4554: foreach my $id (@hidden) {
4555: if ($key =~ /^\Q$id\E/) {
4556: $hide = 1;
4557: last;
4558: }
4559: }
4560: if ($hide) {
4561: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4562: if (($data eq 'award') || ($data eq 'awarddetail')) {
4563: my $value = &format_previous_attempt_value($key,
4564: $returnhash{$version.':'.$key});
4565: $prevattempts.='<td>'.$value.' </td>';
4566: } else {
4567: $prevattempts.='<td> </td>';
4568: }
4569: } else {
4570: if ($key =~ /\./) {
4571: my $value = $returnhash{$version.':'.$key};
4572: if ($key =~ /\.rndseed$/) {
4573: my ($id) = ($key =~ /^(.+)\.[^.]+$/);
4574: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4575: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4576: }
4577: }
4578: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4579: ' </td>';
4580: } else {
4581: $prevattempts.='<td> </td>';
4582: }
4583: }
4584: }
4585: } else {
4586: foreach my $key (sort(keys(%lasthash))) {
4587: next if ($key =~ /\.foilorder$/);
4588: my $value = $returnhash{$version.':'.$key};
4589: if ($key =~ /\.rndseed$/) {
4590: my ($id) = ($key =~ /^(.+)\.[^.]+$/);
4591: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4592: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4593: }
4594: }
4595: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4596: ' </td>';
4597: }
4598: }
4599: $prevattempts.=&end_data_table_row();
4600: }
4601: }
4602: my @currhidden = keys(%lasthidden);
4603: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
4604: foreach my $key (sort(keys(%lasthash))) {
4605: next if ($key =~ /\.foilorder$/);
4606: if (%typeparts) {
4607: my $hidden;
4608: foreach my $id (@currhidden) {
4609: if ($key =~ /^\Q$id\E/) {
4610: $hidden = 1;
4611: last;
4612: }
4613: }
4614: if ($hidden) {
4615: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4616: if (($data eq 'award') || ($data eq 'awarddetail')) {
4617: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4618: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4619: $value = &$gradesub($value);
4620: }
4621: $prevattempts.='<td>'. $value.' </td>';
4622: } else {
4623: $prevattempts.='<td> </td>';
4624: }
4625: } else {
4626: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4627: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4628: $value = &$gradesub($value);
4629: }
4630: $prevattempts.='<td>'.$value.' </td>';
4631: }
4632: } else {
4633: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4634: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4635: $value = &$gradesub($value);
4636: }
4637: $prevattempts.='<td>'.$value.' </td>';
4638: }
4639: }
4640: $prevattempts.= &end_data_table_row().&end_data_table();
4641: } else {
4642: my $msg;
4643: if ($symb =~ /ext\.tool$/) {
4644: $msg = &mt('No grade passed back.');
4645: } else {
4646: $msg = &mt('Nothing submitted - no attempts.');
4647: }
4648: $prevattempts=
4649: &start_data_table().&start_data_table_row().
4650: '<td>'.$msg.'</td>'.
4651: &end_data_table_row().&end_data_table();
4652: }
4653: } else {
4654: $prevattempts=
4655: &start_data_table().&start_data_table_row().
4656: '<td>'.&mt('No data.').'</td>'.
4657: &end_data_table_row().&end_data_table();
4658: }
4659: }
4660:
4661: sub format_previous_attempt_value {
4662: my ($key,$value) = @_;
4663: if (($key =~ /timestamp/) || ($key=~/duedate/)) {
4664: $value = &Apache::lonlocal::locallocaltime($value);
4665: } elsif (ref($value) eq 'ARRAY') {
4666: $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
4667: } elsif ($key =~ /answerstring$/) {
4668: my %answers = &Apache::lonnet::str2hash($value);
4669: my @answer = %answers;
4670: %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
4671: my @anskeys = sort(keys(%answers));
4672: if (@anskeys == 1) {
4673: my $answer = $answers{$anskeys[0]};
4674: if ($answer =~ m{\0}) {
4675: $answer =~ s{\0}{,}g;
4676: }
4677: my $tag_internal_answer_name = 'INTERNAL';
4678: if ($anskeys[0] eq $tag_internal_answer_name) {
4679: $value = $answer;
4680: } else {
4681: $value = $anskeys[0].'='.$answer;
4682: }
4683: } else {
4684: foreach my $ans (@anskeys) {
4685: my $answer = $answers{$ans};
4686: if ($answer =~ m{\0}) {
4687: $answer =~ s{\0}{,}g;
4688: }
4689: $value .= $ans.'='.$answer.'<br />';;
4690: }
4691: }
4692: } else {
4693: $value = &HTML::Entities::encode(&unescape($value), '"<>&');
4694: }
4695: return $value;
4696: }
4697:
4698:
4699: sub relative_to_absolute {
4700: my ($url,$output)=@_;
4701: my $parser=HTML::TokeParser->new(\$output);
4702: my $token;
4703: my $thisdir=$url;
4704: my @rlinks=();
4705: while ($token=$parser->get_token) {
4706: if ($token->[0] eq 'S') {
4707: if ($token->[1] eq 'a') {
4708: if ($token->[2]->{'href'}) {
4709: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
4710: }
4711: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
4712: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
4713: } elsif ($token->[1] eq 'base') {
4714: $thisdir=$token->[2]->{'href'};
4715: }
4716: }
4717: }
4718: $thisdir=~s-/[^/]*$--;
4719: foreach my $link (@rlinks) {
4720: unless (($link=~/^https?\:\/\//i) ||
4721: ($link=~/^\//) ||
4722: ($link=~/^javascript:/i) ||
4723: ($link=~/^mailto:/i) ||
4724: ($link=~/^\#/)) {
4725: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
4726: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
4727: }
4728: }
4729: # -------------------------------------------------- Deal with Applet codebases
4730: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
4731: return $output;
4732: }
4733:
4734: =pod
4735:
4736: =item * &get_student_view()
4737:
4738: show a snapshot of what student was looking at
4739:
4740: =cut
4741:
4742: sub get_student_view {
4743: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
4744: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4745: my (%form);
4746: my @elements=('symb','courseid','domain','username');
4747: foreach my $element (@elements) {
4748: $form{'grade_'.$element}=eval '$'.$element #'
4749: }
4750: if (defined($moreenv)) {
4751: %form=(%form,%{$moreenv});
4752: }
4753: if (defined($target)) { $form{'grade_target'} = $target; }
4754: $feedurl=&Apache::lonnet::clutter($feedurl);
4755: if (($feedurl =~ /ext\.tool$/) && ($target eq 'tex')) {
4756: $feedurl =~ s{^/adm/wrapper}{};
4757: }
4758: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
4759: $userview=~s/\<body[^\>]*\>//gi;
4760: $userview=~s/\<\/body\>//gi;
4761: $userview=~s/\<html\>//gi;
4762: $userview=~s/\<\/html\>//gi;
4763: $userview=~s/\<head\>//gi;
4764: $userview=~s/\<\/head\>//gi;
4765: $userview=~s/action\s*\=/would_be_action\=/gi;
4766: $userview=&relative_to_absolute($feedurl,$userview);
4767: if (wantarray) {
4768: return ($userview,$response);
4769: } else {
4770: return $userview;
4771: }
4772: }
4773:
4774: sub get_student_view_with_retries {
4775: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
4776:
4777: my $ok = 0; # True if we got a good response.
4778: my $content;
4779: my $response;
4780:
4781: # Try to get the student_view done. within the retries count:
4782:
4783: do {
4784: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
4785: $ok = $response->is_success;
4786: if (!$ok) {
4787: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
4788: }
4789: $retries--;
4790: } while (!$ok && ($retries > 0));
4791:
4792: if (!$ok) {
4793: $content = ''; # On error return an empty content.
4794: }
4795: if (wantarray) {
4796: return ($content, $response);
4797: } else {
4798: return $content;
4799: }
4800: }
4801:
4802: =pod
4803:
4804: =item * &get_student_answers()
4805:
4806: show a snapshot of how student was answering problem
4807:
4808: =cut
4809:
4810: sub get_student_answers {
4811: my ($symb,$username,$domain,$courseid,%form) = @_;
4812: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4813: my (%moreenv);
4814: my @elements=('symb','courseid','domain','username');
4815: foreach my $element (@elements) {
4816: $moreenv{'grade_'.$element}=eval '$'.$element #'
4817: }
4818: $moreenv{'grade_target'}='answer';
4819: %moreenv=(%form,%moreenv);
4820: $feedurl = &Apache::lonnet::clutter($feedurl);
4821: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
4822: return $userview;
4823: }
4824:
4825: =pod
4826:
4827: =item * &submlink()
4828:
4829: Inputs: $text $uname $udom $symb $target
4830:
4831: Returns: A link to grades.pm such as to see the SUBM view of a student
4832:
4833: =cut
4834:
4835: ###############################################
4836: sub submlink {
4837: my ($text,$uname,$udom,$symb,$target)=@_;
4838: if (!($uname && $udom)) {
4839: (my $cursymb, my $courseid,$udom,$uname)=
4840: &Apache::lonnet::whichuser($symb);
4841: if (!$symb) { $symb=$cursymb; }
4842: }
4843: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4844: $symb=&escape($symb);
4845: if ($target) { $target=" target=\"$target\""; }
4846: return
4847: '<a href="/adm/grades?command=submission'.
4848: '&symb='.$symb.
4849: '&student='.$uname.
4850: '&userdom='.$udom.'"'.
4851: $target.'>'.$text.'</a>';
4852: }
4853: ##############################################
4854:
4855: =pod
4856:
4857: =item * &pgrdlink()
4858:
4859: Inputs: $text $uname $udom $symb $target
4860:
4861: Returns: A link to grades.pm such as to see the PGRD view of a student
4862:
4863: =cut
4864:
4865: ###############################################
4866: sub pgrdlink {
4867: my $link=&submlink(@_);
4868: $link=~s/(&command=submission)/$1&showgrading=yes/;
4869: return $link;
4870: }
4871: ##############################################
4872:
4873: =pod
4874:
4875: =item * &pprmlink()
4876:
4877: Inputs: $text $uname $udom $symb $target
4878:
4879: Returns: A link to parmset.pm such as to see the PPRM view of a
4880: student and a specific resource
4881:
4882: =cut
4883:
4884: ###############################################
4885: sub pprmlink {
4886: my ($text,$uname,$udom,$symb,$target)=@_;
4887: if (!($uname && $udom)) {
4888: (my $cursymb, my $courseid,$udom,$uname)=
4889: &Apache::lonnet::whichuser($symb);
4890: if (!$symb) { $symb=$cursymb; }
4891: }
4892: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4893: $symb=&escape($symb);
4894: if ($target) { $target="target=\"$target\""; }
4895: return '<a href="/adm/parmset?command=set&'.
4896: 'symb='.$symb.'&uname='.$uname.
4897: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
4898: }
4899: ##############################################
4900:
4901: =pod
4902:
4903: =back
4904:
4905: =cut
4906:
4907: ###############################################
4908:
4909:
4910: sub timehash {
4911: my ($thistime) = @_;
4912: my $timezone = &Apache::lonlocal::gettimezone();
4913: my $dt = DateTime->from_epoch(epoch => $thistime)
4914: ->set_time_zone($timezone);
4915: my $wday = $dt->day_of_week();
4916: if ($wday == 7) { $wday = 0; }
4917: return ( 'second' => $dt->second(),
4918: 'minute' => $dt->minute(),
4919: 'hour' => $dt->hour(),
4920: 'day' => $dt->day_of_month(),
4921: 'month' => $dt->month(),
4922: 'year' => $dt->year(),
4923: 'weekday' => $wday,
4924: 'dayyear' => $dt->day_of_year(),
4925: 'dlsav' => $dt->is_dst() );
4926: }
4927:
4928: sub utc_string {
4929: my ($date)=@_;
4930: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
4931: }
4932:
4933: sub maketime {
4934: my %th=@_;
4935: my ($epoch_time,$timezone,$dt);
4936: $timezone = &Apache::lonlocal::gettimezone();
4937: eval {
4938: $dt = DateTime->new( year => $th{'year'},
4939: month => $th{'month'},
4940: day => $th{'day'},
4941: hour => $th{'hour'},
4942: minute => $th{'minute'},
4943: second => $th{'second'},
4944: time_zone => $timezone,
4945: );
4946: };
4947: if (!$@) {
4948: $epoch_time = $dt->epoch;
4949: if ($epoch_time) {
4950: return $epoch_time;
4951: }
4952: }
4953: return POSIX::mktime(
4954: ($th{'seconds'},$th{'minutes'},$th{'hours'},
4955: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
4956: }
4957:
4958: #########################################
4959:
4960: sub findallcourses {
4961: my ($roles,$uname,$udom) = @_;
4962: my %roles;
4963: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
4964: my %courses;
4965: my $now=time;
4966: if (!defined($uname)) {
4967: $uname = $env{'user.name'};
4968: }
4969: if (!defined($udom)) {
4970: $udom = $env{'user.domain'};
4971: }
4972: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
4973: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
4974: if (!%roles) {
4975: %roles = (
4976: cc => 1,
4977: co => 1,
4978: in => 1,
4979: ep => 1,
4980: ta => 1,
4981: cr => 1,
4982: st => 1,
4983: );
4984: }
4985: foreach my $entry (keys(%roleshash)) {
4986: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
4987: if ($trole =~ /^cr/) {
4988: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
4989: } else {
4990: next if (!exists($roles{$trole}));
4991: }
4992: if ($tend) {
4993: next if ($tend < $now);
4994: }
4995: if ($tstart) {
4996: next if ($tstart > $now);
4997: }
4998: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
4999: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
5000: my $value = $trole.'/'.$cdom.'/';
5001: if ($secpart eq '') {
5002: ($cnum,$role) = split(/_/,$cnumpart);
5003: $sec = 'none';
5004: $value .= $cnum.'/';
5005: } else {
5006: $cnum = $cnumpart;
5007: ($sec,$role) = split(/_/,$secpart);
5008: $value .= $cnum.'/'.$sec;
5009: }
5010: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
5011: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
5012: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
5013: }
5014: } else {
5015: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
5016: }
5017: }
5018: } else {
5019: foreach my $key (keys(%env)) {
5020: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
5021: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
5022: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
5023: next if ($role eq 'ca' || $role eq 'aa');
5024: next if (%roles && !exists($roles{$role}));
5025: my ($starttime,$endtime)=split(/\./,$env{$key});
5026: my $active=1;
5027: if ($starttime) {
5028: if ($now<$starttime) { $active=0; }
5029: }
5030: if ($endtime) {
5031: if ($now>$endtime) { $active=0; }
5032: }
5033: if ($active) {
5034: my $value = $role.'/'.$cdom.'/'.$cnum.'/';
5035: if ($sec eq '') {
5036: $sec = 'none';
5037: } else {
5038: $value .= $sec;
5039: }
5040: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
5041: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
5042: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
5043: }
5044: } else {
5045: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
5046: }
5047: }
5048: }
5049: }
5050: }
5051: return %courses;
5052: }
5053:
5054: ###############################################
5055:
5056: sub blockcheck {
5057: my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
5058:
5059: if (defined($udom) && defined($uname)) {
5060: # If uname and udom are for a course, check for blocks in the course.
5061: if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
5062: my ($startblock,$endblock,$triggerblock) =
5063: &get_blocks($setters,$activity,$udom,$uname,$url);
5064: return ($startblock,$endblock,$triggerblock);
5065: }
5066: } else {
5067: $udom = $env{'user.domain'};
5068: $uname = $env{'user.name'};
5069: }
5070:
5071: my $startblock = 0;
5072: my $endblock = 0;
5073: my $triggerblock = '';
5074: my %live_courses = &findallcourses(undef,$uname,$udom);
5075:
5076: # If uname is for a user, and activity is course-specific, i.e.,
5077: # boards, chat or groups, check for blocking in current course only.
5078:
5079: if (($activity eq 'boards' || $activity eq 'chat' ||
5080: $activity eq 'groups' || $activity eq 'printout' ||
5081: $activity eq 'reinit' || $activity eq 'alert') &&
5082: ($env{'request.course.id'})) {
5083: foreach my $key (keys(%live_courses)) {
5084: if ($key ne $env{'request.course.id'}) {
5085: delete($live_courses{$key});
5086: }
5087: }
5088: }
5089:
5090: my $otheruser = 0;
5091: my %own_courses;
5092: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
5093: # Resource belongs to user other than current user.
5094: $otheruser = 1;
5095: # Gather courses for current user
5096: %own_courses =
5097: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
5098: }
5099:
5100: # Gather active course roles - course coordinator, instructor,
5101: # exam proctor, ta, student, or custom role.
5102:
5103: foreach my $course (keys(%live_courses)) {
5104: my ($cdom,$cnum);
5105: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
5106: $cdom = $env{'course.'.$course.'.domain'};
5107: $cnum = $env{'course.'.$course.'.num'};
5108: } else {
5109: ($cdom,$cnum) = split(/_/,$course);
5110: }
5111: my $no_ownblock = 0;
5112: my $no_userblock = 0;
5113: if ($otheruser && $activity ne 'com') {
5114: # Check if current user has 'evb' priv for this
5115: if (defined($own_courses{$course})) {
5116: foreach my $sec (keys(%{$own_courses{$course}})) {
5117: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
5118: if ($sec ne 'none') {
5119: $checkrole .= '/'.$sec;
5120: }
5121: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
5122: $no_ownblock = 1;
5123: last;
5124: }
5125: }
5126: }
5127: # if they have 'evb' priv and are currently not playing student
5128: next if (($no_ownblock) &&
5129: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
5130: }
5131: foreach my $sec (keys(%{$live_courses{$course}})) {
5132: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
5133: if ($sec ne 'none') {
5134: $checkrole .= '/'.$sec;
5135: }
5136: if ($otheruser) {
5137: # Resource belongs to user other than current user.
5138: # Assemble privs for that user, and check for 'evb' priv.
5139: my (%allroles,%userroles);
5140: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
5141: foreach my $entry (@{$live_courses{$course}{$sec}}) {
5142: my ($trole,$tdom,$tnum,$tsec);
5143: if ($entry =~ /^cr/) {
5144: ($trole,$tdom,$tnum,$tsec) =
5145: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
5146: } else {
5147: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
5148: }
5149: my ($spec,$area,$trest);
5150: $area = '/'.$tdom.'/'.$tnum;
5151: $trest = $tnum;
5152: if ($tsec ne '') {
5153: $area .= '/'.$tsec;
5154: $trest .= '/'.$tsec;
5155: }
5156: $spec = $trole.'.'.$area;
5157: if ($trole =~ /^cr/) {
5158: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
5159: $tdom,$spec,$trest,$area);
5160: } else {
5161: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
5162: $tdom,$spec,$trest,$area);
5163: }
5164: }
5165: my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
5166: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
5167: if ($1) {
5168: $no_userblock = 1;
5169: last;
5170: }
5171: }
5172: }
5173: } else {
5174: # Resource belongs to current user
5175: # Check for 'evb' priv via lonnet::allowed().
5176: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
5177: $no_ownblock = 1;
5178: last;
5179: }
5180: }
5181: }
5182: # if they have the evb priv and are currently not playing student
5183: next if (($no_ownblock) &&
5184: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
5185: next if ($no_userblock);
5186:
5187: # Retrieve blocking times and identity of blocker for course
5188: # of specified user, unless user has 'evb' privilege.
5189:
5190: my ($start,$end,$trigger) =
5191: &get_blocks($setters,$activity,$cdom,$cnum,$url);
5192: if (($start != 0) &&
5193: (($startblock == 0) || ($startblock > $start))) {
5194: $startblock = $start;
5195: if ($trigger ne '') {
5196: $triggerblock = $trigger;
5197: }
5198: }
5199: if (($end != 0) &&
5200: (($endblock == 0) || ($endblock < $end))) {
5201: $endblock = $end;
5202: if ($trigger ne '') {
5203: $triggerblock = $trigger;
5204: }
5205: }
5206: }
5207: return ($startblock,$endblock,$triggerblock);
5208: }
5209:
5210: sub get_blocks {
5211: my ($setters,$activity,$cdom,$cnum,$url) = @_;
5212: my $startblock = 0;
5213: my $endblock = 0;
5214: my $triggerblock = '';
5215: my $course = $cdom.'_'.$cnum;
5216: $setters->{$course} = {};
5217: $setters->{$course}{'staff'} = [];
5218: $setters->{$course}{'times'} = [];
5219: $setters->{$course}{'triggers'} = [];
5220: my (@blockers,%triggered);
5221: my $now = time;
5222: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
5223: if ($activity eq 'docs') {
5224: @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
5225: foreach my $block (@blockers) {
5226: if ($block =~ /^firstaccess____(.+)$/) {
5227: my $item = $1;
5228: my $type = 'map';
5229: my $timersymb = $item;
5230: if ($item eq 'course') {
5231: $type = 'course';
5232: } elsif ($item =~ /___\d+___/) {
5233: $type = 'resource';
5234: } else {
5235: $timersymb = &Apache::lonnet::symbread($item);
5236: }
5237: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
5238: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
5239: $triggered{$block} = {
5240: start => $start,
5241: end => $end,
5242: type => $type,
5243: };
5244: }
5245: }
5246: } else {
5247: foreach my $block (keys(%commblocks)) {
5248: if ($block =~ m/^(\d+)____(\d+)$/) {
5249: my ($start,$end) = ($1,$2);
5250: if ($start <= time && $end >= time) {
5251: if (ref($commblocks{$block}) eq 'HASH') {
5252: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
5253: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
5254: unless(grep(/^\Q$block\E$/,@blockers)) {
5255: push(@blockers,$block);
5256: }
5257: }
5258: }
5259: }
5260: }
5261: } elsif ($block =~ /^firstaccess____(.+)$/) {
5262: my $item = $1;
5263: my $timersymb = $item;
5264: my $type = 'map';
5265: if ($item eq 'course') {
5266: $type = 'course';
5267: } elsif ($item =~ /___\d+___/) {
5268: $type = 'resource';
5269: } else {
5270: $timersymb = &Apache::lonnet::symbread($item);
5271: }
5272: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
5273: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
5274: if ($start && $end) {
5275: if (($start <= time) && ($end >= time)) {
5276: if (ref($commblocks{$block}) eq 'HASH') {
5277: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
5278: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
5279: unless(grep(/^\Q$block\E$/,@blockers)) {
5280: push(@blockers,$block);
5281: $triggered{$block} = {
5282: start => $start,
5283: end => $end,
5284: type => $type,
5285: };
5286: }
5287: }
5288: }
5289: }
5290: }
5291: }
5292: }
5293: }
5294: }
5295: foreach my $blocker (@blockers) {
5296: my ($staff_name,$staff_dom,$title,$blocks) =
5297: &parse_block_record($commblocks{$blocker});
5298: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
5299: my ($start,$end,$triggertype);
5300: if ($blocker =~ m/^(\d+)____(\d+)$/) {
5301: ($start,$end) = ($1,$2);
5302: } elsif (ref($triggered{$blocker}) eq 'HASH') {
5303: $start = $triggered{$blocker}{'start'};
5304: $end = $triggered{$blocker}{'end'};
5305: $triggertype = $triggered{$blocker}{'type'};
5306: }
5307: if ($start) {
5308: push(@{$$setters{$course}{'times'}}, [$start,$end]);
5309: if ($triggertype) {
5310: push(@{$$setters{$course}{'triggers'}},$triggertype);
5311: } else {
5312: push(@{$$setters{$course}{'triggers'}},0);
5313: }
5314: if ( ($startblock == 0) || ($startblock > $start) ) {
5315: $startblock = $start;
5316: if ($triggertype) {
5317: $triggerblock = $blocker;
5318: }
5319: }
5320: if ( ($endblock == 0) || ($endblock < $end) ) {
5321: $endblock = $end;
5322: if ($triggertype) {
5323: $triggerblock = $blocker;
5324: }
5325: }
5326: }
5327: }
5328: return ($startblock,$endblock,$triggerblock);
5329: }
5330:
5331: sub parse_block_record {
5332: my ($record) = @_;
5333: my ($setuname,$setudom,$title,$blocks);
5334: if (ref($record) eq 'HASH') {
5335: ($setuname,$setudom) = split(/:/,$record->{'setter'});
5336: $title = &unescape($record->{'event'});
5337: $blocks = $record->{'blocks'};
5338: } else {
5339: my @data = split(/:/,$record,3);
5340: if (scalar(@data) eq 2) {
5341: $title = $data[1];
5342: ($setuname,$setudom) = split(/@/,$data[0]);
5343: } else {
5344: ($setuname,$setudom,$title) = @data;
5345: }
5346: $blocks = { 'com' => 'on' };
5347: }
5348: return ($setuname,$setudom,$title,$blocks);
5349: }
5350:
5351: sub blocking_status {
5352: my ($activity,$uname,$udom,$url,$is_course) = @_;
5353: my %setters;
5354:
5355: # check for active blocking
5356: my ($startblock,$endblock,$triggerblock) =
5357: &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
5358: my $blocked = 0;
5359: if ($startblock && $endblock) {
5360: $blocked = 1;
5361: }
5362:
5363: # caller just wants to know whether a block is active
5364: if (!wantarray) { return $blocked; }
5365:
5366: # build a link to a popup window containing the details
5367: my $querystring = "?activity=$activity";
5368: # $uname and $udom decide whose portfolio the user is trying to look at
5369: if (($activity eq 'port') || ($activity eq 'passwd')) {
5370: $querystring .= "&udom=$udom" if ($udom =~ /^$match_domain$/);
5371: $querystring .= "&uname=$uname" if ($uname =~ /^$match_username$/);
5372: } elsif ($activity eq 'docs') {
5373: $querystring .= '&url='.&HTML::Entities::encode($url,'&"');
5374: }
5375:
5376: my $output .= <<'END_MYBLOCK';
5377: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
5378: var options = "width=" + w + ",height=" + h + ",";
5379: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
5380: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
5381: var newWin = window.open(url, wdwName, options);
5382: newWin.focus();
5383: }
5384: END_MYBLOCK
5385:
5386: $output = Apache::lonhtmlcommon::scripttag($output);
5387:
5388: my $popupUrl = "/adm/blockingstatus/$querystring";
5389: my $text = &mt('Communication Blocked');
5390: my $class = 'LC_comblock';
5391: if ($activity eq 'docs') {
5392: $text = &mt('Content Access Blocked');
5393: $class = '';
5394: } elsif ($activity eq 'printout') {
5395: $text = &mt('Printing Blocked');
5396: } elsif ($activity eq 'passwd') {
5397: $text = &mt('Password Changing Blocked');
5398: } elsif ($activity eq 'alert') {
5399: $text = &mt('Checking Critical Messages Blocked');
5400: } elsif ($activity eq 'reinit') {
5401: $text = &mt('Checking Course Update Blocked');
5402: }
5403: $output .= <<"END_BLOCK";
5404: <div class='$class'>
5405: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
5406: title='$text'>
5407: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
5408: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
5409: title='$text'>$text</a>
5410: </div>
5411:
5412: END_BLOCK
5413:
5414: return ($blocked, $output);
5415: }
5416:
5417: ###############################################
5418:
5419: sub check_ip_acc {
5420: my ($acc,$clientip)=@_;
5421: &Apache::lonxml::debug("acc is $acc");
5422: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
5423: return 1;
5424: }
5425: my $allowed;
5426: my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
5427:
5428: my $name;
5429: my %access = (
5430: allowfrom => 1,
5431: denyfrom => 0,
5432: );
5433: my @allows;
5434: my @denies;
5435: foreach my $item (split(',',$acc)) {
5436: $item =~ s/^\s*//;
5437: $item =~ s/\s*$//;
5438: my $pattern;
5439: if ($item =~ /^\!(.+)$/) {
5440: push(@denies,$1);
5441: } else {
5442: push(@allows,$item);
5443: }
5444: }
5445: my $numdenies = scalar(@denies);
5446: my $numallows = scalar(@allows);
5447: my $count = 0;
5448: foreach my $pattern (@denies,@allows) {
5449: $count ++;
5450: my $acctype = 'allowfrom';
5451: if ($count <= $numdenies) {
5452: $acctype = 'denyfrom';
5453: }
5454: if ($pattern =~ /\*$/) {
5455: #35.8.*
5456: $pattern=~s/\*//;
5457: if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
5458: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
5459: #35.8.3.[34-56]
5460: my $low=$2;
5461: my $high=$3;
5462: $pattern=$1;
5463: if ($ip =~ /^\Q$pattern\E/) {
5464: my $last=(split(/\./,$ip))[3];
5465: if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
5466: }
5467: } elsif ($pattern =~ /^\*/) {
5468: #*.msu.edu
5469: $pattern=~s/\*//;
5470: if (!defined($name)) {
5471: use Socket;
5472: my $netaddr=inet_aton($ip);
5473: ($name)=gethostbyaddr($netaddr,AF_INET);
5474: }
5475: if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
5476: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
5477: #127.0.0.1
5478: if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
5479: } else {
5480: #some.name.com
5481: if (!defined($name)) {
5482: use Socket;
5483: my $netaddr=inet_aton($ip);
5484: ($name)=gethostbyaddr($netaddr,AF_INET);
5485: }
5486: if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
5487: }
5488: if ($allowed =~ /^(0|1)$/) { last; }
5489: }
5490: if ($allowed eq '') {
5491: if ($numdenies && !$numallows) {
5492: $allowed = 1;
5493: } else {
5494: $allowed = 0;
5495: }
5496: }
5497: return $allowed;
5498: }
5499:
5500: ###############################################
5501:
5502: =pod
5503:
5504: =head1 Domain Template Functions
5505:
5506: =over 4
5507:
5508: =item * &determinedomain()
5509:
5510: Inputs: $domain (usually will be undef)
5511:
5512: Returns: Determines which domain should be used for designs
5513:
5514: =cut
5515:
5516: ###############################################
5517: sub determinedomain {
5518: my $domain=shift;
5519: if (! $domain) {
5520: # Determine domain if we have not been given one
5521: $domain = &Apache::lonnet::default_login_domain();
5522: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
5523: if ($env{'request.role.domain'}) {
5524: $domain=$env{'request.role.domain'};
5525: }
5526: }
5527: return $domain;
5528: }
5529: ###############################################
5530:
5531: sub devalidate_domconfig_cache {
5532: my ($udom)=@_;
5533: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
5534: }
5535:
5536: # ---------------------- Get domain configuration for a domain
5537: sub get_domainconf {
5538: my ($udom) = @_;
5539: my $cachetime=1800;
5540: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
5541: if (defined($cached)) { return %{$result}; }
5542:
5543: my %domconfig = &Apache::lonnet::get_dom('configuration',
5544: ['login','rolecolors','autoenroll'],$udom);
5545: my (%designhash,%legacy);
5546: if (keys(%domconfig) > 0) {
5547: if (ref($domconfig{'login'}) eq 'HASH') {
5548: if (keys(%{$domconfig{'login'}})) {
5549: foreach my $key (keys(%{$domconfig{'login'}})) {
5550: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5551: if (($key eq 'loginvia') || ($key eq 'headtag')) {
5552: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5553: foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
5554: if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
5555: if ($key eq 'loginvia') {
5556: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
5557: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
5558: $designhash{$udom.'.login.loginvia'} = $server;
5559: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
5560:
5561: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
5562: } else {
5563: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
5564: }
5565: }
5566: } elsif ($key eq 'headtag') {
5567: if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
5568: $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
5569: }
5570: }
5571: if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
5572: $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
5573: }
5574: }
5575: }
5576: }
5577: } else {
5578: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
5579: $designhash{$udom.'.login.'.$key.'_'.$img} =
5580: $domconfig{'login'}{$key}{$img};
5581: }
5582: }
5583: } else {
5584: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
5585: }
5586: }
5587: } else {
5588: $legacy{'login'} = 1;
5589: }
5590: } else {
5591: $legacy{'login'} = 1;
5592: }
5593: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
5594: if (keys(%{$domconfig{'rolecolors'}})) {
5595: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
5596: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
5597: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
5598: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
5599: }
5600: }
5601: }
5602: } else {
5603: $legacy{'rolecolors'} = 1;
5604: }
5605: } else {
5606: $legacy{'rolecolors'} = 1;
5607: }
5608: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5609: if ($domconfig{'autoenroll'}{'co-owners'}) {
5610: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
5611: }
5612: }
5613: if (keys(%legacy) > 0) {
5614: my %legacyhash = &get_legacy_domconf($udom);
5615: foreach my $item (keys(%legacyhash)) {
5616: if ($item =~ /^\Q$udom\E\.login/) {
5617: if ($legacy{'login'}) {
5618: $designhash{$item} = $legacyhash{$item};
5619: }
5620: } else {
5621: if ($legacy{'rolecolors'}) {
5622: $designhash{$item} = $legacyhash{$item};
5623: }
5624: }
5625: }
5626: }
5627: } else {
5628: %designhash = &get_legacy_domconf($udom);
5629: }
5630: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
5631: $cachetime);
5632: return %designhash;
5633: }
5634:
5635: sub get_legacy_domconf {
5636: my ($udom) = @_;
5637: my %legacyhash;
5638: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
5639: my $designfile = $designdir.'/'.$udom.'.tab';
5640: if (-e $designfile) {
5641: if ( open (my $fh,"<$designfile") ) {
5642: while (my $line = <$fh>) {
5643: next if ($line =~ /^\#/);
5644: chomp($line);
5645: my ($key,$val)=(split(/\=/,$line));
5646: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
5647: }
5648: close($fh);
5649: }
5650: }
5651: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
5652: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
5653: }
5654: return %legacyhash;
5655: }
5656:
5657: =pod
5658:
5659: =item * &domainlogo()
5660:
5661: Inputs: $domain (usually will be undef)
5662:
5663: Returns: A link to a domain logo, if the domain logo exists.
5664: If the domain logo does not exist, a description of the domain.
5665:
5666: =cut
5667:
5668: ###############################################
5669: sub domainlogo {
5670: my $domain = &determinedomain(shift);
5671: my %designhash = &get_domainconf($domain);
5672: # See if there is a logo
5673: if ($designhash{$domain.'.login.domlogo'} ne '') {
5674: my $imgsrc = $designhash{$domain.'.login.domlogo'};
5675: if ($imgsrc =~ m{^/(adm|res)/}) {
5676: if ($imgsrc =~ m{^/res/}) {
5677: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
5678: &Apache::lonnet::repcopy($local_name);
5679: }
5680: $imgsrc = &lonhttpdurl($imgsrc);
5681: }
5682: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
5683: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
5684: return &Apache::lonnet::domain($domain,'description');
5685: } else {
5686: return '';
5687: }
5688: }
5689: ##############################################
5690:
5691: =pod
5692:
5693: =item * &designparm()
5694:
5695: Inputs: $which parameter; $domain (usually will be undef)
5696:
5697: Returns: value of designparamter $which
5698:
5699: =cut
5700:
5701:
5702: ##############################################
5703: sub designparm {
5704: my ($which,$domain)=@_;
5705: if (exists($env{'environment.color.'.$which})) {
5706: return $env{'environment.color.'.$which};
5707: }
5708: $domain=&determinedomain($domain);
5709: my %domdesign;
5710: unless ($domain eq 'public') {
5711: %domdesign = &get_domainconf($domain);
5712: }
5713: my $output;
5714: if ($domdesign{$domain.'.'.$which} ne '') {
5715: $output = $domdesign{$domain.'.'.$which};
5716: } else {
5717: $output = $defaultdesign{$which};
5718: }
5719: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
5720: ($which =~ /login\.(img|logo|domlogo|login)/)) {
5721: if ($output =~ m{^/(adm|res)/}) {
5722: if ($output =~ m{^/res/}) {
5723: my $local_name = &Apache::lonnet::filelocation('',$output);
5724: &Apache::lonnet::repcopy($local_name);
5725: }
5726: $output = &lonhttpdurl($output);
5727: }
5728: }
5729: return $output;
5730: }
5731:
5732: ##############################################
5733: =pod
5734:
5735: =item * &authorspace()
5736:
5737: Inputs: $url (usually will be undef).
5738:
5739: Returns: Path to Authoring Space containing the resource or
5740: directory being viewed (or for which action is being taken).
5741: If $url is provided, and begins /priv/<domain>/<uname>
5742: the path will be that portion of the $context argument.
5743: Otherwise the path will be for the author space of the current
5744: user when the current role is author, or for that of the
5745: co-author/assistant co-author space when the current role
5746: is co-author or assistant co-author.
5747:
5748: =cut
5749:
5750: sub authorspace {
5751: my ($url) = @_;
5752: if ($url ne '') {
5753: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
5754: return $1;
5755: }
5756: }
5757: my $caname = '';
5758: my $cadom = '';
5759: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
5760: ($cadom,$caname) =
5761: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
5762: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
5763: $caname = $env{'user.name'};
5764: $cadom = $env{'user.domain'};
5765: }
5766: if (($caname ne '') && ($cadom ne '')) {
5767: return "/priv/$cadom/$caname/";
5768: }
5769: return;
5770: }
5771:
5772: ##############################################
5773: =pod
5774:
5775: =item * &head_subbox()
5776:
5777: Inputs: $content (contains HTML code with page functions, etc.)
5778:
5779: Returns: HTML div with $content
5780: To be included in page header
5781:
5782: =cut
5783:
5784: sub head_subbox {
5785: my ($content)=@_;
5786: my $output =
5787: '<div class="LC_head_subbox">'
5788: .$content
5789: .'</div>'
5790: }
5791:
5792: ##############################################
5793: =pod
5794:
5795: =item * &CSTR_pageheader()
5796:
5797: Input: (optional) filename from which breadcrumb trail is built.
5798: In most cases no input as needed, as $env{'request.filename'}
5799: is appropriate for use in building the breadcrumb trail.
5800:
5801: Returns: HTML div with CSTR path and recent box
5802: To be included on Authoring Space pages
5803:
5804: =cut
5805:
5806: sub CSTR_pageheader {
5807: my ($trailfile) = @_;
5808: if ($trailfile eq '') {
5809: $trailfile = $env{'request.filename'};
5810: }
5811:
5812: # this is for resources; directories have customtitle, and crumbs
5813: # and select recent are created in lonpubdir.pm
5814:
5815: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
5816: my ($udom,$uname,$thisdisfn)=
5817: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
5818: my $formaction = "/priv/$udom/$uname/$thisdisfn";
5819: $formaction =~ s{/+}{/}g;
5820:
5821: my $parentpath = '';
5822: my $lastitem = '';
5823: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
5824: $parentpath = $1;
5825: $lastitem = $2;
5826: } else {
5827: $lastitem = $thisdisfn;
5828: }
5829:
5830: my ($crsauthor,$title);
5831: if (($env{'request.course.id'}) &&
5832: ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
5833: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
5834: $crsauthor = 1;
5835: $title = &mt('Course Authoring Space');
5836: } else {
5837: $title = &mt('Authoring Space');
5838: }
5839:
5840: my $target;
5841: if (($env{'request.lti.login'}) && ($env{'request.lti.target'} eq 'iframe')) {
5842: $target = ' target="_top"'; #FIXME lonpubdir: target="_parent"
5843: }
5844:
5845: my $output =
5846: '<div>'
5847: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
5848: .'<b>'.$title.'</b> '
5849: .'<form name="dirs" method="post" action="'.$formaction.$target.'>'
5850: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
5851:
5852: if ($lastitem) {
5853: $output .=
5854: '<span class="LC_filename">'
5855: .$lastitem
5856: .'</span>';
5857: }
5858:
5859: if ($crsauthor) {
5860: $output .= '</form>'.&Apache::lonmenu::constspaceform();
5861: } else {
5862: $output .=
5863: '<br />'
5864: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
5865: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
5866: .'</form>'
5867: .&Apache::lonmenu::constspaceform();
5868: }
5869: $output .= '</div>';
5870:
5871: return $output;
5872: }
5873:
5874: ###############################################
5875: ###############################################
5876:
5877: =pod
5878:
5879: =back
5880:
5881: =head1 HTML Helpers
5882:
5883: =over 4
5884:
5885: =item * &bodytag()
5886:
5887: Returns a uniform header for LON-CAPA web pages.
5888:
5889: Inputs:
5890:
5891: =over 4
5892:
5893: =item * $title, A title to be displayed on the page.
5894:
5895: =item * $function, the current role (can be undef).
5896:
5897: =item * $addentries, extra parameters for the <body> tag.
5898:
5899: =item * $bodyonly, if defined, only return the <body> tag.
5900:
5901: =item * $domain, if defined, force a given domain.
5902:
5903: =item * $forcereg, if page should register as content page (relevant for
5904: text interface only)
5905:
5906: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
5907: navigational links
5908:
5909: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
5910:
5911: =item * $args, optional argument valid values are
5912: no_auto_mt_title -> prevents &mt()ing the title arg
5913: use_absolute -> for external resource or syllabus, this will
5914: contain https://<hostname> if server uses
5915: https (as per hosts.tab), but request is for http
5916: hostname -> hostname, from $r->hostname().
5917:
5918: =item * $advtoolsref, optional argument, ref to an array containing
5919: inlineremote items to be added in "Functions" menu below
5920: breadcrumbs.
5921:
5922: =back
5923:
5924: Returns: A uniform header for LON-CAPA web pages.
5925: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
5926: If $bodyonly is undef or zero, an html string containing a <body> tag and
5927: other decorations will be returned.
5928:
5929: =cut
5930:
5931: sub bodytag {
5932: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
5933: $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
5934:
5935: my $public;
5936: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
5937: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
5938: $public = 1;
5939: }
5940: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
5941: my $httphost = $args->{'use_absolute'};
5942: my $hostname = $args->{'hostname'};
5943:
5944: $function = &get_users_function() if (!$function);
5945: my $img = &designparm($function.'.img',$domain);
5946: my $font = &designparm($function.'.font',$domain);
5947: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
5948:
5949: my %design = ( 'style' => 'margin-top: 0',
5950: 'bgcolor' => $pgbg,
5951: 'text' => $font,
5952: 'alink' => &designparm($function.'.alink',$domain),
5953: 'vlink' => &designparm($function.'.vlink',$domain),
5954: 'link' => &designparm($function.'.link',$domain),);
5955: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
5956:
5957: # role and realm
5958: my ($role,$realm) = split(m{\./},$env{'request.role'},2);
5959: if ($realm) {
5960: $realm = '/'.$realm;
5961: }
5962: if ($role eq 'ca') {
5963: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
5964: $realm = &plainname($rname,$rdom);
5965: }
5966: # realm
5967: if ($env{'request.course.id'}) {
5968: if ($env{'request.role'} !~ /^cr/) {
5969: $role = &Apache::lonnet::plaintext($role,&course_type());
5970: } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
5971: if ($env{'request.role.desc'}) {
5972: $role = $env{'request.role.desc'};
5973: } else {
5974: $role = &mt('Helpdesk[_1]',' '.$2);
5975: }
5976: } else {
5977: $role = (split(/\//,$role,4))[-1];
5978: }
5979: if ($env{'request.course.sec'}) {
5980: $role .= (' 'x2).'- '.&mt('section:').' '.$env{'request.course.sec'};
5981: }
5982: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
5983: } else {
5984: $role = &Apache::lonnet::plaintext($role);
5985: }
5986:
5987: if (!$realm) { $realm=' '; }
5988:
5989: my $extra_body_attr = &make_attr_string($forcereg,\%design);
5990:
5991: # construct main body tag
5992: my $bodytag = "<body $extra_body_attr>".
5993: &Apache::lontexconvert::init_math_support();
5994:
5995: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
5996:
5997: if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
5998: return $bodytag;
5999: }
6000:
6001: if ($public) {
6002: undef($role);
6003: }
6004:
6005: my $titleinfo = '<h1>'.$title.'</h1>';
6006: #
6007: # Extra info if you are the DC
6008: my $dc_info = '';
6009: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
6010: $env{'course.'.$env{'request.course.id'}.
6011: '.domain'}.'/'})) {
6012: my $cid = $env{'request.course.id'};
6013: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
6014: $dc_info =~ s/\s+$//;
6015: }
6016:
6017: my $crstype;
6018: if ($env{'request.course.id'}) {
6019: $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
6020: } elsif ($args->{'crstype'}) {
6021: $crstype = $args->{'crstype'};
6022: }
6023: if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
6024: undef($role);
6025: } else {
6026: $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
6027: }
6028:
6029: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
6030:
6031: # if ($env{'request.state'} eq 'construct') {
6032: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
6033: # }
6034:
6035: $bodytag .= Apache::lonhtmlcommon::scripttag(
6036: Apache::lonmenu::utilityfunctions($httphost), 'start');
6037:
6038: my ($left,$right) = Apache::lonmenu::primary_menu($crstype);
6039:
6040: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
6041: if ($dc_info) {
6042: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
6043: }
6044: $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
6045: <em>$realm</em> $dc_info</div>|;
6046: return $bodytag;
6047: }
6048:
6049: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
6050: $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
6051: }
6052:
6053: $bodytag .= $right;
6054:
6055: if ($dc_info) {
6056: $dc_info = &dc_courseid_toggle($dc_info);
6057: }
6058: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
6059:
6060: #if directed to not display the secondary menu, don't.
6061: if ($args->{'no_secondary_menu'}) {
6062: return $bodytag;
6063: }
6064: #don't show menus for public users
6065: if (!$public){
6066: $bodytag .= Apache::lonmenu::secondary_menu($httphost);
6067: $bodytag .= Apache::lonmenu::serverform();
6068: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
6069: if ($env{'request.state'} eq 'construct') {
6070: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
6071: $args->{'bread_crumbs'},'','',$hostname);
6072: } elsif ($forcereg) {
6073: $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
6074: $args->{'group'},
6075: $args->{'hide_buttons'},
6076: $hostname);
6077: } else {
6078: $bodytag .=
6079: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
6080: $forcereg,$args->{'group'},
6081: $args->{'bread_crumbs'},
6082: $advtoolsref,'',$hostname);
6083: }
6084: }else{
6085: # this is to seperate menu from content when there's no secondary
6086: # menu. Especially needed for public accessible ressources.
6087: $bodytag .= '<hr style="clear:both" />';
6088: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
6089: }
6090:
6091: return $bodytag;
6092: }
6093:
6094: sub dc_courseid_toggle {
6095: my ($dc_info) = @_;
6096: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
6097: '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
6098: &mt('(More ...)').'</a></span>'.
6099: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
6100: }
6101:
6102: sub make_attr_string {
6103: my ($register,$attr_ref) = @_;
6104:
6105: if ($attr_ref && !ref($attr_ref)) {
6106: die("addentries Must be a hash ref ".
6107: join(':',caller(1))." ".
6108: join(':',caller(0))." ");
6109: }
6110:
6111: if ($register) {
6112: my ($on_load,$on_unload);
6113: foreach my $key (keys(%{$attr_ref})) {
6114: if (lc($key) eq 'onload') {
6115: $on_load.=$attr_ref->{$key}.';';
6116: delete($attr_ref->{$key});
6117:
6118: } elsif (lc($key) eq 'onunload') {
6119: $on_unload.=$attr_ref->{$key}.';';
6120: delete($attr_ref->{$key});
6121: }
6122: }
6123: $attr_ref->{'onload'} = $on_load;
6124: $attr_ref->{'onunload'}= $on_unload;
6125: }
6126:
6127: my $attr_string;
6128: foreach my $attr (sort(keys(%$attr_ref))) {
6129: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
6130: }
6131: return $attr_string;
6132: }
6133:
6134:
6135: ###############################################
6136: ###############################################
6137:
6138: =pod
6139:
6140: =item * &endbodytag()
6141:
6142: Returns a uniform footer for LON-CAPA web pages.
6143:
6144: Inputs: 1 - optional reference to an args hash
6145: If in the hash, key for noredirectlink has a value which evaluates to true,
6146: a 'Continue' link is not displayed if the page contains an
6147: internal redirect in the <head></head> section,
6148: i.e., $env{'internal.head.redirect'} exists
6149:
6150: =cut
6151:
6152: sub endbodytag {
6153: my ($args) = @_;
6154: my $endbodytag;
6155: unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
6156: $endbodytag='</body>';
6157: }
6158: if ( exists( $env{'internal.head.redirect'} ) ) {
6159: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
6160: $endbodytag=
6161: "<br /><a href=\"$env{'internal.head.redirect'}\">".
6162: &mt('Continue').'</a>'.
6163: $endbodytag;
6164: }
6165: }
6166: return $endbodytag;
6167: }
6168:
6169: =pod
6170:
6171: =item * &standard_css()
6172:
6173: Returns a style sheet
6174:
6175: Inputs: (all optional)
6176: domain -> force to color decorate a page for a specific
6177: domain
6178: function -> force usage of a specific rolish color scheme
6179: bgcolor -> override the default page bgcolor
6180:
6181: =cut
6182:
6183: sub standard_css {
6184: my ($function,$domain,$bgcolor) = @_;
6185: $function = &get_users_function() if (!$function);
6186: my $img = &designparm($function.'.img', $domain);
6187: my $tabbg = &designparm($function.'.tabbg', $domain);
6188: my $font = &designparm($function.'.font', $domain);
6189: my $fontmenu = &designparm($function.'.fontmenu', $domain);
6190: #second colour for later usage
6191: my $sidebg = &designparm($function.'.sidebg',$domain);
6192: my $pgbg_or_bgcolor =
6193: $bgcolor ||
6194: &designparm($function.'.pgbg', $domain);
6195: my $pgbg = &designparm($function.'.pgbg', $domain);
6196: my $alink = &designparm($function.'.alink', $domain);
6197: my $vlink = &designparm($function.'.vlink', $domain);
6198: my $link = &designparm($function.'.link', $domain);
6199:
6200: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
6201: my $mono = 'monospace';
6202: my $data_table_head = $sidebg;
6203: my $data_table_light = '#FAFAFA';
6204: my $data_table_dark = '#E0E0E0';
6205: my $data_table_darker = '#CCCCCC';
6206: my $data_table_highlight = '#FFFF00';
6207: my $mail_new = '#FFBB77';
6208: my $mail_new_hover = '#DD9955';
6209: my $mail_read = '#BBBB77';
6210: my $mail_read_hover = '#999944';
6211: my $mail_replied = '#AAAA88';
6212: my $mail_replied_hover = '#888855';
6213: my $mail_other = '#99BBBB';
6214: my $mail_other_hover = '#669999';
6215: my $table_header = '#DDDDDD';
6216: my $feedback_link_bg = '#BBBBBB';
6217: my $lg_border_color = '#C8C8C8';
6218: my $button_hover = '#BF2317';
6219:
6220: my $border = ($env{'browser.type'} eq 'explorer' ||
6221: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
6222: : '0 3px 0 4px';
6223:
6224:
6225: return <<END;
6226:
6227: /* needed for iframe to allow 100% height in FF */
6228: body, html {
6229: margin: 0;
6230: padding: 0 0.5%;
6231: height: 99%; /* to avoid scrollbars */
6232: }
6233:
6234: body {
6235: font-family: $sans;
6236: line-height:130%;
6237: font-size:0.83em;
6238: color:$font;
6239: }
6240:
6241: a:focus,
6242: a:focus img {
6243: color: red;
6244: }
6245:
6246: form, .inline {
6247: display: inline;
6248: }
6249:
6250: .LC_right {
6251: text-align:right;
6252: }
6253:
6254: .LC_middle {
6255: vertical-align:middle;
6256: }
6257:
6258: .LC_floatleft {
6259: float: left;
6260: }
6261:
6262: .LC_floatright {
6263: float: right;
6264: }
6265:
6266: .LC_400Box {
6267: width:400px;
6268: }
6269:
6270: .LC_iframecontainer {
6271: width: 98%;
6272: margin: 0;
6273: position: fixed;
6274: top: 8.5em;
6275: bottom: 0;
6276: }
6277:
6278: .LC_iframecontainer iframe{
6279: border: none;
6280: width: 100%;
6281: height: 100%;
6282: }
6283:
6284: .LC_filename {
6285: font-family: $mono;
6286: white-space:pre;
6287: font-size: 120%;
6288: }
6289:
6290: .LC_fileicon {
6291: border: none;
6292: height: 1.3em;
6293: vertical-align: text-bottom;
6294: margin-right: 0.3em;
6295: text-decoration:none;
6296: }
6297:
6298: .LC_setting {
6299: text-decoration:underline;
6300: }
6301:
6302: .LC_error {
6303: color: red;
6304: }
6305:
6306: .LC_warning {
6307: color: darkorange;
6308: }
6309:
6310: .LC_diff_removed {
6311: color: red;
6312: }
6313:
6314: .LC_info,
6315: .LC_success,
6316: .LC_diff_added {
6317: color: green;
6318: }
6319:
6320: div.LC_confirm_box {
6321: background-color: #FAFAFA;
6322: border: 1px solid $lg_border_color;
6323: margin-right: 0;
6324: padding: 5px;
6325: }
6326:
6327: div.LC_confirm_box .LC_error img,
6328: div.LC_confirm_box .LC_success img {
6329: vertical-align: middle;
6330: }
6331:
6332: .LC_maxwidth {
6333: max-width: 100%;
6334: height: auto;
6335: }
6336:
6337: .LC_textsize_mobile {
6338: \@media only screen and (max-device-width: 480px) {
6339: -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
6340: }
6341: }
6342:
6343: .LC_icon {
6344: border: none;
6345: vertical-align: middle;
6346: }
6347:
6348: .LC_docs_spacer {
6349: width: 25px;
6350: height: 1px;
6351: border: none;
6352: }
6353:
6354: .LC_internal_info {
6355: color: #999999;
6356: }
6357:
6358: .LC_discussion {
6359: background: $data_table_dark;
6360: border: 1px solid black;
6361: margin: 2px;
6362: }
6363:
6364: .LC_disc_action_left {
6365: background: $sidebg;
6366: text-align: left;
6367: padding: 4px;
6368: margin: 2px;
6369: }
6370:
6371: .LC_disc_action_right {
6372: background: $sidebg;
6373: text-align: right;
6374: padding: 4px;
6375: margin: 2px;
6376: }
6377:
6378: .LC_disc_new_item {
6379: background: white;
6380: border: 2px solid red;
6381: margin: 4px;
6382: padding: 4px;
6383: }
6384:
6385: .LC_disc_old_item {
6386: background: white;
6387: margin: 4px;
6388: padding: 4px;
6389: }
6390:
6391: table.LC_pastsubmission {
6392: border: 1px solid black;
6393: margin: 2px;
6394: }
6395:
6396: table#LC_menubuttons {
6397: width: 100%;
6398: background: $pgbg;
6399: border: 2px;
6400: border-collapse: separate;
6401: padding: 0;
6402: }
6403:
6404: table#LC_title_bar a {
6405: color: $fontmenu;
6406: }
6407:
6408: table#LC_title_bar {
6409: clear: both;
6410: display: none;
6411: }
6412:
6413: table#LC_title_bar,
6414: table.LC_breadcrumbs, /* obsolete? */
6415: table#LC_title_bar.LC_with_remote {
6416: width: 100%;
6417: border-color: $pgbg;
6418: border-style: solid;
6419: border-width: $border;
6420: background: $pgbg;
6421: color: $fontmenu;
6422: border-collapse: collapse;
6423: padding: 0;
6424: margin: 0;
6425: }
6426:
6427: ul.LC_breadcrumb_tools_outerlist {
6428: margin: 0;
6429: padding: 0;
6430: position: relative;
6431: list-style: none;
6432: }
6433: ul.LC_breadcrumb_tools_outerlist li {
6434: display: inline;
6435: }
6436:
6437: .LC_breadcrumb_tools_navigation {
6438: padding: 0;
6439: margin: 0;
6440: float: left;
6441: }
6442: .LC_breadcrumb_tools_tools {
6443: padding: 0;
6444: margin: 0;
6445: float: right;
6446: }
6447:
6448: .LC_placement_prog {
6449: padding-right: 20px;
6450: font-weight: bold;
6451: font-size: 90%;
6452: }
6453:
6454: table#LC_title_bar td {
6455: background: $tabbg;
6456: }
6457:
6458: table#LC_menubuttons img {
6459: border: none;
6460: }
6461:
6462: .LC_breadcrumbs_component {
6463: float: right;
6464: margin: 0 1em;
6465: }
6466: .LC_breadcrumbs_component img {
6467: vertical-align: middle;
6468: }
6469:
6470: .LC_breadcrumbs_hoverable {
6471: background: $sidebg;
6472: }
6473:
6474: td.LC_table_cell_checkbox {
6475: text-align: center;
6476: }
6477:
6478: .LC_fontsize_small {
6479: font-size: 70%;
6480: }
6481:
6482: #LC_breadcrumbs {
6483: clear:both;
6484: background: $sidebg;
6485: border-bottom: 1px solid $lg_border_color;
6486: line-height: 2.5em;
6487: overflow: hidden;
6488: margin: 0;
6489: padding: 0;
6490: text-align: left;
6491: }
6492:
6493: .LC_head_subbox, .LC_actionbox {
6494: clear:both;
6495: background: #F8F8F8; /* $sidebg; */
6496: border: 1px solid $sidebg;
6497: margin: 0 0 10px 0;
6498: padding: 3px;
6499: text-align: left;
6500: }
6501:
6502: .LC_fontsize_medium {
6503: font-size: 85%;
6504: }
6505:
6506: .LC_fontsize_large {
6507: font-size: 120%;
6508: }
6509:
6510: .LC_menubuttons_inline_text {
6511: color: $font;
6512: font-size: 90%;
6513: padding-left:3px;
6514: }
6515:
6516: .LC_menubuttons_inline_text img{
6517: vertical-align: middle;
6518: }
6519:
6520: li.LC_menubuttons_inline_text img {
6521: cursor:pointer;
6522: text-decoration: none;
6523: }
6524:
6525: .LC_menubuttons_link {
6526: text-decoration: none;
6527: }
6528:
6529: .LC_menubuttons_category {
6530: color: $font;
6531: background: $pgbg;
6532: font-size: larger;
6533: font-weight: bold;
6534: }
6535:
6536: td.LC_menubuttons_text {
6537: color: $font;
6538: }
6539:
6540: .LC_current_location {
6541: background: $tabbg;
6542: }
6543:
6544: td.LC_zero_height {
6545: line-height: 0;
6546: cellpadding: 0;
6547: }
6548:
6549: table.LC_data_table {
6550: border: 1px solid #000000;
6551: border-collapse: separate;
6552: border-spacing: 1px;
6553: background: $pgbg;
6554: }
6555:
6556: .LC_data_table_dense {
6557: font-size: small;
6558: }
6559:
6560: table.LC_nested_outer {
6561: border: 1px solid #000000;
6562: border-collapse: collapse;
6563: border-spacing: 0;
6564: width: 100%;
6565: }
6566:
6567: table.LC_innerpickbox,
6568: table.LC_nested {
6569: border: none;
6570: border-collapse: collapse;
6571: border-spacing: 0;
6572: width: 100%;
6573: }
6574:
6575: table.LC_data_table tr th,
6576: table.LC_calendar tr th,
6577: table.LC_prior_tries tr th,
6578: table.LC_innerpickbox tr th {
6579: font-weight: bold;
6580: background-color: $data_table_head;
6581: color:$fontmenu;
6582: font-size:90%;
6583: }
6584:
6585: table.LC_innerpickbox tr th,
6586: table.LC_innerpickbox tr td {
6587: vertical-align: top;
6588: }
6589:
6590: table.LC_data_table tr.LC_info_row > td {
6591: background-color: #CCCCCC;
6592: font-weight: bold;
6593: text-align: left;
6594: }
6595:
6596: table.LC_data_table tr.LC_odd_row > td {
6597: background-color: $data_table_light;
6598: padding: 2px;
6599: vertical-align: top;
6600: }
6601:
6602: table.LC_pick_box tr > td.LC_odd_row {
6603: background-color: $data_table_light;
6604: vertical-align: top;
6605: }
6606:
6607: table.LC_data_table tr.LC_even_row > td {
6608: background-color: $data_table_dark;
6609: padding: 2px;
6610: vertical-align: top;
6611: }
6612:
6613: table.LC_pick_box tr > td.LC_even_row {
6614: background-color: $data_table_dark;
6615: vertical-align: top;
6616: }
6617:
6618: table.LC_data_table tr.LC_data_table_highlight td {
6619: background-color: $data_table_darker;
6620: }
6621:
6622: table.LC_data_table tr td.LC_leftcol_header {
6623: background-color: $data_table_head;
6624: font-weight: bold;
6625: }
6626:
6627: table.LC_data_table tr.LC_empty_row td,
6628: table.LC_nested tr.LC_empty_row td {
6629: font-weight: bold;
6630: font-style: italic;
6631: text-align: center;
6632: padding: 8px;
6633: }
6634:
6635: table.LC_data_table tr.LC_empty_row td,
6636: table.LC_data_table tr.LC_footer_row td {
6637: background-color: $sidebg;
6638: }
6639:
6640: table.LC_nested tr.LC_empty_row td {
6641: background-color: #FFFFFF;
6642: }
6643:
6644: table.LC_caption {
6645: }
6646:
6647: table.LC_nested tr.LC_empty_row td {
6648: padding: 4ex
6649: }
6650:
6651: table.LC_nested_outer tr th {
6652: font-weight: bold;
6653: color:$fontmenu;
6654: background-color: $data_table_head;
6655: font-size: small;
6656: border-bottom: 1px solid #000000;
6657: }
6658:
6659: table.LC_nested_outer tr td.LC_subheader {
6660: background-color: $data_table_head;
6661: font-weight: bold;
6662: font-size: small;
6663: border-bottom: 1px solid #000000;
6664: text-align: right;
6665: }
6666:
6667: table.LC_nested tr.LC_info_row td {
6668: background-color: #CCCCCC;
6669: font-weight: bold;
6670: font-size: small;
6671: text-align: center;
6672: }
6673:
6674: table.LC_nested tr.LC_info_row td.LC_left_item,
6675: table.LC_nested_outer tr th.LC_left_item {
6676: text-align: left;
6677: }
6678:
6679: table.LC_nested td {
6680: background-color: #FFFFFF;
6681: font-size: small;
6682: }
6683:
6684: table.LC_nested_outer tr th.LC_right_item,
6685: table.LC_nested tr.LC_info_row td.LC_right_item,
6686: table.LC_nested tr.LC_odd_row td.LC_right_item,
6687: table.LC_nested tr td.LC_right_item {
6688: text-align: right;
6689: }
6690:
6691: table.LC_nested tr.LC_odd_row td {
6692: background-color: #EEEEEE;
6693: }
6694:
6695: table.LC_createuser {
6696: }
6697:
6698: table.LC_createuser tr.LC_section_row td {
6699: font-size: small;
6700: }
6701:
6702: table.LC_createuser tr.LC_info_row td {
6703: background-color: #CCCCCC;
6704: font-weight: bold;
6705: text-align: center;
6706: }
6707:
6708: table.LC_calendar {
6709: border: 1px solid #000000;
6710: border-collapse: collapse;
6711: width: 98%;
6712: }
6713:
6714: table.LC_calendar_pickdate {
6715: font-size: xx-small;
6716: }
6717:
6718: table.LC_calendar tr td {
6719: border: 1px solid #000000;
6720: vertical-align: top;
6721: width: 14%;
6722: }
6723:
6724: table.LC_calendar tr td.LC_calendar_day_empty {
6725: background-color: $data_table_dark;
6726: }
6727:
6728: table.LC_calendar tr td.LC_calendar_day_current {
6729: background-color: $data_table_highlight;
6730: }
6731:
6732: table.LC_data_table tr td.LC_mail_new {
6733: background-color: $mail_new;
6734: }
6735:
6736: table.LC_data_table tr.LC_mail_new:hover {
6737: background-color: $mail_new_hover;
6738: }
6739:
6740: table.LC_data_table tr td.LC_mail_read {
6741: background-color: $mail_read;
6742: }
6743:
6744: /*
6745: table.LC_data_table tr.LC_mail_read:hover {
6746: background-color: $mail_read_hover;
6747: }
6748: */
6749:
6750: table.LC_data_table tr td.LC_mail_replied {
6751: background-color: $mail_replied;
6752: }
6753:
6754: /*
6755: table.LC_data_table tr.LC_mail_replied:hover {
6756: background-color: $mail_replied_hover;
6757: }
6758: */
6759:
6760: table.LC_data_table tr td.LC_mail_other {
6761: background-color: $mail_other;
6762: }
6763:
6764: /*
6765: table.LC_data_table tr.LC_mail_other:hover {
6766: background-color: $mail_other_hover;
6767: }
6768: */
6769:
6770: table.LC_data_table tr > td.LC_browser_file,
6771: table.LC_data_table tr > td.LC_browser_file_published {
6772: background: #AAEE77;
6773: }
6774:
6775: table.LC_data_table tr > td.LC_browser_file_locked,
6776: table.LC_data_table tr > td.LC_browser_file_unpublished {
6777: background: #FFAA99;
6778: }
6779:
6780: table.LC_data_table tr > td.LC_browser_file_obsolete {
6781: background: #888888;
6782: }
6783:
6784: table.LC_data_table tr > td.LC_browser_file_modified,
6785: table.LC_data_table tr > td.LC_browser_file_metamodified {
6786: background: #F8F866;
6787: }
6788:
6789: table.LC_data_table tr.LC_browser_folder > td {
6790: background: #E0E8FF;
6791: }
6792:
6793: table.LC_data_table tr > td.LC_roles_is {
6794: /* background: #77FF77; */
6795: }
6796:
6797: table.LC_data_table tr > td.LC_roles_future {
6798: border-right: 8px solid #FFFF77;
6799: }
6800:
6801: table.LC_data_table tr > td.LC_roles_will {
6802: border-right: 8px solid #FFAA77;
6803: }
6804:
6805: table.LC_data_table tr > td.LC_roles_expired {
6806: border-right: 8px solid #FF7777;
6807: }
6808:
6809: table.LC_data_table tr > td.LC_roles_will_not {
6810: border-right: 8px solid #AAFF77;
6811: }
6812:
6813: table.LC_data_table tr > td.LC_roles_selected {
6814: border-right: 8px solid #11CC55;
6815: }
6816:
6817: span.LC_current_location {
6818: font-size:larger;
6819: background: $pgbg;
6820: }
6821:
6822: span.LC_current_nav_location {
6823: font-weight:bold;
6824: background: $sidebg;
6825: }
6826:
6827: span.LC_parm_menu_item {
6828: font-size: larger;
6829: }
6830:
6831: span.LC_parm_scope_all {
6832: color: red;
6833: }
6834:
6835: span.LC_parm_scope_folder {
6836: color: green;
6837: }
6838:
6839: span.LC_parm_scope_resource {
6840: color: orange;
6841: }
6842:
6843: span.LC_parm_part {
6844: color: blue;
6845: }
6846:
6847: span.LC_parm_folder,
6848: span.LC_parm_symb {
6849: font-size: x-small;
6850: font-family: $mono;
6851: color: #AAAAAA;
6852: }
6853:
6854: ul.LC_parm_parmlist li {
6855: display: inline-block;
6856: padding: 0.3em 0.8em;
6857: vertical-align: top;
6858: width: 150px;
6859: border-top:1px solid $lg_border_color;
6860: }
6861:
6862: td.LC_parm_overview_level_menu,
6863: td.LC_parm_overview_map_menu,
6864: td.LC_parm_overview_parm_selectors,
6865: td.LC_parm_overview_restrictions {
6866: border: 1px solid black;
6867: border-collapse: collapse;
6868: }
6869:
6870: span.LC_parm_recursive,
6871: td.LC_parm_recursive {
6872: font-weight: bold;
6873: font-size: smaller;
6874: }
6875:
6876: table.LC_parm_overview_restrictions td {
6877: border-width: 1px 4px 1px 4px;
6878: border-style: solid;
6879: border-color: $pgbg;
6880: text-align: center;
6881: }
6882:
6883: table.LC_parm_overview_restrictions th {
6884: background: $tabbg;
6885: border-width: 1px 4px 1px 4px;
6886: border-style: solid;
6887: border-color: $pgbg;
6888: }
6889:
6890: table#LC_helpmenu {
6891: border: none;
6892: height: 55px;
6893: border-spacing: 0;
6894: }
6895:
6896: table#LC_helpmenu fieldset legend {
6897: font-size: larger;
6898: }
6899:
6900: table#LC_helpmenu_links {
6901: width: 100%;
6902: border: 1px solid black;
6903: background: $pgbg;
6904: padding: 0;
6905: border-spacing: 1px;
6906: }
6907:
6908: table#LC_helpmenu_links tr td {
6909: padding: 1px;
6910: background: $tabbg;
6911: text-align: center;
6912: font-weight: bold;
6913: }
6914:
6915: table#LC_helpmenu_links a:link,
6916: table#LC_helpmenu_links a:visited,
6917: table#LC_helpmenu_links a:active {
6918: text-decoration: none;
6919: color: $font;
6920: }
6921:
6922: table#LC_helpmenu_links a:hover {
6923: text-decoration: underline;
6924: color: $vlink;
6925: }
6926:
6927: .LC_chrt_popup_exists {
6928: border: 1px solid #339933;
6929: margin: -1px;
6930: }
6931:
6932: .LC_chrt_popup_up {
6933: border: 1px solid yellow;
6934: margin: -1px;
6935: }
6936:
6937: .LC_chrt_popup {
6938: border: 1px solid #8888FF;
6939: background: #CCCCFF;
6940: }
6941:
6942: table.LC_pick_box {
6943: border-collapse: separate;
6944: background: white;
6945: border: 1px solid black;
6946: border-spacing: 1px;
6947: }
6948:
6949: table.LC_pick_box td.LC_pick_box_title {
6950: background: $sidebg;
6951: font-weight: bold;
6952: text-align: left;
6953: vertical-align: top;
6954: width: 184px;
6955: padding: 8px;
6956: }
6957:
6958: table.LC_pick_box td.LC_pick_box_value {
6959: text-align: left;
6960: padding: 8px;
6961: }
6962:
6963: table.LC_pick_box td.LC_pick_box_select {
6964: text-align: left;
6965: padding: 8px;
6966: }
6967:
6968: table.LC_pick_box td.LC_pick_box_separator {
6969: padding: 0;
6970: height: 1px;
6971: background: black;
6972: }
6973:
6974: table.LC_pick_box td.LC_pick_box_submit {
6975: text-align: right;
6976: }
6977:
6978: table.LC_pick_box td.LC_evenrow_value {
6979: text-align: left;
6980: padding: 8px;
6981: background-color: $data_table_light;
6982: }
6983:
6984: table.LC_pick_box td.LC_oddrow_value {
6985: text-align: left;
6986: padding: 8px;
6987: background-color: $data_table_light;
6988: }
6989:
6990: span.LC_helpform_receipt_cat {
6991: font-weight: bold;
6992: }
6993:
6994: table.LC_group_priv_box {
6995: background: white;
6996: border: 1px solid black;
6997: border-spacing: 1px;
6998: }
6999:
7000: table.LC_group_priv_box td.LC_pick_box_title {
7001: background: $tabbg;
7002: font-weight: bold;
7003: text-align: right;
7004: width: 184px;
7005: }
7006:
7007: table.LC_group_priv_box td.LC_groups_fixed {
7008: background: $data_table_light;
7009: text-align: center;
7010: }
7011:
7012: table.LC_group_priv_box td.LC_groups_optional {
7013: background: $data_table_dark;
7014: text-align: center;
7015: }
7016:
7017: table.LC_group_priv_box td.LC_groups_functionality {
7018: background: $data_table_darker;
7019: text-align: center;
7020: font-weight: bold;
7021: }
7022:
7023: table.LC_group_priv td {
7024: text-align: left;
7025: padding: 0;
7026: }
7027:
7028: .LC_navbuttons {
7029: margin: 2ex 0ex 2ex 0ex;
7030: }
7031:
7032: .LC_topic_bar {
7033: font-weight: bold;
7034: background: $tabbg;
7035: margin: 1em 0em 1em 2em;
7036: padding: 3px;
7037: font-size: 1.2em;
7038: }
7039:
7040: .LC_topic_bar span {
7041: left: 0.5em;
7042: position: absolute;
7043: vertical-align: middle;
7044: font-size: 1.2em;
7045: }
7046:
7047: table.LC_course_group_status {
7048: margin: 20px;
7049: }
7050:
7051: table.LC_status_selector td {
7052: vertical-align: top;
7053: text-align: center;
7054: padding: 4px;
7055: }
7056:
7057: div.LC_feedback_link {
7058: clear: both;
7059: background: $sidebg;
7060: width: 100%;
7061: padding-bottom: 10px;
7062: border: 1px $tabbg solid;
7063: height: 22px;
7064: line-height: 22px;
7065: padding-top: 5px;
7066: }
7067:
7068: div.LC_feedback_link img {
7069: height: 22px;
7070: vertical-align:middle;
7071: }
7072:
7073: div.LC_feedback_link a {
7074: text-decoration: none;
7075: }
7076:
7077: div.LC_comblock {
7078: display:inline;
7079: color:$font;
7080: font-size:90%;
7081: }
7082:
7083: div.LC_feedback_link div.LC_comblock {
7084: padding-left:5px;
7085: }
7086:
7087: div.LC_feedback_link div.LC_comblock a {
7088: color:$font;
7089: }
7090:
7091: span.LC_feedback_link {
7092: /* background: $feedback_link_bg; */
7093: font-size: larger;
7094: }
7095:
7096: span.LC_message_link {
7097: /* background: $feedback_link_bg; */
7098: font-size: larger;
7099: position: absolute;
7100: right: 1em;
7101: }
7102:
7103: table.LC_prior_tries {
7104: border: 1px solid #000000;
7105: border-collapse: separate;
7106: border-spacing: 1px;
7107: }
7108:
7109: table.LC_prior_tries td {
7110: padding: 2px;
7111: }
7112:
7113: .LC_answer_correct {
7114: background: lightgreen;
7115: color: darkgreen;
7116: padding: 6px;
7117: }
7118:
7119: .LC_answer_charged_try {
7120: background: #FFAAAA;
7121: color: darkred;
7122: padding: 6px;
7123: }
7124:
7125: .LC_answer_not_charged_try,
7126: .LC_answer_no_grade,
7127: .LC_answer_late {
7128: background: lightyellow;
7129: color: black;
7130: padding: 6px;
7131: }
7132:
7133: .LC_answer_previous {
7134: background: lightblue;
7135: color: darkblue;
7136: padding: 6px;
7137: }
7138:
7139: .LC_answer_no_message {
7140: background: #FFFFFF;
7141: color: black;
7142: padding: 6px;
7143: }
7144:
7145: .LC_answer_unknown {
7146: background: orange;
7147: color: black;
7148: padding: 6px;
7149: }
7150:
7151: span.LC_prior_numerical,
7152: span.LC_prior_string,
7153: span.LC_prior_custom,
7154: span.LC_prior_reaction,
7155: span.LC_prior_math {
7156: font-family: $mono;
7157: white-space: pre;
7158: }
7159:
7160: span.LC_prior_string {
7161: font-family: $mono;
7162: white-space: pre;
7163: }
7164:
7165: table.LC_prior_option {
7166: width: 100%;
7167: border-collapse: collapse;
7168: }
7169:
7170: table.LC_prior_rank,
7171: table.LC_prior_match {
7172: border-collapse: collapse;
7173: }
7174:
7175: table.LC_prior_option tr td,
7176: table.LC_prior_rank tr td,
7177: table.LC_prior_match tr td {
7178: border: 1px solid #000000;
7179: }
7180:
7181: .LC_nobreak {
7182: white-space: nowrap;
7183: }
7184:
7185: span.LC_cusr_emph {
7186: font-style: italic;
7187: }
7188:
7189: span.LC_cusr_subheading {
7190: font-weight: normal;
7191: font-size: 85%;
7192: }
7193:
7194: div.LC_docs_entry_move {
7195: border: 1px solid #BBBBBB;
7196: background: #DDDDDD;
7197: width: 22px;
7198: padding: 1px;
7199: margin: 0;
7200: }
7201:
7202: table.LC_data_table tr > td.LC_docs_entry_commands,
7203: table.LC_data_table tr > td.LC_docs_entry_parameter {
7204: font-size: x-small;
7205: }
7206:
7207: .LC_docs_entry_parameter {
7208: white-space: nowrap;
7209: }
7210:
7211: .LC_docs_copy {
7212: color: #000099;
7213: }
7214:
7215: .LC_docs_cut {
7216: color: #550044;
7217: }
7218:
7219: .LC_docs_rename {
7220: color: #009900;
7221: }
7222:
7223: .LC_docs_remove {
7224: color: #990000;
7225: }
7226:
7227: .LC_docs_alias {
7228: color: #440055;
7229: }
7230:
7231: .LC_domprefs_email,
7232: .LC_docs_alias_name,
7233: .LC_docs_reinit_warn,
7234: .LC_docs_ext_edit {
7235: font-size: x-small;
7236: }
7237:
7238: table.LC_docs_adddocs td,
7239: table.LC_docs_adddocs th {
7240: border: 1px solid #BBBBBB;
7241: padding: 4px;
7242: background: #DDDDDD;
7243: }
7244:
7245: table.LC_sty_begin {
7246: background: #BBFFBB;
7247: }
7248:
7249: table.LC_sty_end {
7250: background: #FFBBBB;
7251: }
7252:
7253: table.LC_double_column {
7254: border-width: 0;
7255: border-collapse: collapse;
7256: width: 100%;
7257: padding: 2px;
7258: }
7259:
7260: table.LC_double_column tr td.LC_left_col {
7261: top: 2px;
7262: left: 2px;
7263: width: 47%;
7264: vertical-align: top;
7265: }
7266:
7267: table.LC_double_column tr td.LC_right_col {
7268: top: 2px;
7269: right: 2px;
7270: width: 47%;
7271: vertical-align: top;
7272: }
7273:
7274: div.LC_left_float {
7275: float: left;
7276: padding-right: 5%;
7277: padding-bottom: 4px;
7278: }
7279:
7280: div.LC_clear_float_header {
7281: padding-bottom: 2px;
7282: }
7283:
7284: div.LC_clear_float_footer {
7285: padding-top: 10px;
7286: clear: both;
7287: }
7288:
7289: div.LC_grade_show_user {
7290: /* border-left: 5px solid $sidebg; */
7291: border-top: 5px solid #000000;
7292: margin: 50px 0 0 0;
7293: padding: 15px 0 5px 10px;
7294: }
7295:
7296: div.LC_grade_show_user_odd_row {
7297: /* border-left: 5px solid #000000; */
7298: }
7299:
7300: div.LC_grade_show_user div.LC_Box {
7301: margin-right: 50px;
7302: }
7303:
7304: div.LC_grade_submissions,
7305: div.LC_grade_message_center,
7306: div.LC_grade_info_links {
7307: margin: 5px;
7308: width: 99%;
7309: background: #FFFFFF;
7310: }
7311:
7312: div.LC_grade_submissions_header,
7313: div.LC_grade_message_center_header {
7314: font-weight: bold;
7315: font-size: large;
7316: }
7317:
7318: div.LC_grade_submissions_body,
7319: div.LC_grade_message_center_body {
7320: border: 1px solid black;
7321: width: 99%;
7322: background: #FFFFFF;
7323: }
7324:
7325: table.LC_scantron_action {
7326: width: 100%;
7327: }
7328:
7329: table.LC_scantron_action tr th {
7330: font-weight:bold;
7331: font-style:normal;
7332: }
7333:
7334: .LC_edit_problem_header,
7335: div.LC_edit_problem_footer {
7336: font-weight: normal;
7337: font-size: medium;
7338: margin: 2px;
7339: background-color: $sidebg;
7340: }
7341:
7342: div.LC_edit_problem_header,
7343: div.LC_edit_problem_header div,
7344: div.LC_edit_problem_footer,
7345: div.LC_edit_problem_footer div,
7346: div.LC_edit_problem_editxml_header,
7347: div.LC_edit_problem_editxml_header div {
7348: z-index: 100;
7349: }
7350:
7351: div.LC_edit_problem_header_title {
7352: font-weight: bold;
7353: font-size: larger;
7354: background: $tabbg;
7355: padding: 3px;
7356: margin: 0 0 5px 0;
7357: }
7358:
7359: table.LC_edit_problem_header_title {
7360: width: 100%;
7361: background: $tabbg;
7362: }
7363:
7364: div.LC_edit_actionbar {
7365: background-color: $sidebg;
7366: margin: 0;
7367: padding: 0;
7368: line-height: 200%;
7369: }
7370:
7371: div.LC_edit_actionbar div{
7372: padding: 0;
7373: margin: 0;
7374: display: inline-block;
7375: }
7376:
7377: .LC_edit_opt {
7378: padding-left: 1em;
7379: white-space: nowrap;
7380: }
7381:
7382: .LC_edit_problem_latexhelper{
7383: text-align: right;
7384: }
7385:
7386: #LC_edit_problem_colorful div{
7387: margin-left: 40px;
7388: }
7389:
7390: #LC_edit_problem_codemirror div{
7391: margin-left: 0px;
7392: }
7393:
7394: img.stift {
7395: border-width: 0;
7396: vertical-align: middle;
7397: }
7398:
7399: table td.LC_mainmenu_col_fieldset {
7400: vertical-align: top;
7401: }
7402:
7403: div.LC_createcourse {
7404: margin: 10px 10px 10px 10px;
7405: }
7406:
7407: .LC_dccid {
7408: float: right;
7409: margin: 0.2em 0 0 0;
7410: padding: 0;
7411: font-size: 90%;
7412: display:none;
7413: }
7414:
7415: ol.LC_primary_menu a:hover,
7416: ol#LC_MenuBreadcrumbs a:hover,
7417: ol#LC_PathBreadcrumbs a:hover,
7418: ul#LC_secondary_menu a:hover,
7419: .LC_FormSectionClearButton input:hover
7420: ul.LC_TabContent li:hover a {
7421: color:$button_hover;
7422: text-decoration:none;
7423: }
7424:
7425: h1 {
7426: padding: 0;
7427: line-height:130%;
7428: }
7429:
7430: h2,
7431: h3,
7432: h4,
7433: h5,
7434: h6 {
7435: margin: 5px 0 5px 0;
7436: padding: 0;
7437: line-height:130%;
7438: }
7439:
7440: .LC_hcell {
7441: padding:3px 15px 3px 15px;
7442: margin: 0;
7443: background-color:$tabbg;
7444: color:$fontmenu;
7445: border-bottom:solid 1px $lg_border_color;
7446: }
7447:
7448: .LC_Box > .LC_hcell {
7449: margin: 0 -10px 10px -10px;
7450: }
7451:
7452: .LC_noBorder {
7453: border: 0;
7454: }
7455:
7456: .LC_FormSectionClearButton input {
7457: background-color:transparent;
7458: border: none;
7459: cursor:pointer;
7460: text-decoration:underline;
7461: }
7462:
7463: .LC_help_open_topic {
7464: color: #FFFFFF;
7465: background-color: #EEEEFF;
7466: margin: 1px;
7467: padding: 4px;
7468: border: 1px solid #000033;
7469: white-space: nowrap;
7470: /* vertical-align: middle; */
7471: }
7472:
7473: dl,
7474: ul,
7475: div,
7476: fieldset {
7477: margin: 10px 10px 10px 0;
7478: /* overflow: hidden; */
7479: }
7480:
7481: article.geogebraweb div {
7482: margin: 0;
7483: }
7484:
7485: fieldset > legend {
7486: font-weight: bold;
7487: padding: 0 5px 0 5px;
7488: }
7489:
7490: #LC_nav_bar {
7491: float: left;
7492: background-color: $pgbg_or_bgcolor;
7493: margin: 0 0 2px 0;
7494: }
7495:
7496: #LC_realm {
7497: margin: 0.2em 0 0 0;
7498: padding: 0;
7499: font-weight: bold;
7500: text-align: center;
7501: background-color: $pgbg_or_bgcolor;
7502: }
7503:
7504: #LC_nav_bar em {
7505: font-weight: bold;
7506: font-style: normal;
7507: }
7508:
7509: ol.LC_primary_menu {
7510: margin: 0;
7511: padding: 0;
7512: }
7513:
7514: ol#LC_PathBreadcrumbs {
7515: margin: 0;
7516: }
7517:
7518: ol.LC_primary_menu li {
7519: color: RGB(80, 80, 80);
7520: vertical-align: middle;
7521: text-align: left;
7522: list-style: none;
7523: position: relative;
7524: float: left;
7525: z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
7526: line-height: 1.5em;
7527: }
7528:
7529: ol.LC_primary_menu li a,
7530: ol.LC_primary_menu li p {
7531: display: block;
7532: margin: 0;
7533: padding: 0 5px 0 10px;
7534: text-decoration: none;
7535: }
7536:
7537: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
7538: display: inline-block;
7539: width: 95%;
7540: text-align: left;
7541: }
7542:
7543: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
7544: display: inline-block;
7545: width: 5%;
7546: float: right;
7547: text-align: right;
7548: font-size: 70%;
7549: }
7550:
7551: ol.LC_primary_menu ul {
7552: display: none;
7553: width: 15em;
7554: background-color: $data_table_light;
7555: position: absolute;
7556: top: 100%;
7557: }
7558:
7559: ol.LC_primary_menu ul ul {
7560: left: 100%;
7561: top: 0;
7562: }
7563:
7564: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
7565: display: block;
7566: position: absolute;
7567: margin: 0;
7568: padding: 0;
7569: z-index: 2;
7570: }
7571:
7572: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
7573: /* First Submenu -> size should be smaller than the menu title of the whole menu */
7574: font-size: 90%;
7575: vertical-align: top;
7576: float: none;
7577: border-left: 1px solid black;
7578: border-right: 1px solid black;
7579: /* A dark bottom border to visualize different menu options;
7580: overwritten in the create_submenu routine for the last border-bottom of the menu */
7581: border-bottom: 1px solid $data_table_dark;
7582: }
7583:
7584: ol.LC_primary_menu li li p:hover {
7585: color:$button_hover;
7586: text-decoration:none;
7587: background-color:$data_table_dark;
7588: }
7589:
7590: ol.LC_primary_menu li li a:hover {
7591: color:$button_hover;
7592: background-color:$data_table_dark;
7593: }
7594:
7595: /* Font-size equal to the size of the predecessors*/
7596: ol.LC_primary_menu li:hover li li {
7597: font-size: 100%;
7598: }
7599:
7600: ol.LC_primary_menu li img {
7601: vertical-align: bottom;
7602: height: 1.1em;
7603: margin: 0.2em 0 0 0;
7604: }
7605:
7606: ol.LC_primary_menu a {
7607: color: RGB(80, 80, 80);
7608: text-decoration: none;
7609: }
7610:
7611: ol.LC_primary_menu a.LC_new_message {
7612: font-weight:bold;
7613: color: darkred;
7614: }
7615:
7616: ol.LC_docs_parameters {
7617: margin-left: 0;
7618: padding: 0;
7619: list-style: none;
7620: }
7621:
7622: ol.LC_docs_parameters li {
7623: margin: 0;
7624: padding-right: 20px;
7625: display: inline;
7626: }
7627:
7628: ol.LC_docs_parameters li:before {
7629: content: "\\002022 \\0020";
7630: }
7631:
7632: li.LC_docs_parameters_title {
7633: font-weight: bold;
7634: }
7635:
7636: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
7637: content: "";
7638: }
7639:
7640: ul#LC_secondary_menu {
7641: clear: right;
7642: color: $fontmenu;
7643: background: $tabbg;
7644: list-style: none;
7645: padding: 0;
7646: margin: 0;
7647: width: 100%;
7648: text-align: left;
7649: float: left;
7650: }
7651:
7652: ul#LC_secondary_menu li {
7653: font-weight: bold;
7654: line-height: 1.8em;
7655: border-right: 1px solid black;
7656: float: left;
7657: }
7658:
7659: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
7660: background-color: $data_table_light;
7661: }
7662:
7663: ul#LC_secondary_menu li a {
7664: padding: 0 0.8em;
7665: }
7666:
7667: ul#LC_secondary_menu li ul {
7668: display: none;
7669: }
7670:
7671: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
7672: display: block;
7673: position: absolute;
7674: margin: 0;
7675: padding: 0;
7676: list-style:none;
7677: float: none;
7678: background-color: $data_table_light;
7679: z-index: 2;
7680: margin-left: -1px;
7681: }
7682:
7683: ul#LC_secondary_menu li ul li {
7684: font-size: 90%;
7685: vertical-align: top;
7686: border-left: 1px solid black;
7687: border-right: 1px solid black;
7688: background-color: $data_table_light;
7689: list-style:none;
7690: float: none;
7691: }
7692:
7693: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
7694: background-color: $data_table_dark;
7695: }
7696:
7697: ul.LC_TabContent {
7698: display:block;
7699: background: $sidebg;
7700: border-bottom: solid 1px $lg_border_color;
7701: list-style:none;
7702: margin: -1px -10px 0 -10px;
7703: padding: 0;
7704: }
7705:
7706: ul.LC_TabContent li,
7707: ul.LC_TabContentBigger li {
7708: float:left;
7709: }
7710:
7711: ul#LC_secondary_menu li a {
7712: color: $fontmenu;
7713: text-decoration: none;
7714: }
7715:
7716: ul.LC_TabContent {
7717: min-height:20px;
7718: }
7719:
7720: ul.LC_TabContent li {
7721: vertical-align:middle;
7722: padding: 0 16px 0 10px;
7723: background-color:$tabbg;
7724: border-bottom:solid 1px $lg_border_color;
7725: border-left: solid 1px $font;
7726: }
7727:
7728: ul.LC_TabContent .right {
7729: float:right;
7730: }
7731:
7732: ul.LC_TabContent li a,
7733: ul.LC_TabContent li {
7734: color:rgb(47,47,47);
7735: text-decoration:none;
7736: font-size:95%;
7737: font-weight:bold;
7738: min-height:20px;
7739: }
7740:
7741: ul.LC_TabContent li a:hover,
7742: ul.LC_TabContent li a:focus {
7743: color: $button_hover;
7744: background:none;
7745: outline:none;
7746: }
7747:
7748: ul.LC_TabContent li:hover {
7749: color: $button_hover;
7750: cursor:pointer;
7751: }
7752:
7753: ul.LC_TabContent li.active {
7754: color: $font;
7755: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
7756: border-bottom:solid 1px #FFFFFF;
7757: cursor: default;
7758: }
7759:
7760: ul.LC_TabContent li.active a {
7761: color:$font;
7762: background:#FFFFFF;
7763: outline: none;
7764: }
7765:
7766: ul.LC_TabContent li.goback {
7767: float: left;
7768: border-left: none;
7769: }
7770:
7771: #maincoursedoc {
7772: clear:both;
7773: }
7774:
7775: ul.LC_TabContentBigger {
7776: display:block;
7777: list-style:none;
7778: padding: 0;
7779: }
7780:
7781: ul.LC_TabContentBigger li {
7782: vertical-align:bottom;
7783: height: 30px;
7784: font-size:110%;
7785: font-weight:bold;
7786: color: #737373;
7787: }
7788:
7789: ul.LC_TabContentBigger li.active {
7790: position: relative;
7791: top: 1px;
7792: }
7793:
7794: ul.LC_TabContentBigger li a {
7795: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
7796: height: 30px;
7797: line-height: 30px;
7798: text-align: center;
7799: display: block;
7800: text-decoration: none;
7801: outline: none;
7802: }
7803:
7804: ul.LC_TabContentBigger li.active a {
7805: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
7806: color:$font;
7807: }
7808:
7809: ul.LC_TabContentBigger li b {
7810: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
7811: display: block;
7812: float: left;
7813: padding: 0 30px;
7814: border-bottom: 1px solid $lg_border_color;
7815: }
7816:
7817: ul.LC_TabContentBigger li:hover b {
7818: color:$button_hover;
7819: }
7820:
7821: ul.LC_TabContentBigger li.active b {
7822: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
7823: color:$font;
7824: border: 0;
7825: }
7826:
7827:
7828: ul.LC_CourseBreadcrumbs {
7829: background: $sidebg;
7830: height: 2em;
7831: padding-left: 10px;
7832: margin: 0;
7833: list-style-position: inside;
7834: }
7835:
7836: ol#LC_MenuBreadcrumbs,
7837: ol#LC_PathBreadcrumbs {
7838: padding-left: 10px;
7839: margin: 0;
7840: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
7841: }
7842:
7843: ol#LC_MenuBreadcrumbs li,
7844: ol#LC_PathBreadcrumbs li,
7845: ul.LC_CourseBreadcrumbs li {
7846: display: inline;
7847: white-space: normal;
7848: }
7849:
7850: ol#LC_MenuBreadcrumbs li a,
7851: ul.LC_CourseBreadcrumbs li a {
7852: text-decoration: none;
7853: font-size:90%;
7854: }
7855:
7856: ol#LC_MenuBreadcrumbs h1 {
7857: display: inline;
7858: font-size: 90%;
7859: line-height: 2.5em;
7860: margin: 0;
7861: padding: 0;
7862: }
7863:
7864: ol#LC_PathBreadcrumbs li a {
7865: text-decoration:none;
7866: font-size:100%;
7867: font-weight:bold;
7868: }
7869:
7870: .LC_Box {
7871: border: solid 1px $lg_border_color;
7872: padding: 0 10px 10px 10px;
7873: }
7874:
7875: .LC_DocsBox {
7876: border: solid 1px $lg_border_color;
7877: padding: 0 0 10px 10px;
7878: }
7879:
7880: .LC_AboutMe_Image {
7881: float:left;
7882: margin-right:10px;
7883: }
7884:
7885: .LC_Clear_AboutMe_Image {
7886: clear:left;
7887: }
7888:
7889: dl.LC_ListStyleClean dt {
7890: padding-right: 5px;
7891: display: table-header-group;
7892: }
7893:
7894: dl.LC_ListStyleClean dd {
7895: display: table-row;
7896: }
7897:
7898: .LC_ListStyleClean,
7899: .LC_ListStyleSimple,
7900: .LC_ListStyleNormal,
7901: .LC_ListStyleSpecial {
7902: /* display:block; */
7903: list-style-position: inside;
7904: list-style-type: none;
7905: overflow: hidden;
7906: padding: 0;
7907: }
7908:
7909: .LC_ListStyleSimple li,
7910: .LC_ListStyleSimple dd,
7911: .LC_ListStyleNormal li,
7912: .LC_ListStyleNormal dd,
7913: .LC_ListStyleSpecial li,
7914: .LC_ListStyleSpecial dd {
7915: margin: 0;
7916: padding: 5px 5px 5px 10px;
7917: clear: both;
7918: }
7919:
7920: .LC_ListStyleClean li,
7921: .LC_ListStyleClean dd {
7922: padding-top: 0;
7923: padding-bottom: 0;
7924: }
7925:
7926: .LC_ListStyleSimple dd,
7927: .LC_ListStyleSimple li {
7928: border-bottom: solid 1px $lg_border_color;
7929: }
7930:
7931: .LC_ListStyleSpecial li,
7932: .LC_ListStyleSpecial dd {
7933: list-style-type: none;
7934: background-color: RGB(220, 220, 220);
7935: margin-bottom: 4px;
7936: }
7937:
7938: table.LC_SimpleTable {
7939: margin:5px;
7940: border:solid 1px $lg_border_color;
7941: }
7942:
7943: table.LC_SimpleTable tr {
7944: padding: 0;
7945: border:solid 1px $lg_border_color;
7946: }
7947:
7948: table.LC_SimpleTable thead {
7949: background:rgb(220,220,220);
7950: }
7951:
7952: div.LC_columnSection {
7953: display: block;
7954: clear: both;
7955: overflow: hidden;
7956: margin: 0;
7957: }
7958:
7959: div.LC_columnSection>* {
7960: float: left;
7961: margin: 10px 20px 10px 0;
7962: overflow:hidden;
7963: }
7964:
7965: table em {
7966: font-weight: bold;
7967: font-style: normal;
7968: }
7969:
7970: table.LC_tableBrowseRes,
7971: table.LC_tableOfContent {
7972: border:none;
7973: border-spacing: 1px;
7974: padding: 3px;
7975: background-color: #FFFFFF;
7976: font-size: 90%;
7977: }
7978:
7979: table.LC_tableOfContent {
7980: border-collapse: collapse;
7981: }
7982:
7983: table.LC_tableBrowseRes a,
7984: table.LC_tableOfContent a {
7985: background-color: transparent;
7986: text-decoration: none;
7987: }
7988:
7989: table.LC_tableOfContent img {
7990: border: none;
7991: height: 1.3em;
7992: vertical-align: text-bottom;
7993: margin-right: 0.3em;
7994: }
7995:
7996: a#LC_content_toolbar_firsthomework {
7997: background-image:url(/res/adm/pages/open-first-problem.gif);
7998: }
7999:
8000: a#LC_content_toolbar_everything {
8001: background-image:url(/res/adm/pages/show-all.gif);
8002: }
8003:
8004: a#LC_content_toolbar_uncompleted {
8005: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
8006: }
8007:
8008: #LC_content_toolbar_clearbubbles {
8009: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
8010: }
8011:
8012: a#LC_content_toolbar_changefolder {
8013: background : url(/res/adm/pages/close-all-folders.gif) top center ;
8014: }
8015:
8016: a#LC_content_toolbar_changefolder_toggled {
8017: background-image:url(/res/adm/pages/open-all-folders.gif);
8018: }
8019:
8020: a#LC_content_toolbar_edittoplevel {
8021: background-image:url(/res/adm/pages/edittoplevel.gif);
8022: }
8023:
8024: ul#LC_toolbar li a:hover {
8025: background-position: bottom center;
8026: }
8027:
8028: ul#LC_toolbar {
8029: padding: 0;
8030: margin: 2px;
8031: list-style:none;
8032: position:relative;
8033: background-color:white;
8034: overflow: auto;
8035: }
8036:
8037: ul#LC_toolbar li {
8038: border:1px solid white;
8039: padding: 0;
8040: margin: 0;
8041: float: left;
8042: display:inline;
8043: vertical-align:middle;
8044: white-space: nowrap;
8045: }
8046:
8047:
8048: a.LC_toolbarItem {
8049: display:block;
8050: padding: 0;
8051: margin: 0;
8052: height: 32px;
8053: width: 32px;
8054: color:white;
8055: border: none;
8056: background-repeat:no-repeat;
8057: background-color:transparent;
8058: }
8059:
8060: ul.LC_funclist {
8061: margin: 0;
8062: padding: 0.5em 1em 0.5em 0;
8063: }
8064:
8065: ul.LC_funclist > li:first-child {
8066: font-weight:bold;
8067: margin-left:0.8em;
8068: }
8069:
8070: ul.LC_funclist + ul.LC_funclist {
8071: /*
8072: left border as a seperator if we have more than
8073: one list
8074: */
8075: border-left: 1px solid $sidebg;
8076: /*
8077: this hides the left border behind the border of the
8078: outer box if element is wrapped to the next 'line'
8079: */
8080: margin-left: -1px;
8081: }
8082:
8083: ul.LC_funclist li {
8084: display: inline;
8085: white-space: nowrap;
8086: margin: 0 0 0 25px;
8087: line-height: 150%;
8088: }
8089:
8090: .LC_hidden {
8091: display: none;
8092: }
8093:
8094: .LCmodal-overlay {
8095: position:fixed;
8096: top:0;
8097: right:0;
8098: bottom:0;
8099: left:0;
8100: height:100%;
8101: width:100%;
8102: margin:0;
8103: padding:0;
8104: background:#999;
8105: opacity:.75;
8106: filter: alpha(opacity=75);
8107: -moz-opacity: 0.75;
8108: z-index:101;
8109: }
8110:
8111: * html .LCmodal-overlay {
8112: position: absolute;
8113: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
8114: }
8115:
8116: .LCmodal-window {
8117: position:fixed;
8118: top:50%;
8119: left:50%;
8120: margin:0;
8121: padding:0;
8122: z-index:102;
8123: }
8124:
8125: * html .LCmodal-window {
8126: position:absolute;
8127: }
8128:
8129: .LCclose-window {
8130: position:absolute;
8131: width:32px;
8132: height:32px;
8133: right:8px;
8134: top:8px;
8135: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
8136: text-indent:-99999px;
8137: overflow:hidden;
8138: cursor:pointer;
8139: }
8140:
8141: /*
8142: styles used for response display
8143: */
8144: div.LC_radiofoil, div.LC_rankfoil {
8145: margin: .5em 0em .5em 0em;
8146: }
8147: table.LC_itemgroup {
8148: margin-top: 1em;
8149: }
8150:
8151: /*
8152: styles used by TTH when "Default set of options to pass to tth/m
8153: when converting TeX" in course settings has been set
8154:
8155: option passed: -t
8156:
8157: */
8158:
8159: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
8160: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
8161: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
8162: td div.norm {line-height:normal;}
8163:
8164: /*
8165: option passed -y3
8166: */
8167:
8168: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
8169: span.overacc2 {position: relative; left: .8em; top: -1.2ex;}
8170: span.overacc1 {position: relative; left: .6em; top: -1.2ex;}
8171:
8172: /*
8173: sections with roles, for content only
8174: */
8175: section[class^="role-"] {
8176: padding-left: 10px;
8177: padding-right: 5px;
8178: margin-top: 8px;
8179: margin-bottom: 8px;
8180: border: 1px solid #2A4;
8181: border-radius: 5px;
8182: box-shadow: 0px 1px 1px #BBB;
8183: }
8184: section[class^="role-"]>h1 {
8185: position: relative;
8186: margin: 0px;
8187: padding-top: 10px;
8188: padding-left: 40px;
8189: }
8190: section[class^="role-"]>h1:before {
8191: position: absolute;
8192: left: -5px;
8193: top: 5px;
8194: }
8195: section.role-activity>h1:before {
8196: content:url('/adm/daxe/images/section_icons/activity.png');
8197: }
8198: section.role-advice>h1:before {
8199: content:url('/adm/daxe/images/section_icons/advice.png');
8200: }
8201: section.role-bibliography>h1:before {
8202: content:url('/adm/daxe/images/section_icons/bibliography.png');
8203: }
8204: section.role-citation>h1:before {
8205: content:url('/adm/daxe/images/section_icons/citation.png');
8206: }
8207: section.role-conclusion>h1:before {
8208: content:url('/adm/daxe/images/section_icons/conclusion.png');
8209: }
8210: section.role-definition>h1:before {
8211: content:url('/adm/daxe/images/section_icons/definition.png');
8212: }
8213: section.role-demonstration>h1:before {
8214: content:url('/adm/daxe/images/section_icons/demonstration.png');
8215: }
8216: section.role-example>h1:before {
8217: content:url('/adm/daxe/images/section_icons/example.png');
8218: }
8219: section.role-explanation>h1:before {
8220: content:url('/adm/daxe/images/section_icons/explanation.png');
8221: }
8222: section.role-introduction>h1:before {
8223: content:url('/adm/daxe/images/section_icons/introduction.png');
8224: }
8225: section.role-method>h1:before {
8226: content:url('/adm/daxe/images/section_icons/method.png');
8227: }
8228: section.role-more_information>h1:before {
8229: content:url('/adm/daxe/images/section_icons/more_information.png');
8230: }
8231: section.role-objectives>h1:before {
8232: content:url('/adm/daxe/images/section_icons/objectives.png');
8233: }
8234: section.role-prerequisites>h1:before {
8235: content:url('/adm/daxe/images/section_icons/prerequisites.png');
8236: }
8237: section.role-remark>h1:before {
8238: content:url('/adm/daxe/images/section_icons/remark.png');
8239: }
8240: section.role-reminder>h1:before {
8241: content:url('/adm/daxe/images/section_icons/reminder.png');
8242: }
8243: section.role-summary>h1:before {
8244: content:url('/adm/daxe/images/section_icons/summary.png');
8245: }
8246: section.role-syntax>h1:before {
8247: content:url('/adm/daxe/images/section_icons/syntax.png');
8248: }
8249: section.role-warning>h1:before {
8250: content:url('/adm/daxe/images/section_icons/warning.png');
8251: }
8252:
8253: #LC_minitab_header {
8254: float:left;
8255: width:100%;
8256: background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
8257: font-size:93%;
8258: line-height:normal;
8259: margin: 0.5em 0 0.5em 0;
8260: }
8261: #LC_minitab_header ul {
8262: margin:0;
8263: padding:10px 10px 0;
8264: list-style:none;
8265: }
8266: #LC_minitab_header li {
8267: float:left;
8268: background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
8269: margin:0;
8270: padding:0 0 0 9px;
8271: }
8272: #LC_minitab_header a {
8273: display:block;
8274: background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
8275: padding:5px 15px 4px 6px;
8276: }
8277: #LC_minitab_header #LC_current_minitab {
8278: background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
8279: }
8280: #LC_minitab_header #LC_current_minitab a {
8281: background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
8282: padding-bottom:5px;
8283: }
8284:
8285:
8286: END
8287: }
8288:
8289: =pod
8290:
8291: =item * &headtag()
8292:
8293: Returns a uniform footer for LON-CAPA web pages.
8294:
8295: Inputs: $title - optional title for the head
8296: $head_extra - optional extra HTML to put inside the <head>
8297: $args - optional arguments
8298: force_register - if is true call registerurl so the remote is
8299: informed
8300: redirect -> array ref of
8301: 1- seconds before redirect occurs
8302: 2- url to redirect to
8303: 3- whether the side effect should occur
8304: (side effect of setting
8305: $env{'internal.head.redirect'} to the url
8306: redirected too)
8307: domain -> force to color decorate a page for a specific
8308: domain
8309: function -> force usage of a specific rolish color scheme
8310: bgcolor -> override the default page bgcolor
8311: no_auto_mt_title
8312: -> prevent &mt()ing the title arg
8313:
8314: =cut
8315:
8316: sub headtag {
8317: my ($title,$head_extra,$args) = @_;
8318:
8319: my $function = $args->{'function'} || &get_users_function();
8320: my $domain = $args->{'domain'} || &determinedomain();
8321: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
8322: my $httphost = $args->{'use_absolute'};
8323: my $url = join(':',$env{'user.name'},$env{'user.domain'},
8324: $Apache::lonnet::perlvar{'lonVersion'},
8325: #time(),
8326: $env{'environment.color.timestamp'},
8327: $function,$domain,$bgcolor);
8328:
8329: $url = '/adm/css/'.&escape($url).'.css';
8330:
8331: my $result =
8332: '<head>'.
8333: &font_settings($args);
8334:
8335: my $inhibitprint;
8336: if ($args->{'print_suppress'}) {
8337: $inhibitprint = &print_suppression();
8338: }
8339:
8340: if (!$args->{'frameset'}) {
8341: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
8342: }
8343: if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
8344: $result .= Apache::lonxml::display_title();
8345: }
8346: if (!$args->{'no_nav_bar'}
8347: && !$args->{'only_body'}
8348: && !$args->{'frameset'}) {
8349: $result .= &help_menu_js($httphost);
8350: $result.=&modal_window();
8351: $result.=&togglebox_script();
8352: $result.=&wishlist_window();
8353: $result.=&LCprogressbarUpdate_script();
8354: } else {
8355: if ($args->{'add_modal'}) {
8356: $result.=&modal_window();
8357: }
8358: if ($args->{'add_wishlist'}) {
8359: $result.=&wishlist_window();
8360: }
8361: if ($args->{'add_togglebox'}) {
8362: $result.=&togglebox_script();
8363: }
8364: if ($args->{'add_progressbar'}) {
8365: $result.=&LCprogressbarUpdate_script();
8366: }
8367: }
8368: if (ref($args->{'redirect'})) {
8369: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
8370: $url = &Apache::lonenc::check_encrypt($url);
8371: if (!$inhibit_continue) {
8372: $env{'internal.head.redirect'} = $url;
8373: }
8374: $result.=<<ADDMETA
8375: <meta http-equiv="pragma" content="no-cache" />
8376: <meta http-equiv="Refresh" content="$time; url=$url" />
8377: ADDMETA
8378: } else {
8379: unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
8380: my $requrl = $env{'request.uri'};
8381: if ($requrl eq '') {
8382: $requrl = $ENV{'REQUEST_URI'};
8383: $requrl =~ s/\?.+$//;
8384: }
8385: unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
8386: (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
8387: ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
8388: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
8389: unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
8390: my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
8391: if (ref($domdefs{'offloadnow'}) eq 'HASH') {
8392: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
8393: if ($domdefs{'offloadnow'}{$lonhost}) {
8394: my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
8395: if (($newserver) && ($newserver ne $lonhost)) {
8396: my $numsec = 5;
8397: my $timeout = $numsec * 1000;
8398: my ($newurl,$locknum,%locks,$msg);
8399: if ($env{'request.role.adv'}) {
8400: ($locknum,%locks) = &Apache::lonnet::get_locks();
8401: }
8402: my $disable_submit = 0;
8403: if ($requrl =~ /$LONCAPA::assess_re/) {
8404: $disable_submit = 1;
8405: }
8406: if ($locknum) {
8407: my @lockinfo = sort(values(%locks));
8408: $msg = &mt('Once the following tasks are complete: ')."\\n".
8409: join(", ",sort(values(%locks)))."\\n".
8410: &mt('your session will be transferred to a different server, after you click "Roles".');
8411: } else {
8412: if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
8413: $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
8414: }
8415: $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
8416: $newurl = '/adm/switchserver?otherserver='.$newserver;
8417: if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
8418: $newurl .= '&role='.$env{'request.role'};
8419: }
8420: if ($env{'request.symb'}) {
8421: $newurl .= '&symb='.$env{'request.symb'};
8422: } else {
8423: $newurl .= '&origurl='.$requrl;
8424: }
8425: }
8426: &js_escape(\$msg);
8427: $result.=<<OFFLOAD
8428: <meta http-equiv="pragma" content="no-cache" />
8429: <script type="text/javascript">
8430: // <![CDATA[
8431: function LC_Offload_Now() {
8432: var dest = "$newurl";
8433: if (dest != '') {
8434: window.location.href="$newurl";
8435: }
8436: }
8437: \$(document).ready(function () {
8438: window.alert('$msg');
8439: if ($disable_submit) {
8440: \$(".LC_hwk_submit").prop("disabled", true);
8441: \$( ".LC_textline" ).prop( "readonly", "readonly");
8442: }
8443: setTimeout('LC_Offload_Now()', $timeout);
8444: });
8445: // ]]>
8446: </script>
8447: OFFLOAD
8448: }
8449: }
8450: }
8451: }
8452: }
8453: }
8454: }
8455: if (!defined($title)) {
8456: $title = 'The LearningOnline Network with CAPA';
8457: }
8458: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
8459: $result .= '<title> LON-CAPA '.$title.'</title>'
8460: .'<link rel="stylesheet" type="text/css" href="'.$url.'"';
8461: if (!$args->{'frameset'}) {
8462: $result .= ' /';
8463: }
8464: $result .= '>'
8465: .$inhibitprint
8466: .$head_extra;
8467: my $clientmobile;
8468: if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
8469: (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
8470: } else {
8471: $clientmobile = $env{'browser.mobile'};
8472: }
8473: if ($clientmobile) {
8474: $result .= '
8475: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
8476: <meta name="apple-mobile-web-app-capable" content="yes" />';
8477: }
8478: $result .= '<meta name="google" content="notranslate" />'."\n";
8479: return $result.'</head>';
8480: }
8481:
8482: =pod
8483:
8484: =item * &font_settings()
8485:
8486: Returns neccessary <meta> to set the proper encoding
8487:
8488: Inputs: optional reference to HASH -- $args passed to &headtag()
8489:
8490: =cut
8491:
8492: sub font_settings {
8493: my ($args) = @_;
8494: my $headerstring='';
8495: if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
8496: ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
8497: $headerstring.=
8498: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
8499: if (!$args->{'frameset'}) {
8500: $headerstring.= ' /';
8501: }
8502: $headerstring .= '>'."\n";
8503: }
8504: return $headerstring;
8505: }
8506:
8507: =pod
8508:
8509: =item * &print_suppression()
8510:
8511: In course context returns css which causes the body to be blank when media="print",
8512: if printout generation is unavailable for the current resource.
8513:
8514: This could be because:
8515:
8516: (a) printstartdate is in the future
8517:
8518: (b) printenddate is in the past
8519:
8520: (c) there is an active exam block with "printout"
8521: functionality blocked
8522:
8523: Users with pav, pfo or evb privileges are exempt.
8524:
8525: Inputs: none
8526:
8527: =cut
8528:
8529:
8530: sub print_suppression {
8531: my $noprint;
8532: if ($env{'request.course.id'}) {
8533: my $scope = $env{'request.course.id'};
8534: if ((&Apache::lonnet::allowed('pav',$scope)) ||
8535: (&Apache::lonnet::allowed('pfo',$scope))) {
8536: return;
8537: }
8538: if ($env{'request.course.sec'} ne '') {
8539: $scope .= "/$env{'request.course.sec'}";
8540: if ((&Apache::lonnet::allowed('pav',$scope)) ||
8541: (&Apache::lonnet::allowed('pfo',$scope))) {
8542: return;
8543: }
8544: }
8545: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8546: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8547: my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
8548: if ($blocked) {
8549: my $checkrole = "cm./$cdom/$cnum";
8550: if ($env{'request.course.sec'} ne '') {
8551: $checkrole .= "/$env{'request.course.sec'}";
8552: }
8553: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
8554: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
8555: $noprint = 1;
8556: }
8557: }
8558: unless ($noprint) {
8559: my $symb = &Apache::lonnet::symbread();
8560: if ($symb ne '') {
8561: my $navmap = Apache::lonnavmaps::navmap->new();
8562: if (ref($navmap)) {
8563: my $res = $navmap->getBySymb($symb);
8564: if (ref($res)) {
8565: if (!$res->resprintable()) {
8566: $noprint = 1;
8567: }
8568: }
8569: }
8570: }
8571: }
8572: if ($noprint) {
8573: return <<"ENDSTYLE";
8574: <style type="text/css" media="print">
8575: body { display:none }
8576: </style>
8577: ENDSTYLE
8578: }
8579: }
8580: return;
8581: }
8582:
8583: =pod
8584:
8585: =item * &xml_begin()
8586:
8587: Returns the needed doctype and <html>
8588:
8589: Inputs: none
8590:
8591: =cut
8592:
8593: sub xml_begin {
8594: my ($is_frameset) = @_;
8595: my $output='';
8596:
8597: if ($env{'browser.mathml'}) {
8598: $output='<?xml version="1.0"?>'
8599: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
8600: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
8601:
8602: # .'<!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">] >'
8603: .'<!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">'
8604: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
8605: .'xmlns="http://www.w3.org/1999/xhtml">';
8606: } elsif ($is_frameset) {
8607: $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
8608: '<html>'."\n";
8609: } else {
8610: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
8611: '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
8612: }
8613: return $output;
8614: }
8615:
8616: =pod
8617:
8618: =item * &start_page()
8619:
8620: Returns a complete <html> .. <body> section for LON-CAPA web pages.
8621:
8622: Inputs:
8623:
8624: =over 4
8625:
8626: $title - optional title for the page
8627:
8628: $head_extra - optional extra HTML to incude inside the <head>
8629:
8630: $args - additional optional args supported are:
8631:
8632: =over 8
8633:
8634: only_body -> is true will set &bodytag() onlybodytag
8635: arg on
8636: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
8637: add_entries -> additional attributes to add to the <body>
8638: domain -> force to color decorate a page for a
8639: specific domain
8640: function -> force usage of a specific rolish color
8641: scheme
8642: redirect -> see &headtag()
8643: bgcolor -> override the default page bg color
8644: js_ready -> return a string ready for being used in
8645: a javascript writeln
8646: html_encode -> return a string ready for being used in
8647: a html attribute
8648: force_register -> if is true will turn on the &bodytag()
8649: $forcereg arg
8650: frameset -> if true will start with a <frameset>
8651: rather than <body>
8652: skip_phases -> hash ref of
8653: head -> skip the <html><head> generation
8654: body -> skip all <body> generation
8655: no_auto_mt_title -> prevent &mt()ing the title arg
8656: bread_crumbs -> Array containing breadcrumbs
8657: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
8658: bread_crumbs_nomenu -> if true will pass false as the value of $menulink
8659: to lonhtmlcommon::breadcrumbs
8660: group -> includes the current group, if page is for a
8661: specific group
8662: use_absolute -> for request for external resource or syllabus, this
8663: will contain https://<hostname> if server uses
8664: https (as per hosts.tab), but request is for http
8665: hostname -> hostname, originally from $r->hostname(), (optional).
8666:
8667: =back
8668:
8669: =back
8670:
8671: =cut
8672:
8673: sub start_page {
8674: my ($title,$head_extra,$args) = @_;
8675: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
8676:
8677: $env{'internal.start_page'}++;
8678: my ($result,@advtools);
8679:
8680: if (! exists($args->{'skip_phases'}{'head'}) ) {
8681: $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
8682: }
8683:
8684: if (! exists($args->{'skip_phases'}{'body'}) ) {
8685: if ($args->{'frameset'}) {
8686: my $attr_string = &make_attr_string($args->{'force_register'},
8687: $args->{'add_entries'});
8688: $result .= "\n<frameset $attr_string>\n";
8689: } else {
8690: $result .=
8691: &bodytag($title,
8692: $args->{'function'}, $args->{'add_entries'},
8693: $args->{'only_body'}, $args->{'domain'},
8694: $args->{'force_register'}, $args->{'no_nav_bar'},
8695: $args->{'bgcolor'}, $args,
8696: \@advtools);
8697: }
8698: }
8699:
8700: if ($args->{'js_ready'}) {
8701: $result = &js_ready($result);
8702: }
8703: if ($args->{'html_encode'}) {
8704: $result = &html_encode($result);
8705: }
8706:
8707: # Preparation for new and consistent functionlist at top of screen
8708: # if ($args->{'functionlist'}) {
8709: # $result .= &build_functionlist();
8710: #}
8711:
8712: # Don't add anything more if only_body wanted or in const space
8713: return $result if $args->{'only_body'}
8714: || $env{'request.state'} eq 'construct';
8715:
8716: #Breadcrumbs
8717: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
8718: &Apache::lonhtmlcommon::clear_breadcrumbs();
8719: #if any br links exists, add them to the breadcrumbs
8720: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
8721: foreach my $crumb (@{$args->{'bread_crumbs'}}){
8722: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
8723: }
8724: }
8725: # if @advtools array contains items add then to the breadcrumbs
8726: if (@advtools > 0) {
8727: &Apache::lonmenu::advtools_crumbs(@advtools);
8728: }
8729: my $ltiscope;
8730: if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
8731: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8732: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8733: ($ltiscope) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},$cdom,$cnum);
8734: }
8735: my $menulink;
8736: # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
8737: if ((exists($args->{'bread_crumbs_nomenu'})) ||
8738: ($ltiscope eq 'map') || ($ltiscope eq 'resource') ||
8739: ((($args->{'crstype'} eq 'Placement') || (($env{'request.course.id'}) &&
8740: ($env{'course.'.$env{'request.course.id'}.'.type'} eq 'Placement'))) &&
8741: (!$env{'request.role.adv'}))) {
8742: $menulink = 0;
8743: } else {
8744: undef($menulink);
8745: }
8746: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
8747: if(exists($args->{'bread_crumbs_component'})){
8748: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
8749: } else {
8750: $result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
8751: }
8752: }
8753: return $result;
8754: }
8755:
8756: sub end_page {
8757: my ($args) = @_;
8758: $env{'internal.end_page'}++;
8759: my $result;
8760: if ($args->{'discussion'}) {
8761: my ($target,$parser);
8762: if (ref($args->{'discussion'})) {
8763: ($target,$parser) =($args->{'discussion'}{'target'},
8764: $args->{'discussion'}{'parser'});
8765: }
8766: $result .= &Apache::lonxml::xmlend($target,$parser);
8767: }
8768: if ($args->{'frameset'}) {
8769: $result .= '</frameset>';
8770: } else {
8771: $result .= &endbodytag($args);
8772: }
8773: unless ($args->{'notbody'}) {
8774: $result .= "\n</html>";
8775: }
8776:
8777: if ($args->{'js_ready'}) {
8778: $result = &js_ready($result);
8779: }
8780:
8781: if ($args->{'html_encode'}) {
8782: $result = &html_encode($result);
8783: }
8784:
8785: return $result;
8786: }
8787:
8788: sub wishlist_window {
8789: return(<<'ENDWISHLIST');
8790: <script type="text/javascript">
8791: // <![CDATA[
8792: // <!-- BEGIN LON-CAPA Internal
8793: function set_wishlistlink(title, path) {
8794: if (!title) {
8795: title = document.title;
8796: title = title.replace(/^LON-CAPA /,'');
8797: }
8798: title = encodeURIComponent(title);
8799: title = title.replace("'","\\\'");
8800: if (!path) {
8801: path = location.pathname;
8802: }
8803: path = encodeURIComponent(path);
8804: path = path.replace("'","\\\'");
8805: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
8806: 'wishlistNewLink','width=560,height=350,scrollbars=0');
8807: }
8808: // END LON-CAPA Internal -->
8809: // ]]>
8810: </script>
8811: ENDWISHLIST
8812: }
8813:
8814: sub modal_window {
8815: return(<<'ENDMODAL');
8816: <script type="text/javascript">
8817: // <![CDATA[
8818: // <!-- BEGIN LON-CAPA Internal
8819: var modalWindow = {
8820: parent:"body",
8821: windowId:null,
8822: content:null,
8823: width:null,
8824: height:null,
8825: close:function()
8826: {
8827: $(".LCmodal-window").remove();
8828: $(".LCmodal-overlay").remove();
8829: },
8830: open:function()
8831: {
8832: var modal = "";
8833: modal += "<div class=\"LCmodal-overlay\"></div>";
8834: 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;\">";
8835: modal += this.content;
8836: modal += "</div>";
8837:
8838: $(this.parent).append(modal);
8839:
8840: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
8841: $(".LCclose-window").click(function(){modalWindow.close();});
8842: $(".LCmodal-overlay").click(function(){modalWindow.close();});
8843: }
8844: };
8845: var openMyModal = function(source,width,height,scrolling,transparency,style)
8846: {
8847: source = source.replace(/'/g,"'");
8848: modalWindow.windowId = "myModal";
8849: modalWindow.width = width;
8850: modalWindow.height = height;
8851: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
8852: modalWindow.open();
8853: };
8854: // END LON-CAPA Internal -->
8855: // ]]>
8856: </script>
8857: ENDMODAL
8858: }
8859:
8860: sub modal_link {
8861: my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
8862: unless ($width) { $width=480; }
8863: unless ($height) { $height=400; }
8864: unless ($scrolling) { $scrolling='yes'; }
8865: unless ($transparency) { $transparency='true'; }
8866:
8867: my $target_attr;
8868: if (defined($target)) {
8869: $target_attr = 'target="'.$target.'"';
8870: }
8871: return <<"ENDLINK";
8872: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
8873: $linktext</a>
8874: ENDLINK
8875: }
8876:
8877: sub modal_adhoc_script {
8878: my ($funcname,$width,$height,$content)=@_;
8879: return (<<ENDADHOC);
8880: <script type="text/javascript">
8881: // <![CDATA[
8882: var $funcname = function()
8883: {
8884: modalWindow.windowId = "myModal";
8885: modalWindow.width = $width;
8886: modalWindow.height = $height;
8887: modalWindow.content = '$content';
8888: modalWindow.open();
8889: };
8890: // ]]>
8891: </script>
8892: ENDADHOC
8893: }
8894:
8895: sub modal_adhoc_inner {
8896: my ($funcname,$width,$height,$content)=@_;
8897: my $innerwidth=$width-20;
8898: $content=&js_ready(
8899: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
8900: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
8901: $content.
8902: &end_scrollbox().
8903: &end_page()
8904: );
8905: return &modal_adhoc_script($funcname,$width,$height,$content);
8906: }
8907:
8908: sub modal_adhoc_window {
8909: my ($funcname,$width,$height,$content,$linktext)=@_;
8910: return &modal_adhoc_inner($funcname,$width,$height,$content).
8911: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
8912: }
8913:
8914: sub modal_adhoc_launch {
8915: my ($funcname,$width,$height,$content)=@_;
8916: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
8917: <script type="text/javascript">
8918: // <![CDATA[
8919: $funcname();
8920: // ]]>
8921: </script>
8922: ENDLAUNCH
8923: }
8924:
8925: sub modal_adhoc_close {
8926: return (<<ENDCLOSE);
8927: <script type="text/javascript">
8928: // <![CDATA[
8929: modalWindow.close();
8930: // ]]>
8931: </script>
8932: ENDCLOSE
8933: }
8934:
8935: sub togglebox_script {
8936: return(<<ENDTOGGLE);
8937: <script type="text/javascript">
8938: // <![CDATA[
8939: function LCtoggleDisplay(id,hidetext,showtext) {
8940: link = document.getElementById(id + "link").childNodes[0];
8941: with (document.getElementById(id).style) {
8942: if (display == "none" ) {
8943: display = "inline";
8944: link.nodeValue = hidetext;
8945: } else {
8946: display = "none";
8947: link.nodeValue = showtext;
8948: }
8949: }
8950: }
8951: // ]]>
8952: </script>
8953: ENDTOGGLE
8954: }
8955:
8956: sub start_togglebox {
8957: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
8958: unless ($heading) { $heading=''; } else { $heading.=' '; }
8959: unless ($showtext) { $showtext=&mt('show'); }
8960: unless ($hidetext) { $hidetext=&mt('hide'); }
8961: unless ($headerbg) { $headerbg='#FFFFFF'; }
8962: return &start_data_table().
8963: &start_data_table_header_row().
8964: '<td bgcolor="'.$headerbg.'">'.$heading.
8965: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
8966: $showtext.'\')">'.$showtext.'</a>]</td>'.
8967: &end_data_table_header_row().
8968: '<tr id="'.$id.'" style="display:none""><td>';
8969: }
8970:
8971: sub end_togglebox {
8972: return '</td></tr>'.&end_data_table();
8973: }
8974:
8975: sub LCprogressbar_script {
8976: my ($id,$number_to_do)=@_;
8977: if ($number_to_do) {
8978: return(<<ENDPROGRESS);
8979: <script type="text/javascript">
8980: // <![CDATA[
8981: \$('#progressbar$id').progressbar({
8982: value: 0,
8983: change: function(event, ui) {
8984: var newVal = \$(this).progressbar('option', 'value');
8985: \$('.pblabel', this).text(LCprogressTxt);
8986: }
8987: });
8988: // ]]>
8989: </script>
8990: ENDPROGRESS
8991: } else {
8992: return(<<ENDPROGRESS);
8993: <script type="text/javascript">
8994: // <![CDATA[
8995: \$('#progressbar$id').progressbar({
8996: value: false,
8997: create: function(event, ui) {
8998: \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
8999: \$('.ui-progressbar-overlay', this).css({'margin':'0'});
9000: }
9001: });
9002: // ]]>
9003: </script>
9004: ENDPROGRESS
9005: }
9006: }
9007:
9008: sub LCprogressbarUpdate_script {
9009: return(<<ENDPROGRESSUPDATE);
9010: <style type="text/css">
9011: .ui-progressbar { position:relative; }
9012: .progress-label {position: absolute; width: 100%; text-align: center; top: 1px; font-weight: bold; text-shadow: 1px 1px 0 #fff;margin: 0; line-height: 200%; }
9013: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
9014: </style>
9015: <script type="text/javascript">
9016: // <![CDATA[
9017: var LCprogressTxt='---';
9018:
9019: function LCupdateProgress(percent,progresstext,id,maxnum) {
9020: LCprogressTxt=progresstext;
9021: if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
9022: \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
9023: } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
9024: \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
9025: } else {
9026: \$('#progressbar'+id).progressbar('value',percent);
9027: }
9028: }
9029: // ]]>
9030: </script>
9031: ENDPROGRESSUPDATE
9032: }
9033:
9034: my $LClastpercent;
9035: my $LCidcnt;
9036: my $LCcurrentid;
9037:
9038: sub LCprogressbar {
9039: my ($r,$number_to_do,$preamble)=@_;
9040: $LClastpercent=0;
9041: $LCidcnt++;
9042: $LCcurrentid=$$.'_'.$LCidcnt;
9043: my ($starting,$content);
9044: if ($number_to_do) {
9045: $starting=&mt('Starting');
9046: $content=(<<ENDPROGBAR);
9047: $preamble
9048: <div id="progressbar$LCcurrentid">
9049: <span class="pblabel">$starting</span>
9050: </div>
9051: ENDPROGBAR
9052: } else {
9053: $starting=&mt('Loading...');
9054: $LClastpercent='false';
9055: $content=(<<ENDPROGBAR);
9056: $preamble
9057: <div id="progressbar$LCcurrentid">
9058: <div class="progress-label">$starting</div>
9059: </div>
9060: ENDPROGBAR
9061: }
9062: &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
9063: }
9064:
9065: sub LCprogressbarUpdate {
9066: my ($r,$val,$text,$number_to_do)=@_;
9067: if ($number_to_do) {
9068: unless ($val) {
9069: if ($LClastpercent) {
9070: $val=$LClastpercent;
9071: } else {
9072: $val=0;
9073: }
9074: }
9075: if ($val<0) { $val=0; }
9076: if ($val>100) { $val=0; }
9077: $LClastpercent=$val;
9078: unless ($text) { $text=$val.'%'; }
9079: } else {
9080: $val = 'false';
9081: }
9082: $text=&js_ready($text);
9083: &r_print($r,<<ENDUPDATE);
9084: <script type="text/javascript">
9085: // <![CDATA[
9086: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
9087: // ]]>
9088: </script>
9089: ENDUPDATE
9090: }
9091:
9092: sub LCprogressbarClose {
9093: my ($r)=@_;
9094: $LClastpercent=0;
9095: &r_print($r,<<ENDCLOSE);
9096: <script type="text/javascript">
9097: // <![CDATA[
9098: \$("#progressbar$LCcurrentid").hide('slow');
9099: // ]]>
9100: </script>
9101: ENDCLOSE
9102: }
9103:
9104: sub r_print {
9105: my ($r,$to_print)=@_;
9106: if ($r) {
9107: $r->print($to_print);
9108: $r->rflush();
9109: } else {
9110: print($to_print);
9111: }
9112: }
9113:
9114: sub html_encode {
9115: my ($result) = @_;
9116:
9117: $result = &HTML::Entities::encode($result,'<>&"');
9118:
9119: return $result;
9120: }
9121:
9122: sub js_ready {
9123: my ($result) = @_;
9124:
9125: $result =~ s/[\n\r]/ /xmsg;
9126: $result =~ s/\\/\\\\/xmsg;
9127: $result =~ s/'/\\'/xmsg;
9128: $result =~ s{</}{<\\/}xmsg;
9129:
9130: return $result;
9131: }
9132:
9133: sub validate_page {
9134: if ( exists($env{'internal.start_page'})
9135: && $env{'internal.start_page'} > 1) {
9136: &Apache::lonnet::logthis('start_page called multiple times '.
9137: $env{'internal.start_page'}.' '.
9138: $ENV{'request.filename'});
9139: }
9140: if ( exists($env{'internal.end_page'})
9141: && $env{'internal.end_page'} > 1) {
9142: &Apache::lonnet::logthis('end_page called multiple times '.
9143: $env{'internal.end_page'}.' '.
9144: $env{'request.filename'});
9145: }
9146: if ( exists($env{'internal.start_page'})
9147: && ! exists($env{'internal.end_page'})) {
9148: &Apache::lonnet::logthis('start_page called without end_page '.
9149: $env{'request.filename'});
9150: }
9151: if ( ! exists($env{'internal.start_page'})
9152: && exists($env{'internal.end_page'})) {
9153: &Apache::lonnet::logthis('end_page called without start_page'.
9154: $env{'request.filename'});
9155: }
9156: }
9157:
9158:
9159: sub start_scrollbox {
9160: my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
9161: unless ($outerwidth) { $outerwidth='520px'; }
9162: unless ($width) { $width='500px'; }
9163: unless ($height) { $height='200px'; }
9164: my ($table_id,$div_id,$tdcol);
9165: if ($id ne '') {
9166: $table_id = ' id="table_'.$id.'"';
9167: $div_id = ' id="div_'.$id.'"';
9168: }
9169: if ($bgcolor ne '') {
9170: $tdcol = "background-color: $bgcolor;";
9171: }
9172: my $nicescroll_js;
9173: if ($env{'browser.mobile'}) {
9174: $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
9175: }
9176: return <<"END";
9177: $nicescroll_js
9178:
9179: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
9180: <div style="overflow:auto; width:$width; height:$height;"$div_id>
9181: END
9182: }
9183:
9184: sub end_scrollbox {
9185: return '</div></td></tr></table>';
9186: }
9187:
9188: sub nicescroll_javascript {
9189: my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
9190: my %options;
9191: if (ref($cursor) eq 'HASH') {
9192: %options = %{$cursor};
9193: }
9194: unless ($options{'railalign'} =~ /^left|right$/) {
9195: $options{'railalign'} = 'left';
9196: }
9197: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
9198: my $function = &get_users_function();
9199: $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
9200: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
9201: $options{'cursorcolor'} = '#00F';
9202: }
9203: }
9204: if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
9205: unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
9206: $options{'cursoropacity'}='1.0';
9207: }
9208: } else {
9209: $options{'cursoropacity'}='1.0';
9210: }
9211: if ($options{'cursorfixedheight'} eq 'none') {
9212: delete($options{'cursorfixedheight'});
9213: } else {
9214: unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
9215: }
9216: unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
9217: delete($options{'railoffset'});
9218: }
9219: my @niceoptions;
9220: while (my($key,$value) = each(%options)) {
9221: if ($value =~ /^\{.+\}$/) {
9222: push(@niceoptions,$key.':'.$value);
9223: } else {
9224: push(@niceoptions,$key.':"'.$value.'"');
9225: }
9226: }
9227: my $nicescroll_js = '
9228: $(document).ready(
9229: function() {
9230: $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
9231: }
9232: );
9233: ';
9234: if ($framecheck) {
9235: $nicescroll_js .= '
9236: function expand_div(caller) {
9237: if (top === self) {
9238: document.getElementById("'.$id.'").style.width = "auto";
9239: document.getElementById("'.$id.'").style.height = "auto";
9240: } else {
9241: try {
9242: if (parent.frames) {
9243: if (parent.frames.length > 1) {
9244: var framesrc = parent.frames[1].location.href;
9245: var currsrc = framesrc.replace(/\#.*$/,"");
9246: if ((caller == "search") || (currsrc == "'.$location.'")) {
9247: document.getElementById("'.$id.'").style.width = "auto";
9248: document.getElementById("'.$id.'").style.height = "auto";
9249: }
9250: }
9251: }
9252: } catch (e) {
9253: return;
9254: }
9255: }
9256: return;
9257: }
9258: ';
9259: }
9260: if ($needjsready) {
9261: $nicescroll_js = '
9262: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
9263: } else {
9264: $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
9265: }
9266: return $nicescroll_js;
9267: }
9268:
9269: sub simple_error_page {
9270: my ($r,$title,$msg,$args) = @_;
9271: my %displayargs;
9272: if (ref($args) eq 'HASH') {
9273: if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
9274: if ($args->{'only_body'}) {
9275: $displayargs{'only_body'} = 1;
9276: }
9277: if ($args->{'no_nav_bar'}) {
9278: $displayargs{'no_nav_bar'} = 1;
9279: }
9280: } else {
9281: $msg = &mt($msg);
9282: }
9283:
9284: my $page =
9285: &Apache::loncommon::start_page($title,'',\%displayargs).
9286: '<p class="LC_error">'.$msg.'</p>'.
9287: &Apache::loncommon::end_page();
9288: if (ref($r)) {
9289: $r->print($page);
9290: return;
9291: }
9292: return $page;
9293: }
9294:
9295: {
9296: my @row_count;
9297:
9298: sub start_data_table_count {
9299: unshift(@row_count, 0);
9300: return;
9301: }
9302:
9303: sub end_data_table_count {
9304: shift(@row_count);
9305: return;
9306: }
9307:
9308: sub start_data_table {
9309: my ($add_class,$id) = @_;
9310: my $css_class = (join(' ','LC_data_table',$add_class));
9311: my $table_id;
9312: if (defined($id)) {
9313: $table_id = ' id="'.$id.'"';
9314: }
9315: &start_data_table_count();
9316: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
9317: }
9318:
9319: sub end_data_table {
9320: &end_data_table_count();
9321: return '</table>'."\n";;
9322: }
9323:
9324: sub start_data_table_row {
9325: my ($add_class, $id) = @_;
9326: $row_count[0]++;
9327: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
9328: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
9329: $id = (' id="'.$id.'"') unless ($id eq '');
9330: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
9331: }
9332:
9333: sub continue_data_table_row {
9334: my ($add_class, $id) = @_;
9335: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
9336: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
9337: $id = (' id="'.$id.'"') unless ($id eq '');
9338: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
9339: }
9340:
9341: sub end_data_table_row {
9342: return '</tr>'."\n";;
9343: }
9344:
9345: sub start_data_table_empty_row {
9346: # $row_count[0]++;
9347: return '<tr class="LC_empty_row" >'."\n";;
9348: }
9349:
9350: sub end_data_table_empty_row {
9351: return '</tr>'."\n";;
9352: }
9353:
9354: sub start_data_table_header_row {
9355: return '<tr class="LC_header_row">'."\n";;
9356: }
9357:
9358: sub end_data_table_header_row {
9359: return '</tr>'."\n";;
9360: }
9361:
9362: sub data_table_caption {
9363: my $caption = shift;
9364: return "<caption class=\"LC_caption\">$caption</caption>";
9365: }
9366: }
9367:
9368: =pod
9369:
9370: =item * &inhibit_menu_check($arg)
9371:
9372: Checks for a inhibitmenu state and generates output to preserve it
9373:
9374: Inputs: $arg - can be any of
9375: - undef - in which case the return value is a string
9376: to add into arguments list of a uri
9377: - 'input' - in which case the return value is a HTML
9378: <form> <input> field of type hidden to
9379: preserve the value
9380: - a url - in which case the return value is the url with
9381: the neccesary cgi args added to preserve the
9382: inhibitmenu state
9383: - a ref to a url - no return value, but the string is
9384: updated to include the neccessary cgi
9385: args to preserve the inhibitmenu state
9386:
9387: =cut
9388:
9389: sub inhibit_menu_check {
9390: my ($arg) = @_;
9391: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
9392: if ($arg eq 'input') {
9393: if ($env{'form.inhibitmenu'}) {
9394: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
9395: } else {
9396: return
9397: }
9398: }
9399: if ($env{'form.inhibitmenu'}) {
9400: if (ref($arg)) {
9401: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
9402: } elsif ($arg eq '') {
9403: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
9404: } else {
9405: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
9406: }
9407: }
9408: if (!ref($arg)) {
9409: return $arg;
9410: }
9411: }
9412:
9413: ###############################################
9414:
9415: =pod
9416:
9417: =back
9418:
9419: =head1 User Information Routines
9420:
9421: =over 4
9422:
9423: =item * &get_users_function()
9424:
9425: Used by &bodytag to determine the current users primary role.
9426: Returns either 'student','coordinator','admin', or 'author'.
9427:
9428: =cut
9429:
9430: ###############################################
9431: sub get_users_function {
9432: my $function = 'norole';
9433: if ($env{'request.role'}=~/^(st)/) {
9434: $function='student';
9435: }
9436: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
9437: $function='coordinator';
9438: }
9439: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
9440: $function='admin';
9441: }
9442: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
9443: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
9444: $function='author';
9445: }
9446: return $function;
9447: }
9448:
9449: ###############################################
9450:
9451: =pod
9452:
9453: =item * &show_course()
9454:
9455: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
9456: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
9457:
9458: Inputs:
9459: None
9460:
9461: Outputs:
9462: Scalar: 1 if 'Course' to be used, 0 otherwise.
9463:
9464: =cut
9465:
9466: ###############################################
9467: sub show_course {
9468: my $course = !$env{'user.adv'};
9469: if (!$env{'user.adv'}) {
9470: foreach my $env (keys(%env)) {
9471: next if ($env !~ m/^user\.priv\./);
9472: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
9473: $course = 0;
9474: last;
9475: }
9476: }
9477: }
9478: return $course;
9479: }
9480:
9481: ###############################################
9482:
9483: =pod
9484:
9485: =item * &check_user_status()
9486:
9487: Determines current status of supplied role for a
9488: specific user. Roles can be active, previous or future.
9489:
9490: Inputs:
9491: user's domain, user's username, course's domain,
9492: course's number, optional section ID.
9493:
9494: Outputs:
9495: role status: active, previous or future.
9496:
9497: =cut
9498:
9499: sub check_user_status {
9500: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
9501: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
9502: my @uroles = keys(%userinfo);
9503: my $srchstr;
9504: my $active_chk = 'none';
9505: my $now = time;
9506: if (@uroles > 0) {
9507: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
9508: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
9509: } else {
9510: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
9511: }
9512: if (grep/^\Q$srchstr\E$/,@uroles) {
9513: my $role_end = 0;
9514: my $role_start = 0;
9515: $active_chk = 'active';
9516: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
9517: $role_end = $1;
9518: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
9519: $role_start = $1;
9520: }
9521: }
9522: if ($role_start > 0) {
9523: if ($now < $role_start) {
9524: $active_chk = 'future';
9525: }
9526: }
9527: if ($role_end > 0) {
9528: if ($now > $role_end) {
9529: $active_chk = 'previous';
9530: }
9531: }
9532: }
9533: }
9534: return $active_chk;
9535: }
9536:
9537: ###############################################
9538:
9539: =pod
9540:
9541: =item * &get_sections()
9542:
9543: Determines all the sections for a course including
9544: sections with students and sections containing other roles.
9545: Incoming parameters:
9546:
9547: 1. domain
9548: 2. course number
9549: 3. reference to array containing roles for which sections should
9550: be gathered (optional).
9551: 4. reference to array containing status types for which sections
9552: should be gathered (optional).
9553:
9554: If the third argument is undefined, sections are gathered for any role.
9555: If the fourth argument is undefined, sections are gathered for any status.
9556: Permissible values are 'active' or 'future' or 'previous'.
9557:
9558: Returns section hash (keys are section IDs, values are
9559: number of users in each section), subject to the
9560: optional roles filter, optional status filter
9561:
9562: =cut
9563:
9564: ###############################################
9565: sub get_sections {
9566: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
9567: if (!defined($cdom) || !defined($cnum)) {
9568: my $cid = $env{'request.course.id'};
9569:
9570: return if (!defined($cid));
9571:
9572: $cdom = $env{'course.'.$cid.'.domain'};
9573: $cnum = $env{'course.'.$cid.'.num'};
9574: }
9575:
9576: my %sectioncount;
9577: my $now = time;
9578:
9579: my $check_students = 1;
9580: my $only_students = 0;
9581: if (ref($possible_roles) eq 'ARRAY') {
9582: if (grep(/^st$/,@{$possible_roles})) {
9583: if (@{$possible_roles} == 1) {
9584: $only_students = 1;
9585: }
9586: } else {
9587: $check_students = 0;
9588: }
9589: }
9590:
9591: if ($check_students) {
9592: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
9593: my $sec_index = &Apache::loncoursedata::CL_SECTION();
9594: my $status_index = &Apache::loncoursedata::CL_STATUS();
9595: my $start_index = &Apache::loncoursedata::CL_START();
9596: my $end_index = &Apache::loncoursedata::CL_END();
9597: my $status;
9598: while (my ($student,$data) = each(%$classlist)) {
9599: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
9600: $data->[$status_index],
9601: $data->[$start_index],
9602: $data->[$end_index]);
9603: if ($stu_status eq 'Active') {
9604: $status = 'active';
9605: } elsif ($end < $now) {
9606: $status = 'previous';
9607: } elsif ($start > $now) {
9608: $status = 'future';
9609: }
9610: if ($section ne '-1' && $section !~ /^\s*$/) {
9611: if ((!defined($possible_status)) || (($status ne '') &&
9612: (grep/^\Q$status\E$/,@{$possible_status}))) {
9613: $sectioncount{$section}++;
9614: }
9615: }
9616: }
9617: }
9618: if ($only_students) {
9619: return %sectioncount;
9620: }
9621: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9622: foreach my $user (sort(keys(%courseroles))) {
9623: if ($user !~ /^(\w{2})/) { next; }
9624: my ($role) = ($user =~ /^(\w{2})/);
9625: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
9626: my ($section,$status);
9627: if ($role eq 'cr' &&
9628: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
9629: $section=$1;
9630: }
9631: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
9632: if (!defined($section) || $section eq '-1') { next; }
9633: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
9634: if ($end == -1 && $start == -1) {
9635: next; #deleted role
9636: }
9637: if (!defined($possible_status)) {
9638: $sectioncount{$section}++;
9639: } else {
9640: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
9641: $status = 'active';
9642: } elsif ($end < $now) {
9643: $status = 'future';
9644: } elsif ($start > $now) {
9645: $status = 'previous';
9646: }
9647: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
9648: $sectioncount{$section}++;
9649: }
9650: }
9651: }
9652: return %sectioncount;
9653: }
9654:
9655: ###############################################
9656:
9657: =pod
9658:
9659: =item * &get_course_users()
9660:
9661: Retrieves usernames:domains for users in the specified course
9662: with specific role(s), and access status.
9663:
9664: Incoming parameters:
9665: 1. course domain
9666: 2. course number
9667: 3. access status: users must have - either active,
9668: previous, future, or all.
9669: 4. reference to array of permissible roles
9670: 5. reference to array of section restrictions (optional)
9671: 6. reference to results object (hash of hashes).
9672: 7. reference to optional userdata hash
9673: 8. reference to optional statushash
9674: 9. flag if privileged users (except those set to unhide in
9675: course settings) should be excluded
9676: Keys of top level results hash are roles.
9677: Keys of inner hashes are username:domain, with
9678: values set to access type.
9679: Optional userdata hash returns an array with arguments in the
9680: same order as loncoursedata::get_classlist() for student data.
9681:
9682: Optional statushash returns
9683:
9684: Entries for end, start, section and status are blank because
9685: of the possibility of multiple values for non-student roles.
9686:
9687: =cut
9688:
9689: ###############################################
9690:
9691: sub get_course_users {
9692: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
9693: my %idx = ();
9694: my %seclists;
9695:
9696: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
9697: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
9698: $idx{end} = &Apache::loncoursedata::CL_END();
9699: $idx{start} = &Apache::loncoursedata::CL_START();
9700: $idx{id} = &Apache::loncoursedata::CL_ID();
9701: $idx{section} = &Apache::loncoursedata::CL_SECTION();
9702: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
9703: $idx{status} = &Apache::loncoursedata::CL_STATUS();
9704:
9705: if (grep(/^st$/,@{$roles})) {
9706: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
9707: my $now = time;
9708: foreach my $student (keys(%{$classlist})) {
9709: my $match = 0;
9710: my $secmatch = 0;
9711: my $section = $$classlist{$student}[$idx{section}];
9712: my $status = $$classlist{$student}[$idx{status}];
9713: if ($section eq '') {
9714: $section = 'none';
9715: }
9716: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
9717: if (grep(/^all$/,@{$sections})) {
9718: $secmatch = 1;
9719: } elsif ($$classlist{$student}[$idx{section}] eq '') {
9720: if (grep(/^none$/,@{$sections})) {
9721: $secmatch = 1;
9722: }
9723: } else {
9724: if (grep(/^\Q$section\E$/,@{$sections})) {
9725: $secmatch = 1;
9726: }
9727: }
9728: if (!$secmatch) {
9729: next;
9730: }
9731: }
9732: if (defined($$types{'active'})) {
9733: if ($$classlist{$student}[$idx{status}] eq 'Active') {
9734: push(@{$$users{st}{$student}},'active');
9735: $match = 1;
9736: }
9737: }
9738: if (defined($$types{'previous'})) {
9739: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
9740: push(@{$$users{st}{$student}},'previous');
9741: $match = 1;
9742: }
9743: }
9744: if (defined($$types{'future'})) {
9745: if ($$classlist{$student}[$idx{status}] eq 'Future') {
9746: push(@{$$users{st}{$student}},'future');
9747: $match = 1;
9748: }
9749: }
9750: if ($match) {
9751: push(@{$seclists{$student}},$section);
9752: if (ref($userdata) eq 'HASH') {
9753: $$userdata{$student} = $$classlist{$student};
9754: }
9755: if (ref($statushash) eq 'HASH') {
9756: $statushash->{$student}{'st'}{$section} = $status;
9757: }
9758: }
9759: }
9760: }
9761: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
9762: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9763: my $now = time;
9764: my %displaystatus = ( previous => 'Expired',
9765: active => 'Active',
9766: future => 'Future',
9767: );
9768: my (%nothide,@possdoms);
9769: if ($hidepriv) {
9770: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
9771: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
9772: if ($user !~ /:/) {
9773: $nothide{join(':',split(/[\@]/,$user))}=1;
9774: } else {
9775: $nothide{$user} = 1;
9776: }
9777: }
9778: my @possdoms = ($cdom);
9779: if ($coursehash{'checkforpriv'}) {
9780: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
9781: }
9782: }
9783: foreach my $person (sort(keys(%coursepersonnel))) {
9784: my $match = 0;
9785: my $secmatch = 0;
9786: my $status;
9787: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
9788: $user =~ s/:$//;
9789: my ($end,$start) = split(/:/,$coursepersonnel{$person});
9790: if ($end == -1 || $start == -1) {
9791: next;
9792: }
9793: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
9794: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
9795: my ($uname,$udom) = split(/:/,$user);
9796: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
9797: if (grep(/^all$/,@{$sections})) {
9798: $secmatch = 1;
9799: } elsif ($usec eq '') {
9800: if (grep(/^none$/,@{$sections})) {
9801: $secmatch = 1;
9802: }
9803: } else {
9804: if (grep(/^\Q$usec\E$/,@{$sections})) {
9805: $secmatch = 1;
9806: }
9807: }
9808: if (!$secmatch) {
9809: next;
9810: }
9811: }
9812: if ($usec eq '') {
9813: $usec = 'none';
9814: }
9815: if ($uname ne '' && $udom ne '') {
9816: if ($hidepriv) {
9817: if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
9818: (!$nothide{$uname.':'.$udom})) {
9819: next;
9820: }
9821: }
9822: if ($end > 0 && $end < $now) {
9823: $status = 'previous';
9824: } elsif ($start > $now) {
9825: $status = 'future';
9826: } else {
9827: $status = 'active';
9828: }
9829: foreach my $type (keys(%{$types})) {
9830: if ($status eq $type) {
9831: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
9832: push(@{$$users{$role}{$user}},$type);
9833: }
9834: $match = 1;
9835: }
9836: }
9837: if (($match) && (ref($userdata) eq 'HASH')) {
9838: if (!exists($$userdata{$uname.':'.$udom})) {
9839: &get_user_info($udom,$uname,\%idx,$userdata);
9840: }
9841: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
9842: push(@{$seclists{$uname.':'.$udom}},$usec);
9843: }
9844: if (ref($statushash) eq 'HASH') {
9845: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
9846: }
9847: }
9848: }
9849: }
9850: }
9851: if (grep(/^ow$/,@{$roles})) {
9852: if ((defined($cdom)) && (defined($cnum))) {
9853: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
9854: if ( defined($csettings{'internal.courseowner'}) ) {
9855: my $owner = $csettings{'internal.courseowner'};
9856: next if ($owner eq '');
9857: my ($ownername,$ownerdom);
9858: if ($owner =~ /^([^:]+):([^:]+)$/) {
9859: $ownername = $1;
9860: $ownerdom = $2;
9861: } else {
9862: $ownername = $owner;
9863: $ownerdom = $cdom;
9864: $owner = $ownername.':'.$ownerdom;
9865: }
9866: @{$$users{'ow'}{$owner}} = 'any';
9867: if (defined($userdata) &&
9868: !exists($$userdata{$owner})) {
9869: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
9870: if (!grep(/^none$/,@{$seclists{$owner}})) {
9871: push(@{$seclists{$owner}},'none');
9872: }
9873: if (ref($statushash) eq 'HASH') {
9874: $statushash->{$owner}{'ow'}{'none'} = 'Any';
9875: }
9876: }
9877: }
9878: }
9879: }
9880: foreach my $user (keys(%seclists)) {
9881: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
9882: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
9883: }
9884: }
9885: return;
9886: }
9887:
9888: sub get_user_info {
9889: my ($udom,$uname,$idx,$userdata) = @_;
9890: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
9891: &plainname($uname,$udom,'lastname');
9892: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
9893: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
9894: my %idhash = &Apache::lonnet::idrget($udom,($uname));
9895: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
9896: return;
9897: }
9898:
9899: ###############################################
9900:
9901: =pod
9902:
9903: =item * &get_user_quota()
9904:
9905: Retrieves quota assigned for storage of user files.
9906: Default is to report quota for portfolio files.
9907:
9908: Incoming parameters:
9909: 1. user's username
9910: 2. user's domain
9911: 3. quota name - portfolio, author, or course
9912: (if no quota name provided, defaults to portfolio).
9913: 4. crstype - official, unofficial, textbook, placement or community,
9914: if quota name is course
9915:
9916: Returns:
9917: 1. Disk quota (in MB) assigned to student.
9918: 2. (Optional) Type of setting: custom or default
9919: (individually assigned or default for user's
9920: institutional status).
9921: 3. (Optional) - User's institutional status (e.g., faculty, staff
9922: or student - types as defined in localenroll::inst_usertypes
9923: for user's domain, which determines default quota for user.
9924: 4. (Optional) - Default quota which would apply to the user.
9925:
9926: If a value has been stored in the user's environment,
9927: it will return that, otherwise it returns the maximal default
9928: defined for the user's institutional status(es) in the domain.
9929:
9930: =cut
9931:
9932: ###############################################
9933:
9934:
9935: sub get_user_quota {
9936: my ($uname,$udom,$quotaname,$crstype) = @_;
9937: my ($quota,$quotatype,$settingstatus,$defquota);
9938: if (!defined($udom)) {
9939: $udom = $env{'user.domain'};
9940: }
9941: if (!defined($uname)) {
9942: $uname = $env{'user.name'};
9943: }
9944: if (($udom eq '' || $uname eq '') ||
9945: ($udom eq 'public') && ($uname eq 'public')) {
9946: $quota = 0;
9947: $quotatype = 'default';
9948: $defquota = 0;
9949: } else {
9950: my $inststatus;
9951: if ($quotaname eq 'course') {
9952: if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
9953: ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
9954: $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
9955: } else {
9956: my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
9957: $quota = $cenv{'internal.uploadquota'};
9958: }
9959: } else {
9960: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
9961: if ($quotaname eq 'author') {
9962: $quota = $env{'environment.authorquota'};
9963: } else {
9964: $quota = $env{'environment.portfolioquota'};
9965: }
9966: $inststatus = $env{'environment.inststatus'};
9967: } else {
9968: my %userenv =
9969: &Apache::lonnet::get('environment',['portfolioquota',
9970: 'authorquota','inststatus'],$udom,$uname);
9971: my ($tmp) = keys(%userenv);
9972: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9973: if ($quotaname eq 'author') {
9974: $quota = $userenv{'authorquota'};
9975: } else {
9976: $quota = $userenv{'portfolioquota'};
9977: }
9978: $inststatus = $userenv{'inststatus'};
9979: } else {
9980: undef(%userenv);
9981: }
9982: }
9983: }
9984: if ($quota eq '' || wantarray) {
9985: if ($quotaname eq 'course') {
9986: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
9987: if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
9988: ($crstype eq 'community') || ($crstype eq 'textbook') ||
9989: ($crstype eq 'placement')) {
9990: $defquota = $domdefs{$crstype.'quota'};
9991: }
9992: if ($defquota eq '') {
9993: $defquota = 500;
9994: }
9995: } else {
9996: ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
9997: }
9998: if ($quota eq '') {
9999: $quota = $defquota;
10000: $quotatype = 'default';
10001: } else {
10002: $quotatype = 'custom';
10003: }
10004: }
10005: }
10006: if (wantarray) {
10007: return ($quota,$quotatype,$settingstatus,$defquota);
10008: } else {
10009: return $quota;
10010: }
10011: }
10012:
10013: ###############################################
10014:
10015: =pod
10016:
10017: =item * &default_quota()
10018:
10019: Retrieves default quota assigned for storage of user portfolio files,
10020: given an (optional) user's institutional status.
10021:
10022: Incoming parameters:
10023:
10024: 1. domain
10025: 2. (Optional) institutional status(es). This is a : separated list of
10026: status types (e.g., faculty, staff, student etc.)
10027: which apply to the user for whom the default is being retrieved.
10028: If the institutional status string in undefined, the domain
10029: default quota will be returned.
10030: 3. quota name - portfolio, author, or course
10031: (if no quota name provided, defaults to portfolio).
10032:
10033: Returns:
10034:
10035: 1. Default disk quota (in MB) for user portfolios in the domain.
10036: 2. (Optional) institutional type which determined the value of the
10037: default quota.
10038:
10039: If a value has been stored in the domain's configuration db,
10040: it will return that, otherwise it returns 20 (for backwards
10041: compatibility with domains which have not set up a configuration
10042: db file; the original statically defined portfolio quota was 20 MB).
10043:
10044: If the user's status includes multiple types (e.g., staff and student),
10045: the largest default quota which applies to the user determines the
10046: default quota returned.
10047:
10048: =cut
10049:
10050: ###############################################
10051:
10052:
10053: sub default_quota {
10054: my ($udom,$inststatus,$quotaname) = @_;
10055: my ($defquota,$settingstatus);
10056: my %quotahash = &Apache::lonnet::get_dom('configuration',
10057: ['quotas'],$udom);
10058: my $key = 'defaultquota';
10059: if ($quotaname eq 'author') {
10060: $key = 'authorquota';
10061: }
10062: if (ref($quotahash{'quotas'}) eq 'HASH') {
10063: if ($inststatus ne '') {
10064: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
10065: foreach my $item (@statuses) {
10066: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10067: if ($quotahash{'quotas'}{$key}{$item} ne '') {
10068: if ($defquota eq '') {
10069: $defquota = $quotahash{'quotas'}{$key}{$item};
10070: $settingstatus = $item;
10071: } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
10072: $defquota = $quotahash{'quotas'}{$key}{$item};
10073: $settingstatus = $item;
10074: }
10075: }
10076: } elsif ($key eq 'defaultquota') {
10077: if ($quotahash{'quotas'}{$item} ne '') {
10078: if ($defquota eq '') {
10079: $defquota = $quotahash{'quotas'}{$item};
10080: $settingstatus = $item;
10081: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
10082: $defquota = $quotahash{'quotas'}{$item};
10083: $settingstatus = $item;
10084: }
10085: }
10086: }
10087: }
10088: }
10089: if ($defquota eq '') {
10090: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10091: $defquota = $quotahash{'quotas'}{$key}{'default'};
10092: } elsif ($key eq 'defaultquota') {
10093: $defquota = $quotahash{'quotas'}{'default'};
10094: }
10095: $settingstatus = 'default';
10096: if ($defquota eq '') {
10097: if ($quotaname eq 'author') {
10098: $defquota = 500;
10099: }
10100: }
10101: }
10102: } else {
10103: $settingstatus = 'default';
10104: if ($quotaname eq 'author') {
10105: $defquota = 500;
10106: } else {
10107: $defquota = 20;
10108: }
10109: }
10110: if (wantarray) {
10111: return ($defquota,$settingstatus);
10112: } else {
10113: return $defquota;
10114: }
10115: }
10116:
10117: ###############################################
10118:
10119: =pod
10120:
10121: =item * &excess_filesize_warning()
10122:
10123: Returns warning message if upload of file to authoring space, or copying
10124: of existing file within authoring space will cause quota for the authoring
10125: space to be exceeded.
10126:
10127: Same, if upload of a file directly to a course/community via Course Editor
10128: will cause quota for uploaded content for the course to be exceeded.
10129:
10130: Inputs: 7
10131: 1. username or coursenum
10132: 2. domain
10133: 3. context ('author' or 'course')
10134: 4. filename of file for which action is being requested
10135: 5. filesize (kB) of file
10136: 6. action being taken: copy or upload.
10137: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
10138:
10139: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
10140: otherwise return null.
10141:
10142: =back
10143:
10144: =cut
10145:
10146: sub excess_filesize_warning {
10147: my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
10148: my $current_disk_usage = 0;
10149: my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
10150: if ($context eq 'author') {
10151: my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
10152: $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
10153: } else {
10154: foreach my $subdir ('docs','supplemental') {
10155: $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
10156: }
10157: }
10158: $disk_quota = int($disk_quota * 1000);
10159: if (($current_disk_usage + $filesize) > $disk_quota) {
10160: return '<p class="LC_warning">'.
10161: &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
10162: '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
10163: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10164: $disk_quota,$current_disk_usage).
10165: '</p>';
10166: }
10167: return;
10168: }
10169:
10170: ###############################################
10171:
10172:
10173:
10174:
10175: sub get_secgrprole_info {
10176: my ($cdom,$cnum,$needroles,$type) = @_;
10177: my %sections_count = &get_sections($cdom,$cnum);
10178: my @sections = (sort {$a <=> $b} keys(%sections_count));
10179: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10180: my @groups = sort(keys(%curr_groups));
10181: my $allroles = [];
10182: my $rolehash;
10183: my $accesshash = {
10184: active => 'Currently has access',
10185: future => 'Will have future access',
10186: previous => 'Previously had access',
10187: };
10188: if ($needroles) {
10189: $rolehash = {'all' => 'all'};
10190: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10191: if (&Apache::lonnet::error(%user_roles)) {
10192: undef(%user_roles);
10193: }
10194: foreach my $item (keys(%user_roles)) {
10195: my ($role)=split(/\:/,$item,2);
10196: if ($role eq 'cr') { next; }
10197: if ($role =~ /^cr/) {
10198: $$rolehash{$role} = (split('/',$role))[3];
10199: } else {
10200: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
10201: }
10202: }
10203: foreach my $key (sort(keys(%{$rolehash}))) {
10204: push(@{$allroles},$key);
10205: }
10206: push (@{$allroles},'st');
10207: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
10208: }
10209: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
10210: }
10211:
10212: sub user_picker {
10213: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
10214: my $currdom = $dom;
10215: my @alldoms = &Apache::lonnet::all_domains();
10216: if (@alldoms == 1) {
10217: my %domsrch = &Apache::lonnet::get_dom('configuration',
10218: ['directorysrch'],$alldoms[0]);
10219: my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
10220: my $showdom = $domdesc;
10221: if ($showdom eq '') {
10222: $showdom = $dom;
10223: }
10224: if (ref($domsrch{'directorysrch'}) eq 'HASH') {
10225: if ((!$domsrch{'directorysrch'}{'available'}) &&
10226: ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
10227: return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
10228: }
10229: }
10230: }
10231: my %curr_selected = (
10232: srchin => 'dom',
10233: srchby => 'lastname',
10234: );
10235: my $srchterm;
10236: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
10237: if ($srch->{'srchby'} ne '') {
10238: $curr_selected{'srchby'} = $srch->{'srchby'};
10239: }
10240: if ($srch->{'srchin'} ne '') {
10241: $curr_selected{'srchin'} = $srch->{'srchin'};
10242: }
10243: if ($srch->{'srchtype'} ne '') {
10244: $curr_selected{'srchtype'} = $srch->{'srchtype'};
10245: }
10246: if ($srch->{'srchdomain'} ne '') {
10247: $currdom = $srch->{'srchdomain'};
10248: }
10249: $srchterm = $srch->{'srchterm'};
10250: }
10251: my %html_lt=&Apache::lonlocal::texthash(
10252: 'usr' => 'Search criteria',
10253: 'doma' => 'Domain/institution to search',
10254: 'uname' => 'username',
10255: 'lastname' => 'last name',
10256: 'lastfirst' => 'last name, first name',
10257: 'crs' => 'in this course',
10258: 'dom' => 'in selected LON-CAPA domain',
10259: 'alc' => 'all LON-CAPA',
10260: 'instd' => 'in institutional directory for selected domain',
10261: 'exact' => 'is',
10262: 'contains' => 'contains',
10263: 'begins' => 'begins with',
10264: );
10265: my %js_lt=&Apache::lonlocal::texthash(
10266: 'youm' => "You must include some text to search for.",
10267: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
10268: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
10269: 'yomc' => "You must choose a domain when using an institutional directory search.",
10270: 'ymcd' => "You must choose a domain when using a domain search.",
10271: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
10272: 'whse' => "When searching by last,first you must include at least one character in the first name.",
10273: 'thfo' => "The following need to be corrected before the search can be run:",
10274: );
10275: &html_escape(\%html_lt);
10276: &js_escape(\%js_lt);
10277: my $domform;
10278: my $allow_blank = 1;
10279: if ($fixeddom) {
10280: $allow_blank = 0;
10281: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
10282: } else {
10283: my $defdom = $env{'request.role.domain'};
10284: my ($trusted,$untrusted);
10285: if (($context eq 'requestcrs') || ($context eq 'course')) {
10286: ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
10287: } elsif ($context eq 'author') {
10288: ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
10289: } elsif ($context eq 'domain') {
10290: ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom);
10291: }
10292: $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,$trusted,$untrusted);
10293: }
10294: my $srchinsel = ' <select name="srchin">';
10295:
10296: my @srchins = ('crs','dom','alc','instd');
10297:
10298: foreach my $option (@srchins) {
10299: # FIXME 'alc' option unavailable until
10300: # loncreateuser::print_user_query_page()
10301: # has been completed.
10302: next if ($option eq 'alc');
10303: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
10304: next if ($option eq 'crs' && !$env{'request.course.id'});
10305: next if (($option eq 'instd') && ($noinstd));
10306: if ($curr_selected{'srchin'} eq $option) {
10307: $srchinsel .= '
10308: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10309: } else {
10310: $srchinsel .= '
10311: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10312: }
10313: }
10314: $srchinsel .= "\n </select>\n";
10315:
10316: my $srchbysel = ' <select name="srchby">';
10317: foreach my $option ('lastname','lastfirst','uname') {
10318: if ($curr_selected{'srchby'} eq $option) {
10319: $srchbysel .= '
10320: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10321: } else {
10322: $srchbysel .= '
10323: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10324: }
10325: }
10326: $srchbysel .= "\n </select>\n";
10327:
10328: my $srchtypesel = ' <select name="srchtype">';
10329: foreach my $option ('begins','contains','exact') {
10330: if ($curr_selected{'srchtype'} eq $option) {
10331: $srchtypesel .= '
10332: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10333: } else {
10334: $srchtypesel .= '
10335: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10336: }
10337: }
10338: $srchtypesel .= "\n </select>\n";
10339:
10340: my ($newuserscript,$new_user_create);
10341: my $context_dom = $env{'request.role.domain'};
10342: if ($context eq 'requestcrs') {
10343: if ($env{'form.coursedom'} ne '') {
10344: $context_dom = $env{'form.coursedom'};
10345: }
10346: }
10347: if ($forcenewuser) {
10348: if (ref($srch) eq 'HASH') {
10349: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
10350: if ($cancreate) {
10351: $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>';
10352: } else {
10353: my $helplink = 'javascript:helpMenu('."'display'".')';
10354: my %usertypetext = (
10355: official => 'institutional',
10356: unofficial => 'non-institutional',
10357: );
10358: $new_user_create = '<p class="LC_warning">'
10359: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
10360: .' '
10361: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
10362: ,'<a href="'.$helplink.'">','</a>')
10363: .'</p><br />';
10364: }
10365: }
10366: }
10367:
10368: $newuserscript = <<"ENDSCRIPT";
10369:
10370: function setSearch(createnew,callingForm) {
10371: if (createnew == 1) {
10372: for (var i=0; i<callingForm.srchby.length; i++) {
10373: if (callingForm.srchby.options[i].value == 'uname') {
10374: callingForm.srchby.selectedIndex = i;
10375: }
10376: }
10377: for (var i=0; i<callingForm.srchin.length; i++) {
10378: if ( callingForm.srchin.options[i].value == 'dom') {
10379: callingForm.srchin.selectedIndex = i;
10380: }
10381: }
10382: for (var i=0; i<callingForm.srchtype.length; i++) {
10383: if (callingForm.srchtype.options[i].value == 'exact') {
10384: callingForm.srchtype.selectedIndex = i;
10385: }
10386: }
10387: for (var i=0; i<callingForm.srchdomain.length; i++) {
10388: if (callingForm.srchdomain.options[i].value == '$context_dom') {
10389: callingForm.srchdomain.selectedIndex = i;
10390: }
10391: }
10392: }
10393: }
10394: ENDSCRIPT
10395:
10396: }
10397:
10398: my $output = <<"END_BLOCK";
10399: <script type="text/javascript">
10400: // <![CDATA[
10401: function validateEntry(callingForm) {
10402:
10403: var checkok = 1;
10404: var srchin;
10405: for (var i=0; i<callingForm.srchin.length; i++) {
10406: if ( callingForm.srchin[i].checked ) {
10407: srchin = callingForm.srchin[i].value;
10408: }
10409: }
10410:
10411: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10412: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10413: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10414: var srchterm = callingForm.srchterm.value;
10415: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10416: var msg = "";
10417:
10418: if (srchterm == "") {
10419: checkok = 0;
10420: msg += "$js_lt{'youm'}\\n";
10421: }
10422:
10423: if (srchtype== 'begins') {
10424: if (srchterm.length < 2) {
10425: checkok = 0;
10426: msg += "$js_lt{'thte'}\\n";
10427: }
10428: }
10429:
10430: if (srchtype== 'contains') {
10431: if (srchterm.length < 3) {
10432: checkok = 0;
10433: msg += "$js_lt{'thet'}\\n";
10434: }
10435: }
10436: if (srchin == 'instd') {
10437: if (srchdomain == '') {
10438: checkok = 0;
10439: msg += "$js_lt{'yomc'}\\n";
10440: }
10441: }
10442: if (srchin == 'dom') {
10443: if (srchdomain == '') {
10444: checkok = 0;
10445: msg += "$js_lt{'ymcd'}\\n";
10446: }
10447: }
10448: if (srchby == 'lastfirst') {
10449: if (srchterm.indexOf(",") == -1) {
10450: checkok = 0;
10451: msg += "$js_lt{'whus'}\\n";
10452: }
10453: if (srchterm.indexOf(",") == srchterm.length -1) {
10454: checkok = 0;
10455: msg += "$js_lt{'whse'}\\n";
10456: }
10457: }
10458: if (checkok == 0) {
10459: alert("$js_lt{'thfo'}\\n"+msg);
10460: return;
10461: }
10462: if (checkok == 1) {
10463: callingForm.submit();
10464: }
10465: }
10466:
10467: $newuserscript
10468:
10469: // ]]>
10470: </script>
10471:
10472: $new_user_create
10473:
10474: END_BLOCK
10475:
10476: $output .= &Apache::lonhtmlcommon::start_pick_box().
10477: &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10478: $domform.
10479: &Apache::lonhtmlcommon::row_closure().
10480: &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10481: $srchbysel.
10482: $srchtypesel.
10483: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10484: $srchinsel.
10485: &Apache::lonhtmlcommon::row_closure(1).
10486: &Apache::lonhtmlcommon::end_pick_box().
10487: '<br />';
10488: return ($output,1);
10489: }
10490:
10491: sub user_rule_check {
10492: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10493: my ($response,%inst_response);
10494: if (ref($usershash) eq 'HASH') {
10495: if (keys(%{$usershash}) > 1) {
10496: my (%by_username,%by_id,%userdoms);
10497: my $checkid;
10498: if (ref($checks) eq 'HASH') {
10499: if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10500: $checkid = 1;
10501: }
10502: }
10503: foreach my $user (keys(%{$usershash})) {
10504: my ($uname,$udom) = split(/:/,$user);
10505: if ($checkid) {
10506: if (ref($usershash->{$user}) eq 'HASH') {
10507: if ($usershash->{$user}->{'id'} ne '') {
10508: $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
10509: $userdoms{$udom} = 1;
10510: if (ref($inst_results) eq 'HASH') {
10511: $inst_results->{$uname.':'.$udom} = {};
10512: }
10513: }
10514: }
10515: } else {
10516: $by_username{$udom}{$uname} = 1;
10517: $userdoms{$udom} = 1;
10518: if (ref($inst_results) eq 'HASH') {
10519: $inst_results->{$uname.':'.$udom} = {};
10520: }
10521: }
10522: }
10523: foreach my $udom (keys(%userdoms)) {
10524: if (!$got_rules->{$udom}) {
10525: my %domconfig = &Apache::lonnet::get_dom('configuration',
10526: ['usercreation'],$udom);
10527: if (ref($domconfig{'usercreation'}) eq 'HASH') {
10528: foreach my $item ('username','id') {
10529: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10530: $$curr_rules{$udom}{$item} =
10531: $domconfig{'usercreation'}{$item.'_rule'};
10532: }
10533: }
10534: }
10535: $got_rules->{$udom} = 1;
10536: }
10537: }
10538: if ($checkid) {
10539: foreach my $udom (keys(%by_id)) {
10540: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10541: if ($outcome eq 'ok') {
10542: foreach my $id (keys(%{$by_id{$udom}})) {
10543: my $uname = $by_id{$udom}{$id};
10544: $inst_response{$uname.':'.$udom} = $outcome;
10545: }
10546: if (ref($results) eq 'HASH') {
10547: foreach my $uname (keys(%{$results})) {
10548: if (exists($inst_response{$uname.':'.$udom})) {
10549: $inst_response{$uname.':'.$udom} = $outcome;
10550: $inst_results->{$uname.':'.$udom} = $results->{$uname};
10551: }
10552: }
10553: }
10554: }
10555: }
10556: } else {
10557: foreach my $udom (keys(%by_username)) {
10558: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10559: if ($outcome eq 'ok') {
10560: foreach my $uname (keys(%{$by_username{$udom}})) {
10561: $inst_response{$uname.':'.$udom} = $outcome;
10562: }
10563: if (ref($results) eq 'HASH') {
10564: foreach my $uname (keys(%{$results})) {
10565: $inst_results->{$uname.':'.$udom} = $results->{$uname};
10566: }
10567: }
10568: }
10569: }
10570: }
10571: } elsif (keys(%{$usershash}) == 1) {
10572: my $user = (keys(%{$usershash}))[0];
10573: my ($uname,$udom) = split(/:/,$user);
10574: if (($udom ne '') && ($uname ne '')) {
10575: if (ref($usershash->{$user}) eq 'HASH') {
10576: if (ref($checks) eq 'HASH') {
10577: if (defined($checks->{'username'})) {
10578: ($inst_response{$user},%{$inst_results->{$user}}) =
10579: &Apache::lonnet::get_instuser($udom,$uname);
10580: } elsif (defined($checks->{'id'})) {
10581: if ($usershash->{$user}->{'id'} ne '') {
10582: ($inst_response{$user},%{$inst_results->{$user}}) =
10583: &Apache::lonnet::get_instuser($udom,undef,
10584: $usershash->{$user}->{'id'});
10585: } else {
10586: ($inst_response{$user},%{$inst_results->{$user}}) =
10587: &Apache::lonnet::get_instuser($udom,$uname);
10588: }
10589: }
10590: } else {
10591: ($inst_response{$user},%{$inst_results->{$user}}) =
10592: &Apache::lonnet::get_instuser($udom,$uname);
10593: return;
10594: }
10595: if (!$got_rules->{$udom}) {
10596: my %domconfig = &Apache::lonnet::get_dom('configuration',
10597: ['usercreation'],$udom);
10598: if (ref($domconfig{'usercreation'}) eq 'HASH') {
10599: foreach my $item ('username','id') {
10600: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10601: $$curr_rules{$udom}{$item} =
10602: $domconfig{'usercreation'}{$item.'_rule'};
10603: }
10604: }
10605: }
10606: $got_rules->{$udom} = 1;
10607: }
10608: }
10609: } else {
10610: return;
10611: }
10612: } else {
10613: return;
10614: }
10615: foreach my $user (keys(%{$usershash})) {
10616: my ($uname,$udom) = split(/:/,$user);
10617: next if (($udom eq '') || ($uname eq ''));
10618: my $id;
10619: if (ref($inst_results) eq 'HASH') {
10620: if (ref($inst_results->{$user}) eq 'HASH') {
10621: $id = $inst_results->{$user}->{'id'};
10622: }
10623: }
10624: if ($id eq '') {
10625: if (ref($usershash->{$user})) {
10626: $id = $usershash->{$user}->{'id'};
10627: }
10628: }
10629: foreach my $item (keys(%{$checks})) {
10630: if (ref($$curr_rules{$udom}) eq 'HASH') {
10631: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10632: if (@{$$curr_rules{$udom}{$item}} > 0) {
10633: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10634: $$curr_rules{$udom}{$item});
10635: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10636: if ($rule_check{$rule}) {
10637: $$rulematch{$user}{$item} = $rule;
10638: if ($inst_response{$user} eq 'ok') {
10639: if (ref($inst_results) eq 'HASH') {
10640: if (ref($inst_results->{$user}) eq 'HASH') {
10641: if (keys(%{$inst_results->{$user}}) == 0) {
10642: $$alerts{$item}{$udom}{$uname} = 1;
10643: } elsif ($item eq 'id') {
10644: if ($inst_results->{$user}->{'id'} eq '') {
10645: $$alerts{$item}{$udom}{$uname} = 1;
10646: }
10647: }
10648: }
10649: }
10650: }
10651: last;
10652: }
10653: }
10654: }
10655: }
10656: }
10657: }
10658: }
10659: }
10660: return;
10661: }
10662:
10663: sub user_rule_formats {
10664: my ($domain,$domdesc,$curr_rules,$check) = @_;
10665: my %text = (
10666: 'username' => 'Usernames',
10667: 'id' => 'IDs',
10668: );
10669: my $output;
10670: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10671: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10672: if (@{$ruleorder} > 0) {
10673: $output = '<br />'.
10674: &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10675: '<span class="LC_cusr_emph">','</span>',$domdesc).
10676: ' <ul>';
10677: foreach my $rule (@{$ruleorder}) {
10678: if (ref($curr_rules) eq 'ARRAY') {
10679: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10680: if (ref($rules->{$rule}) eq 'HASH') {
10681: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10682: $rules->{$rule}{'desc'}.'</li>';
10683: }
10684: }
10685: }
10686: }
10687: $output .= '</ul>';
10688: }
10689: }
10690: return $output;
10691: }
10692:
10693: sub instrule_disallow_msg {
10694: my ($checkitem,$domdesc,$count,$mode) = @_;
10695: my $response;
10696: my %text = (
10697: item => 'username',
10698: items => 'usernames',
10699: match => 'matches',
10700: do => 'does',
10701: action => 'a username',
10702: one => 'one',
10703: );
10704: if ($count > 1) {
10705: $text{'item'} = 'usernames';
10706: $text{'match'} ='match';
10707: $text{'do'} = 'do';
10708: $text{'action'} = 'usernames',
10709: $text{'one'} = 'ones';
10710: }
10711: if ($checkitem eq 'id') {
10712: $text{'items'} = 'IDs';
10713: $text{'item'} = 'ID';
10714: $text{'action'} = 'an ID';
10715: if ($count > 1) {
10716: $text{'item'} = 'IDs';
10717: $text{'action'} = 'IDs';
10718: }
10719: }
10720: $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 />';
10721: if ($mode eq 'upload') {
10722: if ($checkitem eq 'username') {
10723: $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'}.");
10724: } elsif ($checkitem eq 'id') {
10725: $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.");
10726: }
10727: } elsif ($mode eq 'selfcreate') {
10728: if ($checkitem eq 'id') {
10729: $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.");
10730: }
10731: } else {
10732: if ($checkitem eq 'username') {
10733: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10734: } elsif ($checkitem eq 'id') {
10735: $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.");
10736: }
10737: }
10738: return $response;
10739: }
10740:
10741: sub personal_data_fieldtitles {
10742: my %fieldtitles = &Apache::lonlocal::texthash (
10743: id => 'Student/Employee ID',
10744: permanentemail => 'E-mail address',
10745: lastname => 'Last Name',
10746: firstname => 'First Name',
10747: middlename => 'Middle Name',
10748: generation => 'Generation',
10749: gen => 'Generation',
10750: inststatus => 'Affiliation',
10751: );
10752: return %fieldtitles;
10753: }
10754:
10755: sub sorted_inst_types {
10756: my ($dom) = @_;
10757: my ($usertypes,$order);
10758: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10759: if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10760: $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10761: $order = $domdefaults{'inststatus'}{'inststatusorder'};
10762: } else {
10763: ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10764: }
10765: my $othertitle = &mt('All users');
10766: if ($env{'request.course.id'}) {
10767: $othertitle = &mt('Any users');
10768: }
10769: my @types;
10770: if (ref($order) eq 'ARRAY') {
10771: @types = @{$order};
10772: }
10773: if (@types == 0) {
10774: if (ref($usertypes) eq 'HASH') {
10775: @types = sort(keys(%{$usertypes}));
10776: }
10777: }
10778: if (keys(%{$usertypes}) > 0) {
10779: $othertitle = &mt('Other users');
10780: }
10781: return ($othertitle,$usertypes,\@types);
10782: }
10783:
10784: sub get_institutional_codes {
10785: my ($settings,$allcourses,$LC_code) = @_;
10786: # Get complete list of course sections to update
10787: my @currsections = ();
10788: my @currxlists = ();
10789: my $coursecode = $$settings{'internal.coursecode'};
10790:
10791: if ($$settings{'internal.sectionnums'} ne '') {
10792: @currsections = split(/,/,$$settings{'internal.sectionnums'});
10793: }
10794:
10795: if ($$settings{'internal.crosslistings'} ne '') {
10796: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10797: }
10798:
10799: if (@currxlists > 0) {
10800: foreach (@currxlists) {
10801: if (m/^([^:]+):(\w*)$/) {
10802: unless (grep/^$1$/,@{$allcourses}) {
10803: push(@{$allcourses},$1);
10804: $$LC_code{$1} = $2;
10805: }
10806: }
10807: }
10808: }
10809:
10810: if (@currsections > 0) {
10811: foreach (@currsections) {
10812: if (m/^(\w+):(\w*)$/) {
10813: my $sec = $coursecode.$1;
10814: my $lc_sec = $2;
10815: unless (grep/^$sec$/,@{$allcourses}) {
10816: push(@{$allcourses},$sec);
10817: $$LC_code{$sec} = $lc_sec;
10818: }
10819: }
10820: }
10821: }
10822: return;
10823: }
10824:
10825: sub get_standard_codeitems {
10826: return ('Year','Semester','Department','Number','Section');
10827: }
10828:
10829: =pod
10830:
10831: =head1 Slot Helpers
10832:
10833: =over 4
10834:
10835: =item * sorted_slots()
10836:
10837: Sorts an array of slot names in order of an optional sort key,
10838: default sort is by slot start time (earliest first).
10839:
10840: Inputs:
10841:
10842: =over 4
10843:
10844: slotsarr - Reference to array of unsorted slot names.
10845:
10846: slots - Reference to hash of hash, where outer hash keys are slot names.
10847:
10848: sortkey - Name of key in inner hash to be sorted on (e.g., starttime).
10849:
10850: =back
10851:
10852: Returns:
10853:
10854: =over 4
10855:
10856: sorted - An array of slot names sorted by a specified sort key
10857: (default sort key is start time of the slot).
10858:
10859: =back
10860:
10861: =cut
10862:
10863:
10864: sub sorted_slots {
10865: my ($slotsarr,$slots,$sortkey) = @_;
10866: if ($sortkey eq '') {
10867: $sortkey = 'starttime';
10868: }
10869: my @sorted;
10870: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10871: @sorted =
10872: sort {
10873: if (ref($slots->{$a}) && ref($slots->{$b})) {
10874: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10875: }
10876: if (ref($slots->{$a})) { return -1;}
10877: if (ref($slots->{$b})) { return 1;}
10878: return 0;
10879: } @{$slotsarr};
10880: }
10881: return @sorted;
10882: }
10883:
10884: =pod
10885:
10886: =item * get_future_slots()
10887:
10888: Inputs:
10889:
10890: =over 4
10891:
10892: cnum - course number
10893:
10894: cdom - course domain
10895:
10896: now - current UNIX time
10897:
10898: symb - optional symb
10899:
10900: =back
10901:
10902: Returns:
10903:
10904: =over 4
10905:
10906: sorted_reservable - ref to array of student_schedulable slots currently
10907: reservable, ordered by end date of reservation period.
10908:
10909: reservable_now - ref to hash of student_schedulable slots currently
10910: reservable.
10911:
10912: Keys in inner hash are:
10913: (a) symb: either blank or symb to which slot use is restricted.
10914: (b) endreserve: end date of reservation period.
10915: (c) uniqueperiod: start,end dates when slot is to be uniquely
10916: selected.
10917:
10918: sorted_future - ref to array of student_schedulable slots reservable in
10919: the future, ordered by start date of reservation period.
10920:
10921: future_reservable - ref to hash of student_schedulable slots reservable
10922: in the future.
10923:
10924: Keys in inner hash are:
10925: (a) symb: either blank or symb to which slot use is restricted.
10926: (b) startreserve: start date of reservation period.
10927: (c) uniqueperiod: start,end dates when slot is to be uniquely
10928: selected.
10929:
10930: =back
10931:
10932: =cut
10933:
10934: sub get_future_slots {
10935: my ($cnum,$cdom,$now,$symb) = @_;
10936: my $map;
10937: if ($symb) {
10938: ($map) = &Apache::lonnet::decode_symb($symb);
10939: }
10940: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10941: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10942: foreach my $slot (keys(%slots)) {
10943: next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10944: if ($symb) {
10945: if ($slots{$slot}->{'symb'} ne '') {
10946: my $canuse;
10947: my %oksymbs;
10948: my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
10949: map { $oksymbs{$_} = 1; } @slotsymbs;
10950: if ($oksymbs{$symb}) {
10951: $canuse = 1;
10952: } else {
10953: foreach my $item (@slotsymbs) {
10954: if ($item =~ /\.(page|sequence)$/) {
10955: (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
10956: if (($map ne '') && ($map eq $sloturl)) {
10957: $canuse = 1;
10958: last;
10959: }
10960: }
10961: }
10962: }
10963: next unless ($canuse);
10964: }
10965: }
10966: if (($slots{$slot}->{'starttime'} > $now) &&
10967: ($slots{$slot}->{'endtime'} > $now)) {
10968: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10969: my $userallowed = 0;
10970: if ($slots{$slot}->{'allowedsections'}) {
10971: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10972: if (!defined($env{'request.role.sec'})
10973: && grep(/^No section assigned$/,@allowed_sec)) {
10974: $userallowed=1;
10975: } else {
10976: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10977: $userallowed=1;
10978: }
10979: }
10980: unless ($userallowed) {
10981: if (defined($env{'request.course.groups'})) {
10982: my @groups = split(/:/,$env{'request.course.groups'});
10983: foreach my $group (@groups) {
10984: if (grep(/^\Q$group\E$/,@allowed_sec)) {
10985: $userallowed=1;
10986: last;
10987: }
10988: }
10989: }
10990: }
10991: }
10992: if ($slots{$slot}->{'allowedusers'}) {
10993: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10994: my $user = $env{'user.name'}.':'.$env{'user.domain'};
10995: if (grep(/^\Q$user\E$/,@allowed_users)) {
10996: $userallowed = 1;
10997: }
10998: }
10999: next unless($userallowed);
11000: }
11001: my $startreserve = $slots{$slot}->{'startreserve'};
11002: my $endreserve = $slots{$slot}->{'endreserve'};
11003: my $symb = $slots{$slot}->{'symb'};
11004: my $uniqueperiod;
11005: if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
11006: $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
11007: }
11008: if (($startreserve < $now) &&
11009: (!$endreserve || $endreserve > $now)) {
11010: my $lastres = $endreserve;
11011: if (!$lastres) {
11012: $lastres = $slots{$slot}->{'starttime'};
11013: }
11014: $reservable_now{$slot} = {
11015: symb => $symb,
11016: endreserve => $lastres,
11017: uniqueperiod => $uniqueperiod,
11018: };
11019: } elsif (($startreserve > $now) &&
11020: (!$endreserve || $endreserve > $startreserve)) {
11021: $future_reservable{$slot} = {
11022: symb => $symb,
11023: startreserve => $startreserve,
11024: uniqueperiod => $uniqueperiod,
11025: };
11026: }
11027: }
11028: }
11029: my @unsorted_reservable = keys(%reservable_now);
11030: if (@unsorted_reservable > 0) {
11031: @sorted_reservable =
11032: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
11033: }
11034: my @unsorted_future = keys(%future_reservable);
11035: if (@unsorted_future > 0) {
11036: @sorted_future =
11037: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
11038: }
11039: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
11040: }
11041:
11042: =pod
11043:
11044: =back
11045:
11046: =head1 HTTP Helpers
11047:
11048: =over 4
11049:
11050: =item * &get_unprocessed_cgi($query,$possible_names)
11051:
11052: Modify the %env hash to contain unprocessed CGI form parameters held in
11053: $query. The parameters listed in $possible_names (an array reference),
11054: will be set in $env{'form.name'} if they do not already exist.
11055:
11056: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
11057: $possible_names is an ref to an array of form element names. As an example:
11058: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
11059: will result in $env{'form.uname'} and $env{'form.udom'} being set.
11060:
11061: =cut
11062:
11063: sub get_unprocessed_cgi {
11064: my ($query,$possible_names)= @_;
11065: # $Apache::lonxml::debug=1;
11066: foreach my $pair (split(/&/,$query)) {
11067: my ($name, $value) = split(/=/,$pair);
11068: $name = &unescape($name);
11069: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
11070: $value =~ tr/+/ /;
11071: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
11072: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
11073: }
11074: }
11075: }
11076:
11077: =pod
11078:
11079: =item * &cacheheader()
11080:
11081: returns cache-controlling header code
11082:
11083: =cut
11084:
11085: sub cacheheader {
11086: unless ($env{'request.method'} eq 'GET') { return ''; }
11087: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
11088: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
11089: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
11090: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
11091: return $output;
11092: }
11093:
11094: =pod
11095:
11096: =item * &no_cache($r)
11097:
11098: specifies header code to not have cache
11099:
11100: =cut
11101:
11102: sub no_cache {
11103: my ($r) = @_;
11104: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
11105: $env{'request.method'} ne 'GET') { return ''; }
11106: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
11107: $r->no_cache(1);
11108: $r->header_out("Expires" => $date);
11109: $r->header_out("Pragma" => "no-cache");
11110: }
11111:
11112: sub content_type {
11113: my ($r,$type,$charset) = @_;
11114: if ($r) {
11115: # Note that printout.pl calls this with undef for $r.
11116: &no_cache($r);
11117: }
11118: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
11119: unless ($charset) {
11120: $charset=&Apache::lonlocal::current_encoding;
11121: }
11122: if ($charset) { $type.='; charset='.$charset; }
11123: if ($r) {
11124: $r->content_type($type);
11125: } else {
11126: print("Content-type: $type\n\n");
11127: }
11128: }
11129:
11130: =pod
11131:
11132: =item * &add_to_env($name,$value)
11133:
11134: adds $name to the %env hash with value
11135: $value, if $name already exists, the entry is converted to an array
11136: reference and $value is added to the array.
11137:
11138: =cut
11139:
11140: sub add_to_env {
11141: my ($name,$value)=@_;
11142: if (defined($env{$name})) {
11143: if (ref($env{$name})) {
11144: #already have multiple values
11145: push(@{ $env{$name} },$value);
11146: } else {
11147: #first time seeing multiple values, convert hash entry to an arrayref
11148: my $first=$env{$name};
11149: undef($env{$name});
11150: push(@{ $env{$name} },$first,$value);
11151: }
11152: } else {
11153: $env{$name}=$value;
11154: }
11155: }
11156:
11157: =pod
11158:
11159: =item * &get_env_multiple($name)
11160:
11161: gets $name from the %env hash, it seemlessly handles the cases where multiple
11162: values may be defined and end up as an array ref.
11163:
11164: returns an array of values
11165:
11166: =cut
11167:
11168: sub get_env_multiple {
11169: my ($name) = @_;
11170: my @values;
11171: if (defined($env{$name})) {
11172: # exists is it an array
11173: if (ref($env{$name})) {
11174: @values=@{ $env{$name} };
11175: } else {
11176: $values[0]=$env{$name};
11177: }
11178: }
11179: return(@values);
11180: }
11181:
11182: # Looks at given dependencies, and returns something depending on the context.
11183: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
11184: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
11185: # For all other contexts, returns ($output, $counter, $numpathchg).
11186: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
11187: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
11188: # $numpathchg: integer with the number of cleaned up dependency paths.
11189: # \%existing: hash reference clean path -> 1 only for existing dependencies.
11190: # \%mapping: hash reference clean path -> original path for all dependencies.
11191: # @param {string} actionurl - The path to the handler, indicative of the context.
11192: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
11193: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
11194: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
11195: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
11196: # @return {Array} - array depending on the context (not a reference)
11197: sub ask_for_embedded_content {
11198: # NOTE: documentation was added afterwards, it could be wrong
11199: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
11200: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
11201: %currsubfile,%unused,$rem);
11202: my $counter = 0;
11203: my $numnew = 0;
11204: my $numremref = 0;
11205: my $numinvalid = 0;
11206: my $numpathchg = 0;
11207: my $numexisting = 0;
11208: my $numunused = 0;
11209: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
11210: $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
11211: my $heading = &mt('Upload embedded files');
11212: my $buttontext = &mt('Upload');
11213:
11214: # fills these variables based on the context:
11215: # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
11216: # $path, $fileloc, $title, $rem, $filename
11217: if ($env{'request.course.id'}) {
11218: if ($actionurl eq '/adm/dependencies') {
11219: $navmap = Apache::lonnavmaps::navmap->new();
11220: }
11221: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11222: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11223: }
11224: if (($actionurl eq '/adm/portfolio') ||
11225: ($actionurl eq '/adm/coursegrp_portfolio')) {
11226: my $current_path='/';
11227: if ($env{'form.currentpath'}) {
11228: $current_path = $env{'form.currentpath'};
11229: }
11230: if ($actionurl eq '/adm/coursegrp_portfolio') {
11231: $udom = $cdom;
11232: $uname = $cnum;
11233: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
11234: } else {
11235: $udom = $env{'user.domain'};
11236: $uname = $env{'user.name'};
11237: $url = '/userfiles/portfolio';
11238: }
11239: $toplevel = $url.'/';
11240: $url .= $current_path;
11241: $getpropath = 1;
11242: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11243: ($actionurl eq '/adm/imsimport')) {
11244: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
11245: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
11246: $toplevel = $url;
11247: if ($rest ne '') {
11248: $url .= $rest;
11249: }
11250: } elsif ($actionurl eq '/adm/coursedocs') {
11251: if (ref($args) eq 'HASH') {
11252: $url = $args->{'docs_url'};
11253: $toplevel = $url;
11254: if ($args->{'context'} eq 'paste') {
11255: ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
11256: ($path) =
11257: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11258: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11259: $fileloc =~ s{^/}{};
11260: }
11261: }
11262: } elsif ($actionurl eq '/adm/dependencies') {
11263: if ($env{'request.course.id'} ne '') {
11264: if (ref($args) eq 'HASH') {
11265: $url = $args->{'docs_url'};
11266: $title = $args->{'docs_title'};
11267: $toplevel = $url;
11268: unless ($toplevel =~ m{^/}) {
11269: $toplevel = "/$url";
11270: }
11271: ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
11272: if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
11273: $path = $1;
11274: } else {
11275: ($path) =
11276: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11277: }
11278: if ($toplevel=~/^\/*(uploaded|editupload)/) {
11279: $fileloc = $toplevel;
11280: $fileloc=~ s/^\s*(\S+)\s*$/$1/;
11281: my ($udom,$uname,$fname) =
11282: ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
11283: $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
11284: } else {
11285: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11286: }
11287: $fileloc =~ s{^/}{};
11288: ($filename) = ($fileloc =~ m{.+/([^/]+)$});
11289: $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
11290: }
11291: }
11292: } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11293: $udom = $cdom;
11294: $uname = $cnum;
11295: $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
11296: $toplevel = $url;
11297: $path = $url;
11298: $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
11299: $fileloc =~ s{^/}{};
11300: }
11301:
11302: # parses the dependency paths to get some info
11303: # fills $newfiles, $mapping, $subdependencies, $dependencies
11304: # $newfiles: hash URL -> 1 for new files or external URLs
11305: # (will be completed later)
11306: # $mapping:
11307: # for external URLs: external URL -> external URL
11308: # for relative paths: clean path -> original path
11309: # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
11310: # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
11311: foreach my $file (keys(%{$allfiles})) {
11312: my $embed_file;
11313: if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
11314: $embed_file = $1;
11315: } else {
11316: $embed_file = $file;
11317: }
11318: my ($absolutepath,$cleaned_file);
11319: if ($embed_file =~ m{^\w+://}) {
11320: $cleaned_file = $embed_file;
11321: $newfiles{$cleaned_file} = 1;
11322: $mapping{$cleaned_file} = $embed_file;
11323: } else {
11324: $cleaned_file = &clean_path($embed_file);
11325: if ($embed_file =~ m{^/}) {
11326: $absolutepath = $embed_file;
11327: }
11328: if ($cleaned_file =~ m{/}) {
11329: my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
11330: $path = &check_for_traversal($path,$url,$toplevel);
11331: my $item = $fname;
11332: if ($path ne '') {
11333: $item = $path.'/'.$fname;
11334: $subdependencies{$path}{$fname} = 1;
11335: } else {
11336: $dependencies{$item} = 1;
11337: }
11338: if ($absolutepath) {
11339: $mapping{$item} = $absolutepath;
11340: } else {
11341: $mapping{$item} = $embed_file;
11342: }
11343: } else {
11344: $dependencies{$embed_file} = 1;
11345: if ($absolutepath) {
11346: $mapping{$cleaned_file} = $absolutepath;
11347: } else {
11348: $mapping{$cleaned_file} = $embed_file;
11349: }
11350: }
11351: }
11352: }
11353:
11354: # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
11355: # and lists
11356: # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
11357: # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
11358: # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
11359: # the path had to be cleaned up
11360: # $existing: hash clean path -> 1 if the file exists
11361: # $numexisting: number of keys in $existing
11362: # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
11363: # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
11364: # dependency subdirectories that are
11365: # not listed as dependencies, with some exceptions using $rem
11366: my $dirptr = 16384;
11367: foreach my $path (keys(%subdependencies)) {
11368: $currsubfile{$path} = {};
11369: if (($actionurl eq '/adm/portfolio') ||
11370: ($actionurl eq '/adm/coursegrp_portfolio')) {
11371: my ($sublistref,$listerror) =
11372: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
11373: if (ref($sublistref) eq 'ARRAY') {
11374: foreach my $line (@{$sublistref}) {
11375: my ($file_name,$rest) = split(/\&/,$line,2);
11376: $currsubfile{$path}{$file_name} = 1;
11377: }
11378: }
11379: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11380: if (opendir(my $dir,$url.'/'.$path)) {
11381: my @subdir_list = grep(!/^\./,readdir($dir));
11382: map {$currsubfile{$path}{$_} = 1;} @subdir_list;
11383: }
11384: } elsif (($actionurl eq '/adm/dependencies') ||
11385: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11386: ($args->{'context'} eq 'paste')) ||
11387: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11388: if ($env{'request.course.id'} ne '') {
11389: my $dir;
11390: if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11391: $dir = $fileloc;
11392: } else {
11393: ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11394: }
11395: if ($dir ne '') {
11396: my ($sublistref,$listerror) =
11397: &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
11398: if (ref($sublistref) eq 'ARRAY') {
11399: foreach my $line (@{$sublistref}) {
11400: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
11401: undef,$mtime)=split(/\&/,$line,12);
11402: unless (($testdir&$dirptr) ||
11403: ($file_name =~ /^\.\.?$/)) {
11404: $currsubfile{$path}{$file_name} = [$size,$mtime];
11405: }
11406: }
11407: }
11408: }
11409: }
11410: }
11411: foreach my $file (keys(%{$subdependencies{$path}})) {
11412: if (exists($currsubfile{$path}{$file})) {
11413: my $item = $path.'/'.$file;
11414: unless ($mapping{$item} eq $item) {
11415: $pathchanges{$item} = 1;
11416: }
11417: $existing{$item} = 1;
11418: $numexisting ++;
11419: } else {
11420: $newfiles{$path.'/'.$file} = 1;
11421: }
11422: }
11423: if ($actionurl eq '/adm/dependencies') {
11424: foreach my $path (keys(%currsubfile)) {
11425: if (ref($currsubfile{$path}) eq 'HASH') {
11426: foreach my $file (keys(%{$currsubfile{$path}})) {
11427: unless ($subdependencies{$path}{$file}) {
11428: next if (($rem ne '') &&
11429: (($env{"httpref.$rem"."$path/$file"} ne '') ||
11430: (ref($navmap) &&
11431: (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
11432: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11433: ($navmap->getResourceByUrl($rem."$path/$1")))))));
11434: $unused{$path.'/'.$file} = 1;
11435: }
11436: }
11437: }
11438: }
11439: }
11440: }
11441:
11442: # fills $currfile, hash file name -> 1 or [$size,$mtime]
11443: # for files in $url or $fileloc (target directory) in some contexts
11444: my %currfile;
11445: if (($actionurl eq '/adm/portfolio') ||
11446: ($actionurl eq '/adm/coursegrp_portfolio')) {
11447: my ($dirlistref,$listerror) =
11448: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
11449: if (ref($dirlistref) eq 'ARRAY') {
11450: foreach my $line (@{$dirlistref}) {
11451: my ($file_name,$rest) = split(/\&/,$line,2);
11452: $currfile{$file_name} = 1;
11453: }
11454: }
11455: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11456: if (opendir(my $dir,$url)) {
11457: my @dir_list = grep(!/^\./,readdir($dir));
11458: map {$currfile{$_} = 1;} @dir_list;
11459: }
11460: } elsif (($actionurl eq '/adm/dependencies') ||
11461: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11462: ($args->{'context'} eq 'paste')) ||
11463: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11464: if ($env{'request.course.id'} ne '') {
11465: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11466: if ($dir ne '') {
11467: my ($dirlistref,$listerror) =
11468: &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11469: if (ref($dirlistref) eq 'ARRAY') {
11470: foreach my $line (@{$dirlistref}) {
11471: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11472: $size,undef,$mtime)=split(/\&/,$line,12);
11473: unless (($testdir&$dirptr) ||
11474: ($file_name =~ /^\.\.?$/)) {
11475: $currfile{$file_name} = [$size,$mtime];
11476: }
11477: }
11478: }
11479: }
11480: }
11481: }
11482: # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
11483: # are not in subdirectories, using $currfile
11484: foreach my $file (keys(%dependencies)) {
11485: if (exists($currfile{$file})) {
11486: unless ($mapping{$file} eq $file) {
11487: $pathchanges{$file} = 1;
11488: }
11489: $existing{$file} = 1;
11490: $numexisting ++;
11491: } else {
11492: $newfiles{$file} = 1;
11493: }
11494: }
11495: foreach my $file (keys(%currfile)) {
11496: unless (($file eq $filename) ||
11497: ($file eq $filename.'.bak') ||
11498: ($dependencies{$file})) {
11499: if ($actionurl eq '/adm/dependencies') {
11500: unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
11501: next if (($rem ne '') &&
11502: (($env{"httpref.$rem".$file} ne '') ||
11503: (ref($navmap) &&
11504: (($navmap->getResourceByUrl($rem.$file) ne '') ||
11505: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11506: ($navmap->getResourceByUrl($rem.$1)))))));
11507: }
11508: }
11509: $unused{$file} = 1;
11510: }
11511: }
11512:
11513: # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
11514: if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11515: ($args->{'context'} eq 'paste')) {
11516: $counter = scalar(keys(%existing));
11517: $numpathchg = scalar(keys(%pathchanges));
11518: return ($output,$counter,$numpathchg,\%existing);
11519: } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
11520: (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
11521: $counter = scalar(keys(%existing));
11522: $numpathchg = scalar(keys(%pathchanges));
11523: return ($output,$counter,$numpathchg,\%existing,\%mapping);
11524: }
11525:
11526: # returns HTML otherwise, with dependency results and to ask for more uploads
11527:
11528: # $upload_output: missing dependencies (with upload form)
11529: # $modify_output: uploaded dependencies (in use)
11530: # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
11531: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
11532: if ($actionurl eq '/adm/dependencies') {
11533: next if ($embed_file =~ m{^\w+://});
11534: }
11535: $upload_output .= &start_data_table_row().
11536: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
11537: '<span class="LC_filename">'.$embed_file.'</span>';
11538: unless ($mapping{$embed_file} eq $embed_file) {
11539: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
11540: &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
11541: }
11542: $upload_output .= '</td>';
11543: if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) {
11544: $upload_output.='<td align="right">'.
11545: '<span class="LC_info LC_fontsize_medium">'.
11546: &mt("URL points to web address").'</span>';
11547: $numremref++;
11548: } elsif ($args->{'error_on_invalid_names'}
11549: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
11550: $upload_output.='<td align="right"><span class="LC_warning">'.
11551: &mt('Invalid characters').'</span>';
11552: $numinvalid++;
11553: } else {
11554: $upload_output .= '<td>'.
11555: &embedded_file_element('upload_embedded',$counter,
11556: $embed_file,\%mapping,
11557: $allfiles,$codebase,'upload');
11558: $counter ++;
11559: $numnew ++;
11560: }
11561: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
11562: }
11563: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
11564: if ($actionurl eq '/adm/dependencies') {
11565: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
11566: $modify_output .= &start_data_table_row().
11567: '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
11568: '<img src="'.&icon($embed_file).'" border="0" />'.
11569: ' <span class="LC_filename">'.$embed_file.'</span></a></td>'.
11570: '<td>'.$size.'</td>'.
11571: '<td>'.$mtime.'</td>'.
11572: '<td><label><input type="checkbox" name="mod_upload_dep" '.
11573: 'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
11574: $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11575: '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11576: &embedded_file_element('upload_embedded',$counter,
11577: $embed_file,\%mapping,
11578: $allfiles,$codebase,'modify').
11579: '</div></td>'.
11580: &end_data_table_row()."\n";
11581: $counter ++;
11582: } else {
11583: $upload_output .= &start_data_table_row().
11584: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
11585: '<span class="LC_filename">'.$embed_file.'</span></td>'.
11586: '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11587: &Apache::loncommon::end_data_table_row()."\n";
11588: }
11589: }
11590: my $delidx = $counter;
11591: foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11592: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11593: $delete_output .= &start_data_table_row().
11594: '<td><img src="'.&icon($oldfile).'" />'.
11595: ' <span class="LC_filename">'.$oldfile.'</span></td>'.
11596: '<td>'.$size.'</td>'.
11597: '<td>'.$mtime.'</td>'.
11598: '<td><label><input type="checkbox" name="del_upload_dep" '.
11599: ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11600: &embedded_file_element('upload_embedded',$delidx,
11601: $oldfile,\%mapping,$allfiles,
11602: $codebase,'delete').'</td>'.
11603: &end_data_table_row()."\n";
11604: $numunused ++;
11605: $delidx ++;
11606: }
11607: if ($upload_output) {
11608: $upload_output = &start_data_table().
11609: $upload_output.
11610: &end_data_table()."\n";
11611: }
11612: if ($modify_output) {
11613: $modify_output = &start_data_table().
11614: &start_data_table_header_row().
11615: '<th>'.&mt('File').'</th>'.
11616: '<th>'.&mt('Size (KB)').'</th>'.
11617: '<th>'.&mt('Modified').'</th>'.
11618: '<th>'.&mt('Upload replacement?').'</th>'.
11619: &end_data_table_header_row().
11620: $modify_output.
11621: &end_data_table()."\n";
11622: }
11623: if ($delete_output) {
11624: $delete_output = &start_data_table().
11625: &start_data_table_header_row().
11626: '<th>'.&mt('File').'</th>'.
11627: '<th>'.&mt('Size (KB)').'</th>'.
11628: '<th>'.&mt('Modified').'</th>'.
11629: '<th>'.&mt('Delete?').'</th>'.
11630: &end_data_table_header_row().
11631: $delete_output.
11632: &end_data_table()."\n";
11633: }
11634: my $applies = 0;
11635: if ($numremref) {
11636: $applies ++;
11637: }
11638: if ($numinvalid) {
11639: $applies ++;
11640: }
11641: if ($numexisting) {
11642: $applies ++;
11643: }
11644: if ($counter || $numunused) {
11645: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11646: ' method="post" enctype="multipart/form-data">'."\n".
11647: $state.'<h3>'.$heading.'</h3>';
11648: if ($actionurl eq '/adm/dependencies') {
11649: if ($numnew) {
11650: $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11651: '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11652: $upload_output.'<br />'."\n";
11653: }
11654: if ($numexisting) {
11655: $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11656: '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11657: $modify_output.'<br />'."\n";
11658: $buttontext = &mt('Save changes');
11659: }
11660: if ($numunused) {
11661: $output .= '<h4>'.&mt('Unused files').'</h4>'.
11662: '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11663: $delete_output.'<br />'."\n";
11664: $buttontext = &mt('Save changes');
11665: }
11666: } else {
11667: $output .= $upload_output.'<br />'."\n";
11668: }
11669: $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11670: $counter.'" />'."\n";
11671: if ($actionurl eq '/adm/dependencies') {
11672: $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11673: $numnew.'" />'."\n";
11674: } elsif ($actionurl eq '') {
11675: $output .= '<input type="hidden" name="phase" value="three" />';
11676: }
11677: } elsif ($applies) {
11678: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11679: if ($applies > 1) {
11680: $output .=
11681: &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11682: if ($numremref) {
11683: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11684: }
11685: if ($numinvalid) {
11686: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11687: }
11688: if ($numexisting) {
11689: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11690: }
11691: $output .= '</ul><br />';
11692: } elsif ($numremref) {
11693: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11694: } elsif ($numinvalid) {
11695: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11696: } elsif ($numexisting) {
11697: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11698: }
11699: $output .= $upload_output.'<br />';
11700: }
11701: my ($pathchange_output,$chgcount);
11702: $chgcount = $counter;
11703: if (keys(%pathchanges) > 0) {
11704: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11705: if ($counter) {
11706: $output .= &embedded_file_element('pathchange',$chgcount,
11707: $embed_file,\%mapping,
11708: $allfiles,$codebase,'change');
11709: } else {
11710: $pathchange_output .=
11711: &start_data_table_row().
11712: '<td><input type ="checkbox" name="namechange" value="'.
11713: $chgcount.'" checked="checked" /></td>'.
11714: '<td>'.$mapping{$embed_file}.'</td>'.
11715: '<td>'.$embed_file.
11716: &embedded_file_element('pathchange',$numpathchg,$embed_file,
11717: \%mapping,$allfiles,$codebase,'change').
11718: '</td>'.&end_data_table_row();
11719: }
11720: $numpathchg ++;
11721: $chgcount ++;
11722: }
11723: }
11724: if (($counter) || ($numunused)) {
11725: if ($numpathchg) {
11726: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11727: $numpathchg.'" />'."\n";
11728: }
11729: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11730: ($actionurl eq '/adm/imsimport')) {
11731: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11732: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11733: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11734: } elsif ($actionurl eq '/adm/dependencies') {
11735: $output .= '<input type="hidden" name="action" value="process_changes" />';
11736: }
11737: $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11738: } elsif ($numpathchg) {
11739: my %pathchange = ();
11740: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11741: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11742: $output .= '<p>'.&mt('or').'</p>';
11743: }
11744: }
11745: return ($output,$counter,$numpathchg);
11746: }
11747:
11748: =pod
11749:
11750: =item * clean_path($name)
11751:
11752: Performs clean-up of directories, subdirectories and filename in an
11753: embedded object, referenced in an HTML file which is being uploaded
11754: to a course or portfolio, where
11755: "Upload embedded images/multimedia files if HTML file" checkbox was
11756: checked.
11757:
11758: Clean-up is similar to replacements in lonnet::clean_filename()
11759: except each / between sub-directory and next level is preserved.
11760:
11761: =cut
11762:
11763: sub clean_path {
11764: my ($embed_file) = @_;
11765: $embed_file =~s{^/+}{};
11766: my @contents;
11767: if ($embed_file =~ m{/}) {
11768: @contents = split(/\//,$embed_file);
11769: } else {
11770: @contents = ($embed_file);
11771: }
11772: my $lastidx = scalar(@contents)-1;
11773: for (my $i=0; $i<=$lastidx; $i++) {
11774: $contents[$i]=~s{\\}{/}g;
11775: $contents[$i]=~s/\s+/\_/g;
11776: $contents[$i]=~s{[^/\w\.\-]}{}g;
11777: if ($i == $lastidx) {
11778: $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11779: }
11780: }
11781: if ($lastidx > 0) {
11782: return join('/',@contents);
11783: } else {
11784: return $contents[0];
11785: }
11786: }
11787:
11788: sub embedded_file_element {
11789: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11790: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11791: (ref($codebase) eq 'HASH'));
11792: my $output;
11793: if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11794: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11795: }
11796: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11797: &escape($embed_file).'" />';
11798: unless (($context eq 'upload_embedded') &&
11799: ($mapping->{$embed_file} eq $embed_file)) {
11800: $output .='
11801: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11802: }
11803: my $attrib;
11804: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11805: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11806: }
11807: $output .=
11808: "\n\t\t".
11809: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11810: $attrib.'" />';
11811: if (exists($codebase->{$mapping->{$embed_file}})) {
11812: $output .=
11813: "\n\t\t".
11814: '<input name="codebase_'.$num.'" type="hidden" value="'.
11815: &escape($codebase->{$mapping->{$embed_file}}).'" />';
11816: }
11817: return $output;
11818: }
11819:
11820: sub get_dependency_details {
11821: my ($currfile,$currsubfile,$embed_file) = @_;
11822: my ($size,$mtime,$showsize,$showmtime);
11823: if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11824: if ($embed_file =~ m{/}) {
11825: my ($path,$fname) = split(/\//,$embed_file);
11826: if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11827: ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11828: }
11829: } else {
11830: if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11831: ($size,$mtime) = @{$currfile->{$embed_file}};
11832: }
11833: }
11834: $showsize = $size/1024.0;
11835: $showsize = sprintf("%.1f",$showsize);
11836: if ($mtime > 0) {
11837: $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11838: }
11839: }
11840: return ($showsize,$showmtime);
11841: }
11842:
11843: sub ask_embedded_js {
11844: return <<"END";
11845: <script type="text/javascript"">
11846: // <![CDATA[
11847: function toggleBrowse(counter) {
11848: var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11849: var fileid = document.getElementById('embedded_item_'+counter);
11850: var uploaddivid = document.getElementById('moduploaddep_'+counter);
11851: if (chkboxid.checked == true) {
11852: uploaddivid.style.display='block';
11853: } else {
11854: uploaddivid.style.display='none';
11855: fileid.value = '';
11856: }
11857: }
11858: // ]]>
11859: </script>
11860:
11861: END
11862: }
11863:
11864: sub upload_embedded {
11865: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11866: $current_disk_usage,$hiddenstate,$actionurl) = @_;
11867: my (%pathchange,$output,$modifyform,$footer,$returnflag);
11868: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11869: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11870: my $orig_uploaded_filename =
11871: $env{'form.embedded_item_'.$i.'.filename'};
11872: foreach my $type ('orig','ref','attrib','codebase') {
11873: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11874: $env{'form.embedded_'.$type.'_'.$i} =
11875: &unescape($env{'form.embedded_'.$type.'_'.$i});
11876: }
11877: }
11878: my ($path,$fname) =
11879: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11880: # no path, whole string is fname
11881: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11882: $fname = &Apache::lonnet::clean_filename($fname);
11883: # See if there is anything left
11884: next if ($fname eq '');
11885:
11886: # Check if file already exists as a file or directory.
11887: my ($state,$msg);
11888: if ($context eq 'portfolio') {
11889: my $port_path = $dirpath;
11890: if ($group ne '') {
11891: $port_path = "groups/$group/$port_path";
11892: }
11893: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11894: $fname,$group,'embedded_item_'.$i,
11895: $dir_root,$port_path,$disk_quota,
11896: $current_disk_usage,$uname,$udom);
11897: if ($state eq 'will_exceed_quota'
11898: || $state eq 'file_locked') {
11899: $output .= $msg;
11900: next;
11901: }
11902: } elsif (($context eq 'author') || ($context eq 'testbank')) {
11903: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11904: if ($state eq 'exists') {
11905: $output .= $msg;
11906: next;
11907: }
11908: }
11909: # Check if extension is valid
11910: if (($fname =~ /\.(\w+)$/) &&
11911: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11912: $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11913: .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11914: next;
11915: } elsif (($fname =~ /\.(\w+)$/) &&
11916: (!defined(&Apache::loncommon::fileembstyle($1)))) {
11917: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11918: next;
11919: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11920: $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11921: next;
11922: }
11923: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11924: my $subdir = $path;
11925: $subdir =~ s{/+$}{};
11926: if ($context eq 'portfolio') {
11927: my $result;
11928: if ($state eq 'existingfile') {
11929: $result=
11930: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11931: $dirpath.$env{'form.currentpath'}.$subdir);
11932: } else {
11933: $result=
11934: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11935: $dirpath.
11936: $env{'form.currentpath'}.$subdir);
11937: if ($result !~ m|^/uploaded/|) {
11938: $output .= '<span class="LC_error">'
11939: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11940: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11941: .'</span><br />';
11942: next;
11943: } else {
11944: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11945: $path.$fname.'</span>').'<br />';
11946: }
11947: }
11948: } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11949: my $extendedsubdir = $dirpath.'/'.$subdir;
11950: $extendedsubdir =~ s{/+$}{};
11951: my $result =
11952: &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11953: if ($result !~ m|^/uploaded/|) {
11954: $output .= '<span class="LC_error">'
11955: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11956: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11957: .'</span><br />';
11958: next;
11959: } else {
11960: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11961: $path.$fname.'</span>').'<br />';
11962: if ($context eq 'syllabus') {
11963: &Apache::lonnet::make_public_indefinitely($result);
11964: }
11965: }
11966: } else {
11967: # Save the file
11968: my $target = $env{'form.embedded_item_'.$i};
11969: my $fullpath = $dir_root.$dirpath.'/'.$path;
11970: my $dest = $fullpath.$fname;
11971: my $url = $url_root.$dirpath.'/'.$path.$fname;
11972: my @parts=split(/\//,"$dirpath/$path");
11973: my $count;
11974: my $filepath = $dir_root;
11975: foreach my $subdir (@parts) {
11976: $filepath .= "/$subdir";
11977: if (!-e $filepath) {
11978: mkdir($filepath,0770);
11979: }
11980: }
11981: my $fh;
11982: if (!open($fh,'>'.$dest)) {
11983: &Apache::lonnet::logthis('Failed to create '.$dest);
11984: $output .= '<span class="LC_error">'.
11985: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11986: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11987: '</span><br />';
11988: } else {
11989: if (!print $fh $env{'form.embedded_item_'.$i}) {
11990: &Apache::lonnet::logthis('Failed to write to '.$dest);
11991: $output .= '<span class="LC_error">'.
11992: &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11993: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11994: '</span><br />';
11995: } else {
11996: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11997: $url.'</span>').'<br />';
11998: unless ($context eq 'testbank') {
11999: $footer .= &mt('View embedded file: [_1]',
12000: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
12001: }
12002: }
12003: close($fh);
12004: }
12005: }
12006: if ($env{'form.embedded_ref_'.$i}) {
12007: $pathchange{$i} = 1;
12008: }
12009: }
12010: if ($output) {
12011: $output = '<p>'.$output.'</p>';
12012: }
12013: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
12014: $returnflag = 'ok';
12015: my $numpathchgs = scalar(keys(%pathchange));
12016: if ($numpathchgs > 0) {
12017: if ($context eq 'portfolio') {
12018: $output .= '<p>'.&mt('or').'</p>';
12019: } elsif ($context eq 'testbank') {
12020: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
12021: '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
12022: $returnflag = 'modify_orightml';
12023: }
12024: }
12025: return ($output.$footer,$returnflag,$numpathchgs);
12026: }
12027:
12028: sub modify_html_form {
12029: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
12030: my $end = 0;
12031: my $modifyform;
12032: if ($context eq 'upload_embedded') {
12033: return unless (ref($pathchange) eq 'HASH');
12034: if ($env{'form.number_embedded_items'}) {
12035: $end += $env{'form.number_embedded_items'};
12036: }
12037: if ($env{'form.number_pathchange_items'}) {
12038: $end += $env{'form.number_pathchange_items'};
12039: }
12040: if ($end) {
12041: for (my $i=0; $i<$end; $i++) {
12042: if ($i < $env{'form.number_embedded_items'}) {
12043: next unless($pathchange->{$i});
12044: }
12045: $modifyform .=
12046: &start_data_table_row().
12047: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
12048: 'checked="checked" /></td>'.
12049: '<td>'.$env{'form.embedded_ref_'.$i}.
12050: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
12051: &escape($env{'form.embedded_ref_'.$i}).'" />'.
12052: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
12053: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
12054: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
12055: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
12056: '<td>'.$env{'form.embedded_orig_'.$i}.
12057: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
12058: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
12059: &end_data_table_row();
12060: }
12061: }
12062: } else {
12063: $modifyform = $pathchgtable;
12064: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12065: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
12066: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12067: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
12068: }
12069: }
12070: if ($modifyform) {
12071: if ($actionurl eq '/adm/dependencies') {
12072: $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
12073: }
12074: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
12075: '<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".
12076: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
12077: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
12078: '</ol></p>'."\n".'<p>'.
12079: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
12080: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
12081: &start_data_table()."\n".
12082: &start_data_table_header_row().
12083: '<th>'.&mt('Change?').'</th>'.
12084: '<th>'.&mt('Current reference').'</th>'.
12085: '<th>'.&mt('Required reference').'</th>'.
12086: &end_data_table_header_row()."\n".
12087: $modifyform.
12088: &end_data_table().'<br />'."\n".$hiddenstate.
12089: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
12090: '</form>'."\n";
12091: }
12092: return;
12093: }
12094:
12095: sub modify_html_refs {
12096: my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
12097: my $container;
12098: if ($context eq 'portfolio') {
12099: $container = $env{'form.container'};
12100: } elsif ($context eq 'coursedoc') {
12101: $container = $env{'form.primaryurl'};
12102: } elsif ($context eq 'manage_dependencies') {
12103: (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
12104: $container = "/$container";
12105: } elsif ($context eq 'syllabus') {
12106: $container = $url;
12107: } else {
12108: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
12109: }
12110: my (%allfiles,%codebase,$output,$content);
12111: my @changes = &get_env_multiple('form.namechange');
12112: unless ((@changes > 0) || ($context eq 'syllabus')) {
12113: if (wantarray) {
12114: return ('',0,0);
12115: } else {
12116: return;
12117: }
12118: }
12119: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
12120: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12121: unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
12122: if (wantarray) {
12123: return ('',0,0);
12124: } else {
12125: return;
12126: }
12127: }
12128: $content = &Apache::lonnet::getfile($container);
12129: if ($content eq '-1') {
12130: if (wantarray) {
12131: return ('',0,0);
12132: } else {
12133: return;
12134: }
12135: }
12136: } else {
12137: unless ($container =~ /^\Q$dir_root\E/) {
12138: if (wantarray) {
12139: return ('',0,0);
12140: } else {
12141: return;
12142: }
12143: }
12144: if (open(my $fh,"<$container")) {
12145: $content = join('', <$fh>);
12146: close($fh);
12147: } else {
12148: if (wantarray) {
12149: return ('',0,0);
12150: } else {
12151: return;
12152: }
12153: }
12154: }
12155: my ($count,$codebasecount) = (0,0);
12156: my $mm = new File::MMagic;
12157: my $mime_type = $mm->checktype_contents($content);
12158: if ($mime_type eq 'text/html') {
12159: my $parse_result =
12160: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
12161: \%codebase,\$content);
12162: if ($parse_result eq 'ok') {
12163: foreach my $i (@changes) {
12164: my $orig = &unescape($env{'form.embedded_orig_'.$i});
12165: my $ref = &unescape($env{'form.embedded_ref_'.$i});
12166: if ($allfiles{$ref}) {
12167: my $newname = $orig;
12168: my ($attrib_regexp,$codebase);
12169: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
12170: if ($attrib_regexp =~ /:/) {
12171: $attrib_regexp =~ s/\:/|/g;
12172: }
12173: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12174: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12175: $count += $numchg;
12176: $allfiles{$newname} = $allfiles{$ref};
12177: delete($allfiles{$ref});
12178: }
12179: if ($env{'form.embedded_codebase_'.$i} ne '') {
12180: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
12181: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
12182: $codebasecount ++;
12183: }
12184: }
12185: }
12186: my $skiprewrites;
12187: if ($count || $codebasecount) {
12188: my $saveresult;
12189: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
12190: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12191: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12192: if ($url eq $container) {
12193: my ($fname) = ($container =~ m{/([^/]+)$});
12194: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12195: $count,'<span class="LC_filename">'.
12196: $fname.'</span>').'</p>';
12197: } else {
12198: $output = '<p class="LC_error">'.
12199: &mt('Error: update failed for: [_1].',
12200: '<span class="LC_filename">'.
12201: $container.'</span>').'</p>';
12202: }
12203: if ($context eq 'syllabus') {
12204: unless ($saveresult eq 'ok') {
12205: $skiprewrites = 1;
12206: }
12207: }
12208: } else {
12209: if (open(my $fh,">$container")) {
12210: print $fh $content;
12211: close($fh);
12212: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12213: $count,'<span class="LC_filename">'.
12214: $container.'</span>').'</p>';
12215: } else {
12216: $output = '<p class="LC_error">'.
12217: &mt('Error: could not update [_1].',
12218: '<span class="LC_filename">'.
12219: $container.'</span>').'</p>';
12220: }
12221: }
12222: }
12223: if (($context eq 'syllabus') && (!$skiprewrites)) {
12224: my ($actionurl,$state);
12225: $actionurl = "/public/$udom/$uname/syllabus";
12226: my ($ignore,$num,$numpathchanges,$existing,$mapping) =
12227: &ask_for_embedded_content($actionurl,$state,\%allfiles,
12228: \%codebase,
12229: {'context' => 'rewrites',
12230: 'ignore_remote_references' => 1,});
12231: if (ref($mapping) eq 'HASH') {
12232: my $rewrites = 0;
12233: foreach my $key (keys(%{$mapping})) {
12234: next if ($key =~ m{^https?://});
12235: my $ref = $mapping->{$key};
12236: my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
12237: my $attrib;
12238: if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
12239: $attrib = join('|',@{$allfiles{$mapping->{$key}}});
12240: }
12241: if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12242: my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12243: $rewrites += $numchg;
12244: }
12245: }
12246: if ($rewrites) {
12247: my $saveresult;
12248: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12249: if ($url eq $container) {
12250: my ($fname) = ($container =~ m{/([^/]+)$});
12251: $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
12252: $count,'<span class="LC_filename">'.
12253: $fname.'</span>').'</p>';
12254: } else {
12255: $output .= '<p class="LC_error">'.
12256: &mt('Error: could not update links in [_1].',
12257: '<span class="LC_filename">'.
12258: $container.'</span>').'</p>';
12259:
12260: }
12261: }
12262: }
12263: }
12264: } else {
12265: &logthis('Failed to parse '.$container.
12266: ' to modify references: '.$parse_result);
12267: }
12268: }
12269: if (wantarray) {
12270: return ($output,$count,$codebasecount);
12271: } else {
12272: return $output;
12273: }
12274: }
12275:
12276: sub check_for_existing {
12277: my ($path,$fname,$element) = @_;
12278: my ($state,$msg);
12279: if (-d $path.'/'.$fname) {
12280: $state = 'exists';
12281: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12282: } elsif (-e $path.'/'.$fname) {
12283: $state = 'exists';
12284: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12285: }
12286: if ($state eq 'exists') {
12287: $msg = '<span class="LC_error">'.$msg.'</span><br />';
12288: }
12289: return ($state,$msg);
12290: }
12291:
12292: sub check_for_upload {
12293: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
12294: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
12295: my $filesize = length($env{'form.'.$element});
12296: if (!$filesize) {
12297: my $msg = '<span class="LC_error">'.
12298: &mt('Unable to upload [_1]. (size = [_2] bytes)',
12299: '<span class="LC_filename">'.$fname.'</span>',
12300: $filesize).'<br />'.
12301: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
12302: '</span>';
12303: return ('zero_bytes',$msg);
12304: }
12305: $filesize = $filesize/1000; #express in k (1024?)
12306: my $getpropath = 1;
12307: my ($dirlistref,$listerror) =
12308: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
12309: my $found_file = 0;
12310: my $locked_file = 0;
12311: my @lockers;
12312: my $navmap;
12313: if ($env{'request.course.id'}) {
12314: $navmap = Apache::lonnavmaps::navmap->new();
12315: }
12316: if (ref($dirlistref) eq 'ARRAY') {
12317: foreach my $line (@{$dirlistref}) {
12318: my ($file_name,$rest)=split(/\&/,$line,2);
12319: if ($file_name eq $fname){
12320: $file_name = $path.$file_name;
12321: if ($group ne '') {
12322: $file_name = $group.$file_name;
12323: }
12324: $found_file = 1;
12325: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
12326: foreach my $lock (@lockers) {
12327: if (ref($lock) eq 'ARRAY') {
12328: my ($symb,$crsid) = @{$lock};
12329: if ($crsid eq $env{'request.course.id'}) {
12330: if (ref($navmap)) {
12331: my $res = $navmap->getBySymb($symb);
12332: foreach my $part (@{$res->parts()}) {
12333: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
12334: unless (($slot_status == $res->RESERVED) ||
12335: ($slot_status == $res->RESERVED_LOCATION)) {
12336: $locked_file = 1;
12337: }
12338: }
12339: } else {
12340: $locked_file = 1;
12341: }
12342: } else {
12343: $locked_file = 1;
12344: }
12345: }
12346: }
12347: } else {
12348: my @info = split(/\&/,$rest);
12349: my $currsize = $info[6]/1000;
12350: if ($currsize < $filesize) {
12351: my $extra = $filesize - $currsize;
12352: if (($current_disk_usage + $extra) > $disk_quota) {
12353: my $msg = '<p class="LC_warning">'.
12354: &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.',
12355: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
12356: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
12357: $disk_quota,$current_disk_usage).'</p>';
12358: return ('will_exceed_quota',$msg);
12359: }
12360: }
12361: }
12362: }
12363: }
12364: }
12365: if (($current_disk_usage + $filesize) > $disk_quota){
12366: my $msg = '<p class="LC_warning">'.
12367: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
12368: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
12369: return ('will_exceed_quota',$msg);
12370: } elsif ($found_file) {
12371: if ($locked_file) {
12372: my $msg = '<p class="LC_warning">';
12373: $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>');
12374: $msg .= '</p>';
12375: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
12376: return ('file_locked',$msg);
12377: } else {
12378: my $msg = '<p class="LC_error">';
12379: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
12380: $msg .= '</p>';
12381: return ('existingfile',$msg);
12382: }
12383: }
12384: }
12385:
12386: sub check_for_traversal {
12387: my ($path,$url,$toplevel) = @_;
12388: my @parts=split(/\//,$path);
12389: my $cleanpath;
12390: my $fullpath = $url;
12391: for (my $i=0;$i<@parts;$i++) {
12392: next if ($parts[$i] eq '.');
12393: if ($parts[$i] eq '..') {
12394: $fullpath =~ s{([^/]+/)$}{};
12395: } else {
12396: $fullpath .= $parts[$i].'/';
12397: }
12398: }
12399: if ($fullpath =~ /^\Q$url\E(.*)$/) {
12400: $cleanpath = $1;
12401: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
12402: my $curr_toprel = $1;
12403: my @parts = split(/\//,$curr_toprel);
12404: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
12405: my @urlparts = split(/\//,$url_toprel);
12406: my $doubledots;
12407: my $startdiff = -1;
12408: for (my $i=0; $i<@urlparts; $i++) {
12409: if ($startdiff == -1) {
12410: unless ($urlparts[$i] eq $parts[$i]) {
12411: $startdiff = $i;
12412: $doubledots .= '../';
12413: }
12414: } else {
12415: $doubledots .= '../';
12416: }
12417: }
12418: if ($startdiff > -1) {
12419: $cleanpath = $doubledots;
12420: for (my $i=$startdiff; $i<@parts; $i++) {
12421: $cleanpath .= $parts[$i].'/';
12422: }
12423: }
12424: }
12425: $cleanpath =~ s{(/)$}{};
12426: return $cleanpath;
12427: }
12428:
12429: sub is_archive_file {
12430: my ($mimetype) = @_;
12431: if (($mimetype eq 'application/octet-stream') ||
12432: ($mimetype eq 'application/x-stuffit') ||
12433: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
12434: return 1;
12435: }
12436: return;
12437: }
12438:
12439: sub decompress_form {
12440: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
12441: my %lt = &Apache::lonlocal::texthash (
12442: this => 'This file is an archive file.',
12443: camt => 'This file is a Camtasia archive file.',
12444: itsc => 'Its contents are as follows:',
12445: youm => 'You may wish to extract its contents.',
12446: extr => 'Extract contents',
12447: auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
12448: proa => 'Process automatically?',
12449: yes => 'Yes',
12450: no => 'No',
12451: fold => 'Title for folder containing movie',
12452: movi => 'Title for page containing embedded movie',
12453: );
12454: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
12455: my ($is_camtasia,$topdir,%toplevel,@paths);
12456: my $info = &list_archive_contents($fileloc,\@paths);
12457: if (@paths) {
12458: foreach my $path (@paths) {
12459: $path =~ s{^/}{};
12460: if ($path =~ m{^([^/]+)/$}) {
12461: $topdir = $1;
12462: }
12463: if ($path =~ m{^([^/]+)/}) {
12464: $toplevel{$1} = $path;
12465: } else {
12466: $toplevel{$path} = $path;
12467: }
12468: }
12469: }
12470: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12471: my @camtasia6 = ("$topdir/","$topdir/index.html",
12472: "$topdir/media/",
12473: "$topdir/media/$topdir.mp4",
12474: "$topdir/media/FirstFrame.png",
12475: "$topdir/media/player.swf",
12476: "$topdir/media/swfobject.js",
12477: "$topdir/media/expressInstall.swf");
12478: my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12479: "$topdir/$topdir.mp4",
12480: "$topdir/$topdir\_config.xml",
12481: "$topdir/$topdir\_controller.swf",
12482: "$topdir/$topdir\_embed.css",
12483: "$topdir/$topdir\_First_Frame.png",
12484: "$topdir/$topdir\_player.html",
12485: "$topdir/$topdir\_Thumbnails.png",
12486: "$topdir/playerProductInstall.swf",
12487: "$topdir/scripts/",
12488: "$topdir/scripts/config_xml.js",
12489: "$topdir/scripts/handlebars.js",
12490: "$topdir/scripts/jquery-1.7.1.min.js",
12491: "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12492: "$topdir/scripts/modernizr.js",
12493: "$topdir/scripts/player-min.js",
12494: "$topdir/scripts/swfobject.js",
12495: "$topdir/skins/",
12496: "$topdir/skins/configuration_express.xml",
12497: "$topdir/skins/express_show/",
12498: "$topdir/skins/express_show/player-min.css",
12499: "$topdir/skins/express_show/spritesheet.png");
12500: my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
12501: "$topdir/$topdir.mp4",
12502: "$topdir/$topdir\_config.xml",
12503: "$topdir/$topdir\_controller.swf",
12504: "$topdir/$topdir\_embed.css",
12505: "$topdir/$topdir\_First_Frame.png",
12506: "$topdir/$topdir\_player.html",
12507: "$topdir/$topdir\_Thumbnails.png",
12508: "$topdir/playerProductInstall.swf",
12509: "$topdir/scripts/",
12510: "$topdir/scripts/config_xml.js",
12511: "$topdir/scripts/techsmith-smart-player.min.js",
12512: "$topdir/skins/",
12513: "$topdir/skins/configuration_express.xml",
12514: "$topdir/skins/express_show/",
12515: "$topdir/skins/express_show/spritesheet.min.css",
12516: "$topdir/skins/express_show/spritesheet.png",
12517: "$topdir/skins/express_show/techsmith-smart-player.min.css");
12518: my @diffs = &compare_arrays(\@paths,\@camtasia6);
12519: if (@diffs == 0) {
12520: $is_camtasia = 6;
12521: } else {
12522: @diffs = &compare_arrays(\@paths,\@camtasia8_1);
12523: if (@diffs == 0) {
12524: $is_camtasia = 8;
12525: } else {
12526: @diffs = &compare_arrays(\@paths,\@camtasia8_4);
12527: if (@diffs == 0) {
12528: $is_camtasia = 8;
12529: }
12530: }
12531: }
12532: }
12533: my $output;
12534: if ($is_camtasia) {
12535: $output = <<"ENDCAM";
12536: <script type="text/javascript" language="Javascript">
12537: // <![CDATA[
12538:
12539: function camtasiaToggle() {
12540: for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
12541: if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
12542: if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
12543: document.getElementById('camtasia_titles').style.display='block';
12544: } else {
12545: document.getElementById('camtasia_titles').style.display='none';
12546: }
12547: }
12548: }
12549: return;
12550: }
12551:
12552: // ]]>
12553: </script>
12554: <p>$lt{'camt'}</p>
12555: ENDCAM
12556: } else {
12557: $output = '<p>'.$lt{'this'};
12558: if ($info eq '') {
12559: $output .= ' '.$lt{'youm'}.'</p>'."\n";
12560: } else {
12561: $output .= ' '.$lt{'itsc'}.'</p>'."\n".
12562: '<div><pre>'.$info.'</pre></div>';
12563: }
12564: }
12565: $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
12566: my $duplicates;
12567: my $num = 0;
12568: if (ref($dirlist) eq 'ARRAY') {
12569: foreach my $item (@{$dirlist}) {
12570: if (ref($item) eq 'ARRAY') {
12571: if (exists($toplevel{$item->[0]})) {
12572: $duplicates .=
12573: &start_data_table_row().
12574: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12575: 'value="0" checked="checked" />'.&mt('No').'</label>'.
12576: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '.
12577: 'value="1" />'.&mt('Yes').'</label>'.
12578: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12579: '<td>'.$item->[0].'</td>';
12580: if ($item->[2]) {
12581: $duplicates .= '<td>'.&mt('Directory').'</td>';
12582: } else {
12583: $duplicates .= '<td>'.&mt('File').'</td>';
12584: }
12585: $duplicates .= '<td>'.$item->[3].'</td>'.
12586: '<td>'.
12587: &Apache::lonlocal::locallocaltime($item->[4]).
12588: '</td>'.
12589: &end_data_table_row();
12590: $num ++;
12591: }
12592: }
12593: }
12594: }
12595: my $itemcount;
12596: if (@paths > 0) {
12597: $itemcount = scalar(@paths);
12598: } else {
12599: $itemcount = 1;
12600: }
12601: if ($is_camtasia) {
12602: $output .= $lt{'auto'}.'<br />'.
12603: '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12604: '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12605: $lt{'yes'}.'</label> <label>'.
12606: '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12607: $lt{'no'}.'</label></span><br />'.
12608: '<div id="camtasia_titles" style="display:block">'.
12609: &Apache::lonhtmlcommon::start_pick_box().
12610: &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12611: '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12612: &Apache::lonhtmlcommon::row_closure().
12613: &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12614: '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12615: &Apache::lonhtmlcommon::row_closure(1).
12616: &Apache::lonhtmlcommon::end_pick_box().
12617: '</div>';
12618: }
12619: $output .=
12620: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12621: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12622: "\n";
12623: if ($duplicates ne '') {
12624: $output .= '<p><span class="LC_warning">'.
12625: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.
12626: &start_data_table().
12627: &start_data_table_header_row().
12628: '<th>'.&mt('Overwrite?').'</th>'.
12629: '<th>'.&mt('Name').'</th>'.
12630: '<th>'.&mt('Type').'</th>'.
12631: '<th>'.&mt('Size').'</th>'.
12632: '<th>'.&mt('Last modified').'</th>'.
12633: &end_data_table_header_row().
12634: $duplicates.
12635: &end_data_table().
12636: '</p>';
12637: }
12638: $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12639: if (ref($hiddenelements) eq 'HASH') {
12640: foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12641: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12642: }
12643: }
12644: $output .= <<"END";
12645: <br />
12646: <input type="submit" name="decompress" value="$lt{'extr'}" />
12647: </form>
12648: $noextract
12649: END
12650: return $output;
12651: }
12652:
12653: sub decompression_utility {
12654: my ($program) = @_;
12655: my @utilities = ('tar','gunzip','bunzip2','unzip');
12656: my $location;
12657: if (grep(/^\Q$program\E$/,@utilities)) {
12658: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12659: '/usr/sbin/') {
12660: if (-x $dir.$program) {
12661: $location = $dir.$program;
12662: last;
12663: }
12664: }
12665: }
12666: return $location;
12667: }
12668:
12669: sub list_archive_contents {
12670: my ($file,$pathsref) = @_;
12671: my (@cmd,$output);
12672: my $needsregexp;
12673: if ($file =~ /\.zip$/) {
12674: @cmd = (&decompression_utility('unzip'),"-l");
12675: $needsregexp = 1;
12676: } elsif (($file =~ m/\.tar\.gz$/) ||
12677: ($file =~ /\.tgz$/)) {
12678: @cmd = (&decompression_utility('tar'),"-ztf");
12679: } elsif ($file =~ /\.tar\.bz2$/) {
12680: @cmd = (&decompression_utility('tar'),"-jtf");
12681: } elsif ($file =~ m|\.tar$|) {
12682: @cmd = (&decompression_utility('tar'),"-tf");
12683: }
12684: if (@cmd) {
12685: undef($!);
12686: undef($@);
12687: if (open(my $fh,"-|", @cmd, $file)) {
12688: while (my $line = <$fh>) {
12689: $output .= $line;
12690: chomp($line);
12691: my $item;
12692: if ($needsregexp) {
12693: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/);
12694: } else {
12695: $item = $line;
12696: }
12697: if ($item ne '') {
12698: unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12699: push(@{$pathsref},$item);
12700: }
12701: }
12702: }
12703: close($fh);
12704: }
12705: }
12706: return $output;
12707: }
12708:
12709: sub decompress_uploaded_file {
12710: my ($file,$dir) = @_;
12711: &Apache::lonnet::appenv({'cgi.file' => $file});
12712: &Apache::lonnet::appenv({'cgi.dir' => $dir});
12713: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12714: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12715: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12716: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12717: my $decompressed = $env{'cgi.decompressed'};
12718: &Apache::lonnet::delenv('cgi.file');
12719: &Apache::lonnet::delenv('cgi.dir');
12720: &Apache::lonnet::delenv('cgi.decompressed');
12721: return ($decompressed,$result);
12722: }
12723:
12724: sub process_decompression {
12725: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12726: unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
12727: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12728: &mt('Unexpected file path.').'</p>'."\n";
12729: }
12730: unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
12731: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12732: &mt('Unexpected course context.').'</p>'."\n";
12733: }
12734: unless ($file eq &Apache::lonnet::clean_filename($file)) {
12735: return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12736: &mt('Filename contained unexpected characters.').'</p>'."\n";
12737: }
12738: my ($dir,$error,$warning,$output);
12739: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12740: $error = &mt('Filename not a supported archive file type.').
12741: '<br />'.&mt('Filename should end with one of: [_1].',
12742: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12743: } else {
12744: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12745: if ($docuhome eq 'no_host') {
12746: $error = &mt('Could not determine home server for course.');
12747: } else {
12748: my @ids=&Apache::lonnet::current_machine_ids();
12749: my $currdir = "$dir_root/$destination";
12750: if (grep(/^\Q$docuhome\E$/,@ids)) {
12751: $dir = &LONCAPA::propath($docudom,$docuname).
12752: "$dir_root/$destination";
12753: } else {
12754: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12755: "$dir_root/$docudom/$docuname/$destination";
12756: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12757: $error = &mt('Archive file not found.');
12758: }
12759: }
12760: my (@to_overwrite,@to_skip);
12761: if ($env{'form.archive_overwrite_total'} > 0) {
12762: my $total = $env{'form.archive_overwrite_total'};
12763: for (my $i=0; $i<$total; $i++) {
12764: if ($env{'form.archive_overwrite_'.$i} == 1) {
12765: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12766: } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12767: push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12768: }
12769: }
12770: }
12771: my $numskip = scalar(@to_skip);
12772: my $numoverwrite = scalar(@to_overwrite);
12773: if (($numskip) && (!$numoverwrite)) {
12774: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');
12775: } elsif ($dir eq '') {
12776: $error = &mt('Directory containing archive file unavailable.');
12777: } elsif (!$error) {
12778: my ($decompressed,$display);
12779: if (($numskip) || ($numoverwrite)) {
12780: my $tempdir = time.'_'.$$.int(rand(10000));
12781: mkdir("$dir/$tempdir",0755);
12782: if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
12783: ($decompressed,$display) =
12784: &decompress_uploaded_file($file,"$dir/$tempdir");
12785: foreach my $item (@to_skip) {
12786: if (($item ne '') && ($item !~ /\.\./)) {
12787: if (-f "$dir/$tempdir/$item") {
12788: unlink("$dir/$tempdir/$item");
12789: } elsif (-d "$dir/$tempdir/$item") {
12790: &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
12791: }
12792: }
12793: }
12794: foreach my $item (@to_overwrite) {
12795: if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
12796: if (($item ne '') && ($item !~ /\.\./)) {
12797: if (-f "$dir/$item") {
12798: unlink("$dir/$item");
12799: } elsif (-d "$dir/$item") {
12800: &File::Path::remove_tree("$dir/$item",{ safe => 1 });
12801: }
12802: &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
12803: }
12804: }
12805: }
12806: if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
12807: &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
12808: }
12809: }
12810: } else {
12811: ($decompressed,$display) =
12812: &decompress_uploaded_file($file,$dir);
12813: }
12814: if ($decompressed eq 'ok') {
12815: $output = '<p class="LC_info">'.
12816: &mt('Files extracted successfully from archive.').
12817: '</p>'."\n";
12818: my ($warning,$result,@contents);
12819: my ($newdirlistref,$newlisterror) =
12820: &Apache::lonnet::dirlist($currdir,$docudom,
12821: $docuname,1);
12822: my (%is_dir,%changes,@newitems);
12823: my $dirptr = 16384;
12824: if (ref($newdirlistref) eq 'ARRAY') {
12825: foreach my $dir_line (@{$newdirlistref}) {
12826: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12827: unless (($item =~ /^\.+$/) || ($item eq $file)) {
12828: push(@newitems,$item);
12829: if ($dirptr&$testdir) {
12830: $is_dir{$item} = 1;
12831: }
12832: $changes{$item} = 1;
12833: }
12834: }
12835: }
12836: if (keys(%changes) > 0) {
12837: foreach my $item (sort(@newitems)) {
12838: if ($changes{$item}) {
12839: push(@contents,$item);
12840: }
12841: }
12842: }
12843: if (@contents > 0) {
12844: my $wantform;
12845: unless ($env{'form.autoextract_camtasia'}) {
12846: $wantform = 1;
12847: }
12848: my (%children,%parent,%dirorder,%titles);
12849: my ($count,$datatable) = &get_extracted($docudom,$docuname,
12850: $currdir,\%is_dir,
12851: \%children,\%parent,
12852: \@contents,\%dirorder,
12853: \%titles,$wantform);
12854: if ($datatable ne '') {
12855: $output .= &archive_options_form('decompressed',$datatable,
12856: $count,$hiddenelem);
12857: my $startcount = 6;
12858: $output .= &archive_javascript($startcount,$count,
12859: \%titles,\%children);
12860: }
12861: if ($env{'form.autoextract_camtasia'}) {
12862: my $version = $env{'form.autoextract_camtasia'};
12863: my %displayed;
12864: my $total = 1;
12865: $env{'form.archive_directory'} = [];
12866: foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12867: my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12868: $path =~ s{/$}{};
12869: my $item;
12870: if ($path ne '') {
12871: $item = "$path/$titles{$i}";
12872: } else {
12873: $item = $titles{$i};
12874: }
12875: $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12876: if ($item eq $contents[0]) {
12877: push(@{$env{'form.archive_directory'}},$i);
12878: $env{'form.archive_'.$i} = 'display';
12879: $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12880: $displayed{'folder'} = $i;
12881: } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12882: (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
12883: $env{'form.archive_'.$i} = 'display';
12884: $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12885: $displayed{'web'} = $i;
12886: } else {
12887: if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12888: ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12889: ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12890: push(@{$env{'form.archive_directory'}},$i);
12891: }
12892: $env{'form.archive_'.$i} = 'dependency';
12893: }
12894: $total ++;
12895: }
12896: for (my $i=1; $i<$total; $i++) {
12897: next if ($i == $displayed{'web'});
12898: next if ($i == $displayed{'folder'});
12899: $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12900: }
12901: $env{'form.phase'} = 'decompress_cleanup';
12902: $env{'form.archivedelete'} = 1;
12903: $env{'form.archive_count'} = $total-1;
12904: $output .=
12905: &process_extracted_files('coursedocs',$docudom,
12906: $docuname,$destination,
12907: $dir_root,$hiddenelem);
12908: }
12909: } else {
12910: $warning = &mt('No new items extracted from archive file.');
12911: }
12912: } else {
12913: $output = $display;
12914: $error = &mt('An error occurred during extraction from the archive file.');
12915: }
12916: }
12917: }
12918: }
12919: if ($error) {
12920: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12921: $error.'</p>'."\n";
12922: }
12923: if ($warning) {
12924: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12925: }
12926: return $output;
12927: }
12928:
12929: sub get_extracted {
12930: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12931: $titles,$wantform) = @_;
12932: my $count = 0;
12933: my $depth = 0;
12934: my $datatable;
12935: my @hierarchy;
12936: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12937: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12938: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12939: foreach my $item (@{$contents}) {
12940: $count ++;
12941: @{$dirorder->{$count}} = @hierarchy;
12942: $titles->{$count} = $item;
12943: &archive_hierarchy($depth,$count,$parent,$children);
12944: if ($wantform) {
12945: $datatable .= &archive_row($is_dir->{$item},$item,
12946: $currdir,$depth,$count);
12947: }
12948: if ($is_dir->{$item}) {
12949: $depth ++;
12950: push(@hierarchy,$count);
12951: $parent->{$depth} = $count;
12952: $datatable .=
12953: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12954: \$depth,\$count,\@hierarchy,$dirorder,
12955: $children,$parent,$titles,$wantform);
12956: $depth --;
12957: pop(@hierarchy);
12958: }
12959: }
12960: return ($count,$datatable);
12961: }
12962:
12963: sub recurse_extracted_archive {
12964: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12965: $children,$parent,$titles,$wantform) = @_;
12966: my $result='';
12967: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12968: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12969: (ref($dirorder) eq 'HASH')) {
12970: return $result;
12971: }
12972: my $dirptr = 16384;
12973: my ($newdirlistref,$newlisterror) =
12974: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12975: if (ref($newdirlistref) eq 'ARRAY') {
12976: foreach my $dir_line (@{$newdirlistref}) {
12977: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12978: unless ($item =~ /^\.+$/) {
12979: $$count ++;
12980: @{$dirorder->{$$count}} = @{$hierarchy};
12981: $titles->{$$count} = $item;
12982: &archive_hierarchy($$depth,$$count,$parent,$children);
12983:
12984: my $is_dir;
12985: if ($dirptr&$testdir) {
12986: $is_dir = 1;
12987: }
12988: if ($wantform) {
12989: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12990: }
12991: if ($is_dir) {
12992: $$depth ++;
12993: push(@{$hierarchy},$$count);
12994: $parent->{$$depth} = $$count;
12995: $result .=
12996: &recurse_extracted_archive("$currdir/$item",$docudom,
12997: $docuname,$depth,$count,
12998: $hierarchy,$dirorder,$children,
12999: $parent,$titles,$wantform);
13000: $$depth --;
13001: pop(@{$hierarchy});
13002: }
13003: }
13004: }
13005: }
13006: return $result;
13007: }
13008:
13009: sub archive_hierarchy {
13010: my ($depth,$count,$parent,$children) =@_;
13011: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
13012: if (exists($parent->{$depth})) {
13013: $children->{$parent->{$depth}} .= $count.':';
13014: }
13015: }
13016: return;
13017: }
13018:
13019: sub archive_row {
13020: my ($is_dir,$item,$currdir,$depth,$count) = @_;
13021: my ($name) = ($item =~ m{([^/]+)$});
13022: my %choices = &Apache::lonlocal::texthash (
13023: 'display' => 'Add as file',
13024: 'dependency' => 'Include as dependency',
13025: 'discard' => 'Discard',
13026: );
13027: if ($is_dir) {
13028: $choices{'display'} = &mt('Add as folder');
13029: }
13030: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
13031: my $offset = 0;
13032: foreach my $action ('display','dependency','discard') {
13033: $offset ++;
13034: if ($action ne 'display') {
13035: $offset ++;
13036: }
13037: $output .= '<td><span class="LC_nobreak">'.
13038: '<label><input type="radio" name="archive_'.$count.
13039: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
13040: my $text = $choices{$action};
13041: if ($is_dir) {
13042: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
13043: if ($action eq 'display') {
13044: $text = &mt('Add as folder');
13045: }
13046: } else {
13047: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
13048:
13049: }
13050: $output .= ' /> '.$choices{$action}.'</label></span>';
13051: if ($action eq 'dependency') {
13052: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
13053: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '.
13054: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
13055: '<option value=""></option>'."\n".
13056: '</select>'."\n".
13057: '</div>';
13058: } elsif ($action eq 'display') {
13059: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
13060: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
13061: '</div>';
13062: }
13063: $output .= '</td>';
13064: }
13065: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
13066: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2);
13067: for (my $i=0; $i<$depth; $i++) {
13068: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
13069: }
13070: if ($is_dir) {
13071: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n".
13072: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
13073: } else {
13074: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
13075: }
13076: $output .= ' '.$name.'</td>'."\n".
13077: &end_data_table_row();
13078: return $output;
13079: }
13080:
13081: sub archive_options_form {
13082: my ($form,$display,$count,$hiddenelem) = @_;
13083: my %lt = &Apache::lonlocal::texthash(
13084: perm => 'Permanently remove archive file?',
13085: hows => 'How should each extracted item be incorporated in the course?',
13086: cont => 'Content actions for all',
13087: addf => 'Add as folder/file',
13088: incd => 'Include as dependency for a displayed file',
13089: disc => 'Discard',
13090: no => 'No',
13091: yes => 'Yes',
13092: save => 'Save',
13093: );
13094: my $output = <<"END";
13095: <form name="$form" method="post" action="">
13096: <p><span class="LC_nobreak">$lt{'perm'}
13097: <label>
13098: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
13099: </label>
13100:
13101: <label>
13102: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
13103: </span>
13104: </p>
13105: <input type="hidden" name="phase" value="decompress_cleanup" />
13106: <br />$lt{'hows'}
13107: <div class="LC_columnSection">
13108: <fieldset>
13109: <legend>$lt{'cont'}</legend>
13110: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" />
13111: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
13112: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
13113: </fieldset>
13114: </div>
13115: END
13116: return $output.
13117: &start_data_table()."\n".
13118: $display."\n".
13119: &end_data_table()."\n".
13120: '<input type="hidden" name="archive_count" value="'.$count.'" />'.
13121: $hiddenelem.
13122: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
13123: '</form>';
13124: }
13125:
13126: sub archive_javascript {
13127: my ($startcount,$numitems,$titles,$children) = @_;
13128: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
13129: my $maintitle = $env{'form.comment'};
13130: my $scripttag = <<START;
13131: <script type="text/javascript">
13132: // <![CDATA[
13133:
13134: function checkAll(form,prefix) {
13135: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$");
13136: for (var i=0; i < form.elements.length; i++) {
13137: var id = form.elements[i].id;
13138: if ((id != '') && (id != undefined)) {
13139: if (idstr.test(id)) {
13140: if (form.elements[i].type == 'radio') {
13141: form.elements[i].checked = true;
13142: var nostart = i-$startcount;
13143: var offset = nostart%7;
13144: var count = (nostart-offset)/7;
13145: dependencyCheck(form,count,offset);
13146: }
13147: }
13148: }
13149: }
13150: }
13151:
13152: function propagateCheck(form,count) {
13153: if (count > 0) {
13154: var startelement = $startcount + ((count-1) * 7);
13155: for (var j=1; j<6; j++) {
13156: if ((j != 2) && (j != 4)) {
13157: var item = startelement + j;
13158: if (form.elements[item].type == 'radio') {
13159: if (form.elements[item].checked) {
13160: containerCheck(form,count,j);
13161: break;
13162: }
13163: }
13164: }
13165: }
13166: }
13167: }
13168:
13169: numitems = $numitems
13170: var titles = new Array(numitems);
13171: var parents = new Array(numitems);
13172: for (var i=0; i<numitems; i++) {
13173: parents[i] = new Array;
13174: }
13175: var maintitle = '$maintitle';
13176:
13177: START
13178:
13179: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
13180: my @contents = split(/:/,$children->{$container});
13181: for (my $i=0; $i<@contents; $i ++) {
13182: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
13183: }
13184: }
13185:
13186: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
13187: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
13188: }
13189:
13190: $scripttag .= <<END;
13191:
13192: function containerCheck(form,count,offset) {
13193: if (count > 0) {
13194: dependencyCheck(form,count,offset);
13195: var item = (offset+$startcount)+7*(count-1);
13196: form.elements[item].checked = true;
13197: if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
13198: if (parents[count].length > 0) {
13199: for (var j=0; j<parents[count].length; j++) {
13200: containerCheck(form,parents[count][j],offset);
13201: }
13202: }
13203: }
13204: }
13205: }
13206:
13207: function dependencyCheck(form,count,offset) {
13208: if (count > 0) {
13209: var chosen = (offset+$startcount)+7*(count-1);
13210: var depitem = $startcount + ((count-1) * 7) + 4;
13211: var currtype = form.elements[depitem].type;
13212: if (form.elements[chosen].value == 'dependency') {
13213: document.getElementById('arc_depon_'+count).style.display='block';
13214: form.elements[depitem].options.length = 0;
13215: form.elements[depitem].options[0] = new Option('Select','',true,true);
13216: for (var i=1; i<=numitems; i++) {
13217: if (i == count) {
13218: continue;
13219: }
13220: var startelement = $startcount + (i-1) * 7;
13221: for (var j=1; j<6; j++) {
13222: if ((j != 2) && (j!= 4)) {
13223: var item = startelement + j;
13224: if (form.elements[item].type == 'radio') {
13225: if (form.elements[item].checked) {
13226: if (form.elements[item].value == 'display') {
13227: var n = form.elements[depitem].options.length;
13228: form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
13229: }
13230: }
13231: }
13232: }
13233: }
13234: }
13235: } else {
13236: document.getElementById('arc_depon_'+count).style.display='none';
13237: form.elements[depitem].options.length = 0;
13238: form.elements[depitem].options[0] = new Option('Select','',true,true);
13239: }
13240: titleCheck(form,count,offset);
13241: }
13242: }
13243:
13244: function propagateSelect(form,count,offset) {
13245: if (count > 0) {
13246: var item = (1+offset+$startcount)+7*(count-1);
13247: var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
13248: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13249: if (parents[count].length > 0) {
13250: for (var j=0; j<parents[count].length; j++) {
13251: containerSelect(form,parents[count][j],offset,picked);
13252: }
13253: }
13254: }
13255: }
13256: }
13257:
13258: function containerSelect(form,count,offset,picked) {
13259: if (count > 0) {
13260: var item = (offset+$startcount)+7*(count-1);
13261: if (form.elements[item].type == 'radio') {
13262: if (form.elements[item].value == 'dependency') {
13263: if (form.elements[item+1].type == 'select-one') {
13264: for (var i=0; i<form.elements[item+1].options.length; i++) {
13265: if (form.elements[item+1].options[i].value == picked) {
13266: form.elements[item+1].selectedIndex = i;
13267: break;
13268: }
13269: }
13270: }
13271: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13272: if (parents[count].length > 0) {
13273: for (var j=0; j<parents[count].length; j++) {
13274: containerSelect(form,parents[count][j],offset,picked);
13275: }
13276: }
13277: }
13278: }
13279: }
13280: }
13281: }
13282:
13283: function titleCheck(form,count,offset) {
13284: if (count > 0) {
13285: var chosen = (offset+$startcount)+7*(count-1);
13286: var depitem = $startcount + ((count-1) * 7) + 2;
13287: var currtype = form.elements[depitem].type;
13288: if (form.elements[chosen].value == 'display') {
13289: document.getElementById('arc_title_'+count).style.display='block';
13290: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
13291: document.getElementById('archive_title_'+count).value=maintitle;
13292: }
13293: } else {
13294: document.getElementById('arc_title_'+count).style.display='none';
13295: if (currtype == 'text') {
13296: document.getElementById('archive_title_'+count).value='';
13297: }
13298: }
13299: }
13300: return;
13301: }
13302:
13303: // ]]>
13304: </script>
13305: END
13306: return $scripttag;
13307: }
13308:
13309: sub process_extracted_files {
13310: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
13311: my $numitems = $env{'form.archive_count'};
13312: return if ((!$numitems) || ($numitems =~ /\D/));
13313: my @ids=&Apache::lonnet::current_machine_ids();
13314: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
13315: %folders,%containers,%mapinner,%prompttofetch);
13316: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13317: if (grep(/^\Q$docuhome\E$/,@ids)) {
13318: $prefix = &LONCAPA::propath($docudom,$docuname);
13319: $pathtocheck = "$dir_root/$destination";
13320: $dir = $dir_root;
13321: $ishome = 1;
13322: } else {
13323: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
13324: $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
13325: $dir = "$dir_root/$docudom/$docuname";
13326: }
13327: my $currdir = "$dir_root/$destination";
13328: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
13329: if ($env{'form.folderpath'}) {
13330: my @items = split('&',$env{'form.folderpath'});
13331: $folders{'0'} = $items[-2];
13332: if ($env{'form.folderpath'} =~ /\:1$/) {
13333: $containers{'0'}='page';
13334: } else {
13335: $containers{'0'}='sequence';
13336: }
13337: }
13338: my @archdirs = &get_env_multiple('form.archive_directory');
13339: if ($numitems) {
13340: for (my $i=1; $i<=$numitems; $i++) {
13341: my $path = $env{'form.archive_content_'.$i};
13342: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
13343: my $item = $1;
13344: $toplevelitems{$item} = $i;
13345: if (grep(/^\Q$i\E$/,@archdirs)) {
13346: $is_dir{$item} = 1;
13347: }
13348: }
13349: }
13350: }
13351: my ($output,%children,%parent,%titles,%dirorder,$result);
13352: if (keys(%toplevelitems) > 0) {
13353: my @contents = sort(keys(%toplevelitems));
13354: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
13355: \%parent,\@contents,\%dirorder,\%titles);
13356: }
13357: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
13358: if ($numitems) {
13359: for (my $i=1; $i<=$numitems; $i++) {
13360: next if ($env{'form.archive_'.$i} eq 'dependency');
13361: my $path = $env{'form.archive_content_'.$i};
13362: if ($path =~ /^\Q$pathtocheck\E/) {
13363: if ($env{'form.archive_'.$i} eq 'discard') {
13364: if ($prefix ne '' && $path ne '') {
13365: if (-e $prefix.$path) {
13366: if ((@archdirs > 0) &&
13367: (grep(/^\Q$i\E$/,@archdirs))) {
13368: $todeletedir{$prefix.$path} = 1;
13369: } else {
13370: $todelete{$prefix.$path} = 1;
13371: }
13372: }
13373: }
13374: } elsif ($env{'form.archive_'.$i} eq 'display') {
13375: my ($docstitle,$title,$url,$outer);
13376: ($title) = ($path =~ m{/([^/]+)$});
13377: $docstitle = $env{'form.archive_title_'.$i};
13378: if ($docstitle eq '') {
13379: $docstitle = $title;
13380: }
13381: $outer = 0;
13382: if (ref($dirorder{$i}) eq 'ARRAY') {
13383: if (@{$dirorder{$i}} > 0) {
13384: foreach my $item (reverse(@{$dirorder{$i}})) {
13385: if ($env{'form.archive_'.$item} eq 'display') {
13386: $outer = $item;
13387: last;
13388: }
13389: }
13390: }
13391: }
13392: my ($errtext,$fatal) =
13393: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
13394: '/'.$folders{$outer}.'.'.
13395: $containers{$outer});
13396: next if ($fatal);
13397: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
13398: if ($context eq 'coursedocs') {
13399: $mapinner{$i} = time;
13400: $folders{$i} = 'default_'.$mapinner{$i};
13401: $containers{$i} = 'sequence';
13402: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13403: $folders{$i}.'.'.$containers{$i};
13404: my $newidx = &LONCAPA::map::getresidx();
13405: $LONCAPA::map::resources[$newidx]=
13406: $docstitle.':'.$url.':false:normal:res';
13407: push(@LONCAPA::map::order,$newidx);
13408: my ($outtext,$errtext) =
13409: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13410: $docuname.'/'.$folders{$outer}.
13411: '.'.$containers{$outer},1,1);
13412: $newseqid{$i} = $newidx;
13413: unless ($errtext) {
13414: $result .= '<li>'.&mt('Folder: [_1] added to course',
13415: &HTML::Entities::encode($docstitle,'<>&"')).
13416: '</li>'."\n";
13417: }
13418: }
13419: } else {
13420: if ($context eq 'coursedocs') {
13421: my $newidx=&LONCAPA::map::getresidx();
13422: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13423: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
13424: $title;
13425: if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
13426: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
13427: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
13428: }
13429: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13430: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
13431: }
13432: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13433: if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
13434: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
13435: unless ($ishome) {
13436: my $fetch = "$newdest{$i}/$title";
13437: $fetch =~ s/^\Q$prefix$dir\E//;
13438: $prompttofetch{$fetch} = 1;
13439: }
13440: }
13441: }
13442: $LONCAPA::map::resources[$newidx]=
13443: $docstitle.':'.$url.':false:normal:res';
13444: push(@LONCAPA::map::order, $newidx);
13445: my ($outtext,$errtext)=
13446: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13447: $docuname.'/'.$folders{$outer}.
13448: '.'.$containers{$outer},1,1);
13449: unless ($errtext) {
13450: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
13451: $result .= '<li>'.&mt('File: [_1] added to course',
13452: &HTML::Entities::encode($docstitle,'<>&"')).
13453: '</li>'."\n";
13454: }
13455: }
13456: } else {
13457: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13458: &HTML::Entities::encode($path,'<>&"')).'<br />';
13459: }
13460: }
13461: }
13462: }
13463: } else {
13464: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13465: &HTML::Entities::encode($path,'<>&"')).'<br />';
13466: }
13467: }
13468: for (my $i=1; $i<=$numitems; $i++) {
13469: next unless ($env{'form.archive_'.$i} eq 'dependency');
13470: my $path = $env{'form.archive_content_'.$i};
13471: if ($path =~ /^\Q$pathtocheck\E/) {
13472: my ($title) = ($path =~ m{/([^/]+)$});
13473: $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13474: if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13475: if (ref($dirorder{$i}) eq 'ARRAY') {
13476: my ($itemidx,$fullpath,$relpath);
13477: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13478: my $container = $dirorder{$referrer{$i}}->[-1];
13479: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13480: if ($dirorder{$i}->[$j] eq $container) {
13481: $itemidx = $j;
13482: }
13483: }
13484: }
13485: if ($itemidx eq '') {
13486: $itemidx = 0;
13487: }
13488: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13489: if ($mapinner{$referrer{$i}}) {
13490: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13491: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13492: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13493: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13494: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13495: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13496: if (!-e $fullpath) {
13497: mkdir($fullpath,0755);
13498: }
13499: }
13500: } else {
13501: last;
13502: }
13503: }
13504: }
13505: } elsif ($newdest{$referrer{$i}}) {
13506: $fullpath = $newdest{$referrer{$i}};
13507: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13508: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
13509: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
13510: last;
13511: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13512: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13513: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13514: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13515: if (!-e $fullpath) {
13516: mkdir($fullpath,0755);
13517: }
13518: }
13519: } else {
13520: last;
13521: }
13522: }
13523: }
13524: if ($fullpath ne '') {
13525: if (-e "$prefix$path") {
13526: unless (rename("$prefix$path","$fullpath/$title")) {
13527: $warning .= &mt('Failed to rename dependency').'<br />';
13528: }
13529: }
13530: if (-e "$fullpath/$title") {
13531: my $showpath;
13532: if ($relpath ne '') {
13533: $showpath = "$relpath/$title";
13534: } else {
13535: $showpath = "/$title";
13536: }
13537: $result .= '<li>'.&mt('[_1] included as a dependency',
13538: &HTML::Entities::encode($showpath,'<>&"')).
13539: '</li>'."\n";
13540: unless ($ishome) {
13541: my $fetch = "$fullpath/$title";
13542: $fetch =~ s/^\Q$prefix$dir\E//;
13543: $prompttofetch{$fetch} = 1;
13544: }
13545: }
13546: }
13547: }
13548: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
13549: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
13550: &HTML::Entities::encode($path,'<>&"'),
13551: &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
13552: '<br />';
13553: }
13554: } else {
13555: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13556: &HTML::Entities::encode($path)).'<br />';
13557: }
13558: }
13559: if (keys(%todelete)) {
13560: foreach my $key (keys(%todelete)) {
13561: unlink($key);
13562: }
13563: }
13564: if (keys(%todeletedir)) {
13565: foreach my $key (keys(%todeletedir)) {
13566: rmdir($key);
13567: }
13568: }
13569: foreach my $dir (sort(keys(%is_dir))) {
13570: if (($pathtocheck ne '') && ($dir ne '')) {
13571: &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
13572: }
13573: }
13574: if ($result ne '') {
13575: $output .= '<ul>'."\n".
13576: $result."\n".
13577: '</ul>';
13578: }
13579: unless ($ishome) {
13580: my $replicationfail;
13581: foreach my $item (keys(%prompttofetch)) {
13582: my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13583: unless ($fetchresult eq 'ok') {
13584: $replicationfail .= '<li>'.$item.'</li>'."\n";
13585: }
13586: }
13587: if ($replicationfail) {
13588: $output .= '<p class="LC_error">'.
13589: &mt('Course home server failed to retrieve:').'<ul>'.
13590: $replicationfail.
13591: '</ul></p>';
13592: }
13593: }
13594: } else {
13595: $warning = &mt('No items found in archive.');
13596: }
13597: if ($error) {
13598: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13599: $error.'</p>'."\n";
13600: }
13601: if ($warning) {
13602: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13603: }
13604: return $output;
13605: }
13606:
13607: sub cleanup_empty_dirs {
13608: my ($path) = @_;
13609: if (($path ne '') && (-d $path)) {
13610: if (opendir(my $dirh,$path)) {
13611: my @dircontents = grep(!/^\./,readdir($dirh));
13612: my $numitems = 0;
13613: foreach my $item (@dircontents) {
13614: if (-d "$path/$item") {
13615: &cleanup_empty_dirs("$path/$item");
13616: if (-e "$path/$item") {
13617: $numitems ++;
13618: }
13619: } else {
13620: $numitems ++;
13621: }
13622: }
13623: if ($numitems == 0) {
13624: rmdir($path);
13625: }
13626: closedir($dirh);
13627: }
13628: }
13629: return;
13630: }
13631:
13632: =pod
13633:
13634: =item * &get_folder_hierarchy()
13635:
13636: Provides hierarchy of names of folders/sub-folders containing the current
13637: item,
13638:
13639: Inputs: 3
13640: - $navmap - navmaps object
13641:
13642: - $map - url for map (either the trigger itself, or map containing
13643: the resource, which is the trigger).
13644:
13645: - $showitem - 1 => show title for map itself; 0 => do not show.
13646:
13647: Outputs: 1 @pathitems - array of folder/subfolder names.
13648:
13649: =cut
13650:
13651: sub get_folder_hierarchy {
13652: my ($navmap,$map,$showitem) = @_;
13653: my @pathitems;
13654: if (ref($navmap)) {
13655: my $mapres = $navmap->getResourceByUrl($map);
13656: if (ref($mapres)) {
13657: my $pcslist = $mapres->map_hierarchy();
13658: if ($pcslist ne '') {
13659: my @pcs = split(/,/,$pcslist);
13660: foreach my $pc (@pcs) {
13661: if ($pc == 1) {
13662: push(@pathitems,&mt('Main Content'));
13663: } else {
13664: my $res = $navmap->getByMapPc($pc);
13665: if (ref($res)) {
13666: my $title = $res->compTitle();
13667: $title =~ s/\W+/_/g;
13668: if ($title ne '') {
13669: push(@pathitems,$title);
13670: }
13671: }
13672: }
13673: }
13674: }
13675: if ($showitem) {
13676: if ($mapres->{ID} eq '0.0') {
13677: push(@pathitems,&mt('Main Content'));
13678: } else {
13679: my $maptitle = $mapres->compTitle();
13680: $maptitle =~ s/\W+/_/g;
13681: if ($maptitle ne '') {
13682: push(@pathitems,$maptitle);
13683: }
13684: }
13685: }
13686: }
13687: }
13688: return @pathitems;
13689: }
13690:
13691: =pod
13692:
13693: =item * &get_turnedin_filepath()
13694:
13695: Determines path in a user's portfolio file for storage of files uploaded
13696: to a specific essayresponse or dropbox item.
13697:
13698: Inputs: 3 required + 1 optional.
13699: $symb is symb for resource, $uname and $udom are for current user (required).
13700: $caller is optional (can be "submission", if routine is called when storing
13701: an upoaded file when "Submit Answer" button was pressed).
13702:
13703: Returns array containing $path and $multiresp.
13704: $path is path in portfolio. $multiresp is 1 if this resource contains more
13705: than one file upload item. Callers of routine should append partid as a
13706: subdirectory to $path in cases where $multiresp is 1.
13707:
13708: Called by: homework/essayresponse.pm and homework/structuretags.pm
13709:
13710: =cut
13711:
13712: sub get_turnedin_filepath {
13713: my ($symb,$uname,$udom,$caller) = @_;
13714: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13715: my $turnindir;
13716: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13717: $turnindir = $userhash{'turnindir'};
13718: my ($path,$multiresp);
13719: if ($turnindir eq '') {
13720: if ($caller eq 'submission') {
13721: $turnindir = &mt('turned in');
13722: $turnindir =~ s/\W+/_/g;
13723: my %newhash = (
13724: 'turnindir' => $turnindir,
13725: );
13726: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13727: }
13728: }
13729: if ($turnindir ne '') {
13730: $path = '/'.$turnindir.'/';
13731: my ($multipart,$turnin,@pathitems);
13732: my $navmap = Apache::lonnavmaps::navmap->new();
13733: if (defined($navmap)) {
13734: my $mapres = $navmap->getResourceByUrl($map);
13735: if (ref($mapres)) {
13736: my $pcslist = $mapres->map_hierarchy();
13737: if ($pcslist ne '') {
13738: foreach my $pc (split(/,/,$pcslist)) {
13739: my $res = $navmap->getByMapPc($pc);
13740: if (ref($res)) {
13741: my $title = $res->compTitle();
13742: $title =~ s/\W+/_/g;
13743: if ($title ne '') {
13744: if (($pc > 1) && (length($title) > 12)) {
13745: $title = substr($title,0,12);
13746: }
13747: push(@pathitems,$title);
13748: }
13749: }
13750: }
13751: }
13752: my $maptitle = $mapres->compTitle();
13753: $maptitle =~ s/\W+/_/g;
13754: if ($maptitle ne '') {
13755: if (length($maptitle) > 12) {
13756: $maptitle = substr($maptitle,0,12);
13757: }
13758: push(@pathitems,$maptitle);
13759: }
13760: unless ($env{'request.state'} eq 'construct') {
13761: my $res = $navmap->getBySymb($symb);
13762: if (ref($res)) {
13763: my $partlist = $res->parts();
13764: my $totaluploads = 0;
13765: if (ref($partlist) eq 'ARRAY') {
13766: foreach my $part (@{$partlist}) {
13767: my @types = $res->responseType($part);
13768: my @ids = $res->responseIds($part);
13769: for (my $i=0; $i < scalar(@ids); $i++) {
13770: if ($types[$i] eq 'essay') {
13771: my $partid = $part.'_'.$ids[$i];
13772: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13773: $totaluploads ++;
13774: }
13775: }
13776: }
13777: }
13778: if ($totaluploads > 1) {
13779: $multiresp = 1;
13780: }
13781: }
13782: }
13783: }
13784: } else {
13785: return;
13786: }
13787: } else {
13788: return;
13789: }
13790: my $restitle=&Apache::lonnet::gettitle($symb);
13791: $restitle =~ s/\W+/_/g;
13792: if ($restitle eq '') {
13793: $restitle = ($resurl =~ m{/[^/]+$});
13794: if ($restitle eq '') {
13795: $restitle = time;
13796: }
13797: }
13798: if (length($restitle) > 12) {
13799: $restitle = substr($restitle,0,12);
13800: }
13801: push(@pathitems,$restitle);
13802: $path .= join('/',@pathitems);
13803: }
13804: return ($path,$multiresp);
13805: }
13806:
13807: =pod
13808:
13809: =back
13810:
13811: =head1 CSV Upload/Handling functions
13812:
13813: =over 4
13814:
13815: =item * &upfile_store($r)
13816:
13817: Store uploaded file, $r should be the HTTP Request object,
13818: needs $env{'form.upfile'}
13819: returns $datatoken to be put into hidden field
13820:
13821: =cut
13822:
13823: sub upfile_store {
13824: my $r=shift;
13825: $env{'form.upfile'}=~s/\r/\n/gs;
13826: $env{'form.upfile'}=~s/\f/\n/gs;
13827: $env{'form.upfile'}=~s/\n+/\n/gs;
13828: $env{'form.upfile'}=~s/\n+$//gs;
13829:
13830: my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
13831: '_enroll_'.$env{'request.course.id'}.'_'.
13832: time.'_'.$$);
13833: return if ($datatoken eq '');
13834:
13835: {
13836: my $datafile = $r->dir_config('lonDaemons').
13837: '/tmp/'.$datatoken.'.tmp';
13838: if ( open(my $fh,">$datafile") ) {
13839: print $fh $env{'form.upfile'};
13840: close($fh);
13841: }
13842: }
13843: return $datatoken;
13844: }
13845:
13846: =pod
13847:
13848: =item * &load_tmp_file($r,$datatoken)
13849:
13850: Load uploaded file from tmp, $r should be the HTTP Request object,
13851: $datatoken is the name to assign to the temporary file.
13852: sets $env{'form.upfile'} to the contents of the file
13853:
13854: =cut
13855:
13856: sub load_tmp_file {
13857: my ($r,$datatoken) = @_;
13858: return if ($datatoken eq '');
13859: my @studentdata=();
13860: {
13861: my $studentfile = $r->dir_config('lonDaemons').
13862: '/tmp/'.$datatoken.'.tmp';
13863: if ( open(my $fh,"<$studentfile") ) {
13864: @studentdata=<$fh>;
13865: close($fh);
13866: }
13867: }
13868: $env{'form.upfile'}=join('',@studentdata);
13869: }
13870:
13871: sub valid_datatoken {
13872: my ($datatoken) = @_;
13873: if ($datatoken =~ /^$match_username\_$match_domain\_enroll_$match_domain\_$match_courseid\_\d+_\d+$/) {
13874: return $datatoken;
13875: }
13876: return;
13877: }
13878:
13879: =pod
13880:
13881: =item * &upfile_record_sep()
13882:
13883: Separate uploaded file into records
13884: returns array of records,
13885: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13886:
13887: =cut
13888:
13889: sub upfile_record_sep {
13890: if ($env{'form.upfiletype'} eq 'xml') {
13891: } else {
13892: my @records;
13893: foreach my $line (split(/\n/,$env{'form.upfile'})) {
13894: if ($line=~/^\s*$/) { next; }
13895: push(@records,$line);
13896: }
13897: return @records;
13898: }
13899: }
13900:
13901: =pod
13902:
13903: =item * &record_sep($record)
13904:
13905: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13906:
13907: =cut
13908:
13909: sub takeleft {
13910: my $index=shift;
13911: return substr('0000'.$index,-4,4);
13912: }
13913:
13914: sub record_sep {
13915: my $record=shift;
13916: my %components=();
13917: if ($env{'form.upfiletype'} eq 'xml') {
13918: } elsif ($env{'form.upfiletype'} eq 'space') {
13919: my $i=0;
13920: foreach my $field (split(/\s+/,$record)) {
13921: $field=~s/^(\"|\')//;
13922: $field=~s/(\"|\')$//;
13923: $components{&takeleft($i)}=$field;
13924: $i++;
13925: }
13926: } elsif ($env{'form.upfiletype'} eq 'tab') {
13927: my $i=0;
13928: foreach my $field (split(/\t/,$record)) {
13929: $field=~s/^(\"|\')//;
13930: $field=~s/(\"|\')$//;
13931: $components{&takeleft($i)}=$field;
13932: $i++;
13933: }
13934: } else {
13935: my $separator=',';
13936: if ($env{'form.upfiletype'} eq 'semisv') {
13937: $separator=';';
13938: }
13939: my $i=0;
13940: # the character we are looking for to indicate the end of a quote or a record
13941: my $looking_for=$separator;
13942: # do not add the characters to the fields
13943: my $ignore=0;
13944: # we just encountered a separator (or the beginning of the record)
13945: my $just_found_separator=1;
13946: # store the field we are working on here
13947: my $field='';
13948: # work our way through all characters in record
13949: foreach my $character ($record=~/(.)/g) {
13950: if ($character eq $looking_for) {
13951: if ($character ne $separator) {
13952: # Found the end of a quote, again looking for separator
13953: $looking_for=$separator;
13954: $ignore=1;
13955: } else {
13956: # Found a separator, store away what we got
13957: $components{&takeleft($i)}=$field;
13958: $i++;
13959: $just_found_separator=1;
13960: $ignore=0;
13961: $field='';
13962: }
13963: next;
13964: }
13965: # single or double quotation marks after a separator indicate beginning of a quote
13966: # we are now looking for the end of the quote and need to ignore separators
13967: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
13968: $looking_for=$character;
13969: next;
13970: }
13971: # ignore would be true after we reached the end of a quote
13972: if ($ignore) { next; }
13973: if (($just_found_separator) && ($character=~/\s/)) { next; }
13974: $field.=$character;
13975: $just_found_separator=0;
13976: }
13977: # catch the very last entry, since we never encountered the separator
13978: $components{&takeleft($i)}=$field;
13979: }
13980: return %components;
13981: }
13982:
13983: ######################################################
13984: ######################################################
13985:
13986: =pod
13987:
13988: =item * &upfile_select_html()
13989:
13990: Return HTML code to select a file from the users machine and specify
13991: the file type.
13992:
13993: =cut
13994:
13995: ######################################################
13996: ######################################################
13997: sub upfile_select_html {
13998: my %Types = (
13999: csv => &mt('CSV (comma separated values, spreadsheet)'),
14000: semisv => &mt('Semicolon separated values'),
14001: space => &mt('Space separated'),
14002: tab => &mt('Tabulator separated'),
14003: # xml => &mt('HTML/XML'),
14004: );
14005: my $Str = '<input type="file" name="upfile" size="50" />'.
14006: '<br />'.&mt('Type').': <select name="upfiletype">';
14007: foreach my $type (sort(keys(%Types))) {
14008: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
14009: }
14010: $Str .= "</select>\n";
14011: return $Str;
14012: }
14013:
14014: sub get_samples {
14015: my ($records,$toget) = @_;
14016: my @samples=({});
14017: my $got=0;
14018: foreach my $rec (@$records) {
14019: my %temp = &record_sep($rec);
14020: if (! grep(/\S/, values(%temp))) { next; }
14021: if (%temp) {
14022: $samples[$got]=\%temp;
14023: $got++;
14024: if ($got == $toget) { last; }
14025: }
14026: }
14027: return \@samples;
14028: }
14029:
14030: ######################################################
14031: ######################################################
14032:
14033: =pod
14034:
14035: =item * &csv_print_samples($r,$records)
14036:
14037: Prints a table of sample values from each column uploaded $r is an
14038: Apache Request ref, $records is an arrayref from
14039: &Apache::loncommon::upfile_record_sep
14040:
14041: =cut
14042:
14043: ######################################################
14044: ######################################################
14045: sub csv_print_samples {
14046: my ($r,$records) = @_;
14047: my $samples = &get_samples($records,5);
14048:
14049: $r->print(&mt('Samples').'<br />'.&start_data_table().
14050: &start_data_table_header_row());
14051: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14052: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
14053: $r->print(&end_data_table_header_row());
14054: foreach my $hash (@$samples) {
14055: $r->print(&start_data_table_row());
14056: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14057: $r->print('<td>');
14058: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
14059: $r->print('</td>');
14060: }
14061: $r->print(&end_data_table_row());
14062: }
14063: $r->print(&end_data_table().'<br />'."\n");
14064: }
14065:
14066: ######################################################
14067: ######################################################
14068:
14069: =pod
14070:
14071: =item * &csv_print_select_table($r,$records,$d)
14072:
14073: Prints a table to create associations between values and table columns.
14074:
14075: $r is an Apache Request ref,
14076: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14077: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
14078:
14079: =cut
14080:
14081: ######################################################
14082: ######################################################
14083: sub csv_print_select_table {
14084: my ($r,$records,$d) = @_;
14085: my $i=0;
14086: my $samples = &get_samples($records,1);
14087: $r->print(&mt('Associate columns with student attributes.')."\n".
14088: &start_data_table().&start_data_table_header_row().
14089: '<th>'.&mt('Attribute').'</th>'.
14090: '<th>'.&mt('Column').'</th>'.
14091: &end_data_table_header_row()."\n");
14092: foreach my $array_ref (@$d) {
14093: my ($value,$display,$defaultcol)=@{ $array_ref };
14094: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
14095:
14096: $r->print('<td><select name="f'.$i.'"'.
14097: ' onchange="javascript:flip(this.form,'.$i.');">');
14098: $r->print('<option value="none"></option>');
14099: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14100: $r->print('<option value="'.$sample.'"'.
14101: ($sample eq $defaultcol ? ' selected="selected" ' : '').
14102: '>'.&mt('Column [_1]',($sample+1)).'</option>');
14103: }
14104: $r->print('</select></td>'.&end_data_table_row()."\n");
14105: $i++;
14106: }
14107: $r->print(&end_data_table());
14108: $i--;
14109: return $i;
14110: }
14111:
14112: ######################################################
14113: ######################################################
14114:
14115: =pod
14116:
14117: =item * &csv_samples_select_table($r,$records,$d)
14118:
14119: Prints a table of sample values from the upload and can make associate samples to internal names.
14120:
14121: $r is an Apache Request ref,
14122: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14123: $d is an array of 2 element arrays (internal name, displayed name)
14124:
14125: =cut
14126:
14127: ######################################################
14128: ######################################################
14129: sub csv_samples_select_table {
14130: my ($r,$records,$d) = @_;
14131: my $i=0;
14132: #
14133: my $max_samples = 5;
14134: my $samples = &get_samples($records,$max_samples);
14135: $r->print(&start_data_table().
14136: &start_data_table_header_row().'<th>'.
14137: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
14138: &end_data_table_header_row());
14139:
14140: foreach my $key (sort(keys(%{ $samples->[0] }))) {
14141: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
14142: ' onchange="javascript:flip(this.form,'.$i.');">');
14143: foreach my $option (@$d) {
14144: my ($value,$display,$defaultcol)=@{ $option };
14145: $r->print('<option value="'.$value.'"'.
14146: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
14147: $display.'</option>');
14148: }
14149: $r->print('</select></td><td>');
14150: foreach my $line (0..($max_samples-1)) {
14151: if (defined($samples->[$line]{$key})) {
14152: $r->print($samples->[$line]{$key}."<br />\n");
14153: }
14154: }
14155: $r->print('</td>'.&end_data_table_row());
14156: $i++;
14157: }
14158: $r->print(&end_data_table());
14159: $i--;
14160: return($i);
14161: }
14162:
14163: ######################################################
14164: ######################################################
14165:
14166: =pod
14167:
14168: =item * &clean_excel_name($name)
14169:
14170: Returns a replacement for $name which does not contain any illegal characters.
14171:
14172: =cut
14173:
14174: ######################################################
14175: ######################################################
14176: sub clean_excel_name {
14177: my ($name) = @_;
14178: $name =~ s/[:\*\?\/\\]//g;
14179: if (length($name) > 31) {
14180: $name = substr($name,0,31);
14181: }
14182: return $name;
14183: }
14184:
14185: =pod
14186:
14187: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
14188:
14189: Returns either 1 or undef
14190:
14191: 1 if the part is to be hidden, undef if it is to be shown
14192:
14193: Arguments are:
14194:
14195: $id the id of the part to be checked
14196: $symb, optional the symb of the resource to check
14197: $udom, optional the domain of the user to check for
14198: $uname, optional the username of the user to check for
14199:
14200: =cut
14201:
14202: sub check_if_partid_hidden {
14203: my ($id,$symb,$udom,$uname) = @_;
14204: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
14205: $symb,$udom,$uname);
14206: my $truth=1;
14207: #if the string starts with !, then the list is the list to show not hide
14208: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
14209: my @hiddenlist=split(/,/,$hiddenparts);
14210: foreach my $checkid (@hiddenlist) {
14211: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
14212: }
14213: return !$truth;
14214: }
14215:
14216:
14217: ############################################################
14218: ############################################################
14219:
14220: =pod
14221:
14222: =back
14223:
14224: =head1 cgi-bin script and graphing routines
14225:
14226: =over 4
14227:
14228: =item * &get_cgi_id()
14229:
14230: Inputs: none
14231:
14232: Returns an id which can be used to pass environment variables
14233: to various cgi-bin scripts. These environment variables will
14234: be removed from the users environment after a given time by
14235: the routine &Apache::lonnet::transfer_profile_to_env.
14236:
14237: =cut
14238:
14239: ############################################################
14240: ############################################################
14241: my $uniq=0;
14242: sub get_cgi_id {
14243: $uniq=($uniq+1)%100000;
14244: return (time.'_'.$$.'_'.$uniq);
14245: }
14246:
14247: ############################################################
14248: ############################################################
14249:
14250: =pod
14251:
14252: =item * &DrawBarGraph()
14253:
14254: Facilitates the plotting of data in a (stacked) bar graph.
14255: Puts plot definition data into the users environment in order for
14256: graph.png to plot it. Returns an <img> tag for the plot.
14257: The bars on the plot are labeled '1','2',...,'n'.
14258:
14259: Inputs:
14260:
14261: =over 4
14262:
14263: =item $Title: string, the title of the plot
14264:
14265: =item $xlabel: string, text describing the X-axis of the plot
14266:
14267: =item $ylabel: string, text describing the Y-axis of the plot
14268:
14269: =item $Max: scalar, the maximum Y value to use in the plot
14270: If $Max is < any data point, the graph will not be rendered.
14271:
14272: =item $colors: array ref holding the colors to be used for the data sets when
14273: they are plotted. If undefined, default values will be used.
14274:
14275: =item $labels: array ref holding the labels to use on the x-axis for the bars.
14276:
14277: =item @Values: An array of array references. Each array reference holds data
14278: to be plotted in a stacked bar chart.
14279:
14280: =item If the final element of @Values is a hash reference the key/value
14281: pairs will be added to the graph definition.
14282:
14283: =back
14284:
14285: Returns:
14286:
14287: An <img> tag which references graph.png and the appropriate identifying
14288: information for the plot.
14289:
14290: =cut
14291:
14292: ############################################################
14293: ############################################################
14294: sub DrawBarGraph {
14295: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
14296: #
14297: if (! defined($colors)) {
14298: $colors = ['#33ff00',
14299: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
14300: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
14301: ];
14302: }
14303: my $extra_settings = {};
14304: if (ref($Values[-1]) eq 'HASH') {
14305: $extra_settings = pop(@Values);
14306: }
14307: #
14308: my $identifier = &get_cgi_id();
14309: my $id = 'cgi.'.$identifier;
14310: if (! @Values || ref($Values[0]) ne 'ARRAY') {
14311: return '';
14312: }
14313: #
14314: my @Labels;
14315: if (defined($labels)) {
14316: @Labels = @$labels;
14317: } else {
14318: for (my $i=0;$i<@{$Values[0]};$i++) {
14319: push(@Labels,$i+1);
14320: }
14321: }
14322: #
14323: my $NumBars = scalar(@{$Values[0]});
14324: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
14325: my %ValuesHash;
14326: my $NumSets=1;
14327: foreach my $array (@Values) {
14328: next if (! ref($array));
14329: $ValuesHash{$id.'.data.'.$NumSets++} =
14330: join(',',@$array);
14331: }
14332: #
14333: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
14334: if ($NumBars < 3) {
14335: $width = 120+$NumBars*32;
14336: $xskip = 1;
14337: $bar_width = 30;
14338: } elsif ($NumBars < 5) {
14339: $width = 120+$NumBars*20;
14340: $xskip = 1;
14341: $bar_width = 20;
14342: } elsif ($NumBars < 10) {
14343: $width = 120+$NumBars*15;
14344: $xskip = 1;
14345: $bar_width = 15;
14346: } elsif ($NumBars <= 25) {
14347: $width = 120+$NumBars*11;
14348: $xskip = 5;
14349: $bar_width = 8;
14350: } elsif ($NumBars <= 50) {
14351: $width = 120+$NumBars*8;
14352: $xskip = 5;
14353: $bar_width = 4;
14354: } else {
14355: $width = 120+$NumBars*8;
14356: $xskip = 5;
14357: $bar_width = 4;
14358: }
14359: #
14360: $Max = 1 if ($Max < 1);
14361: if ( int($Max) < $Max ) {
14362: $Max++;
14363: $Max = int($Max);
14364: }
14365: $Title = '' if (! defined($Title));
14366: $xlabel = '' if (! defined($xlabel));
14367: $ylabel = '' if (! defined($ylabel));
14368: $ValuesHash{$id.'.title'} = &escape($Title);
14369: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
14370: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
14371: $ValuesHash{$id.'.y_max_value'} = $Max;
14372: $ValuesHash{$id.'.NumBars'} = $NumBars;
14373: $ValuesHash{$id.'.NumSets'} = $NumSets;
14374: $ValuesHash{$id.'.PlotType'} = 'bar';
14375: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
14376: $ValuesHash{$id.'.height'} = $height;
14377: $ValuesHash{$id.'.width'} = $width;
14378: $ValuesHash{$id.'.xskip'} = $xskip;
14379: $ValuesHash{$id.'.bar_width'} = $bar_width;
14380: $ValuesHash{$id.'.labels'} = join(',',@Labels);
14381: #
14382: # Deal with other parameters
14383: while (my ($key,$value) = each(%$extra_settings)) {
14384: $ValuesHash{$id.'.'.$key} = $value;
14385: }
14386: #
14387: &Apache::lonnet::appenv(\%ValuesHash);
14388: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14389: }
14390:
14391: ############################################################
14392: ############################################################
14393:
14394: =pod
14395:
14396: =item * &DrawXYGraph()
14397:
14398: Facilitates the plotting of data in an XY graph.
14399: Puts plot definition data into the users environment in order for
14400: graph.png to plot it. Returns an <img> tag for the plot.
14401:
14402: Inputs:
14403:
14404: =over 4
14405:
14406: =item $Title: string, the title of the plot
14407:
14408: =item $xlabel: string, text describing the X-axis of the plot
14409:
14410: =item $ylabel: string, text describing the Y-axis of the plot
14411:
14412: =item $Max: scalar, the maximum Y value to use in the plot
14413: If $Max is < any data point, the graph will not be rendered.
14414:
14415: =item $colors: Array ref containing the hex color codes for the data to be
14416: plotted in. If undefined, default values will be used.
14417:
14418: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14419:
14420: =item $Ydata: Array ref containing Array refs.
14421: Each of the contained arrays will be plotted as a separate curve.
14422:
14423: =item %Values: hash indicating or overriding any default values which are
14424: passed to graph.png.
14425: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14426:
14427: =back
14428:
14429: Returns:
14430:
14431: An <img> tag which references graph.png and the appropriate identifying
14432: information for the plot.
14433:
14434: =cut
14435:
14436: ############################################################
14437: ############################################################
14438: sub DrawXYGraph {
14439: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
14440: #
14441: # Create the identifier for the graph
14442: my $identifier = &get_cgi_id();
14443: my $id = 'cgi.'.$identifier;
14444: #
14445: $Title = '' if (! defined($Title));
14446: $xlabel = '' if (! defined($xlabel));
14447: $ylabel = '' if (! defined($ylabel));
14448: my %ValuesHash =
14449: (
14450: $id.'.title' => &escape($Title),
14451: $id.'.xlabel' => &escape($xlabel),
14452: $id.'.ylabel' => &escape($ylabel),
14453: $id.'.y_max_value'=> $Max,
14454: $id.'.labels' => join(',',@$Xlabels),
14455: $id.'.PlotType' => 'XY',
14456: );
14457: #
14458: if (defined($colors) && ref($colors) eq 'ARRAY') {
14459: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
14460: }
14461: #
14462: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
14463: return '';
14464: }
14465: my $NumSets=1;
14466: foreach my $array (@{$Ydata}){
14467: next if (! ref($array));
14468: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14469: }
14470: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14471: #
14472: # Deal with other parameters
14473: while (my ($key,$value) = each(%Values)) {
14474: $ValuesHash{$id.'.'.$key} = $value;
14475: }
14476: #
14477: &Apache::lonnet::appenv(\%ValuesHash);
14478: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14479: }
14480:
14481: ############################################################
14482: ############################################################
14483:
14484: =pod
14485:
14486: =item * &DrawXYYGraph()
14487:
14488: Facilitates the plotting of data in an XY graph with two Y axes.
14489: Puts plot definition data into the users environment in order for
14490: graph.png to plot it. Returns an <img> tag for the plot.
14491:
14492: Inputs:
14493:
14494: =over 4
14495:
14496: =item $Title: string, the title of the plot
14497:
14498: =item $xlabel: string, text describing the X-axis of the plot
14499:
14500: =item $ylabel: string, text describing the Y-axis of the plot
14501:
14502: =item $colors: Array ref containing the hex color codes for the data to be
14503: plotted in. If undefined, default values will be used.
14504:
14505: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14506:
14507: =item $Ydata1: The first data set
14508:
14509: =item $Min1: The minimum value of the left Y-axis
14510:
14511: =item $Max1: The maximum value of the left Y-axis
14512:
14513: =item $Ydata2: The second data set
14514:
14515: =item $Min2: The minimum value of the right Y-axis
14516:
14517: =item $Max2: The maximum value of the left Y-axis
14518:
14519: =item %Values: hash indicating or overriding any default values which are
14520: passed to graph.png.
14521: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14522:
14523: =back
14524:
14525: Returns:
14526:
14527: An <img> tag which references graph.png and the appropriate identifying
14528: information for the plot.
14529:
14530: =cut
14531:
14532: ############################################################
14533: ############################################################
14534: sub DrawXYYGraph {
14535: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
14536: $Ydata2,$Min2,$Max2,%Values)=@_;
14537: #
14538: # Create the identifier for the graph
14539: my $identifier = &get_cgi_id();
14540: my $id = 'cgi.'.$identifier;
14541: #
14542: $Title = '' if (! defined($Title));
14543: $xlabel = '' if (! defined($xlabel));
14544: $ylabel = '' if (! defined($ylabel));
14545: my %ValuesHash =
14546: (
14547: $id.'.title' => &escape($Title),
14548: $id.'.xlabel' => &escape($xlabel),
14549: $id.'.ylabel' => &escape($ylabel),
14550: $id.'.labels' => join(',',@$Xlabels),
14551: $id.'.PlotType' => 'XY',
14552: $id.'.NumSets' => 2,
14553: $id.'.two_axes' => 1,
14554: $id.'.y1_max_value' => $Max1,
14555: $id.'.y1_min_value' => $Min1,
14556: $id.'.y2_max_value' => $Max2,
14557: $id.'.y2_min_value' => $Min2,
14558: );
14559: #
14560: if (defined($colors) && ref($colors) eq 'ARRAY') {
14561: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
14562: }
14563: #
14564: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
14565: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
14566: return '';
14567: }
14568: my $NumSets=1;
14569: foreach my $array ($Ydata1,$Ydata2){
14570: next if (! ref($array));
14571: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14572: }
14573: #
14574: # Deal with other parameters
14575: while (my ($key,$value) = each(%Values)) {
14576: $ValuesHash{$id.'.'.$key} = $value;
14577: }
14578: #
14579: &Apache::lonnet::appenv(\%ValuesHash);
14580: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14581: }
14582:
14583: ############################################################
14584: ############################################################
14585:
14586: =pod
14587:
14588: =back
14589:
14590: =head1 Statistics helper routines?
14591:
14592: Bad place for them but what the hell.
14593:
14594: =over 4
14595:
14596: =item * &chartlink()
14597:
14598: Returns a link to the chart for a specific student.
14599:
14600: Inputs:
14601:
14602: =over 4
14603:
14604: =item $linktext: The text of the link
14605:
14606: =item $sname: The students username
14607:
14608: =item $sdomain: The students domain
14609:
14610: =back
14611:
14612: =back
14613:
14614: =cut
14615:
14616: ############################################################
14617: ############################################################
14618: sub chartlink {
14619: my ($linktext, $sname, $sdomain) = @_;
14620: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14621: '&SelectedStudent='.&escape($sname.':'.$sdomain).
14622: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
14623: '">'.$linktext.'</a>';
14624: }
14625:
14626: #######################################################
14627: #######################################################
14628:
14629: =pod
14630:
14631: =head1 Course Environment Routines
14632:
14633: =over 4
14634:
14635: =item * &restore_course_settings()
14636:
14637: =item * &store_course_settings()
14638:
14639: Restores/Store indicated form parameters from the course environment.
14640: Will not overwrite existing values of the form parameters.
14641:
14642: Inputs:
14643: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14644:
14645: a hash ref describing the data to be stored. For example:
14646:
14647: %Save_Parameters = ('Status' => 'scalar',
14648: 'chartoutputmode' => 'scalar',
14649: 'chartoutputdata' => 'scalar',
14650: 'Section' => 'array',
14651: 'Group' => 'array',
14652: 'StudentData' => 'array',
14653: 'Maps' => 'array');
14654:
14655: Returns: both routines return nothing
14656:
14657: =back
14658:
14659: =cut
14660:
14661: #######################################################
14662: #######################################################
14663: sub store_course_settings {
14664: return &store_settings($env{'request.course.id'},@_);
14665: }
14666:
14667: sub store_settings {
14668: # save to the environment
14669: # appenv the same items, just to be safe
14670: my $udom = $env{'user.domain'};
14671: my $uname = $env{'user.name'};
14672: my ($context,$prefix,$Settings) = @_;
14673: my %SaveHash;
14674: my %AppHash;
14675: while (my ($setting,$type) = each(%$Settings)) {
14676: my $basename = join('.','internal',$context,$prefix,$setting);
14677: my $envname = 'environment.'.$basename;
14678: if (exists($env{'form.'.$setting})) {
14679: # Save this value away
14680: if ($type eq 'scalar' &&
14681: (! exists($env{$envname}) ||
14682: $env{$envname} ne $env{'form.'.$setting})) {
14683: $SaveHash{$basename} = $env{'form.'.$setting};
14684: $AppHash{$envname} = $env{'form.'.$setting};
14685: } elsif ($type eq 'array') {
14686: my $stored_form;
14687: if (ref($env{'form.'.$setting})) {
14688: $stored_form = join(',',
14689: map {
14690: &escape($_);
14691: } sort(@{$env{'form.'.$setting}}));
14692: } else {
14693: $stored_form =
14694: &escape($env{'form.'.$setting});
14695: }
14696: # Determine if the array contents are the same.
14697: if ($stored_form ne $env{$envname}) {
14698: $SaveHash{$basename} = $stored_form;
14699: $AppHash{$envname} = $stored_form;
14700: }
14701: }
14702: }
14703: }
14704: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14705: $udom,$uname);
14706: if ($put_result !~ /^(ok|delayed)/) {
14707: &Apache::lonnet::logthis('unable to save form parameters, '.
14708: 'got error:'.$put_result);
14709: }
14710: # Make sure these settings stick around in this session, too
14711: &Apache::lonnet::appenv(\%AppHash);
14712: return;
14713: }
14714:
14715: sub restore_course_settings {
14716: return &restore_settings($env{'request.course.id'},@_);
14717: }
14718:
14719: sub restore_settings {
14720: my ($context,$prefix,$Settings) = @_;
14721: while (my ($setting,$type) = each(%$Settings)) {
14722: next if (exists($env{'form.'.$setting}));
14723: my $envname = 'environment.internal.'.$context.'.'.$prefix.
14724: '.'.$setting;
14725: if (exists($env{$envname})) {
14726: if ($type eq 'scalar') {
14727: $env{'form.'.$setting} = $env{$envname};
14728: } elsif ($type eq 'array') {
14729: $env{'form.'.$setting} = [
14730: map {
14731: &unescape($_);
14732: } split(',',$env{$envname})
14733: ];
14734: }
14735: }
14736: }
14737: }
14738:
14739: #######################################################
14740: #######################################################
14741:
14742: =pod
14743:
14744: =head1 Domain E-mail Routines
14745:
14746: =over 4
14747:
14748: =item * &build_recipient_list()
14749:
14750: Build recipient lists for following types of e-mail:
14751: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14752: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14753: module change checking, student/employee ID conflict checks, as
14754: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14755: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14756:
14757: Inputs:
14758: defmail (scalar - email address of default recipient),
14759: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14760: requestsmail, updatesmail, or idconflictsmail).
14761:
14762: defdom (domain for which to retrieve configuration settings),
14763:
14764: origmail (scalar - email address of recipient from loncapa.conf,
14765: i.e., predates configuration by DC via domainprefs.pm
14766:
14767: $requname username of requester (if mailing type is helpdeskmail)
14768:
14769: $requdom domain of requester (if mailing type is helpdeskmail)
14770:
14771: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
14772:
14773:
14774: Returns: comma separated list of addresses to which to send e-mail.
14775:
14776: =back
14777:
14778: =cut
14779:
14780: ############################################################
14781: ############################################################
14782: sub build_recipient_list {
14783: my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
14784: my @recipients;
14785: my ($otheremails,$lastresort,$allbcc,$addtext);
14786: my %domconfig =
14787: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14788: if (ref($domconfig{'contacts'}) eq 'HASH') {
14789: if (exists($domconfig{'contacts'}{$mailing})) {
14790: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14791: my @contacts = ('adminemail','supportemail');
14792: foreach my $item (@contacts) {
14793: if ($domconfig{'contacts'}{$mailing}{$item}) {
14794: my $addr = $domconfig{'contacts'}{$item};
14795: if (!grep(/^\Q$addr\E$/,@recipients)) {
14796: push(@recipients,$addr);
14797: }
14798: }
14799: }
14800: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14801: if ($mailing eq 'helpdeskmail') {
14802: if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
14803: my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
14804: my @ok_bccs;
14805: foreach my $bcc (@bccs) {
14806: $bcc =~ s/^\s+//g;
14807: $bcc =~ s/\s+$//g;
14808: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14809: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14810: push(@ok_bccs,$bcc);
14811: }
14812: }
14813: }
14814: if (@ok_bccs > 0) {
14815: $allbcc = join(', ',@ok_bccs);
14816: }
14817: }
14818: $addtext = $domconfig{'contacts'}{$mailing}{'include'};
14819: }
14820: }
14821: } elsif ($origmail ne '') {
14822: $lastresort = $origmail;
14823: }
14824: if ($mailing eq 'helpdeskmail') {
14825: if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
14826: (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
14827: my ($inststatus,$inststatus_checked);
14828: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
14829: ($env{'user.domain'} ne 'public')) {
14830: $inststatus_checked = 1;
14831: $inststatus = $env{'environment.inststatus'};
14832: }
14833: unless ($inststatus_checked) {
14834: if (($requname ne '') && ($requdom ne '')) {
14835: if (($requname =~ /^$match_username$/) &&
14836: ($requdom =~ /^$match_domain$/) &&
14837: (&Apache::lonnet::domain($requdom))) {
14838: my $requhome = &Apache::lonnet::homeserver($requname,
14839: $requdom);
14840: unless ($requhome eq 'no_host') {
14841: my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
14842: $inststatus = $userenv{'inststatus'};
14843: $inststatus_checked = 1;
14844: }
14845: }
14846: }
14847: }
14848: unless ($inststatus_checked) {
14849: if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
14850: my %srch = (srchby => 'email',
14851: srchdomain => $defdom,
14852: srchterm => $reqemail,
14853: srchtype => 'exact');
14854: my %srch_results = &Apache::lonnet::usersearch(\%srch);
14855: foreach my $uname (keys(%srch_results)) {
14856: if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14857: $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14858: $inststatus_checked = 1;
14859: last;
14860: }
14861: }
14862: unless ($inststatus_checked) {
14863: my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
14864: if ($dirsrchres eq 'ok') {
14865: foreach my $uname (keys(%srch_results)) {
14866: if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14867: $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14868: $inststatus_checked = 1;
14869: last;
14870: }
14871: }
14872: }
14873: }
14874: }
14875: }
14876: if ($inststatus ne '') {
14877: foreach my $status (split(/\:/,$inststatus)) {
14878: if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
14879: my @contacts = ('adminemail','supportemail');
14880: foreach my $item (@contacts) {
14881: if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
14882: my $addr = $domconfig{'contacts'}{'overrides'}{$status};
14883: if (!grep(/^\Q$addr\E$/,@recipients)) {
14884: push(@recipients,$addr);
14885: }
14886: }
14887: }
14888: $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
14889: if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
14890: my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
14891: my @ok_bccs;
14892: foreach my $bcc (@bccs) {
14893: $bcc =~ s/^\s+//g;
14894: $bcc =~ s/\s+$//g;
14895: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14896: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14897: push(@ok_bccs,$bcc);
14898: }
14899: }
14900: }
14901: if (@ok_bccs > 0) {
14902: $allbcc = join(', ',@ok_bccs);
14903: }
14904: }
14905: $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
14906: last;
14907: }
14908: }
14909: }
14910: }
14911: }
14912: } elsif ($origmail ne '') {
14913: $lastresort = $origmail;
14914: }
14915: if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
14916: unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
14917: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
14918: my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
14919: my %what = (
14920: perlvar => 1,
14921: );
14922: my $primary = &Apache::lonnet::domain($defdom,'primary');
14923: if ($primary) {
14924: my $gotaddr;
14925: my ($result,$returnhash) =
14926: &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
14927: if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
14928: if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
14929: $lastresort = $returnhash->{'lonSupportEMail'};
14930: $gotaddr = 1;
14931: }
14932: }
14933: unless ($gotaddr) {
14934: my $uintdom = &Apache::lonnet::internet_dom($primary);
14935: my $intdom = &Apache::lonnet::internet_dom($lonhost);
14936: unless ($uintdom eq $intdom) {
14937: my %domconfig =
14938: &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
14939: if (ref($domconfig{'contacts'}) eq 'HASH') {
14940: if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
14941: my @contacts = ('adminemail','supportemail');
14942: foreach my $item (@contacts) {
14943: if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
14944: my $addr = $domconfig{'contacts'}{$item};
14945: if (!grep(/^\Q$addr\E$/,@recipients)) {
14946: push(@recipients,$addr);
14947: }
14948: }
14949: }
14950: if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
14951: $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
14952: }
14953: if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
14954: my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
14955: my @ok_bccs;
14956: foreach my $bcc (@bccs) {
14957: $bcc =~ s/^\s+//g;
14958: $bcc =~ s/\s+$//g;
14959: if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14960: if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14961: push(@ok_bccs,$bcc);
14962: }
14963: }
14964: }
14965: if (@ok_bccs > 0) {
14966: $allbcc = join(', ',@ok_bccs);
14967: }
14968: }
14969: $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
14970: }
14971: }
14972: }
14973: }
14974: }
14975: }
14976: }
14977: if (defined($defmail)) {
14978: if ($defmail ne '') {
14979: push(@recipients,$defmail);
14980: }
14981: }
14982: if ($otheremails) {
14983: my @others;
14984: if ($otheremails =~ /,/) {
14985: @others = split(/,/,$otheremails);
14986: } else {
14987: push(@others,$otheremails);
14988: }
14989: foreach my $addr (@others) {
14990: if (!grep(/^\Q$addr\E$/,@recipients)) {
14991: push(@recipients,$addr);
14992: }
14993: }
14994: }
14995: if ($mailing eq 'helpdeskmail') {
14996: if ((!@recipients) && ($lastresort ne '')) {
14997: push(@recipients,$lastresort);
14998: }
14999: } elsif ($lastresort ne '') {
15000: if (!grep(/^\Q$lastresort\E$/,@recipients)) {
15001: push(@recipients,$lastresort);
15002: }
15003: }
15004: my $recipientlist = join(',',@recipients);
15005: if (wantarray) {
15006: return ($recipientlist,$allbcc,$addtext);
15007: } else {
15008: return $recipientlist;
15009: }
15010: }
15011:
15012: ############################################################
15013: ############################################################
15014:
15015: =pod
15016:
15017: =over 4
15018:
15019: =item * &mime_email()
15020:
15021: Sends an email with a possible attachment
15022:
15023: Inputs:
15024:
15025: =over 4
15026:
15027: from - Sender's email address
15028:
15029: to - Email address of recipient
15030:
15031: subject - Subject of email
15032:
15033: body - Body of email
15034:
15035: cc_string - Carbon copy email address
15036:
15037: bcc - Blind carbon copy email address
15038:
15039: type - File type of attachment
15040:
15041: attachment_path - Path of file to be attached
15042:
15043: file_name - Name of file to be attached
15044:
15045: attachment_text - The body of an attachment of type "TEXT"
15046:
15047: =back
15048:
15049: =back
15050:
15051: =cut
15052:
15053: ############################################################
15054: ############################################################
15055:
15056: sub mime_email {
15057: my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path,
15058: $file_name, $attachment_text) = @_;
15059: my $msg = MIME::Lite->new(
15060: From => $from,
15061: To => $to,
15062: Subject => $subject,
15063: Type =>'TEXT',
15064: Data => $body,
15065: );
15066: if ($cc_string ne '') {
15067: $msg->add("Cc" => $cc_string);
15068: }
15069: if ($bcc ne '') {
15070: $msg->add("Bcc" => $bcc);
15071: }
15072: $msg->attr("content-type" => "text/plain");
15073: $msg->attr("content-type.charset" => "UTF-8");
15074: # Attach file if given
15075: if ($attachment_path) {
15076: unless ($file_name) {
15077: if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
15078: }
15079: my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
15080: $msg->attach(Type => $type,
15081: Path => $attachment_path,
15082: Filename => $file_name
15083: );
15084: # Otherwise attach text if given
15085: } elsif ($attachment_text) {
15086: $msg->attach(Type => 'TEXT',
15087: Data => $attachment_text);
15088: }
15089: # Send it
15090: $msg->send('sendmail');
15091: }
15092:
15093: ############################################################
15094: ############################################################
15095:
15096: =pod
15097:
15098: =head1 Course Catalog Routines
15099:
15100: =over 4
15101:
15102: =item * &gather_categories()
15103:
15104: Converts category definitions - keys of categories hash stored in
15105: coursecategories in configuration.db on the primary library server in a
15106: domain - to an array. Also generates javascript and idx hash used to
15107: generate Domain Coordinator interface for editing Course Categories.
15108:
15109: Inputs:
15110:
15111: categories (reference to hash of category definitions).
15112:
15113: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15114: categories and subcategories).
15115:
15116: idx (reference to hash of counters used in Domain Coordinator interface for
15117: editing Course Categories).
15118:
15119: jsarray (reference to array of categories used to create Javascript arrays for
15120: Domain Coordinator interface for editing Course Categories).
15121:
15122: Returns: nothing
15123:
15124: Side effects: populates cats, idx and jsarray.
15125:
15126: =cut
15127:
15128: sub gather_categories {
15129: my ($categories,$cats,$idx,$jsarray) = @_;
15130: my %counters;
15131: my $num = 0;
15132: foreach my $item (keys(%{$categories})) {
15133: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
15134: if ($container eq '' && $depth == 0) {
15135: $cats->[$depth][$categories->{$item}] = $cat;
15136: } else {
15137: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
15138: }
15139: my ($escitem,$tail) = split(/:/,$item,2);
15140: if ($counters{$tail} eq '') {
15141: $counters{$tail} = $num;
15142: $num ++;
15143: }
15144: if (ref($idx) eq 'HASH') {
15145: $idx->{$item} = $counters{$tail};
15146: }
15147: if (ref($jsarray) eq 'ARRAY') {
15148: push(@{$jsarray->[$counters{$tail}]},$item);
15149: }
15150: }
15151: return;
15152: }
15153:
15154: =pod
15155:
15156: =item * &extract_categories()
15157:
15158: Used to generate breadcrumb trails for course categories.
15159:
15160: Inputs:
15161:
15162: categories (reference to hash of category definitions).
15163:
15164: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15165: categories and subcategories).
15166:
15167: trails (reference to array of breacrumb trails for each category).
15168:
15169: allitems (reference to hash - key is category key
15170: (format: escaped(name):escaped(parent category):depth in hierarchy).
15171:
15172: idx (reference to hash of counters used in Domain Coordinator interface for
15173: editing Course Categories).
15174:
15175: jsarray (reference to array of categories used to create Javascript arrays for
15176: Domain Coordinator interface for editing Course Categories).
15177:
15178: subcats (reference to hash of arrays containing all subcategories within each
15179: category, -recursive)
15180:
15181: Returns: nothing
15182:
15183: Side effects: populates trails and allitems hash references.
15184:
15185: =cut
15186:
15187: sub extract_categories {
15188: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
15189: if (ref($categories) eq 'HASH') {
15190: &gather_categories($categories,$cats,$idx,$jsarray);
15191: if (ref($cats->[0]) eq 'ARRAY') {
15192: for (my $i=0; $i<@{$cats->[0]}; $i++) {
15193: my $name = $cats->[0][$i];
15194: my $item = &escape($name).'::0';
15195: my $trailstr;
15196: if ($name eq 'instcode') {
15197: $trailstr = &mt('Official courses (with institutional codes)');
15198: } elsif ($name eq 'communities') {
15199: $trailstr = &mt('Communities');
15200: } elsif ($name eq 'placement') {
15201: $trailstr = &mt('Placement Tests');
15202: } else {
15203: $trailstr = $name;
15204: }
15205: if ($allitems->{$item} eq '') {
15206: push(@{$trails},$trailstr);
15207: $allitems->{$item} = scalar(@{$trails})-1;
15208: }
15209: my @parents = ($name);
15210: if (ref($cats->[1]{$name}) eq 'ARRAY') {
15211: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
15212: my $category = $cats->[1]{$name}[$j];
15213: if (ref($subcats) eq 'HASH') {
15214: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
15215: }
15216: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
15217: }
15218: } else {
15219: if (ref($subcats) eq 'HASH') {
15220: $subcats->{$item} = [];
15221: }
15222: }
15223: }
15224: }
15225: }
15226: return;
15227: }
15228:
15229: =pod
15230:
15231: =item * &recurse_categories()
15232:
15233: Recursively used to generate breadcrumb trails for course categories.
15234:
15235: Inputs:
15236:
15237: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15238: categories and subcategories).
15239:
15240: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
15241:
15242: category (current course category, for which breadcrumb trail is being generated).
15243:
15244: trails (reference to array of breadcrumb trails for each category).
15245:
15246: allitems (reference to hash - key is category key
15247: (format: escaped(name):escaped(parent category):depth in hierarchy).
15248:
15249: parents (array containing containers directories for current category,
15250: back to top level).
15251:
15252: Returns: nothing
15253:
15254: Side effects: populates trails and allitems hash references
15255:
15256: =cut
15257:
15258: sub recurse_categories {
15259: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
15260: my $shallower = $depth - 1;
15261: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
15262: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
15263: my $name = $cats->[$depth]{$category}[$k];
15264: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15265: my $trailstr = join(' -> ',(@{$parents},$category));
15266: if ($allitems->{$item} eq '') {
15267: push(@{$trails},$trailstr);
15268: $allitems->{$item} = scalar(@{$trails})-1;
15269: }
15270: my $deeper = $depth+1;
15271: push(@{$parents},$category);
15272: if (ref($subcats) eq 'HASH') {
15273: my $subcat = &escape($name).':'.$category.':'.$depth;
15274: for (my $j=@{$parents}; $j>=0; $j--) {
15275: my $higher;
15276: if ($j > 0) {
15277: $higher = &escape($parents->[$j]).':'.
15278: &escape($parents->[$j-1]).':'.$j;
15279: } else {
15280: $higher = &escape($parents->[$j]).'::'.$j;
15281: }
15282: push(@{$subcats->{$higher}},$subcat);
15283: }
15284: }
15285: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
15286: $subcats);
15287: pop(@{$parents});
15288: }
15289: } else {
15290: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15291: my $trailstr = join(' -> ',(@{$parents},$category));
15292: if ($allitems->{$item} eq '') {
15293: push(@{$trails},$trailstr);
15294: $allitems->{$item} = scalar(@{$trails})-1;
15295: }
15296: }
15297: return;
15298: }
15299:
15300: =pod
15301:
15302: =item * &assign_categories_table()
15303:
15304: Create a datatable for display of hierarchical categories in a domain,
15305: with checkboxes to allow a course to be categorized.
15306:
15307: Inputs:
15308:
15309: cathash - reference to hash of categories defined for the domain (from
15310: configuration.db)
15311:
15312: currcat - scalar with an & separated list of categories assigned to a course.
15313:
15314: type - scalar contains course type (Course or Community).
15315:
15316: disabled - scalar (optional) contains disabled="disabled" if input elements are
15317: to be readonly (e.g., Domain Helpdesk role viewing course settings).
15318:
15319: Returns: $output (markup to be displayed)
15320:
15321: =cut
15322:
15323: sub assign_categories_table {
15324: my ($cathash,$currcat,$type,$disabled) = @_;
15325: my $output;
15326: if (ref($cathash) eq 'HASH') {
15327: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
15328: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
15329: $maxdepth = scalar(@cats);
15330: if (@cats > 0) {
15331: my $itemcount = 0;
15332: if (ref($cats[0]) eq 'ARRAY') {
15333: my @currcategories;
15334: if ($currcat ne '') {
15335: @currcategories = split('&',$currcat);
15336: }
15337: my $table;
15338: for (my $i=0; $i<@{$cats[0]}; $i++) {
15339: my $parent = $cats[0][$i];
15340: next if ($parent eq 'instcode');
15341: if ($type eq 'Community') {
15342: next unless ($parent eq 'communities');
15343: } elsif ($type eq 'Placement') {
15344: next unless ($parent eq 'placement');
15345: } else {
15346: next if (($parent eq 'communities') || ($parent eq 'placement'));
15347: }
15348: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15349: my $item = &escape($parent).'::0';
15350: my $checked = '';
15351: if (@currcategories > 0) {
15352: if (grep(/^\Q$item\E$/,@currcategories)) {
15353: $checked = ' checked="checked"';
15354: }
15355: }
15356: my $parent_title = $parent;
15357: if ($parent eq 'communities') {
15358: $parent_title = &mt('Communities');
15359: } elsif ($parent eq 'placement') {
15360: $parent_title = &mt('Placement Tests');
15361: }
15362: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
15363: '<input type="checkbox" name="usecategory" value="'.
15364: $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
15365: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
15366: my $depth = 1;
15367: push(@path,$parent);
15368: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
15369: pop(@path);
15370: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
15371: $itemcount ++;
15372: }
15373: if ($itemcount) {
15374: $output = &Apache::loncommon::start_data_table().
15375: $table.
15376: &Apache::loncommon::end_data_table();
15377: }
15378: }
15379: }
15380: }
15381: return $output;
15382: }
15383:
15384: =pod
15385:
15386: =item * &assign_category_rows()
15387:
15388: Create a datatable row for display of nested categories in a domain,
15389: with checkboxes to allow a course to be categorized,called recursively.
15390:
15391: Inputs:
15392:
15393: itemcount - track row number for alternating colors
15394:
15395: cats - reference to array of arrays/hashes which encapsulates hierarchy of
15396: categories and subcategories.
15397:
15398: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
15399:
15400: parent - parent of current category item
15401:
15402: path - Array containing all categories back up through the hierarchy from the
15403: current category to the top level.
15404:
15405: currcategories - reference to array of current categories assigned to the course
15406:
15407: disabled - scalar (optional) contains disabled="disabled" if input elements are
15408: to be readonly (e.g., Domain Helpdesk role viewing course settings).
15409:
15410: Returns: $output (markup to be displayed).
15411:
15412: =cut
15413:
15414: sub assign_category_rows {
15415: my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
15416: my ($text,$name,$item,$chgstr);
15417: if (ref($cats) eq 'ARRAY') {
15418: my $maxdepth = scalar(@{$cats});
15419: if (ref($cats->[$depth]) eq 'HASH') {
15420: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
15421: my $numchildren = @{$cats->[$depth]{$parent}};
15422: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15423: $text .= '<td><table class="LC_data_table">';
15424: for (my $j=0; $j<$numchildren; $j++) {
15425: $name = $cats->[$depth]{$parent}[$j];
15426: $item = &escape($name).':'.&escape($parent).':'.$depth;
15427: my $deeper = $depth+1;
15428: my $checked = '';
15429: if (ref($currcategories) eq 'ARRAY') {
15430: if (@{$currcategories} > 0) {
15431: if (grep(/^\Q$item\E$/,@{$currcategories})) {
15432: $checked = ' checked="checked"';
15433: }
15434: }
15435: }
15436: $text .= '<tr><td><span class="LC_nobreak"><label>'.
15437: '<input type="checkbox" name="usecategory" value="'.
15438: $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
15439: '<input type="hidden" name="catname" value="'.$name.'" />'.
15440: '</td><td>';
15441: if (ref($path) eq 'ARRAY') {
15442: push(@{$path},$name);
15443: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
15444: pop(@{$path});
15445: }
15446: $text .= '</td></tr>';
15447: }
15448: $text .= '</table></td>';
15449: }
15450: }
15451: }
15452: return $text;
15453: }
15454:
15455: =pod
15456:
15457: =back
15458:
15459: =cut
15460:
15461: ############################################################
15462: ############################################################
15463:
15464:
15465: sub commit_customrole {
15466: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
15467: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
15468: ($start?', '.&mt('starting').' '.localtime($start):'').
15469: ($end?', ending '.localtime($end):'').': <b>'.
15470: &Apache::lonnet::assigncustomrole(
15471: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
15472: '</b><br />';
15473: return $output;
15474: }
15475:
15476: sub commit_standardrole {
15477: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
15478: my ($output,$logmsg,$linefeed);
15479: if ($context eq 'auto') {
15480: $linefeed = "\n";
15481: } else {
15482: $linefeed = "<br />\n";
15483: }
15484: if ($three eq 'st') {
15485: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
15486: $one,$two,$sec,$context,$credits);
15487: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
15488: ($result eq 'unknown_course') || ($result eq 'refused')) {
15489: $output = $logmsg.' '.&mt('Error: ').$result."\n";
15490: } else {
15491: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
15492: ($start?', '.&mt('starting').' '.localtime($start):'').
15493: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15494: if ($context eq 'auto') {
15495: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
15496: } else {
15497: $output .= '<b>'.$result.'</b>'.$linefeed.
15498: &mt('Add to classlist').': <b>ok</b>';
15499: }
15500: $output .= $linefeed;
15501: }
15502: } else {
15503: $output = &mt('Assigning').' '.$three.' in '.$url.
15504: ($start?', '.&mt('starting').' '.localtime($start):'').
15505: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15506: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
15507: if ($context eq 'auto') {
15508: $output .= $result.$linefeed;
15509: } else {
15510: $output .= '<b>'.$result.'</b>'.$linefeed;
15511: }
15512: }
15513: return $output;
15514: }
15515:
15516: sub commit_studentrole {
15517: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
15518: $credits) = @_;
15519: my ($result,$linefeed,$oldsecurl,$newsecurl);
15520: if ($context eq 'auto') {
15521: $linefeed = "\n";
15522: } else {
15523: $linefeed = '<br />'."\n";
15524: }
15525: if (defined($one) && defined($two)) {
15526: my $cid=$one.'_'.$two;
15527: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
15528: my $secchange = 0;
15529: my $expire_role_result;
15530: my $modify_section_result;
15531: if ($oldsec ne '-1') {
15532: if ($oldsec ne $sec) {
15533: $secchange = 1;
15534: my $now = time;
15535: my $uurl='/'.$cid;
15536: $uurl=~s/\_/\//g;
15537: if ($oldsec) {
15538: $uurl.='/'.$oldsec;
15539: }
15540: $oldsecurl = $uurl;
15541: $expire_role_result =
15542: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
15543: if ($env{'request.course.sec'} ne '') {
15544: if ($expire_role_result eq 'refused') {
15545: my @roles = ('st');
15546: my @statuses = ('previous');
15547: my @roledoms = ($one);
15548: my $withsec = 1;
15549: my %roleshash =
15550: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
15551: \@statuses,\@roles,\@roledoms,$withsec);
15552: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
15553: my ($oldstart,$oldend) =
15554: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
15555: if ($oldend > 0 && $oldend <= $now) {
15556: $expire_role_result = 'ok';
15557: }
15558: }
15559: }
15560: }
15561: $result = $expire_role_result;
15562: }
15563: }
15564: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
15565: $modify_section_result =
15566: &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
15567: undef,undef,undef,$sec,
15568: $end,$start,'','',$cid,
15569: '',$context,$credits);
15570: if ($modify_section_result =~ /^ok/) {
15571: if ($secchange == 1) {
15572: if ($sec eq '') {
15573: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
15574: } else {
15575: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
15576: }
15577: } elsif ($oldsec eq '-1') {
15578: if ($sec eq '') {
15579: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
15580: } else {
15581: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15582: }
15583: } else {
15584: if ($sec eq '') {
15585: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
15586: } else {
15587: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15588: }
15589: }
15590: } else {
15591: if ($secchange) {
15592: $$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;
15593: } else {
15594: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
15595: }
15596: }
15597: $result = $modify_section_result;
15598: } elsif ($secchange == 1) {
15599: if ($oldsec eq '') {
15600: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
15601: } else {
15602: $$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;
15603: }
15604: if ($expire_role_result eq 'refused') {
15605: my $newsecurl = '/'.$cid;
15606: $newsecurl =~ s/\_/\//g;
15607: if ($sec ne '') {
15608: $newsecurl.='/'.$sec;
15609: }
15610: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
15611: if ($sec eq '') {
15612: $$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;
15613: } else {
15614: $$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;
15615: }
15616: }
15617: }
15618: }
15619: } else {
15620: $$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;
15621: $result = "error: incomplete course id\n";
15622: }
15623: return $result;
15624: }
15625:
15626: sub show_role_extent {
15627: my ($scope,$context,$role) = @_;
15628: $scope =~ s{^/}{};
15629: my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
15630: push(@courseroles,'co');
15631: my @authorroles = &Apache::lonuserutils::roles_by_context('author');
15632: if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
15633: $scope =~ s{/}{_};
15634: return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
15635: } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
15636: my ($audom,$auname) = split(/\//,$scope);
15637: return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
15638: &Apache::loncommon::plainname($auname,$audom).'</span>');
15639: } else {
15640: $scope =~ s{/$}{};
15641: return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
15642: &Apache::lonnet::domain($scope,'description').'</span>');
15643: }
15644: }
15645:
15646: ############################################################
15647: ############################################################
15648:
15649: sub check_clone {
15650: my ($args,$linefeed) = @_;
15651: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
15652: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15653: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15654: my $clonemsg;
15655: my $can_clone = 0;
15656: my $lctype = lc($args->{'crstype'});
15657: if ($lctype ne 'community') {
15658: $lctype = 'course';
15659: }
15660: if ($clonehome eq 'no_host') {
15661: if ($args->{'crstype'} eq 'Community') {
15662: $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'});
15663: } else {
15664: $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'});
15665: }
15666: } else {
15667: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15668: if ($args->{'crstype'} eq 'Community') {
15669: if ($clonedesc{'type'} ne 'Community') {
15670: $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'});
15671: return ($can_clone, $clonemsg, $cloneid, $clonehome);
15672: }
15673: }
15674: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
15675: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15676: $can_clone = 1;
15677: } else {
15678: my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15679: $args->{'clonedomain'},$args->{'clonecourse'});
15680: if ($clonehash{'cloners'} eq '') {
15681: my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15682: if ($domdefs{'canclone'}) {
15683: unless ($domdefs{'canclone'} eq 'none') {
15684: if ($domdefs{'canclone'} eq 'domain') {
15685: if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15686: $can_clone = 1;
15687: }
15688: } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15689: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
15690: if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
15691: $clonehash{'internal.coursecode'},$args->{'crscode'})) {
15692: $can_clone = 1;
15693: }
15694: }
15695: }
15696: }
15697: } else {
15698: my @cloners = split(/,/,$clonehash{'cloners'});
15699: if (grep(/^\*$/,@cloners)) {
15700: $can_clone = 1;
15701: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15702: $can_clone = 1;
15703: } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15704: $can_clone = 1;
15705: }
15706: unless ($can_clone) {
15707: if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15708: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
15709: my (%gotdomdefaults,%gotcodedefaults);
15710: foreach my $cloner (@cloners) {
15711: if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
15712: ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
15713: my (%codedefaults,@code_order);
15714: if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
15715: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
15716: %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15717: }
15718: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15719: @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15720: }
15721: } else {
15722: &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15723: \%codedefaults,
15724: \@code_order);
15725: $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15726: $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15727: }
15728: if (@code_order > 0) {
15729: if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15730: $cloner,$clonehash{'internal.coursecode'},
15731: $args->{'crscode'})) {
15732: $can_clone = 1;
15733: last;
15734: }
15735: }
15736: }
15737: }
15738: }
15739: }
15740: }
15741: unless ($can_clone) {
15742: my $ccrole = 'cc';
15743: if ($args->{'crstype'} eq 'Community') {
15744: $ccrole = 'co';
15745: }
15746: my %roleshash =
15747: &Apache::lonnet::get_my_roles($args->{'ccuname'},
15748: $args->{'ccdomain'},
15749: 'userroles',['active'],[$ccrole],
15750: [$args->{'clonedomain'}]);
15751: if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15752: $can_clone = 1;
15753: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15754: $args->{'ccuname'},$args->{'ccdomain'})) {
15755: $can_clone = 1;
15756: }
15757: }
15758: unless ($can_clone) {
15759: if ($args->{'crstype'} eq 'Community') {
15760: $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'});
15761: } else {
15762: $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'});
15763: }
15764: }
15765: }
15766: }
15767: return ($can_clone, $clonemsg, $cloneid, $clonehome);
15768: }
15769:
15770: sub construct_course {
15771: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
15772: $cnum,$category,$coderef) = @_;
15773: my $outcome;
15774: my $linefeed = '<br />'."\n";
15775: if ($context eq 'auto') {
15776: $linefeed = "\n";
15777: }
15778:
15779: #
15780: # Are we cloning?
15781: #
15782: my ($can_clone, $clonemsg, $cloneid, $clonehome);
15783: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
15784: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
15785: if ($context ne 'auto') {
15786: if ($clonemsg ne '') {
15787: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
15788: }
15789: }
15790: $outcome .= $clonemsg.$linefeed;
15791:
15792: if (!$can_clone) {
15793: return (0,$outcome);
15794: }
15795: }
15796:
15797: #
15798: # Open course
15799: #
15800: my $showncrstype;
15801: if ($args->{'crstype'} eq 'Placement') {
15802: $showncrstype = 'placement test';
15803: } else {
15804: $showncrstype = lc($args->{'crstype'});
15805: }
15806: my %cenv=();
15807: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
15808: $args->{'cdescr'},
15809: $args->{'curl'},
15810: $args->{'course_home'},
15811: $args->{'nonstandard'},
15812: $args->{'crscode'},
15813: $args->{'ccuname'}.':'.
15814: $args->{'ccdomain'},
15815: $args->{'crstype'},
15816: $cnum,$context,$category);
15817:
15818: # Note: The testing routines depend on this being output; see
15819: # Utils::Course. This needs to at least be output as a comment
15820: # if anyone ever decides to not show this, and Utils::Course::new
15821: # will need to be suitably modified.
15822: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
15823: if ($$courseid =~ /^error:/) {
15824: return (0,$outcome);
15825: }
15826:
15827: #
15828: # Check if created correctly
15829: #
15830: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
15831: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
15832: if ($crsuhome eq 'no_host') {
15833: $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
15834: return (0,$outcome);
15835: }
15836: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
15837:
15838: #
15839: # Do the cloning
15840: #
15841: if ($can_clone && $cloneid) {
15842: $clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
15843: if ($context ne 'auto') {
15844: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
15845: }
15846: $outcome .= $clonemsg.$linefeed;
15847: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
15848: # Copy all files
15849: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
15850: # Restore URL
15851: $cenv{'url'}=$oldcenv{'url'};
15852: # Restore title
15853: $cenv{'description'}=$oldcenv{'description'};
15854: # Restore creation date, creator and creation context.
15855: $cenv{'internal.created'}=$oldcenv{'internal.created'};
15856: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
15857: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
15858: # Mark as cloned
15859: $cenv{'clonedfrom'}=$cloneid;
15860: # Need to clone grading mode
15861: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
15862: $cenv{'grading'}=$newenv{'grading'};
15863: # Do not clone these environment entries
15864: &Apache::lonnet::del('environment',
15865: ['default_enrollment_start_date',
15866: 'default_enrollment_end_date',
15867: 'question.email',
15868: 'policy.email',
15869: 'comment.email',
15870: 'pch.users.denied',
15871: 'plc.users.denied',
15872: 'hidefromcat',
15873: 'checkforpriv',
15874: 'categories',
15875: 'internal.uniquecode'],
15876: $$crsudom,$$crsunum);
15877: if ($args->{'textbook'}) {
15878: $cenv{'internal.textbook'} = $args->{'textbook'};
15879: }
15880: }
15881:
15882: #
15883: # Set environment (will override cloned, if existing)
15884: #
15885: my @sections = ();
15886: my @xlists = ();
15887: if ($args->{'crstype'}) {
15888: $cenv{'type'}=$args->{'crstype'};
15889: }
15890: if ($args->{'crsid'}) {
15891: $cenv{'courseid'}=$args->{'crsid'};
15892: }
15893: if ($args->{'crscode'}) {
15894: $cenv{'internal.coursecode'}=$args->{'crscode'};
15895: }
15896: if ($args->{'crsquota'} ne '') {
15897: $cenv{'internal.coursequota'}=$args->{'crsquota'};
15898: } else {
15899: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
15900: }
15901: if ($args->{'ccuname'}) {
15902: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
15903: ':'.$args->{'ccdomain'};
15904: } else {
15905: $cenv{'internal.courseowner'} = $args->{'curruser'};
15906: }
15907: if ($args->{'defaultcredits'}) {
15908: $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
15909: }
15910: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
15911: if ($args->{'crssections'}) {
15912: $cenv{'internal.sectionnums'} = '';
15913: if ($args->{'crssections'} =~ m/,/) {
15914: @sections = split/,/,$args->{'crssections'};
15915: } else {
15916: $sections[0] = $args->{'crssections'};
15917: }
15918: if (@sections > 0) {
15919: foreach my $item (@sections) {
15920: my ($sec,$gp) = split/:/,$item;
15921: my $class = $args->{'crscode'}.$sec;
15922: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
15923: $cenv{'internal.sectionnums'} .= $item.',';
15924: unless ($addcheck eq 'ok') {
15925: push(@badclasses,$class);
15926: }
15927: }
15928: $cenv{'internal.sectionnums'} =~ s/,$//;
15929: }
15930: }
15931: # do not hide course coordinator from staff listing,
15932: # even if privileged
15933: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15934: # add course coordinator's domain to domains to check for privileged users
15935: # if different to course domain
15936: if ($$crsudom ne $args->{'ccdomain'}) {
15937: $cenv{'checkforpriv'} = $args->{'ccdomain'};
15938: }
15939: # add crosslistings
15940: if ($args->{'crsxlist'}) {
15941: $cenv{'internal.crosslistings'}='';
15942: if ($args->{'crsxlist'} =~ m/,/) {
15943: @xlists = split/,/,$args->{'crsxlist'};
15944: } else {
15945: $xlists[0] = $args->{'crsxlist'};
15946: }
15947: if (@xlists > 0) {
15948: foreach my $item (@xlists) {
15949: my ($xl,$gp) = split/:/,$item;
15950: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15951: $cenv{'internal.crosslistings'} .= $item.',';
15952: unless ($addcheck eq 'ok') {
15953: push(@badclasses,$xl);
15954: }
15955: }
15956: $cenv{'internal.crosslistings'} =~ s/,$//;
15957: }
15958: }
15959: if ($args->{'autoadds'}) {
15960: $cenv{'internal.autoadds'}=$args->{'autoadds'};
15961: }
15962: if ($args->{'autodrops'}) {
15963: $cenv{'internal.autodrops'}=$args->{'autodrops'};
15964: }
15965: # check for notification of enrollment changes
15966: my @notified = ();
15967: if ($args->{'notify_owner'}) {
15968: if ($args->{'ccuname'} ne '') {
15969: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15970: }
15971: }
15972: if ($args->{'notify_dc'}) {
15973: if ($uname ne '') {
15974: push(@notified,$uname.':'.$udom);
15975: }
15976: }
15977: if (@notified > 0) {
15978: my $notifylist;
15979: if (@notified > 1) {
15980: $notifylist = join(',',@notified);
15981: } else {
15982: $notifylist = $notified[0];
15983: }
15984: $cenv{'internal.notifylist'} = $notifylist;
15985: }
15986: if (@badclasses > 0) {
15987: my %lt=&Apache::lonlocal::texthash(
15988: 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
15989: 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
15990: 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
15991: );
15992: my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
15993: &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'};
15994: if ($context eq 'auto') {
15995: $outcome .= $badclass_msg.$linefeed;
15996: } else {
15997: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15998: }
15999: foreach my $item (@badclasses) {
16000: if ($context eq 'auto') {
16001: $outcome .= " - $item\n";
16002: } else {
16003: $outcome .= "<li>$item</li>\n";
16004: }
16005: }
16006: if ($context eq 'auto') {
16007: $outcome .= $linefeed;
16008: } else {
16009: $outcome .= "</ul><br /><br /></div>\n";
16010: }
16011: }
16012: if ($args->{'no_end_date'}) {
16013: $args->{'endaccess'} = 0;
16014: }
16015: $cenv{'internal.autostart'}=$args->{'enrollstart'};
16016: $cenv{'internal.autoend'}=$args->{'enrollend'};
16017: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
16018: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
16019: if ($args->{'showphotos'}) {
16020: $cenv{'internal.showphotos'}=$args->{'showphotos'};
16021: }
16022: $cenv{'internal.authtype'} = $args->{'authtype'};
16023: $cenv{'internal.autharg'} = $args->{'autharg'};
16024: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
16025: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
16026: 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');
16027: if ($context eq 'auto') {
16028: $outcome .= $krb_msg;
16029: } else {
16030: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
16031: }
16032: $outcome .= $linefeed;
16033: }
16034: }
16035: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
16036: if ($args->{'setpolicy'}) {
16037: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16038: }
16039: if ($args->{'setcontent'}) {
16040: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16041: }
16042: if ($args->{'setcomment'}) {
16043: $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16044: }
16045: }
16046: if ($args->{'reshome'}) {
16047: $cenv{'reshome'}=$args->{'reshome'}.'/';
16048: $cenv{'reshome'}=~s/\/+$/\//;
16049: }
16050: #
16051: # course has keyed access
16052: #
16053: if ($args->{'setkeys'}) {
16054: $cenv{'keyaccess'}='yes';
16055: }
16056: # if specified, key authority is not course, but user
16057: # only active if keyaccess is yes
16058: if ($args->{'keyauth'}) {
16059: my ($user,$domain) = split(':',$args->{'keyauth'});
16060: $user = &LONCAPA::clean_username($user);
16061: $domain = &LONCAPA::clean_username($domain);
16062: if ($user ne '' && $domain ne '') {
16063: $cenv{'keyauth'}=$user.':'.$domain;
16064: }
16065: }
16066:
16067: #
16068: # generate and store uniquecode (available to course requester), if course should have one.
16069: #
16070: if ($args->{'uniquecode'}) {
16071: my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
16072: if ($code) {
16073: $cenv{'internal.uniquecode'} = $code;
16074: my %crsinfo =
16075: &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
16076: if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
16077: $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
16078: my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
16079: }
16080: if (ref($coderef)) {
16081: $$coderef = $code;
16082: }
16083: }
16084: }
16085:
16086: if ($args->{'disresdis'}) {
16087: $cenv{'pch.roles.denied'}='st';
16088: }
16089: if ($args->{'disablechat'}) {
16090: $cenv{'plc.roles.denied'}='st';
16091: }
16092:
16093: # Record we've not yet viewed the Course Initialization Helper for this
16094: # course
16095: $cenv{'course.helper.not.run'} = 1;
16096: #
16097: # Use new Randomseed
16098: #
16099: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
16100: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
16101: #
16102: # The encryption code and receipt prefix for this course
16103: #
16104: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
16105: $cenv{'internal.encpref'}=100+int(9*rand(99));
16106: #
16107: # By default, use standard grading
16108: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
16109:
16110: $outcome .= $linefeed.&mt('Setting environment').': '.
16111: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
16112: #
16113: # Open all assignments
16114: #
16115: if ($args->{'openall'}) {
16116: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
16117: my %storecontent = ($storeunder => time,
16118: $storeunder.'.type' => 'date_start');
16119:
16120: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
16121: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
16122: }
16123: #
16124: # Set first page
16125: #
16126: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
16127: || ($cloneid)) {
16128: use LONCAPA::map;
16129: $outcome .= &mt('Setting first resource').': ';
16130:
16131: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
16132: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
16133:
16134: $outcome .= ($fatal?$errtext:'read ok').' - ';
16135: my $title; my $url;
16136: if ($args->{'firstres'} eq 'syl') {
16137: $title=&mt('Syllabus');
16138: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
16139: } else {
16140: $title=&mt('Table of Contents');
16141: $url='/adm/navmaps';
16142: }
16143:
16144: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
16145: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
16146:
16147: if ($errtext) { $fatal=2; }
16148: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
16149: }
16150:
16151: #
16152: # Set params for Placement Tests
16153: #
16154: if ($args->{'crstype'} eq 'Placement') {
16155: my %storecontent;
16156: my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
16157: my %defaults = (
16158: buttonshide => { value => 'yes',
16159: type => 'string_yesno',},
16160: type => { value => 'randomizetry',
16161: type => 'string_questiontype',},
16162: maxtries => { value => 1,
16163: type => 'int_pos',},
16164: problemstatus => { value => 'no',
16165: type => 'string_problemstatus',},
16166: );
16167: foreach my $key (keys(%defaults)) {
16168: $storecontent{$prefix.$key} = $defaults{$key}{'value'};
16169: $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
16170: }
16171: &Apache::lonnet::cput
16172: ('resourcedata',\%storecontent,$$crsudom,$$crsunum);
16173: }
16174:
16175: return (1,$outcome);
16176: }
16177:
16178: sub make_unique_code {
16179: my ($cdom,$cnum) = @_;
16180: # get lock on uniquecodes db
16181: my $lockhash = {
16182: $cnum."\0".'uniquecodes' => $env{'user.name'}.
16183: ':'.$env{'user.domain'},
16184: };
16185: my $tries = 0;
16186: my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16187: my ($code,$error);
16188:
16189: while (($gotlock ne 'ok') && ($tries<3)) {
16190: $tries ++;
16191: sleep 1;
16192: $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16193: }
16194: if ($gotlock eq 'ok') {
16195: my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
16196: my $gotcode;
16197: my $attempts = 0;
16198: while ((!$gotcode) && ($attempts < 100)) {
16199: $code = &generate_code();
16200: if (!exists($currcodes{$code})) {
16201: $gotcode = 1;
16202: unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
16203: $error = 'nostore';
16204: }
16205: }
16206: $attempts ++;
16207: }
16208: my @del_lock = ($cnum."\0".'uniquecodes');
16209: my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
16210: } else {
16211: $error = 'nolock';
16212: }
16213: return ($code,$error);
16214: }
16215:
16216: sub generate_code {
16217: my $code;
16218: my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
16219: for (my $i=0; $i<6; $i++) {
16220: my $lettnum = int (rand 2);
16221: my $item = '';
16222: if ($lettnum) {
16223: $item = $letts[int( rand(18) )];
16224: } else {
16225: $item = 1+int( rand(8) );
16226: }
16227: $code .= $item;
16228: }
16229: return $code;
16230: }
16231:
16232: ############################################################
16233: ############################################################
16234:
16235: # Community, Course and Placement Test
16236: sub course_type {
16237: my ($cid) = @_;
16238: if (!defined($cid)) {
16239: $cid = $env{'request.course.id'};
16240: }
16241: if (defined($env{'course.'.$cid.'.type'})) {
16242: return $env{'course.'.$cid.'.type'};
16243: } else {
16244: return 'Course';
16245: }
16246: }
16247:
16248: sub group_term {
16249: my $crstype = &course_type();
16250: my %names = (
16251: 'Course' => 'group',
16252: 'Community' => 'group',
16253: 'Placement' => 'group',
16254: );
16255: return $names{$crstype};
16256: }
16257:
16258: sub course_types {
16259: my @types = ('official','unofficial','community','textbook','placement','lti');
16260: my %typename = (
16261: official => 'Official course',
16262: unofficial => 'Unofficial course',
16263: community => 'Community',
16264: textbook => 'Textbook course',
16265: placement => 'Placement test',
16266: lti => 'LTI provider',
16267: );
16268: return (\@types,\%typename);
16269: }
16270:
16271: sub icon {
16272: my ($file)=@_;
16273: my $curfext = lc((split(/\./,$file))[-1]);
16274: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
16275: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
16276: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
16277: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
16278: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16279: $curfext.".gif") {
16280: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16281: $curfext.".gif";
16282: }
16283: }
16284: return &lonhttpdurl($iconname);
16285: }
16286:
16287: sub lonhttpdurl {
16288: #
16289: # Had been used for "small fry" static images on separate port 8080.
16290: # Modify here if lightweight http functionality desired again.
16291: # Currently eliminated due to increasing firewall issues.
16292: #
16293: my ($url)=@_;
16294: return $url;
16295: }
16296:
16297: sub connection_aborted {
16298: my ($r)=@_;
16299: $r->print(" ");$r->rflush();
16300: my $c = $r->connection;
16301: return $c->aborted();
16302: }
16303:
16304: # Escapes strings that may have embedded 's that will be put into
16305: # strings as 'strings'.
16306: sub escape_single {
16307: my ($input) = @_;
16308: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
16309: $input =~ s/\'/\\\'/g; # Esacpe the 's....
16310: return $input;
16311: }
16312:
16313: # Same as escape_single, but escape's "'s This
16314: # can be used for "strings"
16315: sub escape_double {
16316: my ($input) = @_;
16317: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
16318: $input =~ s/\"/\\\"/g; # Esacpe the "s....
16319: return $input;
16320: }
16321:
16322: # Escapes the last element of a full URL.
16323: sub escape_url {
16324: my ($url) = @_;
16325: my @urlslices = split(/\//, $url,-1);
16326: my $lastitem = &escape(pop(@urlslices));
16327: return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
16328: }
16329:
16330: sub compare_arrays {
16331: my ($arrayref1,$arrayref2) = @_;
16332: my (@difference,%count);
16333: @difference = ();
16334: %count = ();
16335: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
16336: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
16337: foreach my $element (keys(%count)) {
16338: if ($count{$element} == 1) {
16339: push(@difference,$element);
16340: }
16341: }
16342: }
16343: return @difference;
16344: }
16345:
16346: # -------------------------------------------------------- Initialize user login
16347: sub init_user_environment {
16348: my ($r, $username, $domain, $authhost, $form, $args) = @_;
16349: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
16350:
16351: my $public=($username eq 'public' && $domain eq 'public');
16352:
16353: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
16354: my $now=time;
16355:
16356: if ($public) {
16357: my $max_public=100;
16358: my $oldest;
16359: my $oldest_time=0;
16360: for(my $next=1;$next<=$max_public;$next++) {
16361: if (-e $lonids."/publicuser_$next.id") {
16362: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
16363: if ($mtime<$oldest_time || !$oldest_time) {
16364: $oldest_time=$mtime;
16365: $oldest=$next;
16366: }
16367: } else {
16368: $cookie="publicuser_$next";
16369: last;
16370: }
16371: }
16372: if (!$cookie) { $cookie="publicuser_$oldest"; }
16373: } else {
16374: # See if old ID present, if so, remove if this isn't a robot,
16375: # killing any existing non-robot sessions
16376: if (!$args->{'robot'}) {
16377: opendir(DIR,$lonids);
16378: while ($filename=readdir(DIR)) {
16379: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
16380: if ($ENV{'SERVER_PORT'} == 443) {
16381: my $linkedfile;
16382: if (tie(my %oldenv,'GDBM_File',"$lonids/$cookie.id",
16383: &GDBM_READER(),0640)) {
16384: if (exists($oldenv{'user.linkedenv'})) {
16385: $linkedfile = $oldenv{'user.linkedenv'};
16386: }
16387: untie(%oldenv);
16388: }
16389: if (unlink($lonids.'/'.$filename)) {
16390: if ($linkedfile =~ /^[a-f0-9]+_linked\.id$/) {
16391: unlink($lonids.'/'.$linkedfile);
16392: }
16393: }
16394: } else {
16395: unlink($lonids.'/'.$filename);
16396: }
16397: }
16398: }
16399: closedir(DIR);
16400: # If there is a undeleted lockfile for the user's paste buffer remove it.
16401: my $namespace = 'nohist_courseeditor';
16402: my $lockingkey = 'paste'."\0".'locked_num';
16403: my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
16404: $domain,$username);
16405: if (exists($lockhash{$lockingkey})) {
16406: my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
16407: unless ($delresult eq 'ok') {
16408: &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
16409: }
16410: }
16411: }
16412: # Give them a new cookie
16413: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
16414: : $now.$$.int(rand(10000)));
16415: $cookie="$username\_$id\_$domain\_$authhost";
16416:
16417: # Initialize roles
16418:
16419: ($userroles,$firstaccenv,$timerintenv) =
16420: &Apache::lonnet::rolesinit($domain,$username,$authhost);
16421: }
16422: # ------------------------------------ Check browser type and MathML capability
16423:
16424: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
16425: $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
16426:
16427: # ------------------------------------------------------------- Get environment
16428:
16429: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
16430: my ($tmp) = keys(%userenv);
16431: if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
16432: undef(%userenv);
16433: }
16434: if (($userenv{'interface'}) && (!$form->{'interface'})) {
16435: $form->{'interface'}=$userenv{'interface'};
16436: }
16437: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
16438:
16439: # --------------- Do not trust query string to be put directly into environment
16440: foreach my $option ('interface','localpath','localres') {
16441: $form->{$option}=~s/[\n\r\=]//gs;
16442: }
16443: # --------------------------------------------------------- Write first profile
16444:
16445: {
16446: my %initial_env =
16447: ("user.name" => $username,
16448: "user.domain" => $domain,
16449: "user.home" => $authhost,
16450: "browser.type" => $clientbrowser,
16451: "browser.version" => $clientversion,
16452: "browser.mathml" => $clientmathml,
16453: "browser.unicode" => $clientunicode,
16454: "browser.os" => $clientos,
16455: "browser.mobile" => $clientmobile,
16456: "browser.info" => $clientinfo,
16457: "browser.osversion" => $clientosversion,
16458: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
16459: "request.course.fn" => '',
16460: "request.course.uri" => '',
16461: "request.course.sec" => '',
16462: "request.role" => 'cm',
16463: "request.role.adv" => $env{'user.adv'},
16464: "request.host" => $ENV{'REMOTE_ADDR'},);
16465:
16466: if ($form->{'localpath'}) {
16467: $initial_env{"browser.localpath"} = $form->{'localpath'};
16468: $initial_env{"browser.localres"} = $form->{'localres'};
16469: }
16470:
16471: if ($form->{'interface'}) {
16472: $form->{'interface'}=~s/\W//gs;
16473: $initial_env{"browser.interface"} = $form->{'interface'};
16474: $env{'browser.interface'}=$form->{'interface'};
16475: }
16476:
16477: if ($form->{'iptoken'}) {
16478: my $lonhost = $r->dir_config('lonHostID');
16479: $initial_env{"user.noloadbalance"} = $lonhost;
16480: $env{'user.noloadbalance'} = $lonhost;
16481: }
16482:
16483: if ($form->{'noloadbalance'}) {
16484: my @hosts = &Apache::lonnet::current_machine_ids();
16485: my $hosthere = $form->{'noloadbalance'};
16486: if (grep(/^\Q$hosthere\E$/,@hosts)) {
16487: $initial_env{"user.noloadbalance"} = $hosthere;
16488: $env{'user.noloadbalance'} = $hosthere;
16489: }
16490: }
16491:
16492: unless ($domain eq 'public') {
16493: my %is_adv = ( is_adv => $env{'user.adv'} );
16494: my %domdef = &Apache::lonnet::get_domain_defaults($domain);
16495:
16496: foreach my $tool ('aboutme','blog','webdav','portfolio') {
16497: $userenv{'availabletools.'.$tool} =
16498: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
16499: undef,\%userenv,\%domdef,\%is_adv);
16500: }
16501:
16502: foreach my $crstype ('official','unofficial','community','textbook','placement','lti') {
16503: $userenv{'canrequest.'.$crstype} =
16504: &Apache::lonnet::usertools_access($username,$domain,$crstype,
16505: 'reload','requestcourses',
16506: \%userenv,\%domdef,\%is_adv);
16507: }
16508:
16509: $userenv{'canrequest.author'} =
16510: &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
16511: 'reload','requestauthor',
16512: \%userenv,\%domdef,\%is_adv);
16513: my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
16514: $domain,$username);
16515: my $reqstatus = $reqauthor{'author_status'};
16516: if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
16517: if (ref($reqauthor{'author'}) eq 'HASH') {
16518: $userenv{'requestauthorqueued'} = $reqstatus.':'.
16519: $reqauthor{'author'}{'timestamp'};
16520: }
16521: }
16522: my ($types,$typename) = &course_types();
16523: if (ref($types) eq 'ARRAY') {
16524: my @options = ('approval','validate','autolimit');
16525: my $optregex = join('|',@options);
16526: my (%willtrust,%trustchecked);
16527: foreach my $type (@{$types}) {
16528: my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
16529: if ($dom_str ne '') {
16530: my $updatedstr = '';
16531: my @possdomains = split(',',$dom_str);
16532: foreach my $entry (@possdomains) {
16533: my ($extdom,$extopt) = split(':',$entry);
16534: unless ($trustchecked{$extdom}) {
16535: $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$domain,$extdom);
16536: $trustchecked{$extdom} = 1;
16537: }
16538: if ($willtrust{$extdom}) {
16539: $updatedstr .= $entry.',';
16540: }
16541: }
16542: $updatedstr =~ s/,$//;
16543: if ($updatedstr) {
16544: $userenv{'reqcrsotherdom.'.$type} = $updatedstr;
16545: } else {
16546: delete($userenv{'reqcrsotherdom.'.$type});
16547: }
16548: }
16549: }
16550: }
16551: }
16552: $env{'user.environment'} = "$lonids/$cookie.id";
16553:
16554: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
16555: &GDBM_WRCREAT(),0640)) {
16556: &_add_to_env(\%disk_env,\%initial_env);
16557: &_add_to_env(\%disk_env,\%userenv,'environment.');
16558: &_add_to_env(\%disk_env,$userroles);
16559: if (ref($firstaccenv) eq 'HASH') {
16560: &_add_to_env(\%disk_env,$firstaccenv);
16561: }
16562: if (ref($timerintenv) eq 'HASH') {
16563: &_add_to_env(\%disk_env,$timerintenv);
16564: }
16565: if (ref($args->{'extra_env'})) {
16566: &_add_to_env(\%disk_env,$args->{'extra_env'});
16567: }
16568: untie(%disk_env);
16569: } else {
16570: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
16571: 'Could not create environment storage in lonauth: '.$!.'</span>');
16572: return 'error: '.$!;
16573: }
16574: }
16575: $env{'request.role'}='cm';
16576: $env{'request.role.adv'}=$env{'user.adv'};
16577: $env{'browser.type'}=$clientbrowser;
16578:
16579: return $cookie;
16580:
16581: }
16582:
16583: sub _add_to_env {
16584: my ($idf,$env_data,$prefix) = @_;
16585: if (ref($env_data) eq 'HASH') {
16586: while (my ($key,$value) = each(%$env_data)) {
16587: $idf->{$prefix.$key} = $value;
16588: $env{$prefix.$key} = $value;
16589: }
16590: }
16591: }
16592:
16593: # --- Get the symbolic name of a problem and the url
16594: sub get_symb {
16595: my ($request,$silent) = @_;
16596: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
16597: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
16598: if ($symb eq '') {
16599: if (!$silent) {
16600: if (ref($request)) {
16601: $request->print("Unable to handle ambiguous references:$url:.");
16602: }
16603: return ();
16604: }
16605: }
16606: &Apache::lonenc::check_decrypt(\$symb);
16607: return ($symb);
16608: }
16609:
16610: # --------------------------------------------------------------Get annotation
16611:
16612: sub get_annotation {
16613: my ($symb,$enc) = @_;
16614:
16615: my $key = $symb;
16616: if (!$enc) {
16617: $key =
16618: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
16619: }
16620: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
16621: return $annotation{$key};
16622: }
16623:
16624: sub clean_symb {
16625: my ($symb,$delete_enc) = @_;
16626:
16627: &Apache::lonenc::check_decrypt(\$symb);
16628: my $enc = $env{'request.enc'};
16629: if ($delete_enc) {
16630: delete($env{'request.enc'});
16631: }
16632:
16633: return ($symb,$enc);
16634: }
16635:
16636: ############################################################
16637: ############################################################
16638:
16639: =pod
16640:
16641: =head1 Routines for building display used to search for courses
16642:
16643:
16644: =over 4
16645:
16646: =item * &build_filters()
16647:
16648: Create markup for a table used to set filters to use when selecting
16649: courses in a domain. Used by lonpickcourse.pm, lonmodifycourse.pm
16650: and quotacheck.pl
16651:
16652:
16653: Inputs:
16654:
16655: filterlist - anonymous array of fields to include as potential filters
16656:
16657: crstype - course type
16658:
16659: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
16660: to pop-open a course selector (will contain "extra element").
16661:
16662: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
16663:
16664: filter - anonymous hash of criteria and their values
16665:
16666: action - form action
16667:
16668: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
16669:
16670: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
16671:
16672: cloneruname - username of owner of new course who wants to clone
16673:
16674: clonerudom - domain of owner of new course who wants to clone
16675:
16676: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
16677:
16678: codetitlesref - reference to array of titles of components in institutional codes (official courses)
16679:
16680: codedom - domain
16681:
16682: formname - value of form element named "form".
16683:
16684: fixeddom - domain, if fixed.
16685:
16686: prevphase - value to assign to form element named "phase" when going back to the previous screen
16687:
16688: cnameelement - name of form element in form on opener page which will receive title of selected course
16689:
16690: cnumelement - name of form element in form on opener page which will receive courseID of selected course
16691:
16692: cdomelement - name of form element in form on opener page which will receive domain of selected course
16693:
16694: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
16695:
16696: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
16697:
16698: clonewarning - warning message about missing information for intended course owner when DC creates a course
16699:
16700:
16701: Returns: $output - HTML for display of search criteria, and hidden form elements.
16702:
16703:
16704: Side Effects: None
16705:
16706: =cut
16707:
16708: # ---------------------------------------------- search for courses based on last activity etc.
16709:
16710: sub build_filters {
16711: my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
16712: $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
16713: $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
16714: $cnameelement,$cnumelement,$cdomelement,$setroles,
16715: $clonetext,$clonewarning) = @_;
16716: my ($list,$jscript);
16717: my $onchange = 'javascript:updateFilters(this)';
16718: my ($domainselectform,$sincefilterform,$createdfilterform,
16719: $ownerdomselectform,$persondomselectform,$instcodeform,
16720: $typeselectform,$instcodetitle);
16721: if ($formname eq '') {
16722: $formname = $caller;
16723: }
16724: foreach my $item (@{$filterlist}) {
16725: unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
16726: ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
16727: if ($item eq 'domainfilter') {
16728: $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
16729: } elsif ($item eq 'coursefilter') {
16730: $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
16731: } elsif ($item eq 'ownerfilter') {
16732: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16733: } elsif ($item eq 'ownerdomfilter') {
16734: $filter->{'ownerdomfilter'} =
16735: &LONCAPA::clean_domain($filter->{$item});
16736: $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
16737: 'ownerdomfilter',1);
16738: } elsif ($item eq 'personfilter') {
16739: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16740: } elsif ($item eq 'persondomfilter') {
16741: $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
16742: 'persondomfilter',1);
16743: } else {
16744: $filter->{$item} =~ s/\W//g;
16745: }
16746: if (!$filter->{$item}) {
16747: $filter->{$item} = '';
16748: }
16749: }
16750: if ($item eq 'domainfilter') {
16751: my $allow_blank = 1;
16752: if ($formname eq 'portform') {
16753: $allow_blank=0;
16754: } elsif ($formname eq 'studentform') {
16755: $allow_blank=0;
16756: }
16757: if ($fixeddom) {
16758: $domainselectform = '<input type="hidden" name="domainfilter"'.
16759: ' value="'.$codedom.'" />'.
16760: &Apache::lonnet::domain($codedom,'description');
16761: } else {
16762: $domainselectform = &select_dom_form($filter->{$item},
16763: 'domainfilter',
16764: $allow_blank,'',$onchange);
16765: }
16766: } else {
16767: $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
16768: }
16769: }
16770:
16771: # last course activity filter and selection
16772: $sincefilterform = &timebased_select_form('sincefilter',$filter);
16773:
16774: # course created filter and selection
16775: if (exists($filter->{'createdfilter'})) {
16776: $createdfilterform = &timebased_select_form('createdfilter',$filter);
16777: }
16778:
16779: my $prefix = $crstype;
16780: if ($crstype eq 'Placement') {
16781: $prefix = 'Placement Test'
16782: }
16783: my %lt = &Apache::lonlocal::texthash(
16784: 'cac' => "$prefix Activity",
16785: 'ccr' => "$prefix Created",
16786: 'cde' => "$prefix Title",
16787: 'cdo' => "$prefix Domain",
16788: 'ins' => 'Institutional Code',
16789: 'inc' => 'Institutional Categorization',
16790: 'cow' => "$prefix Owner/Co-owner",
16791: 'cop' => "$prefix Personnel Includes",
16792: 'cog' => 'Type',
16793: );
16794:
16795: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16796: my $typeval = 'Course';
16797: if ($crstype eq 'Community') {
16798: $typeval = 'Community';
16799: } elsif ($crstype eq 'Placement') {
16800: $typeval = 'Placement';
16801: }
16802: $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
16803: } else {
16804: $typeselectform = '<select name="type" size="1"';
16805: if ($onchange) {
16806: $typeselectform .= ' onchange="'.$onchange.'"';
16807: }
16808: $typeselectform .= '>'."\n";
16809: foreach my $posstype ('Course','Community','Placement') {
16810: my $shown;
16811: if ($posstype eq 'Placement') {
16812: $shown = &mt('Placement Test');
16813: } else {
16814: $shown = &mt($posstype);
16815: }
16816: $typeselectform.='<option value="'.$posstype.'"'.
16817: ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
16818: }
16819: $typeselectform.="</select>";
16820: }
16821:
16822: my ($cloneableonlyform,$cloneabletitle);
16823: if (exists($filter->{'cloneableonly'})) {
16824: my $cloneableon = '';
16825: my $cloneableoff = ' checked="checked"';
16826: if ($filter->{'cloneableonly'}) {
16827: $cloneableon = $cloneableoff;
16828: $cloneableoff = '';
16829: }
16830: $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>';
16831: if ($formname eq 'ccrs') {
16832: $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
16833: } else {
16834: $cloneabletitle = &mt('Cloneable by you');
16835: }
16836: }
16837: my $officialjs;
16838: if ($crstype eq 'Course') {
16839: if (exists($filter->{'instcodefilter'})) {
16840: # if (($fixeddom) || ($formname eq 'requestcrs') ||
16841: # ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
16842: if ($codedom) {
16843: $officialjs = 1;
16844: ($instcodeform,$jscript,$$numtitlesref) =
16845: &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
16846: $officialjs,$codetitlesref);
16847: if ($jscript) {
16848: $jscript = '<script type="text/javascript">'."\n".
16849: '// <![CDATA['."\n".
16850: $jscript."\n".
16851: '// ]]>'."\n".
16852: '</script>'."\n";
16853: }
16854: }
16855: if ($instcodeform eq '') {
16856: $instcodeform =
16857: '<input type="text" name="instcodefilter" size="10" value="'.
16858: $list->{'instcodefilter'}.'" />';
16859: $instcodetitle = $lt{'ins'};
16860: } else {
16861: $instcodetitle = $lt{'inc'};
16862: }
16863: if ($fixeddom) {
16864: $instcodetitle .= '<br />('.$codedom.')';
16865: }
16866: }
16867: }
16868: my $output = qq|
16869: <form method="post" name="filterpicker" action="$action">
16870: <input type="hidden" name="form" value="$formname" />
16871: |;
16872: if ($formname eq 'modifycourse') {
16873: $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
16874: '<input type="hidden" name="prevphase" value="'.
16875: $prevphase.'" />'."\n";
16876: } elsif ($formname eq 'quotacheck') {
16877: $output .= qq|
16878: <input type="hidden" name="sortby" value="" />
16879: <input type="hidden" name="sortorder" value="" />
16880: |;
16881: } else {
16882: my $name_input;
16883: if ($cnameelement ne '') {
16884: $name_input = '<input type="hidden" name="cnameelement" value="'.
16885: $cnameelement.'" />';
16886: }
16887: $output .= qq|
16888: <input type="hidden" name="cnumelement" value="$cnumelement" />
16889: <input type="hidden" name="cdomelement" value="$cdomelement" />
16890: $name_input
16891: $roleelement
16892: $multelement
16893: $typeelement
16894: |;
16895: if ($formname eq 'portform') {
16896: $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
16897: }
16898: }
16899: if ($fixeddom) {
16900: $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
16901: }
16902: $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
16903: if ($sincefilterform) {
16904: $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
16905: .$sincefilterform
16906: .&Apache::lonhtmlcommon::row_closure();
16907: }
16908: if ($createdfilterform) {
16909: $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
16910: .$createdfilterform
16911: .&Apache::lonhtmlcommon::row_closure();
16912: }
16913: if ($domainselectform) {
16914: $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
16915: .$domainselectform
16916: .&Apache::lonhtmlcommon::row_closure();
16917: }
16918: if ($typeselectform) {
16919: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16920: $output .= $typeselectform;
16921: } else {
16922: $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
16923: .$typeselectform
16924: .&Apache::lonhtmlcommon::row_closure();
16925: }
16926: }
16927: if ($instcodeform) {
16928: $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
16929: .$instcodeform
16930: .&Apache::lonhtmlcommon::row_closure();
16931: }
16932: if (exists($filter->{'ownerfilter'})) {
16933: $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
16934: '<table><tr><td>'.&mt('Username').'<br />'.
16935: '<input type="text" name="ownerfilter" size="20" value="'.
16936: $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16937: $ownerdomselectform.'</td></tr></table>'.
16938: &Apache::lonhtmlcommon::row_closure();
16939: }
16940: if (exists($filter->{'personfilter'})) {
16941: $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
16942: '<table><tr><td>'.&mt('Username').'<br />'.
16943: '<input type="text" name="personfilter" size="20" value="'.
16944: $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16945: $persondomselectform.'</td></tr></table>'.
16946: &Apache::lonhtmlcommon::row_closure();
16947: }
16948: if (exists($filter->{'coursefilter'})) {
16949: $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
16950: .'<input type="text" name="coursefilter" size="25" value="'
16951: .$list->{'coursefilter'}.'" />'
16952: .&Apache::lonhtmlcommon::row_closure();
16953: }
16954: if ($cloneableonlyform) {
16955: $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
16956: $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
16957: }
16958: if (exists($filter->{'descriptfilter'})) {
16959: $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
16960: .'<input type="text" name="descriptfilter" size="40" value="'
16961: .$list->{'descriptfilter'}.'" />'
16962: .&Apache::lonhtmlcommon::row_closure(1);
16963: }
16964: $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
16965: '<input type="hidden" name="updater" value="" />'."\n".
16966: '<input type="submit" name="gosearch" value="'.
16967: &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
16968: return $jscript.$clonewarning.$output;
16969: }
16970:
16971: =pod
16972:
16973: =item * &timebased_select_form()
16974:
16975: Create markup for a dropdown list used to select a time-based
16976: filter e.g., Course Activity, Course Created, when searching for courses
16977: or communities
16978:
16979: Inputs:
16980:
16981: item - name of form element (sincefilter or createdfilter)
16982:
16983: filter - anonymous hash of criteria and their values
16984:
16985: Returns: HTML for a select box contained a blank, then six time selections,
16986: with value set in incoming form variables currently selected.
16987:
16988: Side Effects: None
16989:
16990: =cut
16991:
16992: sub timebased_select_form {
16993: my ($item,$filter) = @_;
16994: if (ref($filter) eq 'HASH') {
16995: $filter->{$item} =~ s/[^\d-]//g;
16996: if (!$filter->{$item}) { $filter->{$item}=-1; }
16997: return &select_form(
16998: $filter->{$item},
16999: $item,
17000: { '-1' => '',
17001: '86400' => &mt('today'),
17002: '604800' => &mt('last week'),
17003: '2592000' => &mt('last month'),
17004: '7776000' => &mt('last three months'),
17005: '15552000' => &mt('last six months'),
17006: '31104000' => &mt('last year'),
17007: 'select_form_order' =>
17008: ['-1','86400','604800','2592000','7776000',
17009: '15552000','31104000']});
17010: }
17011: }
17012:
17013: =pod
17014:
17015: =item * &js_changer()
17016:
17017: Create script tag containing Javascript used to submit course search form
17018: when course type or domain is changed, and also to hide 'Searching ...' on
17019: page load completion for page showing search result.
17020:
17021: Inputs: None
17022:
17023: Returns: markup containing updateFilters() and hideSearching() javascript functions.
17024:
17025: Side Effects: None
17026:
17027: =cut
17028:
17029: sub js_changer {
17030: return <<ENDJS;
17031: <script type="text/javascript">
17032: // <![CDATA[
17033: function updateFilters(caller) {
17034: if (typeof(caller) != "undefined") {
17035: document.filterpicker.updater.value = caller.name;
17036: }
17037: document.filterpicker.submit();
17038: }
17039:
17040: function hideSearching() {
17041: if (document.getElementById('searching')) {
17042: document.getElementById('searching').style.display = 'none';
17043: }
17044: return;
17045: }
17046:
17047: // ]]>
17048: </script>
17049:
17050: ENDJS
17051: }
17052:
17053: =pod
17054:
17055: =item * &search_courses()
17056:
17057: Process selected filters form course search form and pass to lonnet::courseiddump
17058: to retrieve a hash for which keys are courseIDs which match the selected filters.
17059:
17060: Inputs:
17061:
17062: dom - domain being searched
17063:
17064: type - course type ('Course' or 'Community' or '.' if any).
17065:
17066: filter - anonymous hash of criteria and their values
17067:
17068: numtitles - for institutional codes - number of categories
17069:
17070: cloneruname - optional username of new course owner
17071:
17072: clonerudom - optional domain of new course owner
17073:
17074: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
17075: (used when DC is using course creation form)
17076:
17077: codetitles - reference to array of titles of components in institutional codes (official courses).
17078:
17079: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
17080: (and so can clone automatically)
17081:
17082: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
17083:
17084: reqinstcode - institutional code of new course, where search_courses is used to identify potential
17085: courses to clone
17086:
17087: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
17088:
17089:
17090: Side Effects: None
17091:
17092: =cut
17093:
17094:
17095: sub search_courses {
17096: my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
17097: $cc_clone,$reqcrsdom,$reqinstcode) = @_;
17098: my (%courses,%showcourses,$cloner);
17099: if (($filter->{'ownerfilter'} ne '') ||
17100: ($filter->{'ownerdomfilter'} ne '')) {
17101: $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
17102: $filter->{'ownerdomfilter'};
17103: }
17104: foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
17105: if (!$filter->{$item}) {
17106: $filter->{$item}='.';
17107: }
17108: }
17109: my $now = time;
17110: my $timefilter =
17111: ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
17112: my ($createdbefore,$createdafter);
17113: if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
17114: $createdbefore = $now;
17115: $createdafter = $now-$filter->{'createdfilter'};
17116: }
17117: my ($instcodefilter,$regexpok);
17118: if ($numtitles) {
17119: if ($env{'form.official'} eq 'on') {
17120: $instcodefilter =
17121: &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17122: $regexpok = 1;
17123: } elsif ($env{'form.official'} eq 'off') {
17124: $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17125: unless ($instcodefilter eq '') {
17126: $regexpok = -1;
17127: }
17128: }
17129: } else {
17130: $instcodefilter = $filter->{'instcodefilter'};
17131: }
17132: if ($instcodefilter eq '') { $instcodefilter = '.'; }
17133: if ($type eq '') { $type = '.'; }
17134:
17135: if (($clonerudom ne '') && ($cloneruname ne '')) {
17136: $cloner = $cloneruname.':'.$clonerudom;
17137: }
17138: %courses = &Apache::lonnet::courseiddump($dom,
17139: $filter->{'descriptfilter'},
17140: $timefilter,
17141: $instcodefilter,
17142: $filter->{'combownerfilter'},
17143: $filter->{'coursefilter'},
17144: undef,undef,$type,$regexpok,undef,undef,
17145: undef,undef,$cloner,$cc_clone,
17146: $filter->{'cloneableonly'},
17147: $createdbefore,$createdafter,undef,
17148: $domcloner,undef,$reqcrsdom,$reqinstcode);
17149: if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
17150: my $ccrole;
17151: if ($type eq 'Community') {
17152: $ccrole = 'co';
17153: } else {
17154: $ccrole = 'cc';
17155: }
17156: my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
17157: $filter->{'persondomfilter'},
17158: 'userroles',undef,
17159: [$ccrole,'in','ad','ep','ta','cr'],
17160: $dom);
17161: foreach my $role (keys(%rolehash)) {
17162: my ($cnum,$cdom,$courserole) = split(':',$role);
17163: my $cid = $cdom.'_'.$cnum;
17164: if (exists($courses{$cid})) {
17165: if (ref($courses{$cid}) eq 'HASH') {
17166: if (ref($courses{$cid}{roles}) eq 'ARRAY') {
17167: if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
17168: push(@{$courses{$cid}{roles}},$courserole);
17169: }
17170: } else {
17171: $courses{$cid}{roles} = [$courserole];
17172: }
17173: $showcourses{$cid} = $courses{$cid};
17174: }
17175: }
17176: }
17177: %courses = %showcourses;
17178: }
17179: return %courses;
17180: }
17181:
17182: =pod
17183:
17184: =back
17185:
17186: =head1 Routines for version requirements for current course.
17187:
17188: =over 4
17189:
17190: =item * &check_release_required()
17191:
17192: Compares required LON-CAPA version with version on server, and
17193: if required version is newer looks for a server with the required version.
17194:
17195: Looks first at servers in user's owen domain; if none suitable, looks at
17196: servers in course's domain are permitted to host sessions for user's domain.
17197:
17198: Inputs:
17199:
17200: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17201:
17202: $courseid - Course ID of current course
17203:
17204: $rolecode - User's current role in course (for switchserver query string).
17205:
17206: $required - LON-CAPA version needed by course (format: Major.Minor).
17207:
17208:
17209: Returns:
17210:
17211: $switchserver - query string tp append to /adm/switchserver call (if
17212: current server's LON-CAPA version is too old.
17213:
17214: $warning - Message is displayed if no suitable server could be found.
17215:
17216: =cut
17217:
17218: sub check_release_required {
17219: my ($loncaparev,$courseid,$rolecode,$required) = @_;
17220: my ($switchserver,$warning);
17221: if ($required ne '') {
17222: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
17223: my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17224: if ($reqdmajor ne '' && $reqdminor ne '') {
17225: my $otherserver;
17226: if (($major eq '' && $minor eq '') ||
17227: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
17228: my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
17229: my $switchlcrev =
17230: &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
17231: $userdomserver);
17232: my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17233: if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
17234: (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
17235: my $cdom = $env{'course.'.$courseid.'.domain'};
17236: if ($cdom ne $env{'user.domain'}) {
17237: my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
17238: my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
17239: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17240: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
17241: my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
17242: my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
17243: my $canhost =
17244: &Apache::lonnet::can_host_session($env{'user.domain'},
17245: $coursedomserver,
17246: $remoterev,
17247: $udomdefaults{'remotesessions'},
17248: $defdomdefaults{'hostedsessions'});
17249:
17250: if ($canhost) {
17251: $otherserver = $coursedomserver;
17252: } else {
17253: $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.");
17254: }
17255: } else {
17256: $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).");
17257: }
17258: } else {
17259: $otherserver = $userdomserver;
17260: }
17261: }
17262: if ($otherserver ne '') {
17263: $switchserver = 'otherserver='.$otherserver.'&role='.$rolecode;
17264: }
17265: }
17266: }
17267: return ($switchserver,$warning);
17268: }
17269:
17270: =pod
17271:
17272: =item * &check_release_result()
17273:
17274: Inputs:
17275:
17276: $switchwarning - Warning message if no suitable server found to host session.
17277:
17278: $switchserver - query string to append to /adm/switchserver containing lonHostID
17279: and current role.
17280:
17281: Returns: HTML to display with information about requirement to switch server.
17282: Either displaying warning with link to Roles/Courses screen or
17283: display link to switchserver.
17284:
17285: =cut
17286:
17287: sub check_release_result {
17288: my ($switchwarning,$switchserver) = @_;
17289: my $output = &start_page('Selected course unavailable on this server').
17290: '<p class="LC_warning">';
17291: if ($switchwarning) {
17292: $output .= $switchwarning.'<br /><a href="/adm/roles">';
17293: if (&show_course()) {
17294: $output .= &mt('Display courses');
17295: } else {
17296: $output .= &mt('Display roles');
17297: }
17298: $output .= '</a>';
17299: } elsif ($switchserver) {
17300: $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
17301: '<br />'.
17302: '<a href="/adm/switchserver?'.$switchserver.'">'.
17303: &mt('Switch Server').
17304: '</a>';
17305: }
17306: $output .= '</p>'.&end_page();
17307: return $output;
17308: }
17309:
17310: =pod
17311:
17312: =item * &needs_coursereinit()
17313:
17314: Determine if course contents stored for user's session needs to be
17315: refreshed, because content has changed since "Big Hash" last tied.
17316:
17317: Check for change is made if time last checked is more than 10 minutes ago
17318: (by default).
17319:
17320: Inputs:
17321:
17322: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17323:
17324: $interval (optional) - Time which may elapse (in s) between last check for content
17325: change in current course. (default: 600 s).
17326:
17327: Returns: an array; first element is:
17328:
17329: =over 4
17330:
17331: 'switch' - if content updates mean user's session
17332: needs to be switched to a server running a newer LON-CAPA version
17333:
17334: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
17335: on current server hosting user's session
17336:
17337: '' - if no action required.
17338:
17339: =back
17340:
17341: If first item element is 'switch':
17342:
17343: second item is $switchwarning - Warning message if no suitable server found to host session.
17344:
17345: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
17346: and current role.
17347:
17348: otherwise: no other elements returned.
17349:
17350: =back
17351:
17352: =cut
17353:
17354: sub needs_coursereinit {
17355: my ($loncaparev,$interval) = @_;
17356: return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
17357: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17358: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17359: my $now = time;
17360: if ($interval eq '') {
17361: $interval = 600;
17362: }
17363: if (($now-$env{'request.course.timechecked'})>$interval) {
17364: &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
17365: my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
17366: if ($blocked) {
17367: return ();
17368: }
17369: my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
17370: if ($lastchange > $env{'request.course.tied'}) {
17371: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17372: if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
17373: my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
17374: if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
17375: &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
17376: $curr_reqd_hash{'internal.releaserequired'}});
17377: my ($switchserver,$switchwarning) =
17378: &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
17379: $curr_reqd_hash{'internal.releaserequired'});
17380: if ($switchwarning ne '' || $switchserver ne '') {
17381: return ('switch',$switchwarning,$switchserver);
17382: }
17383: }
17384: }
17385: return ('update');
17386: }
17387: }
17388: return ();
17389: }
17390:
17391: sub update_content_constraints {
17392: my ($cdom,$cnum,$chome,$cid) = @_;
17393: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17394: my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
17395: my (%checkresponsetypes,%checkcrsrestypes);
17396: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
17397: my ($item,$name,$value) = split(/:/,$key);
17398: if ($item eq 'resourcetag') {
17399: if ($name eq 'responsetype') {
17400: $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
17401: }
17402: } elsif ($item eq 'course') {
17403: if ($name eq 'courserestype') {
17404: $checkcrsrestypes{$value} = $Apache::lonnet::needsrelease{$key};
17405: }
17406: }
17407: }
17408: my $navmap = Apache::lonnavmaps::navmap->new();
17409: if (defined($navmap)) {
17410: my (%allresponses,%allcrsrestypes);
17411: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() || $_[0]->is_tool() },1,0)) {
17412: if ($res->is_tool()) {
17413: if ($allcrsrestypes{'exttool'}) {
17414: $allcrsrestypes{'exttool'} ++;
17415: } else {
17416: $allcrsrestypes{'exttool'} = 1;
17417: }
17418: next;
17419: }
17420: my %responses = $res->responseTypes();
17421: foreach my $key (keys(%responses)) {
17422: next unless(exists($checkresponsetypes{$key}));
17423: $allresponses{$key} += $responses{$key};
17424: }
17425: }
17426: foreach my $key (keys(%allresponses)) {
17427: my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
17428: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17429: ($reqdmajor,$reqdminor) = ($major,$minor);
17430: }
17431: }
17432: foreach my $key (keys(%allcrsrestypes)) {
17433: my ($major,$minor) = split(/\./,$checkcrsrestypes{$key});
17434: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17435: ($reqdmajor,$reqdminor) = ($major,$minor);
17436: }
17437: }
17438: undef($navmap);
17439: }
17440: my $suppmap = 'supplemental.sequence';
17441: my ($suppcount,$supptools,$errors) = (0,0,0);
17442: ($suppcount,$supptools,$errors) = &recurse_supplemental($cnum,$cdom,$suppmap,
17443: $suppcount,$supptools,$errors);
17444: if ($supptools) {
17445: my ($major,$minor) = split(/\./,$checkcrsrestypes{'exttool'});
17446: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17447: ($reqdmajor,$reqdminor) = ($major,$minor);
17448: }
17449: }
17450: unless (($reqdmajor eq '') && ($reqdminor eq '')) {
17451: &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
17452: }
17453: return;
17454: }
17455:
17456: sub allmaps_incourse {
17457: my ($cdom,$cnum,$chome,$cid) = @_;
17458: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
17459: $cid = $env{'request.course.id'};
17460: $cdom = $env{'course.'.$cid.'.domain'};
17461: $cnum = $env{'course.'.$cid.'.num'};
17462: $chome = $env{'course.'.$cid.'.home'};
17463: }
17464: my %allmaps = ();
17465: my $lastchange =
17466: &Apache::lonnet::get_coursechange($cdom,$cnum);
17467: if ($lastchange > $env{'request.course.tied'}) {
17468: my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
17469: unless ($ferr) {
17470: &update_content_constraints($cdom,$cnum,$chome,$cid);
17471: }
17472: }
17473: my $navmap = Apache::lonnavmaps::navmap->new();
17474: if (defined($navmap)) {
17475: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
17476: $allmaps{$res->src()} = 1;
17477: }
17478: }
17479: return \%allmaps;
17480: }
17481:
17482: sub parse_supplemental_title {
17483: my ($title) = @_;
17484:
17485: my ($foldertitle,$renametitle);
17486: if ($title =~ /&&&/) {
17487: $title = &HTML::Entites::decode($title);
17488: }
17489: if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
17490: $renametitle=$4;
17491: my ($time,$uname,$udom) = ($1,$2,$3);
17492: $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
17493: my $name = &plainname($uname,$udom);
17494: $name = &HTML::Entities::encode($name,'"<>&\'');
17495: $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
17496: $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
17497: $name.': <br />'.$foldertitle;
17498: }
17499: if (wantarray) {
17500: return ($title,$foldertitle,$renametitle);
17501: }
17502: return $title;
17503: }
17504:
17505: sub recurse_supplemental {
17506: my ($cnum,$cdom,$suppmap,$numfiles,$numexttools,$errors) = @_;
17507: if ($suppmap) {
17508: my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
17509: if ($fatal) {
17510: $errors ++;
17511: } else {
17512: if ($#LONCAPA::map::resources > 0) {
17513: foreach my $res (@LONCAPA::map::resources) {
17514: my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
17515: if (($src ne '') && ($status eq 'res')) {
17516: if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
17517: ($numfiles,$numexttools,$errors) = &recurse_supplemental($cnum,$cdom,$1,
17518: $numfiles,$numexttools,$errors);
17519: } else {
17520: if ($src =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
17521: $numexttools ++;
17522: }
17523: $numfiles ++;
17524: }
17525: }
17526: }
17527: }
17528: }
17529: }
17530: return ($numfiles,$numexttools,$errors);
17531: }
17532:
17533: sub symb_to_docspath {
17534: my ($symb,$navmapref) = @_;
17535: return unless ($symb && ref($navmapref));
17536: my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
17537: if ($resurl=~/\.(sequence|page)$/) {
17538: $mapurl=$resurl;
17539: } elsif ($resurl eq 'adm/navmaps') {
17540: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
17541: }
17542: my $mapresobj;
17543: unless (ref($$navmapref)) {
17544: $$navmapref = Apache::lonnavmaps::navmap->new();
17545: }
17546: if (ref($$navmapref)) {
17547: $mapresobj = $$navmapref->getResourceByUrl($mapurl);
17548: }
17549: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
17550: my $type=$2;
17551: my $path;
17552: if (ref($mapresobj)) {
17553: my $pcslist = $mapresobj->map_hierarchy();
17554: if ($pcslist ne '') {
17555: foreach my $pc (split(/,/,$pcslist)) {
17556: next if ($pc <= 1);
17557: my $res = $$navmapref->getByMapPc($pc);
17558: if (ref($res)) {
17559: my $thisurl = $res->src();
17560: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
17561: my $thistitle = $res->title();
17562: $path .= '&'.
17563: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
17564: &escape($thistitle).
17565: ':'.$res->randompick().
17566: ':'.$res->randomout().
17567: ':'.$res->encrypted().
17568: ':'.$res->randomorder().
17569: ':'.$res->is_page();
17570: }
17571: }
17572: }
17573: $path =~ s/^\&//;
17574: my $maptitle = $mapresobj->title();
17575: if ($mapurl eq 'default') {
17576: $maptitle = 'Main Content';
17577: }
17578: $path .= (($path ne '')? '&' : '').
17579: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17580: &escape($maptitle).
17581: ':'.$mapresobj->randompick().
17582: ':'.$mapresobj->randomout().
17583: ':'.$mapresobj->encrypted().
17584: ':'.$mapresobj->randomorder().
17585: ':'.$mapresobj->is_page();
17586: } else {
17587: my $maptitle = &Apache::lonnet::gettitle($mapurl);
17588: my $ispage = (($type eq 'page')? 1 : '');
17589: if ($mapurl eq 'default') {
17590: $maptitle = 'Main Content';
17591: }
17592: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17593: &escape($maptitle).':::::'.$ispage;
17594: }
17595: unless ($mapurl eq 'default') {
17596: $path = 'default&'.
17597: &escape('Main Content').
17598: ':::::&'.$path;
17599: }
17600: return $path;
17601: }
17602:
17603: sub captcha_display {
17604: my ($context,$lonhost) = @_;
17605: my ($output,$error);
17606: my ($captcha,$pubkey,$privkey,$version) =
17607: &get_captcha_config($context,$lonhost);
17608: if ($captcha eq 'original') {
17609: $output = &create_captcha();
17610: unless ($output) {
17611: $error = 'captcha';
17612: }
17613: } elsif ($captcha eq 'recaptcha') {
17614: $output = &create_recaptcha($pubkey,$version);
17615: unless ($output) {
17616: $error = 'recaptcha';
17617: }
17618: }
17619: return ($output,$error,$captcha,$version);
17620: }
17621:
17622: sub captcha_response {
17623: my ($context,$lonhost) = @_;
17624: my ($captcha_chk,$captcha_error);
17625: my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
17626: if ($captcha eq 'original') {
17627: ($captcha_chk,$captcha_error) = &check_captcha();
17628: } elsif ($captcha eq 'recaptcha') {
17629: $captcha_chk = &check_recaptcha($privkey,$version);
17630: } else {
17631: $captcha_chk = 1;
17632: }
17633: return ($captcha_chk,$captcha_error);
17634: }
17635:
17636: sub get_captcha_config {
17637: my ($context,$lonhost) = @_;
17638: my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
17639: my $hostname = &Apache::lonnet::hostname($lonhost);
17640: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
17641: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17642: if ($context eq 'usercreation') {
17643: my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
17644: if (ref($domconfig{$context}) eq 'HASH') {
17645: $hashtocheck = $domconfig{$context}{'cancreate'};
17646: if (ref($hashtocheck) eq 'HASH') {
17647: if ($hashtocheck->{'captcha'} eq 'recaptcha') {
17648: if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
17649: $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
17650: $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
17651: }
17652: if ($privkey && $pubkey) {
17653: $captcha = 'recaptcha';
17654: $version = $hashtocheck->{'recaptchaversion'};
17655: if ($version ne '2') {
17656: $version = 1;
17657: }
17658: } else {
17659: $captcha = 'original';
17660: }
17661: } elsif ($hashtocheck->{'captcha'} ne 'notused') {
17662: $captcha = 'original';
17663: }
17664: }
17665: } else {
17666: $captcha = 'captcha';
17667: }
17668: } elsif ($context eq 'login') {
17669: my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
17670: if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
17671: $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
17672: $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
17673: if ($privkey && $pubkey) {
17674: $captcha = 'recaptcha';
17675: $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
17676: if ($version ne '2') {
17677: $version = 1;
17678: }
17679: } else {
17680: $captcha = 'original';
17681: }
17682: } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
17683: $captcha = 'original';
17684: }
17685: }
17686: return ($captcha,$pubkey,$privkey,$version);
17687: }
17688:
17689: sub create_captcha {
17690: my %captcha_params = &captcha_settings();
17691: my ($output,$maxtries,$tries) = ('',10,0);
17692: while ($tries < $maxtries) {
17693: $tries ++;
17694: my $captcha = Authen::Captcha->new (
17695: output_folder => $captcha_params{'output_dir'},
17696: data_folder => $captcha_params{'db_dir'},
17697: );
17698: my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
17699:
17700: if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
17701: $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
17702: &mt('Type in the letters/numbers shown below').' '.
17703: '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
17704: '<br />'.
17705: '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
17706: last;
17707: }
17708: }
17709: return $output;
17710: }
17711:
17712: sub captcha_settings {
17713: my %captcha_params = (
17714: output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'},
17715: www_output_dir => "/captchaspool",
17716: db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'},
17717: numchars => '5',
17718: );
17719: return %captcha_params;
17720: }
17721:
17722: sub check_captcha {
17723: my ($captcha_chk,$captcha_error);
17724: my $code = $env{'form.code'};
17725: my $md5sum = $env{'form.crypt'};
17726: my %captcha_params = &captcha_settings();
17727: my $captcha = Authen::Captcha->new(
17728: output_folder => $captcha_params{'output_dir'},
17729: data_folder => $captcha_params{'db_dir'},
17730: );
17731: $captcha_chk = $captcha->check_code($code,$md5sum);
17732: my %captcha_hash = (
17733: 0 => 'Code not checked (file error)',
17734: -1 => 'Failed: code expired',
17735: -2 => 'Failed: invalid code (not in database)',
17736: -3 => 'Failed: invalid code (code does not match crypt)',
17737: );
17738: if ($captcha_chk != 1) {
17739: $captcha_error = $captcha_hash{$captcha_chk}
17740: }
17741: return ($captcha_chk,$captcha_error);
17742: }
17743:
17744: sub create_recaptcha {
17745: my ($pubkey,$version) = @_;
17746: if ($version >= 2) {
17747: return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
17748: } else {
17749: my $use_ssl;
17750: if ($ENV{'SERVER_PORT'} == 443) {
17751: $use_ssl = 1;
17752: }
17753: my $captcha = Captcha::reCAPTCHA->new;
17754: return $captcha->get_options_setter({theme => 'white'})."\n".
17755: $captcha->get_html($pubkey,undef,$use_ssl).
17756: &mt('If the text is hard to read, [_1] will replace them.',
17757: '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
17758: '<br /><br />';
17759: }
17760: }
17761:
17762: sub check_recaptcha {
17763: my ($privkey,$version) = @_;
17764: my $captcha_chk;
17765: if ($version >= 2) {
17766: my %info = (
17767: secret => $privkey,
17768: response => $env{'form.g-recaptcha-response'},
17769: remoteip => $ENV{'REMOTE_ADDR'},
17770: );
17771: my $request=new HTTP::Request('POST','https://www.google.com/recaptcha/api/siteverify');
17772: $request->content(join('&',map {
17773: my $name = escape($_);
17774: "$name=" . ( ref($info{$_}) eq 'ARRAY'
17775: ? join("&$name=", map {escape($_) } @{$info{$_}})
17776: : &escape($info{$_}) );
17777: } keys(%info)));
17778: my $response = &LONCAPA::LWPReq::makerequest('',$request,'','',10,1);
17779: if ($response->is_success) {
17780: my $data = JSON::DWIW->from_json($response->decoded_content);
17781: if (ref($data) eq 'HASH') {
17782: if ($data->{'success'}) {
17783: $captcha_chk = 1;
17784: }
17785: }
17786: }
17787: } else {
17788: my $captcha = Captcha::reCAPTCHA->new;
17789: my $captcha_result =
17790: $captcha->check_answer(
17791: $privkey,
17792: $ENV{'REMOTE_ADDR'},
17793: $env{'form.recaptcha_challenge_field'},
17794: $env{'form.recaptcha_response_field'},
17795: );
17796: if ($captcha_result->{is_valid}) {
17797: $captcha_chk = 1;
17798: }
17799: }
17800: return $captcha_chk;
17801: }
17802:
17803: sub emailusername_info {
17804: my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
17805: my %titles = &Apache::lonlocal::texthash (
17806: lastname => 'Last Name',
17807: firstname => 'First Name',
17808: institution => 'School/college/university',
17809: location => "School's city, state/province, country",
17810: web => "School's web address",
17811: officialemail => 'E-mail address at institution (if different)',
17812: id => 'Student/Employee ID',
17813: );
17814: return (\@fields,\%titles);
17815: }
17816:
17817: sub cleanup_html {
17818: my ($incoming) = @_;
17819: my $outgoing;
17820: if ($incoming ne '') {
17821: $outgoing = $incoming;
17822: $outgoing =~ s/;/;/g;
17823: $outgoing =~ s/\#/#/g;
17824: $outgoing =~ s/\&/&/g;
17825: $outgoing =~ s/</</g;
17826: $outgoing =~ s/>/>/g;
17827: $outgoing =~ s/\(/(/g;
17828: $outgoing =~ s/\)/)/g;
17829: $outgoing =~ s/"/"/g;
17830: $outgoing =~ s/'/'/g;
17831: $outgoing =~ s/\$/$/g;
17832: $outgoing =~ s{/}{/}g;
17833: $outgoing =~ s/=/=/g;
17834: $outgoing =~ s/\\/\/g
17835: }
17836: return $outgoing;
17837: }
17838:
17839: # Checks for critical messages and returns a redirect url if one exists.
17840: # $interval indicates how often to check for messages.
17841: # $context is the calling context -- roles, grades, contents, menu or flip.
17842: sub critical_redirect {
17843: my ($interval,$context) = @_;
17844: if ((time-$env{'user.criticalcheck.time'})>$interval) {
17845: if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
17846: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17847: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17848: my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
17849: if ($blocked) {
17850: my $checkrole = "cm./$cdom/$cnum";
17851: if ($env{'request.course.sec'} ne '') {
17852: $checkrole .= "/$env{'request.course.sec'}";
17853: }
17854: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
17855: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
17856: return;
17857: }
17858: }
17859: }
17860: my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
17861: $env{'user.name'});
17862: &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
17863: my $redirecturl;
17864: if ($what[0]) {
17865: if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
17866: $redirecturl='/adm/email?critical=display';
17867: my $url=&Apache::lonnet::absolute_url().$redirecturl;
17868: return (1, $url);
17869: }
17870: }
17871: }
17872: return ();
17873: }
17874:
17875: # Use:
17876: # my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
17877: #
17878: ##################################################
17879: # password associated functions #
17880: ##################################################
17881: sub des_keys {
17882: # Make a new key for DES encryption.
17883: # Each key has two parts which are returned separately.
17884: # Please note: Each key must be passed through the &hex function
17885: # before it is output to the web browser. The hex versions cannot
17886: # be used to decrypt.
17887: my @hexstr=('0','1','2','3','4','5','6','7',
17888: '8','9','a','b','c','d','e','f');
17889: my $lkey='';
17890: for (0..7) {
17891: $lkey.=$hexstr[rand(15)];
17892: }
17893: my $ukey='';
17894: for (0..7) {
17895: $ukey.=$hexstr[rand(15)];
17896: }
17897: return ($lkey,$ukey);
17898: }
17899:
17900: sub des_decrypt {
17901: my ($key,$cyphertext) = @_;
17902: my $keybin=pack("H16",$key);
17903: my $cypher;
17904: if ($Crypt::DES::VERSION>=2.03) {
17905: $cypher=new Crypt::DES $keybin;
17906: } else {
17907: $cypher=new DES $keybin;
17908: }
17909: my $plaintext='';
17910: my $cypherlength = length($cyphertext);
17911: my $numchunks = int($cypherlength/32);
17912: for (my $j=0; $j<$numchunks; $j++) {
17913: my $start = $j*32;
17914: my $cypherblock = substr($cyphertext,$start,32);
17915: my $chunk =
17916: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
17917: $chunk .=
17918: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
17919: $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
17920: $plaintext .= $chunk;
17921: }
17922: return $plaintext;
17923: }
17924:
17925: sub make_short_symbs {
17926: my ($cdom,$cnum,$navmap) = @_;
17927: return unless (ref($navmap));
17928: my ($numnew,@errors);
17929: my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
17930: if (@toshorten) {
17931: my (%maps,%resources,%titles);
17932: &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
17933: 'shorturls',$cdom,$cnum);
17934: my %tocreate;
17935: if (keys(%resources)) {
17936: foreach my $item (sort {$a <=> $b} (@toshorten)) {
17937: my $symb = $resources{$item};
17938: if ($symb) {
17939: $tocreate{$cnum.'&'.$symb} = 1;
17940: }
17941: }
17942: }
17943: if (keys(%tocreate)) {
17944: my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
17945: my $su = Short::URL->new(no_vowels => 1);
17946: my $init = '';
17947: my (%newunique,%addcourse,%courseonly,%failed);
17948: # get lock on tiny db
17949: my $now = time;
17950: my $lockhash = {
17951: "lock\0$now" => $env{'user.name'}.
17952: ':'.$env{'user.domain'},
17953: };
17954: my $tries = 0;
17955: my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
17956: my ($code,$error);
17957: while (($gotlock ne 'ok') && ($tries<3)) {
17958: $tries ++;
17959: sleep 1;
17960: $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
17961: }
17962: if ($gotlock eq 'ok') {
17963: $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
17964: \%addcourse,\%courseonly,\%failed);
17965: if (keys(%failed)) {
17966: my $numfailed = scalar(keys(%failed));
17967: push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
17968: }
17969: if (keys(%newunique)) {
17970: my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
17971: if ($putres eq 'ok') {
17972: $numnew = scalar(keys(%newunique));
17973: my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
17974: unless ($newputres eq 'ok') {
17975: push(@errors,&mt('error: could not store course look-up of short URLs'));
17976: }
17977: } else {
17978: push(@errors,&mt('error: could not store unique six character URLs'));
17979: }
17980: }
17981: my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
17982: unless ($dellockres eq 'ok') {
17983: push(@errors,&mt('error: could not release lockfile'));
17984: }
17985: } else {
17986: push(@errors,&mt('error: could not obtain lockfile'));
17987: }
17988: if (keys(%courseonly)) {
17989: my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
17990: if ($result ne 'ok') {
17991: push(@errors,&mt('error: could not update course look-up of short URLs'));
17992: }
17993: }
17994: }
17995: }
17996: return ($numnew,\@errors);
17997: }
17998:
17999: sub shorten_symbs {
18000: my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
18001: return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
18002: (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
18003: (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
18004: my (%possibles,%collisions);
18005: foreach my $key (keys(%{$tocreate})) {
18006: my $num = String::CRC32::crc32($key);
18007: my $tiny = $su->encode($num,$init);
18008: if ($tiny) {
18009: $possibles{$tiny} = $key;
18010: }
18011: }
18012: if (!$init) {
18013: $init = 1;
18014: } else {
18015: $init ++;
18016: }
18017: if (keys(%possibles)) {
18018: my @posstiny = keys(%possibles);
18019: my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
18020: my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
18021: if (keys(%currtiny)) {
18022: foreach my $key (keys(%currtiny)) {
18023: next if ($currtiny{$key} eq '');
18024: if ($currtiny{$key} eq $possibles{$key}) {
18025: my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
18026: unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18027: $courseonly->{$tsymb} = $key;
18028: }
18029: } else {
18030: $collisions{$possibles{$key}} = 1;
18031: }
18032: delete($possibles{$key});
18033: }
18034: }
18035: foreach my $key (keys(%possibles)) {
18036: $newunique->{$key} = $possibles{$key};
18037: my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
18038: unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18039: $addcourse->{$tsymb} = $key;
18040: }
18041: }
18042: }
18043: if (keys(%collisions)) {
18044: if ($init <5) {
18045: if (!$init) {
18046: $init = 1;
18047: } else {
18048: $init ++;
18049: }
18050: $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
18051: $newunique,$addcourse,$courseonly,$failed);
18052: } else {
18053: foreach my $key (keys(%collisions)) {
18054: $failed->{$key} = 1;
18055: }
18056: }
18057: }
18058: return $init;
18059: }
18060:
18061: 1;
18062: __END__;
18063:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>