File:
[LON-CAPA] /
loncom /
interface /
loncommon.pm
Revision
1.1256:
download - view:
text,
annotated -
select for diffs
Tue Oct 11 22:58:55 2016 UTC (7 years, 10 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- vpa priv allows Course Settings to be viewed, but not modified.
- users with vpa priv in a course receive "View parameter settings
(due dates, etc) for resources and the course" item in the Main Menu,
and a Settings item in the inline menu.
1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1256 2016/10/11 22:58:55 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: # Makes a table out of the previous attempts
30: # Inputs result_from_symbread, user, domain, course_id
31: # Reads in non-network-related .tab files
32:
33: # POD header:
34:
35: =pod
36:
37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
45:
46: =head1 OVERVIEW
47:
48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
55: package Apache::loncommon;
56:
57: use strict;
58: use Apache::lonnet;
59: use GDBM_File;
60: use POSIX qw(strftime mktime);
61: use Apache::lonmenu();
62: use Apache::lonenc();
63: use Apache::lonlocal;
64: use Apache::lonnet();
65: use HTML::Entities;
66: use Apache::lonhtmlcommon();
67: use Apache::loncoursedata();
68: use Apache::lontexconvert();
69: use Apache::lonclonecourse();
70: use Apache::lonuserutils();
71: use Apache::lonuserstate();
72: use Apache::courseclassifier();
73: use LONCAPA qw(:DEFAULT :match);
74: use DateTime::TimeZone;
75: use DateTime::Locale;
76: use Encode();
77: use Text::Aspell;
78: use Authen::Captcha;
79: use Captcha::reCAPTCHA;
80: use JSON::DWIW;
81: use LWP::UserAgent;
82: use Crypt::DES;
83: use DynaLoader; # for Crypt::DES version
84: use MIME::Lite;
85: use MIME::Types;
86:
87: # ---------------------------------------------- Designs
88: use vars qw(%defaultdesign);
89:
90: my $readit;
91:
92:
93: ##
94: ## Global Variables
95: ##
96:
97:
98: # ----------------------------------------------- SSI with retries:
99: #
100:
101: =pod
102:
103: =head1 Server Side include with retries:
104:
105: =over 4
106:
107: =item * &ssi_with_retries(resource,retries form)
108:
109: Performs an ssi with some number of retries. Retries continue either
110: until the result is ok or until the retry count supplied by the
111: caller is exhausted.
112:
113: Inputs:
114:
115: =over 4
116:
117: resource - Identifies the resource to insert.
118:
119: retries - Count of the number of retries allowed.
120:
121: form - Hash that identifies the rendering options.
122:
123: =back
124:
125: Returns:
126:
127: =over 4
128:
129: content - The content of the response. If retries were exhausted this is empty.
130:
131: response - The response from the last attempt (which may or may not have been successful.
132:
133: =back
134:
135: =back
136:
137: =cut
138:
139: sub ssi_with_retries {
140: my ($resource, $retries, %form) = @_;
141:
142:
143: my $ok = 0; # True if we got a good response.
144: my $content;
145: my $response;
146:
147: # Try to get the ssi done. within the retries count:
148:
149: do {
150: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
151: $ok = $response->is_success;
152: if (!$ok) {
153: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
154: }
155: $retries--;
156: } while (!$ok && ($retries > 0));
157:
158: if (!$ok) {
159: $content = ''; # On error return an empty content.
160: }
161: return ($content, $response);
162:
163: }
164:
165:
166:
167: # ----------------------------------------------- Filetypes/Languages/Copyright
168: my %language;
169: my %supported_language;
170: my %supported_codes;
171: my %latex_language; # For choosing hyphenation in <transl..>
172: my %latex_language_bykey; # for choosing hyphenation from metadata
173: my %cprtag;
174: my %scprtag;
175: my %fe; my %fd; my %fm;
176: my %category_extensions;
177:
178: # ---------------------------------------------- Thesaurus variables
179: #
180: # %Keywords:
181: # A hash used by &keyword to determine if a word is considered a keyword.
182: # $thesaurus_db_file
183: # Scalar containing the full path to the thesaurus database.
184:
185: my %Keywords;
186: my $thesaurus_db_file;
187:
188: #
189: # Initialize values from language.tab, copyright.tab, filetypes.tab,
190: # thesaurus.tab, and filecategories.tab.
191: #
192: BEGIN {
193: # Variable initialization
194: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
195: #
196: unless ($readit) {
197: # ------------------------------------------------------------------- languages
198: {
199: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
200: '/language.tab';
201: if ( open(my $fh,"<$langtabfile") ) {
202: while (my $line = <$fh>) {
203: next if ($line=~/^\#/);
204: chomp($line);
205: my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
206: $language{$key}=$val.' - '.$enc;
207: if ($sup) {
208: $supported_language{$key}=$sup;
209: $supported_codes{$key} = $code;
210: }
211: if ($latex) {
212: $latex_language_bykey{$key} = $latex;
213: $latex_language{$code} = $latex;
214: }
215: }
216: close($fh);
217: }
218: }
219: # ------------------------------------------------------------------ copyrights
220: {
221: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
222: '/copyright.tab';
223: if ( open (my $fh,"<$copyrightfile") ) {
224: while (my $line = <$fh>) {
225: next if ($line=~/^\#/);
226: chomp($line);
227: my ($key,$val)=(split(/\s+/,$line,2));
228: $cprtag{$key}=$val;
229: }
230: close($fh);
231: }
232: }
233: # ----------------------------------------------------------- source copyrights
234: {
235: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
236: '/source_copyright.tab';
237: if ( open (my $fh,"<$sourcecopyrightfile") ) {
238: while (my $line = <$fh>) {
239: next if ($line =~ /^\#/);
240: chomp($line);
241: my ($key,$val)=(split(/\s+/,$line,2));
242: $scprtag{$key}=$val;
243: }
244: close($fh);
245: }
246: }
247:
248: # -------------------------------------------------------------- default domain designs
249: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
250: my $designfile = $designdir.'/default.tab';
251: if ( open (my $fh,"<$designfile") ) {
252: while (my $line = <$fh>) {
253: next if ($line =~ /^\#/);
254: chomp($line);
255: my ($key,$val)=(split(/\=/,$line));
256: if ($val) { $defaultdesign{$key}=$val; }
257: }
258: close($fh);
259: }
260:
261: # ------------------------------------------------------------- file categories
262: {
263: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
264: '/filecategories.tab';
265: if ( open (my $fh,"<$categoryfile") ) {
266: while (my $line = <$fh>) {
267: next if ($line =~ /^\#/);
268: chomp($line);
269: my ($extension,$category)=(split(/\s+/,$line,2));
270: push @{$category_extensions{lc($category)}},$extension;
271: }
272: close($fh);
273: }
274:
275: }
276: # ------------------------------------------------------------------ file types
277: {
278: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
279: '/filetypes.tab';
280: if ( open (my $fh,"<$typesfile") ) {
281: while (my $line = <$fh>) {
282: next if ($line =~ /^\#/);
283: chomp($line);
284: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
285: if ($descr ne '') {
286: $fe{$ending}=lc($emb);
287: $fd{$ending}=$descr;
288: if ($mime ne 'unk') { $fm{$ending}=$mime; }
289: }
290: }
291: close($fh);
292: }
293: }
294: &Apache::lonnet::logthis(
295: "<span style='color:yellow;'>INFO: Read file types</span>");
296: $readit=1;
297: } # end of unless($readit)
298:
299: }
300:
301: ###############################################################
302: ## HTML and Javascript Helper Functions ##
303: ###############################################################
304:
305: =pod
306:
307: =head1 HTML and Javascript Functions
308:
309: =over 4
310:
311: =item * &browser_and_searcher_javascript()
312:
313: X<browsing, javascript>X<searching, javascript>Returns a string
314: containing javascript with two functions, C<openbrowser> and
315: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
316: tags.
317:
318: =item * &openbrowser(formname,elementname,only,omit) [javascript]
319:
320: inputs: formname, elementname, only, omit
321:
322: formname and elementname indicate the name of the html form and name of
323: the element that the results of the browsing selection are to be placed in.
324:
325: Specifying 'only' will restrict the browser to displaying only files
326: with the given extension. Can be a comma separated list.
327:
328: Specifying 'omit' will restrict the browser to NOT displaying files
329: with the given extension. Can be a comma separated list.
330:
331: =item * &opensearcher(formname,elementname) [javascript]
332:
333: Inputs: formname, elementname
334:
335: formname and elementname specify the name of the html form and the name
336: of the element the selection from the search results will be placed in.
337:
338: =cut
339:
340: sub browser_and_searcher_javascript {
341: my ($mode)=@_;
342: if (!defined($mode)) { $mode='edit'; }
343: my $resurl=&escape_single(&lastresurl());
344: return <<END;
345: // <!-- BEGIN LON-CAPA Internal
346: var editbrowser = null;
347: function openbrowser(formname,elementname,only,omit,titleelement) {
348: var url = '$resurl/?';
349: if (editbrowser == null) {
350: url += 'launch=1&';
351: }
352: url += 'catalogmode=interactive&';
353: url += 'mode=$mode&';
354: url += 'inhibitmenu=yes&';
355: url += 'form=' + formname + '&';
356: if (only != null) {
357: url += 'only=' + only + '&';
358: } else {
359: url += 'only=&';
360: }
361: if (omit != null) {
362: url += 'omit=' + omit + '&';
363: } else {
364: url += 'omit=&';
365: }
366: if (titleelement != null) {
367: url += 'titleelement=' + titleelement + '&';
368: } else {
369: url += 'titleelement=&';
370: }
371: url += 'element=' + elementname + '';
372: var title = 'Browser';
373: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
374: options += ',width=700,height=600';
375: editbrowser = open(url,title,options,'1');
376: editbrowser.focus();
377: }
378: var editsearcher;
379: function opensearcher(formname,elementname,titleelement) {
380: var url = '/adm/searchcat?';
381: if (editsearcher == null) {
382: url += 'launch=1&';
383: }
384: url += 'catalogmode=interactive&';
385: url += 'mode=$mode&';
386: url += 'form=' + formname + '&';
387: if (titleelement != null) {
388: url += 'titleelement=' + titleelement + '&';
389: } else {
390: url += 'titleelement=&';
391: }
392: url += 'element=' + elementname + '';
393: var title = 'Search';
394: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
395: options += ',width=700,height=600';
396: editsearcher = open(url,title,options,'1');
397: editsearcher.focus();
398: }
399: // END LON-CAPA Internal -->
400: END
401: }
402:
403: sub lastresurl {
404: if ($env{'environment.lastresurl'}) {
405: return $env{'environment.lastresurl'}
406: } else {
407: return '/res';
408: }
409: }
410:
411: sub storeresurl {
412: my $resurl=&Apache::lonnet::clutter(shift);
413: unless ($resurl=~/^\/res/) { return 0; }
414: $resurl=~s/\/$//;
415: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
416: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
417: return 1;
418: }
419:
420: sub studentbrowser_javascript {
421: unless (
422: (($env{'request.course.id'}) &&
423: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
424: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
425: '/'.$env{'request.course.sec'})
426: ))
427: || ($env{'request.role'}=~/^(au|dc|su)/)
428: ) { return ''; }
429: return (<<'ENDSTDBRW');
430: <script type="text/javascript" language="Javascript">
431: // <![CDATA[
432: var stdeditbrowser;
433: function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
434: var url = '/adm/pickstudent?';
435: var filter;
436: if (!ignorefilter) {
437: eval('filter=document.'+formname+'.'+uname+'.value;');
438: }
439: if (filter != null) {
440: if (filter != '') {
441: url += 'filter='+filter+'&';
442: }
443: }
444: url += 'form=' + formname + '&unameelement='+uname+
445: '&udomelement='+udom+
446: '&clicker='+clicker;
447: if (roleflag) { url+="&roles=1"; }
448: if (courseadvonly) { url+="&courseadvonly=1"; }
449: var title = 'Student_Browser';
450: var options = 'scrollbars=1,resizable=1,menubar=0';
451: options += ',width=700,height=600';
452: stdeditbrowser = open(url,title,options,'1');
453: stdeditbrowser.focus();
454: }
455: // ]]>
456: </script>
457: ENDSTDBRW
458: }
459:
460: sub resourcebrowser_javascript {
461: unless ($env{'request.course.id'}) { return ''; }
462: return (<<'ENDRESBRW');
463: <script type="text/javascript" language="Javascript">
464: // <![CDATA[
465: var reseditbrowser;
466: function openresbrowser(formname,reslink) {
467: var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
468: var title = 'Resource_Browser';
469: var options = 'scrollbars=1,resizable=1,menubar=0';
470: options += ',width=700,height=500';
471: reseditbrowser = open(url,title,options,'1');
472: reseditbrowser.focus();
473: }
474: // ]]>
475: </script>
476: ENDRESBRW
477: }
478:
479: sub selectstudent_link {
480: my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
481: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
482: &Apache::lonhtmlcommon::entity_encode($unameele)."','".
483: &Apache::lonhtmlcommon::entity_encode($udomele)."'";
484: if ($env{'request.course.id'}) {
485: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
486: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
487: '/'.$env{'request.course.sec'})) {
488: return '';
489: }
490: $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
491: if ($courseadvonly) {
492: $callargs .= ",'',1,1";
493: }
494: return '<span class="LC_nobreak">'.
495: '<a href="javascript:openstdbrowser('.$callargs.');">'.
496: &mt('Select User').'</a></span>';
497: }
498: if ($env{'request.role'}=~/^(au|dc|su)/) {
499: $callargs .= ",'',1";
500: return '<span class="LC_nobreak">'.
501: '<a href="javascript:openstdbrowser('.$callargs.');">'.
502: &mt('Select User').'</a></span>';
503: }
504: return '';
505: }
506:
507: sub selectresource_link {
508: my ($form,$reslink,$arg)=@_;
509:
510: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
511: &Apache::lonhtmlcommon::entity_encode($reslink)."'";
512: unless ($env{'request.course.id'}) { return $arg; }
513: return '<span class="LC_nobreak">'.
514: '<a href="javascript:openresbrowser('.$callargs.');">'.
515: $arg.'</a></span>';
516: }
517:
518:
519:
520: sub authorbrowser_javascript {
521: return <<"ENDAUTHORBRW";
522: <script type="text/javascript" language="JavaScript">
523: // <![CDATA[
524: var stdeditbrowser;
525:
526: function openauthorbrowser(formname,udom) {
527: var url = '/adm/pickauthor?';
528: url += 'form='+formname+'&roledom='+udom;
529: var title = 'Author_Browser';
530: var options = 'scrollbars=1,resizable=1,menubar=0';
531: options += ',width=700,height=600';
532: stdeditbrowser = open(url,title,options,'1');
533: stdeditbrowser.focus();
534: }
535:
536: // ]]>
537: </script>
538: ENDAUTHORBRW
539: }
540:
541: sub coursebrowser_javascript {
542: my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
543: $credits_element,$instcode) = @_;
544: my $wintitle = 'Course_Browser';
545: if ($crstype eq 'Community') {
546: $wintitle = 'Community_Browser';
547: }
548: my $id_functions = &javascript_index_functions();
549: my $output = '
550: <script type="text/javascript" language="JavaScript">
551: // <![CDATA[
552: var stdeditbrowser;'."\n";
553:
554: $output .= <<"ENDSTDBRW";
555: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
556: var url = '/adm/pickcourse?';
557: var formid = getFormIdByName(formname);
558: var domainfilter = getDomainFromSelectbox(formname,udom);
559: if (domainfilter != null) {
560: if (domainfilter != '') {
561: url += 'domainfilter='+domainfilter+'&';
562: }
563: }
564: url += 'form=' + formname + '&cnumelement='+uname+
565: '&cdomelement='+udom+
566: '&cnameelement='+desc;
567: if (extra_element !=null && extra_element != '') {
568: if (formname == 'rolechoice' || formname == 'studentform') {
569: url += '&roleelement='+extra_element;
570: if (domainfilter == null || domainfilter == '') {
571: url += '&domainfilter='+extra_element;
572: }
573: }
574: else {
575: if (formname == 'portform') {
576: url += '&setroles='+extra_element;
577: } else {
578: if (formname == 'rules') {
579: url += '&fixeddom='+extra_element;
580: }
581: }
582: }
583: }
584: if (type != null && type != '') {
585: url += '&type='+type;
586: }
587: if (type_elem != null && type_elem != '') {
588: url += '&typeelement='+type_elem;
589: }
590: if (formname == 'ccrs') {
591: var ownername = document.forms[formid].ccuname.value;
592: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
593: url += '&cloner='+ownername+':'+ownerdom;
594: if (type == 'Course') {
595: url += '&crscode='+document.forms[formid].crscode.value;
596: }
597: }
598: if (formname == 'requestcrs') {
599: url += '&crsdom=$domainfilter&crscode=$instcode';
600: }
601: if (multflag !=null && multflag != '') {
602: url += '&multiple='+multflag;
603: }
604: var title = '$wintitle';
605: var options = 'scrollbars=1,resizable=1,menubar=0';
606: options += ',width=700,height=600';
607: stdeditbrowser = open(url,title,options,'1');
608: stdeditbrowser.focus();
609: }
610: $id_functions
611: ENDSTDBRW
612: if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
613: $output .= &setsec_javascript($sec_element,$formname,$role_element,
614: $credits_element);
615: }
616: $output .= '
617: // ]]>
618: </script>';
619: return $output;
620: }
621:
622: sub javascript_index_functions {
623: return <<"ENDJS";
624:
625: function getFormIdByName(formname) {
626: for (var i=0;i<document.forms.length;i++) {
627: if (document.forms[i].name == formname) {
628: return i;
629: }
630: }
631: return -1;
632: }
633:
634: function getIndexByName(formid,item) {
635: for (var i=0;i<document.forms[formid].elements.length;i++) {
636: if (document.forms[formid].elements[i].name == item) {
637: return i;
638: }
639: }
640: return -1;
641: }
642:
643: function getDomainFromSelectbox(formname,udom) {
644: var userdom;
645: var formid = getFormIdByName(formname);
646: if (formid > -1) {
647: var domid = getIndexByName(formid,udom);
648: if (domid > -1) {
649: if (document.forms[formid].elements[domid].type == 'select-one') {
650: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
651: }
652: if (document.forms[formid].elements[domid].type == 'hidden') {
653: userdom=document.forms[formid].elements[domid].value;
654: }
655: }
656: }
657: return userdom;
658: }
659:
660: ENDJS
661:
662: }
663:
664: sub javascript_array_indexof {
665: return <<ENDJS;
666: <script type="text/javascript" language="JavaScript">
667: // <![CDATA[
668:
669: if (!Array.prototype.indexOf) {
670: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
671: "use strict";
672: if (this === void 0 || this === null) {
673: throw new TypeError();
674: }
675: var t = Object(this);
676: var len = t.length >>> 0;
677: if (len === 0) {
678: return -1;
679: }
680: var n = 0;
681: if (arguments.length > 0) {
682: n = Number(arguments[1]);
683: if (n !== n) { // shortcut for verifying if it is NaN
684: n = 0;
685: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
686: n = (n > 0 || -1) * Math.floor(Math.abs(n));
687: }
688: }
689: if (n >= len) {
690: return -1;
691: }
692: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
693: for (; k < len; k++) {
694: if (k in t && t[k] === searchElement) {
695: return k;
696: }
697: }
698: return -1;
699: }
700: }
701:
702: // ]]>
703: </script>
704:
705: ENDJS
706:
707: }
708:
709: sub userbrowser_javascript {
710: my $id_functions = &javascript_index_functions();
711: return <<"ENDUSERBRW";
712:
713: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
714: var url = '/adm/pickuser?';
715: var userdom = getDomainFromSelectbox(formname,udom);
716: if (userdom != null) {
717: if (userdom != '') {
718: url += 'srchdom='+userdom+'&';
719: }
720: }
721: url += 'form=' + formname + '&unameelement='+uname+
722: '&udomelement='+udom+
723: '&ulastelement='+ulast+
724: '&ufirstelement='+ufirst+
725: '&uemailelement='+uemail+
726: '&hideudomelement='+hideudom+
727: '&coursedom='+crsdom;
728: if ((caller != null) && (caller != undefined)) {
729: url += '&caller='+caller;
730: }
731: var title = 'User_Browser';
732: var options = 'scrollbars=1,resizable=1,menubar=0';
733: options += ',width=700,height=600';
734: var stdeditbrowser = open(url,title,options,'1');
735: stdeditbrowser.focus();
736: }
737:
738: function fix_domain (formname,udom,origdom,uname) {
739: var formid = getFormIdByName(formname);
740: if (formid > -1) {
741: var unameid = getIndexByName(formid,uname);
742: var domid = getIndexByName(formid,udom);
743: var hidedomid = getIndexByName(formid,origdom);
744: if (hidedomid > -1) {
745: var fixeddom = document.forms[formid].elements[hidedomid].value;
746: var unameval = document.forms[formid].elements[unameid].value;
747: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
748: if (domid > -1) {
749: var slct = document.forms[formid].elements[domid];
750: if (slct.type == 'select-one') {
751: var i;
752: for (i=0;i<slct.length;i++) {
753: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
754: }
755: }
756: if (slct.type == 'hidden') {
757: slct.value = fixeddom;
758: }
759: }
760: }
761: }
762: }
763: return;
764: }
765:
766: $id_functions
767: ENDUSERBRW
768: }
769:
770: sub setsec_javascript {
771: my ($sec_element,$formname,$role_element,$credits_element) = @_;
772: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
773: $communityrolestr);
774: if ($role_element ne '') {
775: my @allroles = ('st','ta','ep','in','ad');
776: foreach my $crstype ('Course','Community') {
777: if ($crstype eq 'Community') {
778: foreach my $role (@allroles) {
779: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
780: }
781: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
782: } else {
783: foreach my $role (@allroles) {
784: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
785: }
786: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
787: }
788: }
789: $rolestr = '"'.join('","',@allroles).'"';
790: $courserolestr = '"'.join('","',@courserolenames).'"';
791: $communityrolestr = '"'.join('","',@communityrolenames).'"';
792: }
793: my $setsections = qq|
794: function setSect(sectionlist) {
795: var sectionsArray = new Array();
796: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
797: sectionsArray = sectionlist.split(",");
798: }
799: var numSections = sectionsArray.length;
800: document.$formname.$sec_element.length = 0;
801: if (numSections == 0) {
802: document.$formname.$sec_element.multiple=false;
803: document.$formname.$sec_element.size=1;
804: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
805: } else {
806: if (numSections == 1) {
807: document.$formname.$sec_element.multiple=false;
808: document.$formname.$sec_element.size=1;
809: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
810: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
811: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
812: } else {
813: for (var i=0; i<numSections; i++) {
814: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
815: }
816: document.$formname.$sec_element.multiple=true
817: if (numSections < 3) {
818: document.$formname.$sec_element.size=numSections;
819: } else {
820: document.$formname.$sec_element.size=3;
821: }
822: document.$formname.$sec_element.options[0].selected = false
823: }
824: }
825: }
826:
827: function setRole(crstype) {
828: |;
829: if ($role_element eq '') {
830: $setsections .= ' return;
831: }
832: ';
833: } else {
834: $setsections .= qq|
835: var elementLength = document.$formname.$role_element.length;
836: var allroles = Array($rolestr);
837: var courserolenames = Array($courserolestr);
838: var communityrolenames = Array($communityrolestr);
839: if (elementLength != undefined) {
840: if (document.$formname.$role_element.options[5].value == 'cc') {
841: if (crstype == 'Course') {
842: return;
843: } else {
844: allroles[5] = 'co';
845: for (var i=0; i<6; i++) {
846: document.$formname.$role_element.options[i].value = allroles[i];
847: document.$formname.$role_element.options[i].text = communityrolenames[i];
848: }
849: }
850: } else {
851: if (crstype == 'Community') {
852: return;
853: } else {
854: allroles[5] = 'cc';
855: for (var i=0; i<6; i++) {
856: document.$formname.$role_element.options[i].value = allroles[i];
857: document.$formname.$role_element.options[i].text = courserolenames[i];
858: }
859: }
860: }
861: }
862: return;
863: }
864: |;
865: }
866: if ($credits_element) {
867: $setsections .= qq|
868: function setCredits(defaultcredits) {
869: document.$formname.$credits_element.value = defaultcredits;
870: return;
871: }
872: |;
873: }
874: return $setsections;
875: }
876:
877: sub selectcourse_link {
878: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
879: $typeelement) = @_;
880: my $type = $selecttype;
881: my $linktext = &mt('Select Course');
882: if ($selecttype eq 'Community') {
883: $linktext = &mt('Select Community');
884: } elsif ($selecttype eq 'Placement') {
885: $linktext = &mt('Select Placement Test');
886: } elsif ($selecttype eq 'Course/Community') {
887: $linktext = &mt('Select Course/Community');
888: $type = '';
889: } elsif ($selecttype eq 'Select') {
890: $linktext = &mt('Select');
891: $type = '';
892: }
893: return '<span class="LC_nobreak">'
894: ."<a href='"
895: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
896: .'","'.$udomele.'","'.$desc.'","'.$extra_element
897: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
898: ."'>".$linktext.'</a>'
899: .'</span>';
900: }
901:
902: sub selectauthor_link {
903: my ($form,$udom)=@_;
904: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
905: &mt('Select Author').'</a>';
906: }
907:
908: sub selectuser_link {
909: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
910: $coursedom,$linktext,$caller) = @_;
911: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
912: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
913: ');">'.$linktext.'</a>';
914: }
915:
916: sub check_uncheck_jscript {
917: my $jscript = <<"ENDSCRT";
918: function checkAll(field) {
919: if (field.length > 0) {
920: for (i = 0; i < field.length; i++) {
921: if (!field[i].disabled) {
922: field[i].checked = true;
923: }
924: }
925: } else {
926: if (!field.disabled) {
927: field.checked = true;
928: }
929: }
930: }
931:
932: function uncheckAll(field) {
933: if (field.length > 0) {
934: for (i = 0; i < field.length; i++) {
935: field[i].checked = false ;
936: }
937: } else {
938: field.checked = false ;
939: }
940: }
941: ENDSCRT
942: return $jscript;
943: }
944:
945: sub select_timezone {
946: my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
947: my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
948: if ($includeempty) {
949: $output .= '<option value=""';
950: if (($selected eq '') || ($selected eq 'local')) {
951: $output .= ' selected="selected" ';
952: }
953: $output .= '> </option>';
954: }
955: my @timezones = DateTime::TimeZone->all_names;
956: foreach my $tzone (@timezones) {
957: $output.= '<option value="'.$tzone.'"';
958: if ($tzone eq $selected) {
959: $output.=' selected="selected"';
960: }
961: $output.=">$tzone</option>\n";
962: }
963: $output.="</select>";
964: return $output;
965: }
966:
967: sub select_datelocale {
968: my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
969: my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
970: if ($includeempty) {
971: $output .= '<option value=""';
972: if ($selected eq '') {
973: $output .= ' selected="selected" ';
974: }
975: $output .= '> </option>';
976: }
977: my @languages = &Apache::lonlocal::preferred_languages();
978: my (@possibles,%locale_names);
979: my @locales = DateTime::Locale->ids();
980: foreach my $id (@locales) {
981: if ($id ne '') {
982: my ($en_terr,$native_terr);
983: my $loc = DateTime::Locale->load($id);
984: if (ref($loc)) {
985: $en_terr = $loc->name();
986: $native_terr = $loc->native_name();
987: if (grep(/^en$/,@languages) || !@languages) {
988: if ($en_terr ne '') {
989: $locale_names{$id} = '('.$en_terr.')';
990: } elsif ($native_terr ne '') {
991: $locale_names{$id} = $native_terr;
992: }
993: } else {
994: if ($native_terr ne '') {
995: $locale_names{$id} = $native_terr.' ';
996: } elsif ($en_terr ne '') {
997: $locale_names{$id} = '('.$en_terr.')';
998: }
999: }
1000: $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1001: push(@possibles,$id);
1002: }
1003: }
1004: }
1005: foreach my $item (sort(@possibles)) {
1006: $output.= '<option value="'.$item.'"';
1007: if ($item eq $selected) {
1008: $output.=' selected="selected"';
1009: }
1010: $output.=">$item";
1011: if ($locale_names{$item} ne '') {
1012: $output.=' '.$locale_names{$item};
1013: }
1014: $output.="</option>\n";
1015: }
1016: $output.="</select>";
1017: return $output;
1018: }
1019:
1020: sub select_language {
1021: my ($name,$selected,$includeempty,$noedit) = @_;
1022: my %langchoices;
1023: if ($includeempty) {
1024: %langchoices = ('' => 'No language preference');
1025: }
1026: foreach my $id (&languageids()) {
1027: my $code = &supportedlanguagecode($id);
1028: if ($code) {
1029: $langchoices{$code} = &plainlanguagedescription($id);
1030: }
1031: }
1032: %langchoices = &Apache::lonlocal::texthash(%langchoices);
1033: return &select_form($selected,$name,\%langchoices,undef,$noedit);
1034: }
1035:
1036: =pod
1037:
1038:
1039: =item * &list_languages()
1040:
1041: Returns an array reference that is suitable for use in language prompters.
1042: Each array element is itself a two element array. The first element
1043: is the language code. The second element a descsriptiuon of the
1044: language itself. This is suitable for use in e.g.
1045: &Apache::edit::select_arg (once dereferenced that is).
1046:
1047: =cut
1048:
1049: sub list_languages {
1050: my @lang_choices;
1051:
1052: foreach my $id (&languageids()) {
1053: my $code = &supportedlanguagecode($id);
1054: if ($code) {
1055: my $selector = $supported_codes{$id};
1056: my $description = &plainlanguagedescription($id);
1057: push (@lang_choices, [$selector, $description]);
1058: }
1059: }
1060: return \@lang_choices;
1061: }
1062:
1063: =pod
1064:
1065: =item * &linked_select_forms(...)
1066:
1067: linked_select_forms returns a string containing a <script></script> block
1068: and html for two <select> menus. The select menus will be linked in that
1069: changing the value of the first menu will result in new values being placed
1070: in the second menu. The values in the select menu will appear in alphabetical
1071: order unless a defined order is provided.
1072:
1073: linked_select_forms takes the following ordered inputs:
1074:
1075: =over 4
1076:
1077: =item * $formname, the name of the <form> tag
1078:
1079: =item * $middletext, the text which appears between the <select> tags
1080:
1081: =item * $firstdefault, the default value for the first menu
1082:
1083: =item * $firstselectname, the name of the first <select> tag
1084:
1085: =item * $secondselectname, the name of the second <select> tag
1086:
1087: =item * $hashref, a reference to a hash containing the data for the menus.
1088:
1089: =item * $menuorder, the order of values in the first menu
1090:
1091: =item * $onchangefirst, additional javascript call to execute for an onchange
1092: event for the first <select> tag
1093:
1094: =item * $onchangesecond, additional javascript call to execute for an onchange
1095: event for the second <select> tag
1096:
1097: =item * $suffix, to differentiate separate uses of select2data javascript
1098: objects in a page.
1099:
1100: =back
1101:
1102: Below is an example of such a hash. Only the 'text', 'default', and
1103: 'select2' keys must appear as stated. keys(%menu) are the possible
1104: values for the first select menu. The text that coincides with the
1105: first menu value is given in $menu{$choice1}->{'text'}. The values
1106: and text for the second menu are given in the hash pointed to by
1107: $menu{$choice1}->{'select2'}.
1108:
1109: my %menu = ( A1 => { text =>"Choice A1" ,
1110: default => "B3",
1111: select2 => {
1112: B1 => "Choice B1",
1113: B2 => "Choice B2",
1114: B3 => "Choice B3",
1115: B4 => "Choice B4"
1116: },
1117: order => ['B4','B3','B1','B2'],
1118: },
1119: A2 => { text =>"Choice A2" ,
1120: default => "C2",
1121: select2 => {
1122: C1 => "Choice C1",
1123: C2 => "Choice C2",
1124: C3 => "Choice C3"
1125: },
1126: order => ['C2','C1','C3'],
1127: },
1128: A3 => { text =>"Choice A3" ,
1129: default => "D6",
1130: select2 => {
1131: D1 => "Choice D1",
1132: D2 => "Choice D2",
1133: D3 => "Choice D3",
1134: D4 => "Choice D4",
1135: D5 => "Choice D5",
1136: D6 => "Choice D6",
1137: D7 => "Choice D7"
1138: },
1139: order => ['D4','D3','D2','D1','D7','D6','D5'],
1140: }
1141: );
1142:
1143: =cut
1144:
1145: sub linked_select_forms {
1146: my ($formname,
1147: $middletext,
1148: $firstdefault,
1149: $firstselectname,
1150: $secondselectname,
1151: $hashref,
1152: $menuorder,
1153: $onchangefirst,
1154: $onchangesecond,
1155: $suffix
1156: ) = @_;
1157: my $second = "document.$formname.$secondselectname";
1158: my $first = "document.$formname.$firstselectname";
1159: # output the javascript to do the changing
1160: my $result = '';
1161: $result.='<script type="text/javascript" language="JavaScript">'."\n";
1162: $result.="// <![CDATA[\n";
1163: $result.="var select2data${suffix} = new Object();\n";
1164: $" = '","';
1165: my $debug = '';
1166: foreach my $s1 (sort(keys(%$hashref))) {
1167: $result.="select2data${suffix}['d_$s1'] = new Object();\n";
1168: $result.="select2data${suffix}['d_$s1'].def = new String('".
1169: $hashref->{$s1}->{'default'}."');\n";
1170: $result.="select2data${suffix}['d_$s1'].values = new Array(";
1171: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1172: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1173: @s2values = @{$hashref->{$s1}->{'order'}};
1174: }
1175: $result.="\"@s2values\");\n";
1176: $result.="select2data${suffix}['d_$s1'].texts = new Array(";
1177: my @s2texts;
1178: foreach my $value (@s2values) {
1179: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
1180: }
1181: $result.="\"@s2texts\");\n";
1182: }
1183: $"=' ';
1184: $result.= <<"END";
1185:
1186: function select1${suffix}_changed() {
1187: // Determine new choice
1188: var newvalue = "d_" + $first.options[$first.selectedIndex].value;
1189: // update select2
1190: var values = select2data${suffix}[newvalue].values;
1191: var texts = select2data${suffix}[newvalue].texts;
1192: var select2def = select2data${suffix}[newvalue].def;
1193: var i;
1194: // out with the old
1195: $second.options.length = 0;
1196: // in with the new
1197: for (i=0;i<values.length; i++) {
1198: $second.options[i] = new Option(values[i]);
1199: $second.options[i].value = values[i];
1200: $second.options[i].text = texts[i];
1201: if (values[i] == select2def) {
1202: $second.options[i].selected = true;
1203: }
1204: }
1205: }
1206: // ]]>
1207: </script>
1208: END
1209: # output the initial values for the selection lists
1210: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
1211: my @order = sort(keys(%{$hashref}));
1212: if (ref($menuorder) eq 'ARRAY') {
1213: @order = @{$menuorder};
1214: }
1215: foreach my $value (@order) {
1216: $result.=" <option value=\"$value\" ";
1217: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1218: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1219: }
1220: $result .= "</select>\n";
1221: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1222: $result .= $middletext;
1223: $result .= "<select size=\"1\" name=\"$secondselectname\"";
1224: if ($onchangesecond) {
1225: $result .= ' onchange="'.$onchangesecond.'"';
1226: }
1227: $result .= ">\n";
1228: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1229:
1230: my @secondorder = sort(keys(%select2));
1231: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1232: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1233: }
1234: foreach my $value (@secondorder) {
1235: $result.=" <option value=\"$value\" ";
1236: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1237: $result.=">".&mt($select2{$value})."</option>\n";
1238: }
1239: $result .= "</select>\n";
1240: # return $debug;
1241: return $result;
1242: } # end of sub linked_select_forms {
1243:
1244: =pod
1245:
1246: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1247:
1248: Returns a string corresponding to an HTML link to the given help
1249: $topic, where $topic corresponds to the name of a .tex file in
1250: /home/httpd/html/adm/help/tex, with underscores replaced by
1251: spaces.
1252:
1253: $text will optionally be linked to the same topic, allowing you to
1254: link text in addition to the graphic. If you do not want to link
1255: text, but wish to specify one of the later parameters, pass an
1256: empty string.
1257:
1258: $stayOnPage is a value that will be interpreted as a boolean. If true,
1259: the link will not open a new window. If false, the link will open
1260: a new window using Javascript. (Default is false.)
1261:
1262: $width and $height are optional numerical parameters that will
1263: override the width and height of the popped up window, which may
1264: be useful for certain help topics with big pictures included.
1265:
1266: $imgid is the id of the img tag used for the help icon. This may be
1267: used in a javascript call to switch the image src. See
1268: lonhtmlcommon::htmlareaselectactive() for an example.
1269:
1270: =cut
1271:
1272: sub help_open_topic {
1273: my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1274: $text = "" if (not defined $text);
1275: $stayOnPage = 0 if (not defined $stayOnPage);
1276: $width = 500 if (not defined $width);
1277: $height = 400 if (not defined $height);
1278: my $filename = $topic;
1279: $filename =~ s/ /_/g;
1280:
1281: my $template = "";
1282: my $link;
1283:
1284: $topic=~s/\W/\_/g;
1285:
1286: if (!$stayOnPage) {
1287: $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1288: } elsif ($stayOnPage eq 'popup') {
1289: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1290: } else {
1291: $link = "/adm/help/${filename}.hlp";
1292: }
1293:
1294: # Add the text
1295: if ($text ne "") {
1296: $template.='<span class="LC_help_open_topic">'
1297: .'<a target="_top" href="'.$link.'">'
1298: .$text.'</a>';
1299: }
1300:
1301: # (Always) Add the graphic
1302: my $title = &mt('Online Help');
1303: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1304: if ($imgid ne '') {
1305: $imgid = ' id="'.$imgid.'"';
1306: }
1307: $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
1308: .'<img src="'.$helpicon.'" border="0"'
1309: .' alt="'.&mt('Help: [_1]',$topic).'"'
1310: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
1311: .' /></a>';
1312: if ($text ne "") {
1313: $template.='</span>';
1314: }
1315: return $template;
1316:
1317: }
1318:
1319: # This is a quicky function for Latex cheatsheet editing, since it
1320: # appears in at least four places
1321: sub helpLatexCheatsheet {
1322: my ($topic,$text,$not_author,$stayOnPage) = @_;
1323: my $out;
1324: my $addOther = '';
1325: if ($topic) {
1326: $addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1327: }
1328: $out = '<span>' # Start cheatsheet
1329: .$addOther
1330: .'<span>'
1331: .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1332: .'</span> <span>'
1333: .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1334: .'</span>';
1335: unless ($not_author) {
1336: $out .= '<span>'
1337: .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1338: .'</span> <span>'
1339: .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1340: .'</span>';
1341: }
1342: $out .= '</span>'; # End cheatsheet
1343: return $out;
1344: }
1345:
1346: sub general_help {
1347: my $helptopic='Student_Intro';
1348: if ($env{'request.role'}=~/^(ca|au)/) {
1349: $helptopic='Authoring_Intro';
1350: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1351: $helptopic='Course_Coordination_Intro';
1352: } elsif ($env{'request.role'}=~/^dc/) {
1353: $helptopic='Domain_Coordination_Intro';
1354: }
1355: return $helptopic;
1356: }
1357:
1358: sub update_help_link {
1359: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1360: my $origurl = $ENV{'REQUEST_URI'};
1361: $origurl=~s|^/~|/priv/|;
1362: my $timestamp = time;
1363: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1364: $$datum = &escape($$datum);
1365: }
1366:
1367: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1368: my $output .= <<"ENDOUTPUT";
1369: <script type="text/javascript">
1370: // <![CDATA[
1371: banner_link = '$banner_link';
1372: // ]]>
1373: </script>
1374: ENDOUTPUT
1375: return $output;
1376: }
1377:
1378: # now just updates the help link and generates a blue icon
1379: sub help_open_menu {
1380: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
1381: = @_;
1382: $stayOnPage = 1;
1383: my $output;
1384: if ($component_help) {
1385: if (!$text) {
1386: $output=&help_open_topic($component_help,undef,$stayOnPage,
1387: $width,$height);
1388: } else {
1389: my $help_text;
1390: $help_text=&unescape($topic);
1391: $output='<table><tr><td>'.
1392: &help_open_topic($component_help,$help_text,$stayOnPage,
1393: $width,$height).'</td></tr></table>';
1394: }
1395: }
1396: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1397: return $output.$banner_link;
1398: }
1399:
1400: sub top_nav_help {
1401: my ($text) = @_;
1402: $text = &mt($text);
1403: my $stay_on_page = 1;
1404:
1405: my ($link,$banner_link);
1406: unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
1407: $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1408: : "javascript:helpMenu('open')";
1409: $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1410: }
1411: my $title = &mt('Get help');
1412: if ($link) {
1413: return <<"END";
1414: $banner_link
1415: <a href="$link" title="$title">$text</a>
1416: END
1417: } else {
1418: return ' '.$text.' ';
1419: }
1420: }
1421:
1422: sub help_menu_js {
1423: my ($httphost) = @_;
1424: my $stayOnPage = 1;
1425: my $width = 620;
1426: my $height = 600;
1427: my $helptopic=&general_help();
1428: my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1429: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1430: my $start_page =
1431: &Apache::loncommon::start_page('Help Menu', undef,
1432: {'frameset' => 1,
1433: 'js_ready' => 1,
1434: 'use_absolute' => $httphost,
1435: 'add_entries' => {
1436: 'border' => '0',
1437: 'rows' => "110,*",},});
1438: my $end_page =
1439: &Apache::loncommon::end_page({'frameset' => 1,
1440: 'js_ready' => 1,});
1441:
1442: my $template .= <<"ENDTEMPLATE";
1443: <script type="text/javascript">
1444: // <![CDATA[
1445: // <!-- BEGIN LON-CAPA Internal
1446: var banner_link = '';
1447: function helpMenu(target) {
1448: var caller = this;
1449: if (target == 'open') {
1450: var newWindow = null;
1451: try {
1452: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1453: }
1454: catch(error) {
1455: writeHelp(caller);
1456: return;
1457: }
1458: if (newWindow) {
1459: caller = newWindow;
1460: }
1461: }
1462: writeHelp(caller);
1463: return;
1464: }
1465: function writeHelp(caller) {
1466: caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
1467: caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
1468: caller.document.close();
1469: caller.focus();
1470: }
1471: // END LON-CAPA Internal -->
1472: // ]]>
1473: </script>
1474: ENDTEMPLATE
1475: return $template;
1476: }
1477:
1478: sub help_open_bug {
1479: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1480: unless ($env{'user.adv'}) { return ''; }
1481: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1482: $text = "" if (not defined $text);
1483: $stayOnPage=1;
1484: $width = 600 if (not defined $width);
1485: $height = 600 if (not defined $height);
1486:
1487: $topic=~s/\W+/\+/g;
1488: my $link='';
1489: my $template='';
1490: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1491: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1492: if (!$stayOnPage)
1493: {
1494: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1495: }
1496: else
1497: {
1498: $link = $url;
1499: }
1500: # Add the text
1501: if ($text ne "")
1502: {
1503: $template .=
1504: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1505: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1506: }
1507:
1508: # Add the graphic
1509: my $title = &mt('Report a Bug');
1510: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1511: $template .= <<"ENDTEMPLATE";
1512: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1513: ENDTEMPLATE
1514: if ($text ne '') { $template.='</td></tr></table>' };
1515: return $template;
1516:
1517: }
1518:
1519: sub help_open_faq {
1520: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1521: unless ($env{'user.adv'}) { return ''; }
1522: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1523: $text = "" if (not defined $text);
1524: $stayOnPage=1;
1525: $width = 350 if (not defined $width);
1526: $height = 400 if (not defined $height);
1527:
1528: $topic=~s/\W+/\+/g;
1529: my $link='';
1530: my $template='';
1531: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1532: if (!$stayOnPage)
1533: {
1534: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1535: }
1536: else
1537: {
1538: $link = $url;
1539: }
1540:
1541: # Add the text
1542: if ($text ne "")
1543: {
1544: $template .=
1545: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1546: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1547: }
1548:
1549: # Add the graphic
1550: my $title = &mt('View the FAQ');
1551: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1552: $template .= <<"ENDTEMPLATE";
1553: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1554: ENDTEMPLATE
1555: if ($text ne '') { $template.='</td></tr></table>' };
1556: return $template;
1557:
1558: }
1559:
1560: ###############################################################
1561: ###############################################################
1562:
1563: =pod
1564:
1565: =item * &change_content_javascript():
1566:
1567: This and the next function allow you to create small sections of an
1568: otherwise static HTML page that you can update on the fly with
1569: Javascript, even in Netscape 4.
1570:
1571: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1572: must be written to the HTML page once. It will prove the Javascript
1573: function "change(name, content)". Calling the change function with the
1574: name of the section
1575: you want to update, matching the name passed to C<changable_area>, and
1576: the new content you want to put in there, will put the content into
1577: that area.
1578:
1579: B<Note>: Netscape 4 only reserves enough space for the changable area
1580: to contain room for the original contents. You need to "make space"
1581: for whatever changes you wish to make, and be B<sure> to check your
1582: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1583: it's adequate for updating a one-line status display, but little more.
1584: This script will set the space to 100% width, so you only need to
1585: worry about height in Netscape 4.
1586:
1587: Modern browsers are much less limiting, and if you can commit to the
1588: user not using Netscape 4, this feature may be used freely with
1589: pretty much any HTML.
1590:
1591: =cut
1592:
1593: sub change_content_javascript {
1594: # If we're on Netscape 4, we need to use Layer-based code
1595: if ($env{'browser.type'} eq 'netscape' &&
1596: $env{'browser.version'} =~ /^4\./) {
1597: return (<<NETSCAPE4);
1598: function change(name, content) {
1599: doc = document.layers[name+"___escape"].layers[0].document;
1600: doc.open();
1601: doc.write(content);
1602: doc.close();
1603: }
1604: NETSCAPE4
1605: } else {
1606: # Otherwise, we need to use semi-standards-compliant code
1607: # (technically, "innerHTML" isn't standard but the equivalent
1608: # is really scary, and every useful browser supports it
1609: return (<<DOMBASED);
1610: function change(name, content) {
1611: element = document.getElementById(name);
1612: element.innerHTML = content;
1613: }
1614: DOMBASED
1615: }
1616: }
1617:
1618: =pod
1619:
1620: =item * &changable_area($name,$origContent):
1621:
1622: This provides a "changable area" that can be modified on the fly via
1623: the Javascript code provided in C<change_content_javascript>. $name is
1624: the name you will use to reference the area later; do not repeat the
1625: same name on a given HTML page more then once. $origContent is what
1626: the area will originally contain, which can be left blank.
1627:
1628: =cut
1629:
1630: sub changable_area {
1631: my ($name, $origContent) = @_;
1632:
1633: if ($env{'browser.type'} eq 'netscape' &&
1634: $env{'browser.version'} =~ /^4\./) {
1635: # If this is netscape 4, we need to use the Layer tag
1636: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1637: } else {
1638: return "<span id='$name'>$origContent</span>";
1639: }
1640: }
1641:
1642: =pod
1643:
1644: =item * &viewport_geometry_js
1645:
1646: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1647:
1648: =cut
1649:
1650:
1651: sub viewport_geometry_js {
1652: return <<"GEOMETRY";
1653: var Geometry = {};
1654: function init_geometry() {
1655: if (Geometry.init) { return };
1656: Geometry.init=1;
1657: if (window.innerHeight) {
1658: Geometry.getViewportHeight = function() { return window.innerHeight; };
1659: Geometry.getViewportWidth = function() { return window.innerWidth; };
1660: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1661: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1662: }
1663: else if (document.documentElement && document.documentElement.clientHeight) {
1664: Geometry.getViewportHeight =
1665: function() { return document.documentElement.clientHeight; };
1666: Geometry.getViewportWidth =
1667: function() { return document.documentElement.clientWidth; };
1668:
1669: Geometry.getHorizontalScroll =
1670: function() { return document.documentElement.scrollLeft; };
1671: Geometry.getVerticalScroll =
1672: function() { return document.documentElement.scrollTop; };
1673: }
1674: else if (document.body.clientHeight) {
1675: Geometry.getViewportHeight =
1676: function() { return document.body.clientHeight; };
1677: Geometry.getViewportWidth =
1678: function() { return document.body.clientWidth; };
1679: Geometry.getHorizontalScroll =
1680: function() { return document.body.scrollLeft; };
1681: Geometry.getVerticalScroll =
1682: function() { return document.body.scrollTop; };
1683: }
1684: }
1685:
1686: GEOMETRY
1687: }
1688:
1689: =pod
1690:
1691: =item * &viewport_size_js()
1692:
1693: 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.
1694:
1695: =cut
1696:
1697: sub viewport_size_js {
1698: my $geometry = &viewport_geometry_js();
1699: return <<"DIMS";
1700:
1701: $geometry
1702:
1703: function getViewportDims(width,height) {
1704: init_geometry();
1705: width.value = Geometry.getViewportWidth();
1706: height.value = Geometry.getViewportHeight();
1707: return;
1708: }
1709:
1710: DIMS
1711: }
1712:
1713: =pod
1714:
1715: =item * &resize_textarea_js()
1716:
1717: emits the needed javascript to resize a textarea to be as big as possible
1718:
1719: creates a function resize_textrea that takes two IDs first should be
1720: the id of the element to resize, second should be the id of a div that
1721: surrounds everything that comes after the textarea, this routine needs
1722: to be attached to the <body> for the onload and onresize events.
1723:
1724: =back
1725:
1726: =cut
1727:
1728: sub resize_textarea_js {
1729: my $geometry = &viewport_geometry_js();
1730: return <<"RESIZE";
1731: <script type="text/javascript">
1732: // <![CDATA[
1733: $geometry
1734:
1735: function getX(element) {
1736: var x = 0;
1737: while (element) {
1738: x += element.offsetLeft;
1739: element = element.offsetParent;
1740: }
1741: return x;
1742: }
1743: function getY(element) {
1744: var y = 0;
1745: while (element) {
1746: y += element.offsetTop;
1747: element = element.offsetParent;
1748: }
1749: return y;
1750: }
1751:
1752:
1753: function resize_textarea(textarea_id,bottom_id) {
1754: init_geometry();
1755: var textarea = document.getElementById(textarea_id);
1756: //alert(textarea);
1757:
1758: var textarea_top = getY(textarea);
1759: var textarea_height = textarea.offsetHeight;
1760: var bottom = document.getElementById(bottom_id);
1761: var bottom_top = getY(bottom);
1762: var bottom_height = bottom.offsetHeight;
1763: var window_height = Geometry.getViewportHeight();
1764: var fudge = 23;
1765: var new_height = window_height-fudge-textarea_top-bottom_height;
1766: if (new_height < 300) {
1767: new_height = 300;
1768: }
1769: textarea.style.height=new_height+'px';
1770: }
1771: // ]]>
1772: </script>
1773: RESIZE
1774:
1775: }
1776:
1777: sub colorfuleditor_js {
1778: my $browse_or_search;
1779: my $respath;
1780: my ($cnum,$cdom) = &crsauthor_url();
1781: if ($cnum) {
1782: $respath = "/res/$cdom/$cnum/";
1783: my %js_lt = &Apache::lonlocal::texthash(
1784: sunm => 'Sub-directory name',
1785: save => 'Save page to make this permanent',
1786: );
1787: &js_escape(\%js_lt);
1788: $browse_or_search = <<"END";
1789:
1790: function toggleChooser(form,element,titleid,only,search) {
1791: var disp = 'none';
1792: if (document.getElementById('chooser_'+element)) {
1793: var curr = document.getElementById('chooser_'+element).style.display;
1794: if (curr == 'none') {
1795: disp='inline';
1796: if (form.elements['chooser_'+element].length) {
1797: for (var i=0; i<form.elements['chooser_'+element].length; i++) {
1798: form.elements['chooser_'+element][i].checked = false;
1799: }
1800: }
1801: toggleResImport(form,element);
1802: }
1803: document.getElementById('chooser_'+element).style.display = disp;
1804: }
1805: }
1806:
1807: function toggleCrsFile(form,element,numdirs) {
1808: if (document.getElementById('chooser_'+element+'_crsres')) {
1809: var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
1810: if (curr == 'none') {
1811: if (numdirs) {
1812: form.elements['coursepath_'+element].selectedIndex = 0;
1813: if (numdirs > 1) {
1814: window['select1'+element+'_changed']();
1815: }
1816: }
1817: }
1818: document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
1819:
1820: }
1821: if (document.getElementById('chooser_'+element+'_upload')) {
1822: document.getElementById('chooser_'+element+'_upload').style.display = 'none';
1823: if (document.getElementById('uploadcrsres_'+element)) {
1824: document.getElementById('uploadcrsres_'+element).value = '';
1825: }
1826: }
1827: return;
1828: }
1829:
1830: function toggleCrsUpload(form,element,numcrsdirs) {
1831: if (document.getElementById('chooser_'+element+'_crsres')) {
1832: document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
1833: }
1834: if (document.getElementById('chooser_'+element+'_upload')) {
1835: var curr = document.getElementById('chooser_'+element+'_upload').style.display;
1836: if (curr == 'none') {
1837: if (numcrsdirs) {
1838: form.elements['crsauthorpath_'+element].selectedIndex = 0;
1839: form.elements['newsubdir_'+element][0].checked = true;
1840: toggleNewsubdir(form,element);
1841: }
1842: }
1843: document.getElementById('chooser_'+element+'_upload').style.display = 'block';
1844: }
1845: return;
1846: }
1847:
1848: function toggleResImport(form,element) {
1849: var choices = new Array('crsres','upload');
1850: for (var i=0; i<choices.length; i++) {
1851: if (document.getElementById('chooser_'+element+'_'+choices[i])) {
1852: document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
1853: }
1854: }
1855: }
1856:
1857: function toggleNewsubdir(form,element) {
1858: var newsub = form.elements['newsubdir_'+element];
1859: if (newsub) {
1860: if (newsub.length) {
1861: for (var j=0; j<newsub.length; j++) {
1862: if (newsub[j].checked) {
1863: if (document.getElementById('newsubdirname_'+element)) {
1864: if (newsub[j].value == '1') {
1865: document.getElementById('newsubdirname_'+element).type = "text";
1866: if (document.getElementById('newsubdir_'+element)) {
1867: document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
1868: }
1869: } else {
1870: document.getElementById('newsubdirname_'+element).type = "hidden";
1871: document.getElementById('newsubdirname_'+element).value = "";
1872: document.getElementById('newsubdir_'+element).innerHTML = "";
1873: }
1874: }
1875: break;
1876: }
1877: }
1878: }
1879: }
1880: }
1881:
1882: function updateCrsFile(form,element) {
1883: var directory = form.elements['coursepath_'+element];
1884: var filename = form.elements['coursefile_'+element];
1885: var path = directory.options[directory.selectedIndex].value;
1886: var file = filename.options[filename.selectedIndex].value;
1887: form.elements[element].value = '$respath';
1888: if (path == '/') {
1889: form.elements[element].value += file;
1890: } else {
1891: form.elements[element].value += path+'/'+file;
1892: }
1893: unClean();
1894: if (document.getElementById('previewimg_'+element)) {
1895: document.getElementById('previewimg_'+element).src = form.elements[element].value;
1896: var newsrc = document.getElementById('previewimg_'+element).src;
1897: }
1898: if (document.getElementById('showimg_'+element)) {
1899: document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
1900: }
1901: toggleChooser(form,element);
1902: return;
1903: }
1904:
1905: function uploadDone(suffix,name) {
1906: if (name) {
1907: document.forms["lonhomework"].elements[suffix].value = name;
1908: unClean();
1909: toggleChooser(document.forms["lonhomework"],suffix);
1910: }
1911: }
1912:
1913: \$(document).ready(function(){
1914:
1915: \$(document).delegate('form :submit', 'click', function( event ) {
1916: if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
1917: var buttonId = this.id;
1918: var suffix = buttonId.toString();
1919: suffix = suffix.replace(/^crsupload_/,'');
1920: event.preventDefault();
1921: document.lonhomework.target = 'crsupload_target_'+suffix;
1922: document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
1923: \$(this.form).submit();
1924: document.lonhomework.target = '';
1925: if (document.getElementById('crsuploadto_'+suffix)) {
1926: document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
1927: }
1928: return false;
1929: }
1930: });
1931: });
1932: END
1933: }
1934: return <<"COLORFULEDIT"
1935: <script type="text/javascript">
1936: // <![CDATA[>
1937: function fold_box(curDepth, lastresource){
1938:
1939: // we need a list because there can be several blocks you need to fold in one tag
1940: var block = document.getElementsByName('foldblock_'+curDepth);
1941: // but there is only one folding button per tag
1942: var foldbutton = document.getElementById('folding_btn_'+curDepth);
1943:
1944: if(block.item(0).style.display == 'none'){
1945:
1946: foldbutton.value = '@{[&mt("Hide")]}';
1947: for (i = 0; i < block.length; i++){
1948: block.item(i).style.display = '';
1949: }
1950: }else{
1951:
1952: foldbutton.value = '@{[&mt("Show")]}';
1953: for (i = 0; i < block.length; i++){
1954: // block.item(i).style.visibility = 'collapse';
1955: block.item(i).style.display = 'none';
1956: }
1957: };
1958: saveState(lastresource);
1959: }
1960:
1961: function saveState (lastresource) {
1962:
1963: var tag_list = getTagList();
1964: if(tag_list != null){
1965: var timestamp = new Date().getTime();
1966: var key = lastresource;
1967:
1968: // the value pattern is: 'time;key1,value1;key2,value2; ... '
1969: // starting with timestamp
1970: var value = timestamp+';';
1971:
1972: // building the list of key-value pairs
1973: for(var i = 0; i < tag_list.length; i++){
1974: value += tag_list[i]+',';
1975: value += document.getElementsByName(tag_list[i])[0].style.display+';';
1976: }
1977:
1978: // only iterate whole storage if nothing to override
1979: if(localStorage.getItem(key) == null){
1980:
1981: // prevent storage from growing large
1982: if(localStorage.length > 50){
1983: var regex_getTimestamp = /^(?:\d)+;/;
1984: var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
1985: var oldest_key;
1986:
1987: for(var i = 1; i < localStorage.length; i++){
1988: if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
1989: oldest_key = localStorage.key(i);
1990: oldest_timestamp = regex_getTimestamp.exec(oldest_key);
1991: }
1992: }
1993: localStorage.removeItem(oldest_key);
1994: }
1995: }
1996: localStorage.setItem(key,value);
1997: }
1998: }
1999:
2000: // restore folding status of blocks (on page load)
2001: function restoreState (lastresource) {
2002: if(localStorage.getItem(lastresource) != null){
2003: var key = lastresource;
2004: var value = localStorage.getItem(key);
2005: var regex_delTimestamp = /^\d+;/;
2006:
2007: value.replace(regex_delTimestamp, '');
2008:
2009: var valueArr = value.split(';');
2010: var pairs;
2011: var elements;
2012: for (var i = 0; i < valueArr.length; i++){
2013: pairs = valueArr[i].split(',');
2014: elements = document.getElementsByName(pairs[0]);
2015:
2016: for (var j = 0; j < elements.length; j++){
2017: elements[j].style.display = pairs[1];
2018: if (pairs[1] == "none"){
2019: var regex_id = /([_\\d]+)\$/;
2020: regex_id.exec(pairs[0]);
2021: document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
2022: }
2023: }
2024: }
2025: }
2026: }
2027:
2028: function getTagList () {
2029:
2030: var stringToSearch = document.lonhomework.innerHTML;
2031:
2032: var ret = new Array();
2033: var regex_findBlock = /(foldblock_.*?)"/g;
2034: var tag_list = stringToSearch.match(regex_findBlock);
2035:
2036: if(tag_list != null){
2037: for(var i = 0; i < tag_list.length; i++){
2038: ret.push(tag_list[i].replace(/"/, ''));
2039: }
2040: }
2041: return ret;
2042: }
2043:
2044: function saveScrollPosition (resource) {
2045: var tag_list = getTagList();
2046:
2047: // we dont always want to jump to the first block
2048: // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
2049: if(\$(window).scrollTop() > 170){
2050: if(tag_list != null){
2051: var result;
2052: for(var i = 0; i < tag_list.length; i++){
2053: if(isElementInViewport(tag_list[i])){
2054: result += tag_list[i]+';';
2055: }
2056: }
2057: sessionStorage.setItem('anchor_'+resource, result);
2058: }
2059: } else {
2060: // we dont need to save zero, just delete the item to leave everything tidy
2061: sessionStorage.removeItem('anchor_'+resource);
2062: }
2063: }
2064:
2065: function restoreScrollPosition(resource){
2066:
2067: var elem = sessionStorage.getItem('anchor_'+resource);
2068: if(elem != null){
2069: var tag_list = elem.split(';');
2070: var elem_list;
2071:
2072: for(var i = 0; i < tag_list.length; i++){
2073: elem_list = document.getElementsByName(tag_list[i]);
2074:
2075: if(elem_list.length > 0){
2076: elem = elem_list[0];
2077: break;
2078: }
2079: }
2080: elem.scrollIntoView();
2081: }
2082: }
2083:
2084: function isElementInViewport(el) {
2085:
2086: // change to last element instead of first
2087: var elem = document.getElementsByName(el);
2088: var rect = elem[0].getBoundingClientRect();
2089:
2090: return (
2091: rect.top >= 0 &&
2092: rect.left >= 0 &&
2093: rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
2094: rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
2095: );
2096: }
2097:
2098: function autosize(depth){
2099: var cmInst = window['cm'+depth];
2100: var fitsizeButton = document.getElementById('fitsize'+depth);
2101:
2102: // is fixed size, switching to dynamic
2103: if (sessionStorage.getItem("autosized_"+depth) == null) {
2104: cmInst.setSize("","auto");
2105: fitsizeButton.value = "@{[&mt('Fixed size')]}";
2106: sessionStorage.setItem("autosized_"+depth, "yes");
2107:
2108: // is dynamic size, switching to fixed
2109: } else {
2110: cmInst.setSize("","300px");
2111: fitsizeButton.value = "@{[&mt('Dynamic size')]}";
2112: sessionStorage.removeItem("autosized_"+depth);
2113: }
2114: }
2115:
2116: $browse_or_search
2117:
2118: // ]]>
2119: </script>
2120: COLORFULEDIT
2121: }
2122:
2123: sub xmleditor_js {
2124: return <<XMLEDIT
2125: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
2126: <script type="text/javascript">
2127: // <![CDATA[>
2128:
2129: function saveScrollPosition (resource) {
2130:
2131: var scrollPos = \$(window).scrollTop();
2132: sessionStorage.setItem(resource,scrollPos);
2133: }
2134:
2135: function restoreScrollPosition(resource){
2136:
2137: var scrollPos = sessionStorage.getItem(resource);
2138: \$(window).scrollTop(scrollPos);
2139: }
2140:
2141: // unless internet explorer
2142: if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
2143:
2144: \$(document).ready(function() {
2145: \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
2146: });
2147: }
2148:
2149: // inserts text at cursor position into codemirror (xml editor only)
2150: function insertText(text){
2151: cm.focus();
2152: var curPos = cm.getCursor();
2153: cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
2154: }
2155: // ]]>
2156: </script>
2157: XMLEDIT
2158: }
2159:
2160: sub insert_folding_button {
2161: my $curDepth = $Apache::lonxml::curdepth;
2162: my $lastresource = $env{'request.ambiguous'};
2163:
2164: return "<input type=\"button\" id=\"folding_btn_$curDepth\"
2165: value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
2166: }
2167:
2168: sub crsauthor_url {
2169: my ($url) = @_;
2170: if ($url eq '') {
2171: $url = $ENV{'REQUEST_URI'};
2172: }
2173: my ($cnum,$cdom);
2174: if ($env{'request.course.id'}) {
2175: my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
2176: if ($audom ne '' && $auname ne '') {
2177: if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
2178: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
2179: $cnum = $auname;
2180: $cdom = $audom;
2181: }
2182: }
2183: }
2184: return ($cnum,$cdom);
2185: }
2186:
2187: sub import_crsauthor_form {
2188: my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix) = @_;
2189: return (0) unless ($env{'request.course.id'});
2190: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
2191: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
2192: my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
2193: return (0) unless (($cnum ne '') && ($cdom ne ''));
2194: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
2195: my @ids=&Apache::lonnet::current_machine_ids();
2196: my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
2197:
2198: if (grep(/^\Q$crshome\E$/,@ids)) {
2199: $is_home = 1;
2200: }
2201: $relpath = "/priv/$cdom/$cnum";
2202: &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
2203: my %lt = &Apache::lonlocal::texthash (
2204: fnam => 'Filename',
2205: dire => 'Directory',
2206: );
2207: my $numdirs = scalar(keys(%files));
2208: my (%possexts,$singledir,@singledirfiles);
2209: if ($only) {
2210: map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
2211: }
2212: my (%nonemptydirs,$possdirs);
2213: if ($numdirs > 1) {
2214: my @order;
2215: foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
2216: if (ref($files{$key}) eq 'HASH') {
2217: my $shown = $key;
2218: if ($key eq '') {
2219: $shown = '/';
2220: }
2221: my @ordered = ();
2222: foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
2223: if ($only) {
2224: my ($ext) = ($file =~ /\.([^.]+)$/);
2225: unless ($possexts{lc($ext)}) {
2226: next;
2227: }
2228: }
2229: $selimport_menus{$key}->{'select2'}->{$file} = $file;
2230: push(@ordered,$file);
2231: }
2232: if (@ordered) {
2233: push(@order,$key);
2234: $nonemptydirs{$key} = 1;
2235: $selimport_menus{$key}->{'text'} = $shown;
2236: $selimport_menus{$key}->{'default'} = '';
2237: $selimport_menus{$key}->{'select2'}->{''} = '';
2238: $selimport_menus{$key}->{'order'} = \@ordered;
2239: }
2240: }
2241: }
2242: $possdirs = scalar(keys(%nonemptydirs));
2243: if ($possdirs > 1) {
2244: my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
2245: $output = $lt{'dire'}.
2246: &linked_select_forms($form,'<br />'.
2247: $lt{'fnam'},'',
2248: $firstselectname,$secondselectname,
2249: \%selimport_menus,\@order,
2250: $onchangefirst,'',$suffix).'<br />';
2251: } elsif ($possdirs == 1) {
2252: $singledir = (keys(%nonemptydirs))[0];
2253: if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
2254: @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
2255: }
2256: delete($selimport_menus{$singledir});
2257: }
2258: } elsif ($numdirs == 1) {
2259: $singledir = (keys(%files))[0];
2260: foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
2261: if ($only) {
2262: my ($ext) = ($file =~ /\.([^.]+)$/);
2263: unless ($possexts{lc($ext)}) {
2264: next;
2265: }
2266: }
2267: push(@singledirfiles,$file);
2268: }
2269: if (@singledirfiles) {
2270: $possdirs == 1;
2271: }
2272: }
2273: if (($possdirs == 1) && (@singledirfiles)) {
2274: my $showdir = $singledir;
2275: if ($singledir eq '') {
2276: $showdir = '/';
2277: }
2278: $output = $lt{'dire'}.
2279: '<select name="'.$firstselectname.'">'.
2280: '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
2281: '</select><br />'.
2282: $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
2283: '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
2284: foreach my $file (@singledirfiles) {
2285: $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
2286: }
2287: $output .= '</select><br />'."\n";
2288: }
2289: return ($possdirs,$output);
2290: }
2291:
2292: =pod
2293:
2294: =head1 Excel and CSV file utility routines
2295:
2296: =cut
2297:
2298: ###############################################################
2299: ###############################################################
2300:
2301: =pod
2302:
2303: =over 4
2304:
2305: =item * &csv_translate($text)
2306:
2307: Translate $text to allow it to be output as a 'comma separated values'
2308: format.
2309:
2310: =cut
2311:
2312: ###############################################################
2313: ###############################################################
2314: sub csv_translate {
2315: my $text = shift;
2316: $text =~ s/\"/\"\"/g;
2317: $text =~ s/\n/ /g;
2318: return $text;
2319: }
2320:
2321: ###############################################################
2322: ###############################################################
2323:
2324: =pod
2325:
2326: =item * &define_excel_formats()
2327:
2328: Define some commonly used Excel cell formats.
2329:
2330: Currently supported formats:
2331:
2332: =over 4
2333:
2334: =item header
2335:
2336: =item bold
2337:
2338: =item h1
2339:
2340: =item h2
2341:
2342: =item h3
2343:
2344: =item h4
2345:
2346: =item i
2347:
2348: =item date
2349:
2350: =back
2351:
2352: Inputs: $workbook
2353:
2354: Returns: $format, a hash reference.
2355:
2356:
2357: =cut
2358:
2359: ###############################################################
2360: ###############################################################
2361: sub define_excel_formats {
2362: my ($workbook) = @_;
2363: my $format;
2364: $format->{'header'} = $workbook->add_format(bold => 1,
2365: bottom => 1,
2366: align => 'center');
2367: $format->{'bold'} = $workbook->add_format(bold=>1);
2368: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
2369: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
2370: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
2371: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
2372: $format->{'i'} = $workbook->add_format(italic=>1);
2373: $format->{'date'} = $workbook->add_format(num_format=>
2374: 'mm/dd/yyyy hh:mm:ss');
2375: return $format;
2376: }
2377:
2378: ###############################################################
2379: ###############################################################
2380:
2381: =pod
2382:
2383: =item * &create_workbook()
2384:
2385: Create an Excel worksheet. If it fails, output message on the
2386: request object and return undefs.
2387:
2388: Inputs: Apache request object
2389:
2390: Returns (undef) on failure,
2391: Excel worksheet object, scalar with filename, and formats
2392: from &Apache::loncommon::define_excel_formats on success
2393:
2394: =cut
2395:
2396: ###############################################################
2397: ###############################################################
2398: sub create_workbook {
2399: my ($r) = @_;
2400: #
2401: # Create the excel spreadsheet
2402: my $filename = '/prtspool/'.
2403: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2404: time.'_'.rand(1000000000).'.xls';
2405: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
2406: if (! defined($workbook)) {
2407: $r->log_error("Error creating excel spreadsheet $filename: $!");
2408: $r->print(
2409: '<p class="LC_error">'
2410: .&mt('Problems occurred in creating the new Excel file.')
2411: .' '.&mt('This error has been logged.')
2412: .' '.&mt('Please alert your LON-CAPA administrator.')
2413: .'</p>'
2414: );
2415: return (undef);
2416: }
2417: #
2418: $workbook->set_tempdir(LONCAPA::tempdir());
2419: #
2420: my $format = &Apache::loncommon::define_excel_formats($workbook);
2421: return ($workbook,$filename,$format);
2422: }
2423:
2424: ###############################################################
2425: ###############################################################
2426:
2427: =pod
2428:
2429: =item * &create_text_file()
2430:
2431: Create a file to write to and eventually make available to the user.
2432: If file creation fails, outputs an error message on the request object and
2433: return undefs.
2434:
2435: Inputs: Apache request object, and file suffix
2436:
2437: Returns (undef) on failure,
2438: Filehandle and filename on success.
2439:
2440: =cut
2441:
2442: ###############################################################
2443: ###############################################################
2444: sub create_text_file {
2445: my ($r,$suffix) = @_;
2446: if (! defined($suffix)) { $suffix = 'txt'; };
2447: my $fh;
2448: my $filename = '/prtspool/'.
2449: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
2450: time.'_'.rand(1000000000).'.'.$suffix;
2451: $fh = Apache::File->new('>/home/httpd'.$filename);
2452: if (! defined($fh)) {
2453: $r->log_error("Couldn't open $filename for output $!");
2454: $r->print(
2455: '<p class="LC_error">'
2456: .&mt('Problems occurred in creating the output file.')
2457: .' '.&mt('This error has been logged.')
2458: .' '.&mt('Please alert your LON-CAPA administrator.')
2459: .'</p>'
2460: );
2461: }
2462: return ($fh,$filename)
2463: }
2464:
2465:
2466: =pod
2467:
2468: =back
2469:
2470: =cut
2471:
2472: ###############################################################
2473: ## Home server <option> list generating code ##
2474: ###############################################################
2475:
2476: # ------------------------------------------
2477:
2478: sub domain_select {
2479: my ($name,$value,$multiple)=@_;
2480: my %domains=map {
2481: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
2482: } &Apache::lonnet::all_domains();
2483: if ($multiple) {
2484: $domains{''}=&mt('Any domain');
2485: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2486: return &multiple_select_form($name,$value,4,\%domains);
2487: } else {
2488: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
2489: return &select_form($name,$value,\%domains);
2490: }
2491: }
2492:
2493: #-------------------------------------------
2494:
2495: =pod
2496:
2497: =head1 Routines for form select boxes
2498:
2499: =over 4
2500:
2501: =item * &multiple_select_form($name,$value,$size,$hash,$order)
2502:
2503: Returns a string containing a <select> element int multiple mode
2504:
2505:
2506: Args:
2507: $name - name of the <select> element
2508: $value - scalar or array ref of values that should already be selected
2509: $size - number of rows long the select element is
2510: $hash - the elements should be 'option' => 'shown text'
2511: (shown text should already have been &mt())
2512: $order - (optional) array ref of the order to show the elements in
2513:
2514: =cut
2515:
2516: #-------------------------------------------
2517: sub multiple_select_form {
2518: my ($name,$value,$size,$hash,$order)=@_;
2519: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
2520: my $output='';
2521: if (! defined($size)) {
2522: $size = 4;
2523: if (scalar(keys(%$hash))<4) {
2524: $size = scalar(keys(%$hash));
2525: }
2526: }
2527: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
2528: my @order;
2529: if (ref($order) eq 'ARRAY') {
2530: @order = @{$order};
2531: } else {
2532: @order = sort(keys(%$hash));
2533: }
2534: if (exists($$hash{'select_form_order'})) {
2535: @order = @{$$hash{'select_form_order'}};
2536: }
2537:
2538: foreach my $key (@order) {
2539: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
2540: $output.='selected="selected" ' if ($selected{$key});
2541: $output.='>'.$hash->{$key}."</option>\n";
2542: }
2543: $output.="</select>\n";
2544: return $output;
2545: }
2546:
2547: #-------------------------------------------
2548:
2549: =pod
2550:
2551: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
2552:
2553: Returns a string containing a <select name='$name' size='1'> form to
2554: allow a user to select options from a ref to a hash containing:
2555: option_name => displayed text. An optional $onchange can include
2556: a javascript onchange item, e.g., onchange="this.form.submit();".
2557: An optional arg -- $readonly -- if true will cause the select form
2558: to be disabled, e.g., for the case where an instructor has a section-
2559: specific role, and is viewing/modifying parameters.
2560:
2561: See lonrights.pm for an example invocation and use.
2562:
2563: =cut
2564:
2565: #-------------------------------------------
2566: sub select_form {
2567: my ($def,$name,$hashref,$onchange,$readonly) = @_;
2568: return unless (ref($hashref) eq 'HASH');
2569: if ($onchange) {
2570: $onchange = ' onchange="'.$onchange.'"';
2571: }
2572: my $disabled;
2573: if ($readonly) {
2574: $disabled = ' disabled="disabled"';
2575: }
2576: my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2577: my @keys;
2578: if (exists($hashref->{'select_form_order'})) {
2579: @keys=@{$hashref->{'select_form_order'}};
2580: } else {
2581: @keys=sort(keys(%{$hashref}));
2582: }
2583: foreach my $key (@keys) {
2584: $selectform.=
2585: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
2586: ($key eq $def ? 'selected="selected" ' : '').
2587: ">".$hashref->{$key}."</option>\n";
2588: }
2589: $selectform.="</select>";
2590: return $selectform;
2591: }
2592:
2593: # For display filters
2594:
2595: sub display_filter {
2596: my ($context) = @_;
2597: if (!$env{'form.show'}) { $env{'form.show'}=10; }
2598: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
2599: my $phraseinput = 'hidden';
2600: my $includeinput = 'hidden';
2601: my ($checked,$includetypestext);
2602: if ($env{'form.displayfilter'} eq 'containing') {
2603: $phraseinput = 'text';
2604: if ($context eq 'parmslog') {
2605: $includeinput = 'checkbox';
2606: if ($env{'form.includetypes'}) {
2607: $checked = ' checked="checked"';
2608: }
2609: $includetypestext = &mt('Include parameter types');
2610: }
2611: } else {
2612: $includetypestext = ' ';
2613: }
2614: my ($additional,$secondid,$thirdid);
2615: if ($context eq 'parmslog') {
2616: $additional =
2617: '<label><input type="'.$includeinput.'" name="includetypes"'.
2618: $checked.' name="includetypes" value="1" id="includetypes" />'.
2619: ' <span id="includetypestext">'.$includetypestext.'</span>'.
2620: '</label>';
2621: $secondid = 'includetypes';
2622: $thirdid = 'includetypestext';
2623: }
2624: my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
2625: '$secondid','$thirdid')";
2626: return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
2627: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
2628: (&mt('all'),10,20,50,100,1000,10000))).
2629: '</label></span> <span class="LC_nobreak">'.
2630: &mt('Filter: [_1]',
2631: &select_form($env{'form.displayfilter'},
2632: 'displayfilter',
2633: {'currentfolder' => 'Current folder/page',
2634: 'containing' => 'Containing phrase',
2635: 'none' => 'None'},$onchange)).' '.
2636: '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
2637: &HTML::Entities::encode($env{'form.containingphrase'}).
2638: '" />'.$additional;
2639: }
2640:
2641: sub display_filter_js {
2642: my $includetext = &mt('Include parameter types');
2643: return <<"ENDJS";
2644:
2645: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
2646: var firstType = 'hidden';
2647: if (setter.options[setter.selectedIndex].value == 'containing') {
2648: firstType = 'text';
2649: }
2650: firstObject = document.getElementById(firstid);
2651: if (typeof(firstObject) == 'object') {
2652: if (firstObject.type != firstType) {
2653: changeInputType(firstObject,firstType);
2654: }
2655: }
2656: if (context == 'parmslog') {
2657: var secondType = 'hidden';
2658: if (firstType == 'text') {
2659: secondType = 'checkbox';
2660: }
2661: secondObject = document.getElementById(secondid);
2662: if (typeof(secondObject) == 'object') {
2663: if (secondObject.type != secondType) {
2664: changeInputType(secondObject,secondType);
2665: }
2666: }
2667: var textItem = document.getElementById(thirdid);
2668: var currtext = textItem.innerHTML;
2669: var newtext;
2670: if (firstType == 'text') {
2671: newtext = '$includetext';
2672: } else {
2673: newtext = ' ';
2674: }
2675: if (currtext != newtext) {
2676: textItem.innerHTML = newtext;
2677: }
2678: }
2679: return;
2680: }
2681:
2682: function changeInputType(oldObject,newType) {
2683: var newObject = document.createElement('input');
2684: newObject.type = newType;
2685: if (oldObject.size) {
2686: newObject.size = oldObject.size;
2687: }
2688: if (oldObject.value) {
2689: newObject.value = oldObject.value;
2690: }
2691: if (oldObject.name) {
2692: newObject.name = oldObject.name;
2693: }
2694: if (oldObject.id) {
2695: newObject.id = oldObject.id;
2696: }
2697: oldObject.parentNode.replaceChild(newObject,oldObject);
2698: return;
2699: }
2700:
2701: ENDJS
2702: }
2703:
2704: sub gradeleveldescription {
2705: my $gradelevel=shift;
2706: my %gradelevels=(0 => 'Not specified',
2707: 1 => 'Grade 1',
2708: 2 => 'Grade 2',
2709: 3 => 'Grade 3',
2710: 4 => 'Grade 4',
2711: 5 => 'Grade 5',
2712: 6 => 'Grade 6',
2713: 7 => 'Grade 7',
2714: 8 => 'Grade 8',
2715: 9 => 'Grade 9',
2716: 10 => 'Grade 10',
2717: 11 => 'Grade 11',
2718: 12 => 'Grade 12',
2719: 13 => 'Grade 13',
2720: 14 => '100 Level',
2721: 15 => '200 Level',
2722: 16 => '300 Level',
2723: 17 => '400 Level',
2724: 18 => 'Graduate Level');
2725: return &mt($gradelevels{$gradelevel});
2726: }
2727:
2728: sub select_level_form {
2729: my ($deflevel,$name)=@_;
2730: unless ($deflevel) { $deflevel=0; }
2731: my $selectform = "<select name=\"$name\" size=\"1\">\n";
2732: for (my $i=0; $i<=18; $i++) {
2733: $selectform.="<option value=\"$i\" ".
2734: ($i==$deflevel ? 'selected="selected" ' : '').
2735: ">".&gradeleveldescription($i)."</option>\n";
2736: }
2737: $selectform.="</select>";
2738: return $selectform;
2739: }
2740:
2741: #-------------------------------------------
2742:
2743: =pod
2744:
2745: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
2746:
2747: Returns a string containing a <select name='$name' size='1'> form to
2748: allow a user to select the domain to preform an operation in.
2749: See loncreateuser.pm for an example invocation and use.
2750:
2751: If the $includeempty flag is set, it also includes an empty choice ("no domain
2752: selected");
2753:
2754: If the $showdomdesc flag is set, the domain name is followed by the domain description.
2755:
2756: 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.
2757:
2758: The optional $incdoms is a reference to an array of domains which will be the only available options.
2759:
2760: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
2761:
2762: The optional $disabled argument, if true, adds the disabled attribute to the select tag.
2763:
2764: =cut
2765:
2766: #-------------------------------------------
2767: sub select_dom_form {
2768: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
2769: if ($onchange) {
2770: $onchange = ' onchange="'.$onchange.'"';
2771: }
2772: if ($disabled) {
2773: $disabled = ' disabled="disabled"';
2774: }
2775: my (@domains,%exclude);
2776: if (ref($incdoms) eq 'ARRAY') {
2777: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
2778: } else {
2779: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
2780: }
2781: if ($includeempty) { @domains=('',@domains); }
2782: if (ref($excdoms) eq 'ARRAY') {
2783: map { $exclude{$_} = 1; } @{$excdoms};
2784: }
2785: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
2786: foreach my $dom (@domains) {
2787: next if ($exclude{$dom});
2788: $selectdomain.="<option value=\"$dom\" ".
2789: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
2790: if ($showdomdesc) {
2791: if ($dom ne '') {
2792: my $domdesc = &Apache::lonnet::domain($dom,'description');
2793: if ($domdesc ne '') {
2794: $selectdomain .= ' ('.$domdesc.')';
2795: }
2796: }
2797: }
2798: $selectdomain .= "</option>\n";
2799: }
2800: $selectdomain.="</select>";
2801: return $selectdomain;
2802: }
2803:
2804: #-------------------------------------------
2805:
2806: =pod
2807:
2808: =item * &home_server_form_item($domain,$name,$defaultflag)
2809:
2810: input: 4 arguments (two required, two optional) -
2811: $domain - domain of new user
2812: $name - name of form element
2813: $default - Value of 'default' causes a default item to be first
2814: option, and selected by default.
2815: $hide - Value of 'hide' causes hiding of the name of the server,
2816: if 1 server found, or default, if 0 found.
2817: output: returns 2 items:
2818: (a) form element which contains either:
2819: (i) <select name="$name">
2820: <option value="$hostid1">$hostid $servers{$hostid}</option>
2821: <option value="$hostid2">$hostid $servers{$hostid}</option>
2822: </select>
2823: form item if there are multiple library servers in $domain, or
2824: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2825: if there is only one library server in $domain.
2826:
2827: (b) number of library servers found.
2828:
2829: See loncreateuser.pm for example of use.
2830:
2831: =cut
2832:
2833: #-------------------------------------------
2834: sub home_server_form_item {
2835: my ($domain,$name,$default,$hide) = @_;
2836: my %servers = &Apache::lonnet::get_servers($domain,'library');
2837: my $result;
2838: my $numlib = keys(%servers);
2839: if ($numlib > 1) {
2840: $result .= '<select name="'.$name.'" />'."\n";
2841: if ($default) {
2842: $result .= '<option value="default" selected="selected">'.&mt('default').
2843: '</option>'."\n";
2844: }
2845: foreach my $hostid (sort(keys(%servers))) {
2846: $result.= '<option value="'.$hostid.'">'.
2847: $hostid.' '.$servers{$hostid}."</option>\n";
2848: }
2849: $result .= '</select>'."\n";
2850: } elsif ($numlib == 1) {
2851: my $hostid;
2852: foreach my $item (keys(%servers)) {
2853: $hostid = $item;
2854: }
2855: $result .= '<input type="hidden" name="'.$name.'" value="'.
2856: $hostid.'" />';
2857: if (!$hide) {
2858: $result .= $hostid.' '.$servers{$hostid};
2859: }
2860: $result .= "\n";
2861: } elsif ($default) {
2862: $result .= '<input type="hidden" name="'.$name.
2863: '" value="default" />';
2864: if (!$hide) {
2865: $result .= &mt('default');
2866: }
2867: $result .= "\n";
2868: }
2869: return ($result,$numlib);
2870: }
2871:
2872: =pod
2873:
2874: =back
2875:
2876: =cut
2877:
2878: ###############################################################
2879: ## Decoding User Agent ##
2880: ###############################################################
2881:
2882: =pod
2883:
2884: =head1 Decoding the User Agent
2885:
2886: =over 4
2887:
2888: =item * &decode_user_agent()
2889:
2890: Inputs: $r
2891:
2892: Outputs:
2893:
2894: =over 4
2895:
2896: =item * $httpbrowser
2897:
2898: =item * $clientbrowser
2899:
2900: =item * $clientversion
2901:
2902: =item * $clientmathml
2903:
2904: =item * $clientunicode
2905:
2906: =item * $clientos
2907:
2908: =item * $clientmobile
2909:
2910: =item * $clientinfo
2911:
2912: =item * $clientosversion
2913:
2914: =back
2915:
2916: =back
2917:
2918: =cut
2919:
2920: ###############################################################
2921: ###############################################################
2922: sub decode_user_agent {
2923: my ($r)=@_;
2924: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
2925: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
2926: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
2927: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
2928: my $clientbrowser='unknown';
2929: my $clientversion='0';
2930: my $clientmathml='';
2931: my $clientunicode='0';
2932: my $clientmobile=0;
2933: my $clientosversion='';
2934: for (my $i=0;$i<=$#browsertype;$i++) {
2935: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
2936: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
2937: $clientbrowser=$bname;
2938: $httpbrowser=~/$vreg/i;
2939: $clientversion=$1;
2940: $clientmathml=($clientversion>=$minv);
2941: $clientunicode=($clientversion>=$univ);
2942: }
2943: }
2944: my $clientos='unknown';
2945: my $clientinfo;
2946: if (($httpbrowser=~/linux/i) ||
2947: ($httpbrowser=~/unix/i) ||
2948: ($httpbrowser=~/ux/i) ||
2949: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
2950: if (($httpbrowser=~/vax/i) ||
2951: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
2952: if ($httpbrowser=~/next/i) { $clientos='next'; }
2953: if (($httpbrowser=~/mac/i) ||
2954: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
2955: if ($httpbrowser=~/win/i) {
2956: $clientos='win';
2957: if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
2958: $clientosversion = $1;
2959: }
2960: }
2961: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
2962: if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
2963: $clientmobile=lc($1);
2964: }
2965: if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
2966: $clientinfo = 'firefox-'.$1;
2967: } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
2968: $clientinfo = 'chromeframe-'.$1;
2969: }
2970: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
2971: $clientunicode,$clientos,$clientmobile,$clientinfo,
2972: $clientosversion);
2973: }
2974:
2975: ###############################################################
2976: ## Authentication changing form generation subroutines ##
2977: ###############################################################
2978: ##
2979: ## All of the authform_xxxxxxx subroutines take their inputs in a
2980: ## hash, and have reasonable default values.
2981: ##
2982: ## formname = the name given in the <form> tag.
2983: #-------------------------------------------
2984:
2985: =pod
2986:
2987: =head1 Authentication Routines
2988:
2989: =over 4
2990:
2991: =item * &authform_xxxxxx()
2992:
2993: The authform_xxxxxx subroutines provide javascript and html forms which
2994: handle some of the conveniences required for authentication forms.
2995: This is not an optimal method, but it works.
2996:
2997: =over 4
2998:
2999: =item * authform_header
3000:
3001: =item * authform_authorwarning
3002:
3003: =item * authform_nochange
3004:
3005: =item * authform_kerberos
3006:
3007: =item * authform_internal
3008:
3009: =item * authform_filesystem
3010:
3011: =back
3012:
3013: See loncreateuser.pm for invocation and use examples.
3014:
3015: =cut
3016:
3017: #-------------------------------------------
3018: sub authform_header{
3019: my %in = (
3020: formname => 'cu',
3021: kerb_def_dom => '',
3022: @_,
3023: );
3024: $in{'formname'} = 'document.' . $in{'formname'};
3025: my $result='';
3026:
3027: #---------------------------------------------- Code for upper case translation
3028: my $Javascript_toUpperCase;
3029: unless ($in{kerb_def_dom}) {
3030: $Javascript_toUpperCase =<<"END";
3031: switch (choice) {
3032: case 'krb': currentform.elements[choicearg].value =
3033: currentform.elements[choicearg].value.toUpperCase();
3034: break;
3035: default:
3036: }
3037: END
3038: } else {
3039: $Javascript_toUpperCase = "";
3040: }
3041:
3042: my $radioval = "'nochange'";
3043: if (defined($in{'curr_authtype'})) {
3044: if ($in{'curr_authtype'} ne '') {
3045: $radioval = "'".$in{'curr_authtype'}."arg'";
3046: }
3047: }
3048: my $argfield = 'null';
3049: if (defined($in{'mode'})) {
3050: if ($in{'mode'} eq 'modifycourse') {
3051: if (defined($in{'curr_autharg'})) {
3052: if ($in{'curr_autharg'} ne '') {
3053: $argfield = "'$in{'curr_autharg'}'";
3054: }
3055: }
3056: }
3057: }
3058:
3059: $result.=<<"END";
3060: var current = new Object();
3061: current.radiovalue = $radioval;
3062: current.argfield = $argfield;
3063:
3064: function changed_radio(choice,currentform) {
3065: var choicearg = choice + 'arg';
3066: // If a radio button in changed, we need to change the argfield
3067: if (current.radiovalue != choice) {
3068: current.radiovalue = choice;
3069: if (current.argfield != null) {
3070: currentform.elements[current.argfield].value = '';
3071: }
3072: if (choice == 'nochange') {
3073: current.argfield = null;
3074: } else {
3075: current.argfield = choicearg;
3076: switch(choice) {
3077: case 'krb':
3078: currentform.elements[current.argfield].value =
3079: "$in{'kerb_def_dom'}";
3080: break;
3081: default:
3082: break;
3083: }
3084: }
3085: }
3086: return;
3087: }
3088:
3089: function changed_text(choice,currentform) {
3090: var choicearg = choice + 'arg';
3091: if (currentform.elements[choicearg].value !='') {
3092: $Javascript_toUpperCase
3093: // clear old field
3094: if ((current.argfield != choicearg) && (current.argfield != null)) {
3095: currentform.elements[current.argfield].value = '';
3096: }
3097: current.argfield = choicearg;
3098: }
3099: set_auth_radio_buttons(choice,currentform);
3100: return;
3101: }
3102:
3103: function set_auth_radio_buttons(newvalue,currentform) {
3104: var numauthchoices = currentform.login.length;
3105: if (typeof numauthchoices == "undefined") {
3106: return;
3107: }
3108: var i=0;
3109: while (i < numauthchoices) {
3110: if (currentform.login[i].value == newvalue) { break; }
3111: i++;
3112: }
3113: if (i == numauthchoices) {
3114: return;
3115: }
3116: current.radiovalue = newvalue;
3117: currentform.login[i].checked = true;
3118: return;
3119: }
3120: END
3121: return $result;
3122: }
3123:
3124: sub authform_authorwarning {
3125: my $result='';
3126: $result='<i>'.
3127: &mt('As a general rule, only authors or co-authors should be '.
3128: 'filesystem authenticated '.
3129: '(which allows access to the server filesystem).')."</i>\n";
3130: return $result;
3131: }
3132:
3133: sub authform_nochange {
3134: my %in = (
3135: formname => 'document.cu',
3136: kerb_def_dom => 'MSU.EDU',
3137: @_,
3138: );
3139: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3140: my $result;
3141: if (!$authnum) {
3142: $result = &mt('Under your current role you are not permitted to change login settings for this user');
3143: } else {
3144: $result = '<label>'.&mt('[_1] Do not change login data',
3145: '<input type="radio" name="login" value="nochange" '.
3146: 'checked="checked" onclick="'.
3147: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
3148: '</label>';
3149: }
3150: return $result;
3151: }
3152:
3153: sub authform_kerberos {
3154: my %in = (
3155: formname => 'document.cu',
3156: kerb_def_dom => 'MSU.EDU',
3157: kerb_def_auth => 'krb4',
3158: @_,
3159: );
3160: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
3161: $autharg,$jscall);
3162: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3163: if ($in{'kerb_def_auth'} eq 'krb5') {
3164: $check5 = ' checked="checked"';
3165: } else {
3166: $check4 = ' checked="checked"';
3167: }
3168: $krbarg = $in{'kerb_def_dom'};
3169: if (defined($in{'curr_authtype'})) {
3170: if ($in{'curr_authtype'} eq 'krb') {
3171: $krbcheck = ' checked="checked"';
3172: if (defined($in{'mode'})) {
3173: if ($in{'mode'} eq 'modifyuser') {
3174: $krbcheck = '';
3175: }
3176: }
3177: if (defined($in{'curr_kerb_ver'})) {
3178: if ($in{'curr_krb_ver'} eq '5') {
3179: $check5 = ' checked="checked"';
3180: $check4 = '';
3181: } else {
3182: $check4 = ' checked="checked"';
3183: $check5 = '';
3184: }
3185: }
3186: if (defined($in{'curr_autharg'})) {
3187: $krbarg = $in{'curr_autharg'};
3188: }
3189: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
3190: if (defined($in{'curr_autharg'})) {
3191: $result =
3192: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
3193: $in{'curr_autharg'},$krbver);
3194: } else {
3195: $result =
3196: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
3197: }
3198: return $result;
3199: }
3200: }
3201: } else {
3202: if ($authnum == 1) {
3203: $authtype = '<input type="hidden" name="login" value="krb" />';
3204: }
3205: }
3206: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
3207: return;
3208: } elsif ($authtype eq '') {
3209: if (defined($in{'mode'})) {
3210: if ($in{'mode'} eq 'modifycourse') {
3211: if ($authnum == 1) {
3212: $authtype = '<input type="radio" name="login" value="krb" />';
3213: }
3214: }
3215: }
3216: }
3217: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
3218: if ($authtype eq '') {
3219: $authtype = '<input type="radio" name="login" value="krb" '.
3220: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
3221: $krbcheck.' />';
3222: }
3223: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
3224: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
3225: $in{'curr_authtype'} eq 'krb5') ||
3226: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
3227: $in{'curr_authtype'} eq 'krb4')) {
3228: $result .= &mt
3229: ('[_1] Kerberos authenticated with domain [_2] '.
3230: '[_3] Version 4 [_4] Version 5 [_5]',
3231: '<label>'.$authtype,
3232: '</label><input type="text" size="10" name="krbarg" '.
3233: 'value="'.$krbarg.'" '.
3234: 'onchange="'.$jscall.'" />',
3235: '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
3236: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
3237: '</label>');
3238: } elsif ($can_assign{'krb4'}) {
3239: $result .= &mt
3240: ('[_1] Kerberos authenticated with domain [_2] '.
3241: '[_3] Version 4 [_4]',
3242: '<label>'.$authtype,
3243: '</label><input type="text" size="10" name="krbarg" '.
3244: 'value="'.$krbarg.'" '.
3245: 'onchange="'.$jscall.'" />',
3246: '<label><input type="hidden" name="krbver" value="4" />',
3247: '</label>');
3248: } elsif ($can_assign{'krb5'}) {
3249: $result .= &mt
3250: ('[_1] Kerberos authenticated with domain [_2] '.
3251: '[_3] Version 5 [_4]',
3252: '<label>'.$authtype,
3253: '</label><input type="text" size="10" name="krbarg" '.
3254: 'value="'.$krbarg.'" '.
3255: 'onchange="'.$jscall.'" />',
3256: '<label><input type="hidden" name="krbver" value="5" />',
3257: '</label>');
3258: }
3259: return $result;
3260: }
3261:
3262: sub authform_internal {
3263: my %in = (
3264: formname => 'document.cu',
3265: kerb_def_dom => 'MSU.EDU',
3266: @_,
3267: );
3268: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
3269: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3270: if (defined($in{'curr_authtype'})) {
3271: if ($in{'curr_authtype'} eq 'int') {
3272: if ($can_assign{'int'}) {
3273: $intcheck = 'checked="checked" ';
3274: if (defined($in{'mode'})) {
3275: if ($in{'mode'} eq 'modifyuser') {
3276: $intcheck = '';
3277: }
3278: }
3279: if (defined($in{'curr_autharg'})) {
3280: $intarg = $in{'curr_autharg'};
3281: }
3282: } else {
3283: $result = &mt('Currently internally authenticated.');
3284: return $result;
3285: }
3286: }
3287: } else {
3288: if ($authnum == 1) {
3289: $authtype = '<input type="hidden" name="login" value="int" />';
3290: }
3291: }
3292: if (!$can_assign{'int'}) {
3293: return;
3294: } elsif ($authtype eq '') {
3295: if (defined($in{'mode'})) {
3296: if ($in{'mode'} eq 'modifycourse') {
3297: if ($authnum == 1) {
3298: $authtype = '<input type="radio" name="login" value="int" />';
3299: }
3300: }
3301: }
3302: }
3303: $jscall = "javascript:changed_radio('int',$in{'formname'});";
3304: if ($authtype eq '') {
3305: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
3306: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
3307: }
3308: $autharg = '<input type="password" size="10" name="intarg" value="'.
3309: $intarg.'" onchange="'.$jscall.'" />';
3310: $result = &mt
3311: ('[_1] Internally authenticated (with initial password [_2])',
3312: '<label>'.$authtype,'</label>'.$autharg);
3313: $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
3314: return $result;
3315: }
3316:
3317: sub authform_local {
3318: my %in = (
3319: formname => 'document.cu',
3320: kerb_def_dom => 'MSU.EDU',
3321: @_,
3322: );
3323: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
3324: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3325: if (defined($in{'curr_authtype'})) {
3326: if ($in{'curr_authtype'} eq 'loc') {
3327: if ($can_assign{'loc'}) {
3328: $loccheck = 'checked="checked" ';
3329: if (defined($in{'mode'})) {
3330: if ($in{'mode'} eq 'modifyuser') {
3331: $loccheck = '';
3332: }
3333: }
3334: if (defined($in{'curr_autharg'})) {
3335: $locarg = $in{'curr_autharg'};
3336: }
3337: } else {
3338: $result = &mt('Currently using local (institutional) authentication.');
3339: return $result;
3340: }
3341: }
3342: } else {
3343: if ($authnum == 1) {
3344: $authtype = '<input type="hidden" name="login" value="loc" />';
3345: }
3346: }
3347: if (!$can_assign{'loc'}) {
3348: return;
3349: } elsif ($authtype eq '') {
3350: if (defined($in{'mode'})) {
3351: if ($in{'mode'} eq 'modifycourse') {
3352: if ($authnum == 1) {
3353: $authtype = '<input type="radio" name="login" value="loc" />';
3354: }
3355: }
3356: }
3357: }
3358: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
3359: if ($authtype eq '') {
3360: $authtype = '<input type="radio" name="login" value="loc" '.
3361: $loccheck.' onchange="'.$jscall.'" onclick="'.
3362: $jscall.'" />';
3363: }
3364: $autharg = '<input type="text" size="10" name="locarg" value="'.
3365: $locarg.'" onchange="'.$jscall.'" />';
3366: $result = &mt('[_1] Local Authentication with argument [_2]',
3367: '<label>'.$authtype,'</label>'.$autharg);
3368: return $result;
3369: }
3370:
3371: sub authform_filesystem {
3372: my %in = (
3373: formname => 'document.cu',
3374: kerb_def_dom => 'MSU.EDU',
3375: @_,
3376: );
3377: my ($fsyscheck,$result,$authtype,$autharg,$jscall);
3378: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
3379: if (defined($in{'curr_authtype'})) {
3380: if ($in{'curr_authtype'} eq 'fsys') {
3381: if ($can_assign{'fsys'}) {
3382: $fsyscheck = 'checked="checked" ';
3383: if (defined($in{'mode'})) {
3384: if ($in{'mode'} eq 'modifyuser') {
3385: $fsyscheck = '';
3386: }
3387: }
3388: } else {
3389: $result = &mt('Currently Filesystem Authenticated.');
3390: return $result;
3391: }
3392: }
3393: } else {
3394: if ($authnum == 1) {
3395: $authtype = '<input type="hidden" name="login" value="fsys" />';
3396: }
3397: }
3398: if (!$can_assign{'fsys'}) {
3399: return;
3400: } elsif ($authtype eq '') {
3401: if (defined($in{'mode'})) {
3402: if ($in{'mode'} eq 'modifycourse') {
3403: if ($authnum == 1) {
3404: $authtype = '<input type="radio" name="login" value="fsys" />';
3405: }
3406: }
3407: }
3408: }
3409: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
3410: if ($authtype eq '') {
3411: $authtype = '<input type="radio" name="login" value="fsys" '.
3412: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
3413: $jscall.'" />';
3414: }
3415: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
3416: ' onchange="'.$jscall.'" />';
3417: $result = &mt
3418: ('[_1] Filesystem Authenticated (with initial password [_2])',
3419: '<label><input type="radio" name="login" value="fsys" '.
3420: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
3421: '</label><input type="password" size="10" name="fsysarg" value="" '.
3422: 'onchange="'.$jscall.'" />');
3423: return $result;
3424: }
3425:
3426: sub get_assignable_auth {
3427: my ($dom) = @_;
3428: if ($dom eq '') {
3429: $dom = $env{'request.role.domain'};
3430: }
3431: my %can_assign = (
3432: krb4 => 1,
3433: krb5 => 1,
3434: int => 1,
3435: loc => 1,
3436: );
3437: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
3438: if (ref($domconfig{'usercreation'}) eq 'HASH') {
3439: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
3440: my $authhash = $domconfig{'usercreation'}{'authtypes'};
3441: my $context;
3442: if ($env{'request.role'} =~ /^au/) {
3443: $context = 'author';
3444: } elsif ($env{'request.role'} =~ /^dc/) {
3445: $context = 'domain';
3446: } elsif ($env{'request.course.id'}) {
3447: $context = 'course';
3448: }
3449: if ($context) {
3450: if (ref($authhash->{$context}) eq 'HASH') {
3451: %can_assign = %{$authhash->{$context}};
3452: }
3453: }
3454: }
3455: }
3456: my $authnum = 0;
3457: foreach my $key (keys(%can_assign)) {
3458: if ($can_assign{$key}) {
3459: $authnum ++;
3460: }
3461: }
3462: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
3463: $authnum --;
3464: }
3465: return ($authnum,%can_assign);
3466: }
3467:
3468: ###############################################################
3469: ## Get Kerberos Defaults for Domain ##
3470: ###############################################################
3471: ##
3472: ## Returns default kerberos version and an associated argument
3473: ## as listed in file domain.tab. If not listed, provides
3474: ## appropriate default domain and kerberos version.
3475: ##
3476: #-------------------------------------------
3477:
3478: =pod
3479:
3480: =item * &get_kerberos_defaults()
3481:
3482: get_kerberos_defaults($target_domain) returns the default kerberos
3483: version and domain. If not found, it defaults to version 4 and the
3484: domain of the server.
3485:
3486: =over 4
3487:
3488: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
3489:
3490: =back
3491:
3492: =back
3493:
3494: =cut
3495:
3496: #-------------------------------------------
3497: sub get_kerberos_defaults {
3498: my $domain=shift;
3499: my ($krbdef,$krbdefdom);
3500: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
3501: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
3502: $krbdef = $domdefaults{'auth_def'};
3503: $krbdefdom = $domdefaults{'auth_arg_def'};
3504: } else {
3505: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
3506: my $krbdefdom=$1;
3507: $krbdefdom=~tr/a-z/A-Z/;
3508: $krbdef = "krb4";
3509: }
3510: return ($krbdef,$krbdefdom);
3511: }
3512:
3513:
3514: ###############################################################
3515: ## Thesaurus Functions ##
3516: ###############################################################
3517:
3518: =pod
3519:
3520: =head1 Thesaurus Functions
3521:
3522: =over 4
3523:
3524: =item * &initialize_keywords()
3525:
3526: Initializes the package variable %Keywords if it is empty. Uses the
3527: package variable $thesaurus_db_file.
3528:
3529: =cut
3530:
3531: ###################################################
3532:
3533: sub initialize_keywords {
3534: return 1 if (scalar keys(%Keywords));
3535: # If we are here, %Keywords is empty, so fill it up
3536: # Make sure the file we need exists...
3537: if (! -e $thesaurus_db_file) {
3538: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
3539: " failed because it does not exist");
3540: return 0;
3541: }
3542: # Set up the hash as a database
3543: my %thesaurus_db;
3544: if (! tie(%thesaurus_db,'GDBM_File',
3545: $thesaurus_db_file,&GDBM_READER(),0640)){
3546: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
3547: $thesaurus_db_file);
3548: return 0;
3549: }
3550: # Get the average number of appearances of a word.
3551: my $avecount = $thesaurus_db{'average.count'};
3552: # Put keywords (those that appear > average) into %Keywords
3553: while (my ($word,$data)=each (%thesaurus_db)) {
3554: my ($count,undef) = split /:/,$data;
3555: $Keywords{$word}++ if ($count > $avecount);
3556: }
3557: untie %thesaurus_db;
3558: # Remove special values from %Keywords.
3559: foreach my $value ('total.count','average.count') {
3560: delete($Keywords{$value}) if (exists($Keywords{$value}));
3561: }
3562: return 1;
3563: }
3564:
3565: ###################################################
3566:
3567: =pod
3568:
3569: =item * &keyword($word)
3570:
3571: Returns true if $word is a keyword. A keyword is a word that appears more
3572: than the average number of times in the thesaurus database. Calls
3573: &initialize_keywords
3574:
3575: =cut
3576:
3577: ###################################################
3578:
3579: sub keyword {
3580: return if (!&initialize_keywords());
3581: my $word=lc(shift());
3582: $word=~s/\W//g;
3583: return exists($Keywords{$word});
3584: }
3585:
3586: ###############################################################
3587:
3588: =pod
3589:
3590: =item * &get_related_words()
3591:
3592: Look up a word in the thesaurus. Takes a scalar argument and returns
3593: an array of words. If the keyword is not in the thesaurus, an empty array
3594: will be returned. The order of the words returned is determined by the
3595: database which holds them.
3596:
3597: Uses global $thesaurus_db_file.
3598:
3599:
3600: =cut
3601:
3602: ###############################################################
3603: sub get_related_words {
3604: my $keyword = shift;
3605: my %thesaurus_db;
3606: if (! -e $thesaurus_db_file) {
3607: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
3608: "failed because the file does not exist");
3609: return ();
3610: }
3611: if (! tie(%thesaurus_db,'GDBM_File',
3612: $thesaurus_db_file,&GDBM_READER(),0640)){
3613: return ();
3614: }
3615: my @Words=();
3616: my $count=0;
3617: if (exists($thesaurus_db{$keyword})) {
3618: # The first element is the number of times
3619: # the word appears. We do not need it now.
3620: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
3621: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
3622: my $threshold=$mostfrequentcount/10;
3623: foreach my $possibleword (@RelatedWords) {
3624: my ($word,$wordcount)=split(/\,/,$possibleword);
3625: if ($wordcount>$threshold) {
3626: push(@Words,$word);
3627: $count++;
3628: if ($count>10) { last; }
3629: }
3630: }
3631: }
3632: untie %thesaurus_db;
3633: return @Words;
3634: }
3635: ###############################################################
3636: #
3637: # Spell checking
3638: #
3639:
3640: =pod
3641:
3642: =back
3643:
3644: =head1 Spell checking
3645:
3646: =over 4
3647:
3648: =item * &check_spelling($wordlist $language)
3649:
3650: Takes a string containing words and feeds it to an external
3651: spellcheck program via a pipeline. Returns a string containing
3652: them mis-spelled words.
3653:
3654: Parameters:
3655:
3656: =over 4
3657:
3658: =item - $wordlist
3659:
3660: String that will be fed into the spellcheck program.
3661:
3662: =item - $language
3663:
3664: Language string that specifies the language for which the spell
3665: check will be performed.
3666:
3667: =back
3668:
3669: =back
3670:
3671: Note: This sub assumes that aspell is installed.
3672:
3673:
3674: =cut
3675:
3676:
3677: sub check_spelling {
3678: my ($wordlist, $language) = @_;
3679: my @misspellings;
3680:
3681: # Generate the speller and set the langauge.
3682: # if explicitly selected:
3683:
3684: my $speller = Text::Aspell->new;
3685: if ($language) {
3686: $speller->set_option('lang', $language);
3687: }
3688:
3689: # Turn the word list into an array of words by splittingon whitespace
3690:
3691: my @words = split(/\s+/, $wordlist);
3692:
3693: foreach my $word (@words) {
3694: if(! $speller->check($word)) {
3695: push(@misspellings, $word);
3696: }
3697: }
3698: return join(' ', @misspellings);
3699:
3700: }
3701:
3702: # -------------------------------------------------------------- Plaintext name
3703: =pod
3704:
3705: =head1 User Name Functions
3706:
3707: =over 4
3708:
3709: =item * &plainname($uname,$udom,$first)
3710:
3711: Takes a users logon name and returns it as a string in
3712: "first middle last generation" form
3713: if $first is set to 'lastname' then it returns it as
3714: 'lastname generation, firstname middlename' if their is a lastname
3715:
3716: =cut
3717:
3718:
3719: ###############################################################
3720: sub plainname {
3721: my ($uname,$udom,$first)=@_;
3722: return if (!defined($uname) || !defined($udom));
3723: my %names=&getnames($uname,$udom);
3724: my $name=&Apache::lonnet::format_name($names{'firstname'},
3725: $names{'middlename'},
3726: $names{'lastname'},
3727: $names{'generation'},$first);
3728: $name=~s/^\s+//;
3729: $name=~s/\s+$//;
3730: $name=~s/\s+/ /g;
3731: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
3732: return $name;
3733: }
3734:
3735: # -------------------------------------------------------------------- Nickname
3736: =pod
3737:
3738: =item * &nickname($uname,$udom)
3739:
3740: Gets a users name and returns it as a string as
3741:
3742: ""nickname""
3743:
3744: if the user has a nickname or
3745:
3746: "first middle last generation"
3747:
3748: if the user does not
3749:
3750: =cut
3751:
3752: sub nickname {
3753: my ($uname,$udom)=@_;
3754: return if (!defined($uname) || !defined($udom));
3755: my %names=&getnames($uname,$udom);
3756: my $name=$names{'nickname'};
3757: if ($name) {
3758: $name='"'.$name.'"';
3759: } else {
3760: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
3761: $names{'lastname'}.' '.$names{'generation'};
3762: $name=~s/\s+$//;
3763: $name=~s/\s+/ /g;
3764: }
3765: return $name;
3766: }
3767:
3768: sub getnames {
3769: my ($uname,$udom)=@_;
3770: return if (!defined($uname) || !defined($udom));
3771: if ($udom eq 'public' && $uname eq 'public') {
3772: return ('lastname' => &mt('Public'));
3773: }
3774: my $id=$uname.':'.$udom;
3775: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
3776: if ($cached) {
3777: return %{$names};
3778: } else {
3779: my %loadnames=&Apache::lonnet::get('environment',
3780: ['firstname','middlename','lastname','generation','nickname'],
3781: $udom,$uname);
3782: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
3783: return %loadnames;
3784: }
3785: }
3786:
3787: # -------------------------------------------------------------------- getemails
3788:
3789: =pod
3790:
3791: =item * &getemails($uname,$udom)
3792:
3793: Gets a user's email information and returns it as a hash with keys:
3794: notification, critnotification, permanentemail
3795:
3796: For notification and critnotification, values are comma-separated lists
3797: of e-mail addresses; for permanentemail, value is a single e-mail address.
3798:
3799:
3800: =cut
3801:
3802:
3803: sub getemails {
3804: my ($uname,$udom)=@_;
3805: if ($udom eq 'public' && $uname eq 'public') {
3806: return;
3807: }
3808: if (!$udom) { $udom=$env{'user.domain'}; }
3809: if (!$uname) { $uname=$env{'user.name'}; }
3810: my $id=$uname.':'.$udom;
3811: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
3812: if ($cached) {
3813: return %{$names};
3814: } else {
3815: my %loadnames=&Apache::lonnet::get('environment',
3816: ['notification','critnotification',
3817: 'permanentemail'],
3818: $udom,$uname);
3819: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
3820: return %loadnames;
3821: }
3822: }
3823:
3824: sub flush_email_cache {
3825: my ($uname,$udom)=@_;
3826: if (!$udom) { $udom =$env{'user.domain'}; }
3827: if (!$uname) { $uname=$env{'user.name'}; }
3828: return if ($udom eq 'public' && $uname eq 'public');
3829: my $id=$uname.':'.$udom;
3830: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
3831: }
3832:
3833: # -------------------------------------------------------------------- getlangs
3834:
3835: =pod
3836:
3837: =item * &getlangs($uname,$udom)
3838:
3839: Gets a user's language preference and returns it as a hash with key:
3840: language.
3841:
3842: =cut
3843:
3844:
3845: sub getlangs {
3846: my ($uname,$udom) = @_;
3847: if (!$udom) { $udom =$env{'user.domain'}; }
3848: if (!$uname) { $uname=$env{'user.name'}; }
3849: my $id=$uname.':'.$udom;
3850: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
3851: if ($cached) {
3852: return %{$langs};
3853: } else {
3854: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
3855: $udom,$uname);
3856: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
3857: return %loadlangs;
3858: }
3859: }
3860:
3861: sub flush_langs_cache {
3862: my ($uname,$udom)=@_;
3863: if (!$udom) { $udom =$env{'user.domain'}; }
3864: if (!$uname) { $uname=$env{'user.name'}; }
3865: return if ($udom eq 'public' && $uname eq 'public');
3866: my $id=$uname.':'.$udom;
3867: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
3868: }
3869:
3870: # ------------------------------------------------------------------ Screenname
3871:
3872: =pod
3873:
3874: =item * &screenname($uname,$udom)
3875:
3876: Gets a users screenname and returns it as a string
3877:
3878: =cut
3879:
3880: sub screenname {
3881: my ($uname,$udom)=@_;
3882: if ($uname eq $env{'user.name'} &&
3883: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
3884: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
3885: return $names{'screenname'};
3886: }
3887:
3888:
3889: # ------------------------------------------------------------- Confirm Wrapper
3890: =pod
3891:
3892: =item * &confirmwrapper($message)
3893:
3894: Wrap messages about completion of operation in box
3895:
3896: =cut
3897:
3898: sub confirmwrapper {
3899: my ($message)=@_;
3900: if ($message) {
3901: return "\n".'<div class="LC_confirm_box">'."\n"
3902: .$message."\n"
3903: .'</div>'."\n";
3904: } else {
3905: return $message;
3906: }
3907: }
3908:
3909: # ------------------------------------------------------------- Message Wrapper
3910:
3911: sub messagewrapper {
3912: my ($link,$username,$domain,$subject,$text)=@_;
3913: return
3914: '<a href="/adm/email?compose=individual&'.
3915: 'recname='.$username.'&recdom='.$domain.
3916: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
3917: 'title="'.&mt('Send message').'">'.$link.'</a>';
3918: }
3919:
3920: # --------------------------------------------------------------- Notes Wrapper
3921:
3922: sub noteswrapper {
3923: my ($link,$un,$do)=@_;
3924: return
3925: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
3926: }
3927:
3928: # ------------------------------------------------------------- Aboutme Wrapper
3929:
3930: sub aboutmewrapper {
3931: my ($link,$username,$domain,$target,$class)=@_;
3932: if (!defined($username) && !defined($domain)) {
3933: return;
3934: }
3935: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
3936: ($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
3937: }
3938:
3939: # ------------------------------------------------------------ Syllabus Wrapper
3940:
3941: sub syllabuswrapper {
3942: my ($linktext,$coursedir,$domain)=@_;
3943: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
3944: }
3945:
3946: # -----------------------------------------------------------------------------
3947:
3948: sub track_student_link {
3949: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
3950: my $link ="/adm/trackstudent?";
3951: my $title = 'View recent activity';
3952: if (defined($sname) && $sname !~ /^\s*$/ &&
3953: defined($sdom) && $sdom !~ /^\s*$/) {
3954: $link .= "selected_student=$sname:$sdom";
3955: $title .= ' of this student';
3956: }
3957: if (defined($target) && $target !~ /^\s*$/) {
3958: $target = qq{target="$target"};
3959: } else {
3960: $target = '';
3961: }
3962: if ($start) { $link.='&start='.$start; }
3963: if ($only_body) { $link .= '&only_body=1'; }
3964: $title = &mt($title);
3965: $linktext = &mt($linktext);
3966: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
3967: &help_open_topic('View_recent_activity');
3968: }
3969:
3970: sub slot_reservations_link {
3971: my ($linktext,$sname,$sdom,$target) = @_;
3972: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
3973: my $title = 'View slot reservation history';
3974: if (defined($sname) && $sname !~ /^\s*$/ &&
3975: defined($sdom) && $sdom !~ /^\s*$/) {
3976: $link .= "&uname=$sname&udom=$sdom";
3977: $title .= ' of this student';
3978: }
3979: if (defined($target) && $target !~ /^\s*$/) {
3980: $target = qq{target="$target"};
3981: } else {
3982: $target = '';
3983: }
3984: $title = &mt($title);
3985: $linktext = &mt($linktext);
3986: return qq{<a href="$link" title="$title" $target>$linktext</a>};
3987: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
3988:
3989: }
3990:
3991: # ===================================================== Display a student photo
3992:
3993:
3994: sub student_image_tag {
3995: my ($domain,$user)=@_;
3996: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
3997: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
3998: return '<img src="'.$imgsrc.'" align="right" />';
3999: } else {
4000: return '';
4001: }
4002: }
4003:
4004: =pod
4005:
4006: =back
4007:
4008: =head1 Access .tab File Data
4009:
4010: =over 4
4011:
4012: =item * &languageids()
4013:
4014: returns list of all language ids
4015:
4016: =cut
4017:
4018: sub languageids {
4019: return sort(keys(%language));
4020: }
4021:
4022: =pod
4023:
4024: =item * &languagedescription()
4025:
4026: returns description of a specified language id
4027:
4028: =cut
4029:
4030: sub languagedescription {
4031: my $code=shift;
4032: return ($supported_language{$code}?'* ':'').
4033: $language{$code}.
4034: ($supported_language{$code}?' ('.&mt('interface available').')':'');
4035: }
4036:
4037: =pod
4038:
4039: =item * &plainlanguagedescription
4040:
4041: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
4042: and the language character encoding (e.g. ISO) separated by a ' - ' string.
4043:
4044: =cut
4045:
4046: sub plainlanguagedescription {
4047: my $code=shift;
4048: return $language{$code};
4049: }
4050:
4051: =pod
4052:
4053: =item * &supportedlanguagecode
4054:
4055: Returns the supported language code (e.g. sptutf maps to pt) given a language
4056: code.
4057:
4058: =cut
4059:
4060: sub supportedlanguagecode {
4061: my $code=shift;
4062: return $supported_language{$code};
4063: }
4064:
4065: =pod
4066:
4067: =item * &latexlanguage()
4068:
4069: Given a language key code returns the correspondnig language to use
4070: to select the correct hyphenation on LaTeX printouts. This is undef if there
4071: is no supported hyphenation for the language code.
4072:
4073: =cut
4074:
4075: sub latexlanguage {
4076: my $code = shift;
4077: return $latex_language{$code};
4078: }
4079:
4080: =pod
4081:
4082: =item * &latexhyphenation()
4083:
4084: Same as above but what's supplied is the language as it might be stored
4085: in the metadata.
4086:
4087: =cut
4088:
4089: sub latexhyphenation {
4090: my $key = shift;
4091: return $latex_language_bykey{$key};
4092: }
4093:
4094: =pod
4095:
4096: =item * ©rightids()
4097:
4098: returns list of all copyrights
4099:
4100: =cut
4101:
4102: sub copyrightids {
4103: return sort(keys(%cprtag));
4104: }
4105:
4106: =pod
4107:
4108: =item * ©rightdescription()
4109:
4110: returns description of a specified copyright id
4111:
4112: =cut
4113:
4114: sub copyrightdescription {
4115: return &mt($cprtag{shift(@_)});
4116: }
4117:
4118: =pod
4119:
4120: =item * &source_copyrightids()
4121:
4122: returns list of all source copyrights
4123:
4124: =cut
4125:
4126: sub source_copyrightids {
4127: return sort(keys(%scprtag));
4128: }
4129:
4130: =pod
4131:
4132: =item * &source_copyrightdescription()
4133:
4134: returns description of a specified source copyright id
4135:
4136: =cut
4137:
4138: sub source_copyrightdescription {
4139: return &mt($scprtag{shift(@_)});
4140: }
4141:
4142: =pod
4143:
4144: =item * &filecategories()
4145:
4146: returns list of all file categories
4147:
4148: =cut
4149:
4150: sub filecategories {
4151: return sort(keys(%category_extensions));
4152: }
4153:
4154: =pod
4155:
4156: =item * &filecategorytypes()
4157:
4158: returns list of file types belonging to a given file
4159: category
4160:
4161: =cut
4162:
4163: sub filecategorytypes {
4164: my ($cat) = @_;
4165: if (ref($category_extensions{lc($cat)}) eq 'ARRAY') {
4166: return @{$category_extensions{lc($cat)}};
4167: } else {
4168: return ();
4169: }
4170: }
4171:
4172: =pod
4173:
4174: =item * &fileembstyle()
4175:
4176: returns embedding style for a specified file type
4177:
4178: =cut
4179:
4180: sub fileembstyle {
4181: return $fe{lc(shift(@_))};
4182: }
4183:
4184: sub filemimetype {
4185: return $fm{lc(shift(@_))};
4186: }
4187:
4188:
4189: sub filecategoryselect {
4190: my ($name,$value)=@_;
4191: return &select_form($value,$name,
4192: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
4193: }
4194:
4195: =pod
4196:
4197: =item * &filedescription()
4198:
4199: returns description for a specified file type
4200:
4201: =cut
4202:
4203: sub filedescription {
4204: my $file_description = $fd{lc(shift())};
4205: $file_description =~ s:([\[\]]):~$1:g;
4206: return &mt($file_description);
4207: }
4208:
4209: =pod
4210:
4211: =item * &filedescriptionex()
4212:
4213: returns description for a specified file type with
4214: extra formatting
4215:
4216: =cut
4217:
4218: sub filedescriptionex {
4219: my $ex=shift;
4220: my $file_description = $fd{lc($ex)};
4221: $file_description =~ s:([\[\]]):~$1:g;
4222: return '.'.$ex.' '.&mt($file_description);
4223: }
4224:
4225: # End of .tab access
4226: =pod
4227:
4228: =back
4229:
4230: =cut
4231:
4232: # ------------------------------------------------------------------ File Types
4233: sub fileextensions {
4234: return sort(keys(%fe));
4235: }
4236:
4237: # ----------------------------------------------------------- Display Languages
4238: # returns a hash with all desired display languages
4239: #
4240:
4241: sub display_languages {
4242: my %languages=();
4243: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
4244: $languages{$lang}=1;
4245: }
4246: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
4247: if ($env{'form.displaylanguage'}) {
4248: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
4249: $languages{$lang}=1;
4250: }
4251: }
4252: return %languages;
4253: }
4254:
4255: sub languages {
4256: my ($possible_langs) = @_;
4257: my @preferred_langs = &Apache::lonlocal::preferred_languages();
4258: if (!ref($possible_langs)) {
4259: if( wantarray ) {
4260: return @preferred_langs;
4261: } else {
4262: return $preferred_langs[0];
4263: }
4264: }
4265: my %possibilities = map { $_ => 1 } (@$possible_langs);
4266: my @preferred_possibilities;
4267: foreach my $preferred_lang (@preferred_langs) {
4268: if (exists($possibilities{$preferred_lang})) {
4269: push(@preferred_possibilities, $preferred_lang);
4270: }
4271: }
4272: if( wantarray ) {
4273: return @preferred_possibilities;
4274: }
4275: return $preferred_possibilities[0];
4276: }
4277:
4278: sub user_lang {
4279: my ($touname,$toudom,$fromcid) = @_;
4280: my @userlangs;
4281: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
4282: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
4283: $env{'course.'.$fromcid.'.languages'}));
4284: } else {
4285: my %langhash = &getlangs($touname,$toudom);
4286: if ($langhash{'languages'} ne '') {
4287: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
4288: } else {
4289: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
4290: if ($domdefs{'lang_def'} ne '') {
4291: @userlangs = ($domdefs{'lang_def'});
4292: }
4293: }
4294: }
4295: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
4296: my $user_lh = Apache::localize->get_handle(@languages);
4297: return $user_lh;
4298: }
4299:
4300:
4301: ###############################################################
4302: ## Student Answer Attempts ##
4303: ###############################################################
4304:
4305: =pod
4306:
4307: =head1 Alternate Problem Views
4308:
4309: =over 4
4310:
4311: =item * &get_previous_attempt($symb, $username, $domain, $course,
4312: $getattempt, $regexp, $gradesub, $usec, $identifier)
4313:
4314: Return string with previous attempt on problem. Arguments:
4315:
4316: =over 4
4317:
4318: =item * $symb: Problem, including path
4319:
4320: =item * $username: username of the desired student
4321:
4322: =item * $domain: domain of the desired student
4323:
4324: =item * $course: Course ID
4325:
4326: =item * $getattempt: Leave blank for all attempts, otherwise put
4327: something
4328:
4329: =item * $regexp: if string matches this regexp, the string will be
4330: sent to $gradesub
4331:
4332: =item * $gradesub: routine that processes the string if it matches $regexp
4333:
4334: =item * $usec: section of the desired student
4335:
4336: =item * $identifier: counter for student (multiple students one problem) or
4337: problem (one student; whole sequence).
4338:
4339: =back
4340:
4341: The output string is a table containing all desired attempts, if any.
4342:
4343: =cut
4344:
4345: sub get_previous_attempt {
4346: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
4347: my $prevattempts='';
4348: no strict 'refs';
4349: if ($symb) {
4350: my (%returnhash)=
4351: &Apache::lonnet::restore($symb,$course,$domain,$username);
4352: if ($returnhash{'version'}) {
4353: my %lasthash=();
4354: my $version;
4355: for ($version=1;$version<=$returnhash{'version'};$version++) {
4356: foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
4357: if ($key =~ /\.rawrndseed$/) {
4358: my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
4359: $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
4360: } else {
4361: $lasthash{$key}=$returnhash{$version.':'.$key};
4362: }
4363: }
4364: }
4365: $prevattempts=&start_data_table().&start_data_table_header_row();
4366: $prevattempts.='<th>'.&mt('History').'</th>';
4367: my (%typeparts,%lasthidden,%regraded,%hidestatus);
4368: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
4369: foreach my $key (sort(keys(%lasthash))) {
4370: my ($ign,@parts) = split(/\./,$key);
4371: if ($#parts > 0) {
4372: my $data=$parts[-1];
4373: next if ($data eq 'foilorder');
4374: pop(@parts);
4375: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
4376: if ($data eq 'type') {
4377: unless ($showsurv) {
4378: my $id = join(',',@parts);
4379: $typeparts{$ign.'.'.$id} = $lasthash{$key};
4380: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
4381: $lasthidden{$ign.'.'.$id} = 1;
4382: }
4383: }
4384: if ($identifier ne '') {
4385: my $id = join(',',@parts);
4386: if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
4387: $domain,$username,$usec,undef,$course) =~ /^no/) {
4388: $hidestatus{$ign.'.'.$id} = 1;
4389: }
4390: }
4391: } elsif ($data eq 'regrader') {
4392: if (($identifier ne '') && (@parts)) {
4393: my $id = join(',',@parts);
4394: $regraded{$ign.'.'.$id} = 1;
4395: }
4396: }
4397: } else {
4398: if ($#parts == 0) {
4399: $prevattempts.='<th>'.$parts[0].'</th>';
4400: } else {
4401: $prevattempts.='<th>'.$ign.'</th>';
4402: }
4403: }
4404: }
4405: $prevattempts.=&end_data_table_header_row();
4406: if ($getattempt eq '') {
4407: my (%solved,%resets,%probstatus);
4408: if (($identifier ne '') && (keys(%regraded) > 0)) {
4409: for ($version=1;$version<=$returnhash{'version'};$version++) {
4410: foreach my $id (keys(%regraded)) {
4411: if (($returnhash{$version.':'.$id.'.regrader'}) &&
4412: ($returnhash{$version.':'.$id.'.tries'} eq '') &&
4413: ($returnhash{$version.':'.$id.'.award'} eq '')) {
4414: push(@{$resets{$id}},$version);
4415: }
4416: }
4417: }
4418: }
4419: for ($version=1;$version<=$returnhash{'version'};$version++) {
4420: my (@hidden,@unsolved);
4421: if (%typeparts) {
4422: foreach my $id (keys(%typeparts)) {
4423: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
4424: ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
4425: push(@hidden,$id);
4426: } elsif ($identifier ne '') {
4427: unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
4428: ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
4429: ($hidestatus{$id})) {
4430: next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
4431: if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
4432: push(@{$solved{$id}},$version);
4433: } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
4434: (ref($solved{$id}) eq 'ARRAY')) {
4435: my $skip;
4436: if (ref($resets{$id}) eq 'ARRAY') {
4437: foreach my $reset (@{$resets{$id}}) {
4438: if ($reset > $solved{$id}[-1]) {
4439: $skip=1;
4440: last;
4441: }
4442: }
4443: }
4444: unless ($skip) {
4445: my ($ign,$partslist) = split(/\./,$id,2);
4446: push(@unsolved,$partslist);
4447: }
4448: }
4449: }
4450: }
4451: }
4452: }
4453: $prevattempts.=&start_data_table_row().
4454: '<td>'.&mt('Transaction [_1]',$version);
4455: if (@unsolved) {
4456: $prevattempts .= '<span class="LC_nobreak"><label>'.
4457: '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
4458: &mt('Hide').'</label></span>';
4459: }
4460: $prevattempts .= '</td>';
4461: if (@hidden) {
4462: foreach my $key (sort(keys(%lasthash))) {
4463: next if ($key =~ /\.foilorder$/);
4464: my $hide;
4465: foreach my $id (@hidden) {
4466: if ($key =~ /^\Q$id\E/) {
4467: $hide = 1;
4468: last;
4469: }
4470: }
4471: if ($hide) {
4472: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4473: if (($data eq 'award') || ($data eq 'awarddetail')) {
4474: my $value = &format_previous_attempt_value($key,
4475: $returnhash{$version.':'.$key});
4476: $prevattempts.='<td>'.$value.' </td>';
4477: } else {
4478: $prevattempts.='<td> </td>';
4479: }
4480: } else {
4481: if ($key =~ /\./) {
4482: my $value = $returnhash{$version.':'.$key};
4483: if ($key =~ /\.rndseed$/) {
4484: my ($id) = ($key =~ /^(.+)\.[^.]+$/);
4485: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4486: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4487: }
4488: }
4489: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4490: ' </td>';
4491: } else {
4492: $prevattempts.='<td> </td>';
4493: }
4494: }
4495: }
4496: } else {
4497: foreach my $key (sort(keys(%lasthash))) {
4498: next if ($key =~ /\.foilorder$/);
4499: my $value = $returnhash{$version.':'.$key};
4500: if ($key =~ /\.rndseed$/) {
4501: my ($id) = ($key =~ /^(.+)\.[^.]+$/);
4502: if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
4503: $value = $returnhash{$version.':'.$id.'.rawrndseed'};
4504: }
4505: }
4506: $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
4507: ' </td>';
4508: }
4509: }
4510: $prevattempts.=&end_data_table_row();
4511: }
4512: }
4513: my @currhidden = keys(%lasthidden);
4514: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
4515: foreach my $key (sort(keys(%lasthash))) {
4516: next if ($key =~ /\.foilorder$/);
4517: if (%typeparts) {
4518: my $hidden;
4519: foreach my $id (@currhidden) {
4520: if ($key =~ /^\Q$id\E/) {
4521: $hidden = 1;
4522: last;
4523: }
4524: }
4525: if ($hidden) {
4526: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
4527: if (($data eq 'award') || ($data eq 'awarddetail')) {
4528: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4529: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4530: $value = &$gradesub($value);
4531: }
4532: $prevattempts.='<td>'. $value.' </td>';
4533: } else {
4534: $prevattempts.='<td> </td>';
4535: }
4536: } else {
4537: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4538: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4539: $value = &$gradesub($value);
4540: }
4541: $prevattempts.='<td>'.$value.' </td>';
4542: }
4543: } else {
4544: my $value = &format_previous_attempt_value($key,$lasthash{$key});
4545: if ($key =~/$regexp$/ && (defined &$gradesub)) {
4546: $value = &$gradesub($value);
4547: }
4548: $prevattempts.='<td>'.$value.' </td>';
4549: }
4550: }
4551: $prevattempts.= &end_data_table_row().&end_data_table();
4552: } else {
4553: $prevattempts=
4554: &start_data_table().&start_data_table_row().
4555: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
4556: &end_data_table_row().&end_data_table();
4557: }
4558: } else {
4559: $prevattempts=
4560: &start_data_table().&start_data_table_row().
4561: '<td>'.&mt('No data.').'</td>'.
4562: &end_data_table_row().&end_data_table();
4563: }
4564: }
4565:
4566: sub format_previous_attempt_value {
4567: my ($key,$value) = @_;
4568: if (($key =~ /timestamp/) || ($key=~/duedate/)) {
4569: $value = &Apache::lonlocal::locallocaltime($value);
4570: } elsif (ref($value) eq 'ARRAY') {
4571: $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
4572: } elsif ($key =~ /answerstring$/) {
4573: my %answers = &Apache::lonnet::str2hash($value);
4574: my @answer = %answers;
4575: %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
4576: my @anskeys = sort(keys(%answers));
4577: if (@anskeys == 1) {
4578: my $answer = $answers{$anskeys[0]};
4579: if ($answer =~ m{\0}) {
4580: $answer =~ s{\0}{,}g;
4581: }
4582: my $tag_internal_answer_name = 'INTERNAL';
4583: if ($anskeys[0] eq $tag_internal_answer_name) {
4584: $value = $answer;
4585: } else {
4586: $value = $anskeys[0].'='.$answer;
4587: }
4588: } else {
4589: foreach my $ans (@anskeys) {
4590: my $answer = $answers{$ans};
4591: if ($answer =~ m{\0}) {
4592: $answer =~ s{\0}{,}g;
4593: }
4594: $value .= $ans.'='.$answer.'<br />';;
4595: }
4596: }
4597: } else {
4598: $value = &HTML::Entities::encode(&unescape($value), '"<>&');
4599: }
4600: return $value;
4601: }
4602:
4603:
4604: sub relative_to_absolute {
4605: my ($url,$output)=@_;
4606: my $parser=HTML::TokeParser->new(\$output);
4607: my $token;
4608: my $thisdir=$url;
4609: my @rlinks=();
4610: while ($token=$parser->get_token) {
4611: if ($token->[0] eq 'S') {
4612: if ($token->[1] eq 'a') {
4613: if ($token->[2]->{'href'}) {
4614: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
4615: }
4616: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
4617: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
4618: } elsif ($token->[1] eq 'base') {
4619: $thisdir=$token->[2]->{'href'};
4620: }
4621: }
4622: }
4623: $thisdir=~s-/[^/]*$--;
4624: foreach my $link (@rlinks) {
4625: unless (($link=~/^https?\:\/\//i) ||
4626: ($link=~/^\//) ||
4627: ($link=~/^javascript:/i) ||
4628: ($link=~/^mailto:/i) ||
4629: ($link=~/^\#/)) {
4630: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
4631: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
4632: }
4633: }
4634: # -------------------------------------------------- Deal with Applet codebases
4635: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
4636: return $output;
4637: }
4638:
4639: =pod
4640:
4641: =item * &get_student_view()
4642:
4643: show a snapshot of what student was looking at
4644:
4645: =cut
4646:
4647: sub get_student_view {
4648: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
4649: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4650: my (%form);
4651: my @elements=('symb','courseid','domain','username');
4652: foreach my $element (@elements) {
4653: $form{'grade_'.$element}=eval '$'.$element #'
4654: }
4655: if (defined($moreenv)) {
4656: %form=(%form,%{$moreenv});
4657: }
4658: if (defined($target)) { $form{'grade_target'} = $target; }
4659: $feedurl=&Apache::lonnet::clutter($feedurl);
4660: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
4661: $userview=~s/\<body[^\>]*\>//gi;
4662: $userview=~s/\<\/body\>//gi;
4663: $userview=~s/\<html\>//gi;
4664: $userview=~s/\<\/html\>//gi;
4665: $userview=~s/\<head\>//gi;
4666: $userview=~s/\<\/head\>//gi;
4667: $userview=~s/action\s*\=/would_be_action\=/gi;
4668: $userview=&relative_to_absolute($feedurl,$userview);
4669: if (wantarray) {
4670: return ($userview,$response);
4671: } else {
4672: return $userview;
4673: }
4674: }
4675:
4676: sub get_student_view_with_retries {
4677: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
4678:
4679: my $ok = 0; # True if we got a good response.
4680: my $content;
4681: my $response;
4682:
4683: # Try to get the student_view done. within the retries count:
4684:
4685: do {
4686: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
4687: $ok = $response->is_success;
4688: if (!$ok) {
4689: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
4690: }
4691: $retries--;
4692: } while (!$ok && ($retries > 0));
4693:
4694: if (!$ok) {
4695: $content = ''; # On error return an empty content.
4696: }
4697: if (wantarray) {
4698: return ($content, $response);
4699: } else {
4700: return $content;
4701: }
4702: }
4703:
4704: =pod
4705:
4706: =item * &get_student_answers()
4707:
4708: show a snapshot of how student was answering problem
4709:
4710: =cut
4711:
4712: sub get_student_answers {
4713: my ($symb,$username,$domain,$courseid,%form) = @_;
4714: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4715: my (%moreenv);
4716: my @elements=('symb','courseid','domain','username');
4717: foreach my $element (@elements) {
4718: $moreenv{'grade_'.$element}=eval '$'.$element #'
4719: }
4720: $moreenv{'grade_target'}='answer';
4721: %moreenv=(%form,%moreenv);
4722: $feedurl = &Apache::lonnet::clutter($feedurl);
4723: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
4724: return $userview;
4725: }
4726:
4727: =pod
4728:
4729: =item * &submlink()
4730:
4731: Inputs: $text $uname $udom $symb $target
4732:
4733: Returns: A link to grades.pm such as to see the SUBM view of a student
4734:
4735: =cut
4736:
4737: ###############################################
4738: sub submlink {
4739: my ($text,$uname,$udom,$symb,$target)=@_;
4740: if (!($uname && $udom)) {
4741: (my $cursymb, my $courseid,$udom,$uname)=
4742: &Apache::lonnet::whichuser($symb);
4743: if (!$symb) { $symb=$cursymb; }
4744: }
4745: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4746: $symb=&escape($symb);
4747: if ($target) { $target=" target=\"$target\""; }
4748: return
4749: '<a href="/adm/grades?command=submission'.
4750: '&symb='.$symb.
4751: '&student='.$uname.
4752: '&userdom='.$udom.'"'.
4753: $target.'>'.$text.'</a>';
4754: }
4755: ##############################################
4756:
4757: =pod
4758:
4759: =item * &pgrdlink()
4760:
4761: Inputs: $text $uname $udom $symb $target
4762:
4763: Returns: A link to grades.pm such as to see the PGRD view of a student
4764:
4765: =cut
4766:
4767: ###############################################
4768: sub pgrdlink {
4769: my $link=&submlink(@_);
4770: $link=~s/(&command=submission)/$1&showgrading=yes/;
4771: return $link;
4772: }
4773: ##############################################
4774:
4775: =pod
4776:
4777: =item * &pprmlink()
4778:
4779: Inputs: $text $uname $udom $symb $target
4780:
4781: Returns: A link to parmset.pm such as to see the PPRM view of a
4782: student and a specific resource
4783:
4784: =cut
4785:
4786: ###############################################
4787: sub pprmlink {
4788: my ($text,$uname,$udom,$symb,$target)=@_;
4789: if (!($uname && $udom)) {
4790: (my $cursymb, my $courseid,$udom,$uname)=
4791: &Apache::lonnet::whichuser($symb);
4792: if (!$symb) { $symb=$cursymb; }
4793: }
4794: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4795: $symb=&escape($symb);
4796: if ($target) { $target="target=\"$target\""; }
4797: return '<a href="/adm/parmset?command=set&'.
4798: 'symb='.$symb.'&uname='.$uname.
4799: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
4800: }
4801: ##############################################
4802:
4803: =pod
4804:
4805: =back
4806:
4807: =cut
4808:
4809: ###############################################
4810:
4811:
4812: sub timehash {
4813: my ($thistime) = @_;
4814: my $timezone = &Apache::lonlocal::gettimezone();
4815: my $dt = DateTime->from_epoch(epoch => $thistime)
4816: ->set_time_zone($timezone);
4817: my $wday = $dt->day_of_week();
4818: if ($wday == 7) { $wday = 0; }
4819: return ( 'second' => $dt->second(),
4820: 'minute' => $dt->minute(),
4821: 'hour' => $dt->hour(),
4822: 'day' => $dt->day_of_month(),
4823: 'month' => $dt->month(),
4824: 'year' => $dt->year(),
4825: 'weekday' => $wday,
4826: 'dayyear' => $dt->day_of_year(),
4827: 'dlsav' => $dt->is_dst() );
4828: }
4829:
4830: sub utc_string {
4831: my ($date)=@_;
4832: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
4833: }
4834:
4835: sub maketime {
4836: my %th=@_;
4837: my ($epoch_time,$timezone,$dt);
4838: $timezone = &Apache::lonlocal::gettimezone();
4839: eval {
4840: $dt = DateTime->new( year => $th{'year'},
4841: month => $th{'month'},
4842: day => $th{'day'},
4843: hour => $th{'hour'},
4844: minute => $th{'minute'},
4845: second => $th{'second'},
4846: time_zone => $timezone,
4847: );
4848: };
4849: if (!$@) {
4850: $epoch_time = $dt->epoch;
4851: if ($epoch_time) {
4852: return $epoch_time;
4853: }
4854: }
4855: return POSIX::mktime(
4856: ($th{'seconds'},$th{'minutes'},$th{'hours'},
4857: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
4858: }
4859:
4860: #########################################
4861:
4862: sub findallcourses {
4863: my ($roles,$uname,$udom) = @_;
4864: my %roles;
4865: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
4866: my %courses;
4867: my $now=time;
4868: if (!defined($uname)) {
4869: $uname = $env{'user.name'};
4870: }
4871: if (!defined($udom)) {
4872: $udom = $env{'user.domain'};
4873: }
4874: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
4875: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
4876: if (!%roles) {
4877: %roles = (
4878: cc => 1,
4879: co => 1,
4880: in => 1,
4881: ep => 1,
4882: ta => 1,
4883: cr => 1,
4884: st => 1,
4885: );
4886: }
4887: foreach my $entry (keys(%roleshash)) {
4888: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
4889: if ($trole =~ /^cr/) {
4890: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
4891: } else {
4892: next if (!exists($roles{$trole}));
4893: }
4894: if ($tend) {
4895: next if ($tend < $now);
4896: }
4897: if ($tstart) {
4898: next if ($tstart > $now);
4899: }
4900: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
4901: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
4902: my $value = $trole.'/'.$cdom.'/';
4903: if ($secpart eq '') {
4904: ($cnum,$role) = split(/_/,$cnumpart);
4905: $sec = 'none';
4906: $value .= $cnum.'/';
4907: } else {
4908: $cnum = $cnumpart;
4909: ($sec,$role) = split(/_/,$secpart);
4910: $value .= $cnum.'/'.$sec;
4911: }
4912: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4913: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4914: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4915: }
4916: } else {
4917: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4918: }
4919: }
4920: } else {
4921: foreach my $key (keys(%env)) {
4922: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
4923: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
4924: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
4925: next if ($role eq 'ca' || $role eq 'aa');
4926: next if (%roles && !exists($roles{$role}));
4927: my ($starttime,$endtime)=split(/\./,$env{$key});
4928: my $active=1;
4929: if ($starttime) {
4930: if ($now<$starttime) { $active=0; }
4931: }
4932: if ($endtime) {
4933: if ($now>$endtime) { $active=0; }
4934: }
4935: if ($active) {
4936: my $value = $role.'/'.$cdom.'/'.$cnum.'/';
4937: if ($sec eq '') {
4938: $sec = 'none';
4939: } else {
4940: $value .= $sec;
4941: }
4942: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4943: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4944: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4945: }
4946: } else {
4947: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4948: }
4949: }
4950: }
4951: }
4952: }
4953: return %courses;
4954: }
4955:
4956: ###############################################
4957:
4958: sub blockcheck {
4959: my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
4960:
4961: if (defined($udom) && defined($uname)) {
4962: # If uname and udom are for a course, check for blocks in the course.
4963: if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
4964: my ($startblock,$endblock,$triggerblock) =
4965: &get_blocks($setters,$activity,$udom,$uname,$url);
4966: return ($startblock,$endblock,$triggerblock);
4967: }
4968: } else {
4969: $udom = $env{'user.domain'};
4970: $uname = $env{'user.name'};
4971: }
4972:
4973: my $startblock = 0;
4974: my $endblock = 0;
4975: my $triggerblock = '';
4976: my %live_courses = &findallcourses(undef,$uname,$udom);
4977:
4978: # If uname is for a user, and activity is course-specific, i.e.,
4979: # boards, chat or groups, check for blocking in current course only.
4980:
4981: if (($activity eq 'boards' || $activity eq 'chat' ||
4982: $activity eq 'groups' || $activity eq 'printout') &&
4983: ($env{'request.course.id'})) {
4984: foreach my $key (keys(%live_courses)) {
4985: if ($key ne $env{'request.course.id'}) {
4986: delete($live_courses{$key});
4987: }
4988: }
4989: }
4990:
4991: my $otheruser = 0;
4992: my %own_courses;
4993: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
4994: # Resource belongs to user other than current user.
4995: $otheruser = 1;
4996: # Gather courses for current user
4997: %own_courses =
4998: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
4999: }
5000:
5001: # Gather active course roles - course coordinator, instructor,
5002: # exam proctor, ta, student, or custom role.
5003:
5004: foreach my $course (keys(%live_courses)) {
5005: my ($cdom,$cnum);
5006: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
5007: $cdom = $env{'course.'.$course.'.domain'};
5008: $cnum = $env{'course.'.$course.'.num'};
5009: } else {
5010: ($cdom,$cnum) = split(/_/,$course);
5011: }
5012: my $no_ownblock = 0;
5013: my $no_userblock = 0;
5014: if ($otheruser && $activity ne 'com') {
5015: # Check if current user has 'evb' priv for this
5016: if (defined($own_courses{$course})) {
5017: foreach my $sec (keys(%{$own_courses{$course}})) {
5018: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
5019: if ($sec ne 'none') {
5020: $checkrole .= '/'.$sec;
5021: }
5022: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
5023: $no_ownblock = 1;
5024: last;
5025: }
5026: }
5027: }
5028: # if they have 'evb' priv and are currently not playing student
5029: next if (($no_ownblock) &&
5030: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
5031: }
5032: foreach my $sec (keys(%{$live_courses{$course}})) {
5033: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
5034: if ($sec ne 'none') {
5035: $checkrole .= '/'.$sec;
5036: }
5037: if ($otheruser) {
5038: # Resource belongs to user other than current user.
5039: # Assemble privs for that user, and check for 'evb' priv.
5040: my (%allroles,%userroles);
5041: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
5042: foreach my $entry (@{$live_courses{$course}{$sec}}) {
5043: my ($trole,$tdom,$tnum,$tsec);
5044: if ($entry =~ /^cr/) {
5045: ($trole,$tdom,$tnum,$tsec) =
5046: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
5047: } else {
5048: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
5049: }
5050: my ($spec,$area,$trest);
5051: $area = '/'.$tdom.'/'.$tnum;
5052: $trest = $tnum;
5053: if ($tsec ne '') {
5054: $area .= '/'.$tsec;
5055: $trest .= '/'.$tsec;
5056: }
5057: $spec = $trole.'.'.$area;
5058: if ($trole =~ /^cr/) {
5059: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
5060: $tdom,$spec,$trest,$area);
5061: } else {
5062: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
5063: $tdom,$spec,$trest,$area);
5064: }
5065: }
5066: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
5067: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
5068: if ($1) {
5069: $no_userblock = 1;
5070: last;
5071: }
5072: }
5073: }
5074: } else {
5075: # Resource belongs to current user
5076: # Check for 'evb' priv via lonnet::allowed().
5077: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
5078: $no_ownblock = 1;
5079: last;
5080: }
5081: }
5082: }
5083: # if they have the evb priv and are currently not playing student
5084: next if (($no_ownblock) &&
5085: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
5086: next if ($no_userblock);
5087:
5088: # Retrieve blocking times and identity of locker for course
5089: # of specified user, unless user has 'evb' privilege.
5090:
5091: my ($start,$end,$trigger) =
5092: &get_blocks($setters,$activity,$cdom,$cnum,$url);
5093: if (($start != 0) &&
5094: (($startblock == 0) || ($startblock > $start))) {
5095: $startblock = $start;
5096: if ($trigger ne '') {
5097: $triggerblock = $trigger;
5098: }
5099: }
5100: if (($end != 0) &&
5101: (($endblock == 0) || ($endblock < $end))) {
5102: $endblock = $end;
5103: if ($trigger ne '') {
5104: $triggerblock = $trigger;
5105: }
5106: }
5107: }
5108: return ($startblock,$endblock,$triggerblock);
5109: }
5110:
5111: sub get_blocks {
5112: my ($setters,$activity,$cdom,$cnum,$url) = @_;
5113: my $startblock = 0;
5114: my $endblock = 0;
5115: my $triggerblock = '';
5116: my $course = $cdom.'_'.$cnum;
5117: $setters->{$course} = {};
5118: $setters->{$course}{'staff'} = [];
5119: $setters->{$course}{'times'} = [];
5120: $setters->{$course}{'triggers'} = [];
5121: my (@blockers,%triggered);
5122: my $now = time;
5123: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
5124: if ($activity eq 'docs') {
5125: @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
5126: foreach my $block (@blockers) {
5127: if ($block =~ /^firstaccess____(.+)$/) {
5128: my $item = $1;
5129: my $type = 'map';
5130: my $timersymb = $item;
5131: if ($item eq 'course') {
5132: $type = 'course';
5133: } elsif ($item =~ /___\d+___/) {
5134: $type = 'resource';
5135: } else {
5136: $timersymb = &Apache::lonnet::symbread($item);
5137: }
5138: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
5139: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
5140: $triggered{$block} = {
5141: start => $start,
5142: end => $end,
5143: type => $type,
5144: };
5145: }
5146: }
5147: } else {
5148: foreach my $block (keys(%commblocks)) {
5149: if ($block =~ m/^(\d+)____(\d+)$/) {
5150: my ($start,$end) = ($1,$2);
5151: if ($start <= time && $end >= time) {
5152: if (ref($commblocks{$block}) eq 'HASH') {
5153: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
5154: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
5155: unless(grep(/^\Q$block\E$/,@blockers)) {
5156: push(@blockers,$block);
5157: }
5158: }
5159: }
5160: }
5161: }
5162: } elsif ($block =~ /^firstaccess____(.+)$/) {
5163: my $item = $1;
5164: my $timersymb = $item;
5165: my $type = 'map';
5166: if ($item eq 'course') {
5167: $type = 'course';
5168: } elsif ($item =~ /___\d+___/) {
5169: $type = 'resource';
5170: } else {
5171: $timersymb = &Apache::lonnet::symbread($item);
5172: }
5173: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
5174: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
5175: if ($start && $end) {
5176: if (($start <= time) && ($end >= time)) {
5177: unless (grep(/^\Q$block\E$/,@blockers)) {
5178: push(@blockers,$block);
5179: $triggered{$block} = {
5180: start => $start,
5181: end => $end,
5182: type => $type,
5183: };
5184: }
5185: }
5186: }
5187: }
5188: }
5189: }
5190: foreach my $blocker (@blockers) {
5191: my ($staff_name,$staff_dom,$title,$blocks) =
5192: &parse_block_record($commblocks{$blocker});
5193: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
5194: my ($start,$end,$triggertype);
5195: if ($blocker =~ m/^(\d+)____(\d+)$/) {
5196: ($start,$end) = ($1,$2);
5197: } elsif (ref($triggered{$blocker}) eq 'HASH') {
5198: $start = $triggered{$blocker}{'start'};
5199: $end = $triggered{$blocker}{'end'};
5200: $triggertype = $triggered{$blocker}{'type'};
5201: }
5202: if ($start) {
5203: push(@{$$setters{$course}{'times'}}, [$start,$end]);
5204: if ($triggertype) {
5205: push(@{$$setters{$course}{'triggers'}},$triggertype);
5206: } else {
5207: push(@{$$setters{$course}{'triggers'}},0);
5208: }
5209: if ( ($startblock == 0) || ($startblock > $start) ) {
5210: $startblock = $start;
5211: if ($triggertype) {
5212: $triggerblock = $blocker;
5213: }
5214: }
5215: if ( ($endblock == 0) || ($endblock < $end) ) {
5216: $endblock = $end;
5217: if ($triggertype) {
5218: $triggerblock = $blocker;
5219: }
5220: }
5221: }
5222: }
5223: return ($startblock,$endblock,$triggerblock);
5224: }
5225:
5226: sub parse_block_record {
5227: my ($record) = @_;
5228: my ($setuname,$setudom,$title,$blocks);
5229: if (ref($record) eq 'HASH') {
5230: ($setuname,$setudom) = split(/:/,$record->{'setter'});
5231: $title = &unescape($record->{'event'});
5232: $blocks = $record->{'blocks'};
5233: } else {
5234: my @data = split(/:/,$record,3);
5235: if (scalar(@data) eq 2) {
5236: $title = $data[1];
5237: ($setuname,$setudom) = split(/@/,$data[0]);
5238: } else {
5239: ($setuname,$setudom,$title) = @data;
5240: }
5241: $blocks = { 'com' => 'on' };
5242: }
5243: return ($setuname,$setudom,$title,$blocks);
5244: }
5245:
5246: sub blocking_status {
5247: my ($activity,$uname,$udom,$url,$is_course) = @_;
5248: my %setters;
5249:
5250: # check for active blocking
5251: my ($startblock,$endblock,$triggerblock) =
5252: &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
5253: my $blocked = 0;
5254: if ($startblock && $endblock) {
5255: $blocked = 1;
5256: }
5257:
5258: # caller just wants to know whether a block is active
5259: if (!wantarray) { return $blocked; }
5260:
5261: # build a link to a popup window containing the details
5262: my $querystring = "?activity=$activity";
5263: # $uname and $udom decide whose portfolio the user is trying to look at
5264: if (($activity eq 'port') || ($activity eq 'passwd')) {
5265: $querystring .= "&udom=$udom" if ($udom =~ /^$match_domain$/);
5266: $querystring .= "&uname=$uname" if ($uname =~ /^$match_username$/);
5267: } elsif ($activity eq 'docs') {
5268: $querystring .= '&url='.&HTML::Entities::encode($url,'&"');
5269: }
5270:
5271: my $output .= <<'END_MYBLOCK';
5272: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
5273: var options = "width=" + w + ",height=" + h + ",";
5274: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
5275: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
5276: var newWin = window.open(url, wdwName, options);
5277: newWin.focus();
5278: }
5279: END_MYBLOCK
5280:
5281: $output = Apache::lonhtmlcommon::scripttag($output);
5282:
5283: my $popupUrl = "/adm/blockingstatus/$querystring";
5284: my $text = &mt('Communication Blocked');
5285: my $class = 'LC_comblock';
5286: if ($activity eq 'docs') {
5287: $text = &mt('Content Access Blocked');
5288: $class = '';
5289: } elsif ($activity eq 'printout') {
5290: $text = &mt('Printing Blocked');
5291: } elsif ($activity eq 'passwd') {
5292: $text = &mt('Password Changing Blocked');
5293: }
5294: $output .= <<"END_BLOCK";
5295: <div class='$class'>
5296: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
5297: title='$text'>
5298: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
5299: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
5300: title='$text'>$text</a>
5301: </div>
5302:
5303: END_BLOCK
5304:
5305: return ($blocked, $output);
5306: }
5307:
5308: ###############################################
5309:
5310: sub check_ip_acc {
5311: my ($acc,$clientip)=@_;
5312: &Apache::lonxml::debug("acc is $acc");
5313: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
5314: return 1;
5315: }
5316: my $allowed;
5317: my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
5318:
5319: my $name;
5320: my %access = (
5321: allowfrom => 1,
5322: denyfrom => 0,
5323: );
5324: my @allows;
5325: my @denies;
5326: foreach my $item (split(',',$acc)) {
5327: $item =~ s/^\s*//;
5328: $item =~ s/\s*$//;
5329: my $pattern;
5330: if ($item =~ /^\!(.+)$/) {
5331: push(@denies,$1);
5332: } else {
5333: push(@allows,$item);
5334: }
5335: }
5336: my $numdenies = scalar(@denies);
5337: my $numallows = scalar(@allows);
5338: my $count = 0;
5339: foreach my $pattern (@denies,@allows) {
5340: $count ++;
5341: my $acctype = 'allowfrom';
5342: if ($count <= $numdenies) {
5343: $acctype = 'denyfrom';
5344: }
5345: if ($pattern =~ /\*$/) {
5346: #35.8.*
5347: $pattern=~s/\*//;
5348: if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
5349: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
5350: #35.8.3.[34-56]
5351: my $low=$2;
5352: my $high=$3;
5353: $pattern=$1;
5354: if ($ip =~ /^\Q$pattern\E/) {
5355: my $last=(split(/\./,$ip))[3];
5356: if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
5357: }
5358: } elsif ($pattern =~ /^\*/) {
5359: #*.msu.edu
5360: $pattern=~s/\*//;
5361: if (!defined($name)) {
5362: use Socket;
5363: my $netaddr=inet_aton($ip);
5364: ($name)=gethostbyaddr($netaddr,AF_INET);
5365: }
5366: if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
5367: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
5368: #127.0.0.1
5369: if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
5370: } else {
5371: #some.name.com
5372: if (!defined($name)) {
5373: use Socket;
5374: my $netaddr=inet_aton($ip);
5375: ($name)=gethostbyaddr($netaddr,AF_INET);
5376: }
5377: if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
5378: }
5379: if ($allowed =~ /^(0|1)$/) { last; }
5380: }
5381: if ($allowed eq '') {
5382: if ($numdenies && !$numallows) {
5383: $allowed = 1;
5384: } else {
5385: $allowed = 0;
5386: }
5387: }
5388: return $allowed;
5389: }
5390:
5391: ###############################################
5392:
5393: =pod
5394:
5395: =head1 Domain Template Functions
5396:
5397: =over 4
5398:
5399: =item * &determinedomain()
5400:
5401: Inputs: $domain (usually will be undef)
5402:
5403: Returns: Determines which domain should be used for designs
5404:
5405: =cut
5406:
5407: ###############################################
5408: sub determinedomain {
5409: my $domain=shift;
5410: if (! $domain) {
5411: # Determine domain if we have not been given one
5412: $domain = &Apache::lonnet::default_login_domain();
5413: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
5414: if ($env{'request.role.domain'}) {
5415: $domain=$env{'request.role.domain'};
5416: }
5417: }
5418: return $domain;
5419: }
5420: ###############################################
5421:
5422: sub devalidate_domconfig_cache {
5423: my ($udom)=@_;
5424: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
5425: }
5426:
5427: # ---------------------- Get domain configuration for a domain
5428: sub get_domainconf {
5429: my ($udom) = @_;
5430: my $cachetime=1800;
5431: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
5432: if (defined($cached)) { return %{$result}; }
5433:
5434: my %domconfig = &Apache::lonnet::get_dom('configuration',
5435: ['login','rolecolors','autoenroll'],$udom);
5436: my (%designhash,%legacy);
5437: if (keys(%domconfig) > 0) {
5438: if (ref($domconfig{'login'}) eq 'HASH') {
5439: if (keys(%{$domconfig{'login'}})) {
5440: foreach my $key (keys(%{$domconfig{'login'}})) {
5441: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5442: if (($key eq 'loginvia') || ($key eq 'headtag')) {
5443: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
5444: foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
5445: if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
5446: if ($key eq 'loginvia') {
5447: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
5448: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
5449: $designhash{$udom.'.login.loginvia'} = $server;
5450: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
5451:
5452: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
5453: } else {
5454: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
5455: }
5456: }
5457: } elsif ($key eq 'headtag') {
5458: if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
5459: $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
5460: }
5461: }
5462: if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
5463: $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
5464: }
5465: }
5466: }
5467: }
5468: } else {
5469: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
5470: $designhash{$udom.'.login.'.$key.'_'.$img} =
5471: $domconfig{'login'}{$key}{$img};
5472: }
5473: }
5474: } else {
5475: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
5476: }
5477: }
5478: } else {
5479: $legacy{'login'} = 1;
5480: }
5481: } else {
5482: $legacy{'login'} = 1;
5483: }
5484: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
5485: if (keys(%{$domconfig{'rolecolors'}})) {
5486: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
5487: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
5488: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
5489: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
5490: }
5491: }
5492: }
5493: } else {
5494: $legacy{'rolecolors'} = 1;
5495: }
5496: } else {
5497: $legacy{'rolecolors'} = 1;
5498: }
5499: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5500: if ($domconfig{'autoenroll'}{'co-owners'}) {
5501: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
5502: }
5503: }
5504: if (keys(%legacy) > 0) {
5505: my %legacyhash = &get_legacy_domconf($udom);
5506: foreach my $item (keys(%legacyhash)) {
5507: if ($item =~ /^\Q$udom\E\.login/) {
5508: if ($legacy{'login'}) {
5509: $designhash{$item} = $legacyhash{$item};
5510: }
5511: } else {
5512: if ($legacy{'rolecolors'}) {
5513: $designhash{$item} = $legacyhash{$item};
5514: }
5515: }
5516: }
5517: }
5518: } else {
5519: %designhash = &get_legacy_domconf($udom);
5520: }
5521: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
5522: $cachetime);
5523: return %designhash;
5524: }
5525:
5526: sub get_legacy_domconf {
5527: my ($udom) = @_;
5528: my %legacyhash;
5529: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
5530: my $designfile = $designdir.'/'.$udom.'.tab';
5531: if (-e $designfile) {
5532: if ( open (my $fh,"<$designfile") ) {
5533: while (my $line = <$fh>) {
5534: next if ($line =~ /^\#/);
5535: chomp($line);
5536: my ($key,$val)=(split(/\=/,$line));
5537: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
5538: }
5539: close($fh);
5540: }
5541: }
5542: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
5543: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
5544: }
5545: return %legacyhash;
5546: }
5547:
5548: =pod
5549:
5550: =item * &domainlogo()
5551:
5552: Inputs: $domain (usually will be undef)
5553:
5554: Returns: A link to a domain logo, if the domain logo exists.
5555: If the domain logo does not exist, a description of the domain.
5556:
5557: =cut
5558:
5559: ###############################################
5560: sub domainlogo {
5561: my $domain = &determinedomain(shift);
5562: my %designhash = &get_domainconf($domain);
5563: # See if there is a logo
5564: if ($designhash{$domain.'.login.domlogo'} ne '') {
5565: my $imgsrc = $designhash{$domain.'.login.domlogo'};
5566: if ($imgsrc =~ m{^/(adm|res)/}) {
5567: if ($imgsrc =~ m{^/res/}) {
5568: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
5569: &Apache::lonnet::repcopy($local_name);
5570: }
5571: $imgsrc = &lonhttpdurl($imgsrc);
5572: }
5573: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
5574: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
5575: return &Apache::lonnet::domain($domain,'description');
5576: } else {
5577: return '';
5578: }
5579: }
5580: ##############################################
5581:
5582: =pod
5583:
5584: =item * &designparm()
5585:
5586: Inputs: $which parameter; $domain (usually will be undef)
5587:
5588: Returns: value of designparamter $which
5589:
5590: =cut
5591:
5592:
5593: ##############################################
5594: sub designparm {
5595: my ($which,$domain)=@_;
5596: if (exists($env{'environment.color.'.$which})) {
5597: return $env{'environment.color.'.$which};
5598: }
5599: $domain=&determinedomain($domain);
5600: my %domdesign;
5601: unless ($domain eq 'public') {
5602: %domdesign = &get_domainconf($domain);
5603: }
5604: my $output;
5605: if ($domdesign{$domain.'.'.$which} ne '') {
5606: $output = $domdesign{$domain.'.'.$which};
5607: } else {
5608: $output = $defaultdesign{$which};
5609: }
5610: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
5611: ($which =~ /login\.(img|logo|domlogo|login)/)) {
5612: if ($output =~ m{^/(adm|res)/}) {
5613: if ($output =~ m{^/res/}) {
5614: my $local_name = &Apache::lonnet::filelocation('',$output);
5615: &Apache::lonnet::repcopy($local_name);
5616: }
5617: $output = &lonhttpdurl($output);
5618: }
5619: }
5620: return $output;
5621: }
5622:
5623: ##############################################
5624: =pod
5625:
5626: =item * &authorspace()
5627:
5628: Inputs: $url (usually will be undef).
5629:
5630: Returns: Path to Authoring Space containing the resource or
5631: directory being viewed (or for which action is being taken).
5632: If $url is provided, and begins /priv/<domain>/<uname>
5633: the path will be that portion of the $context argument.
5634: Otherwise the path will be for the author space of the current
5635: user when the current role is author, or for that of the
5636: co-author/assistant co-author space when the current role
5637: is co-author or assistant co-author.
5638:
5639: =cut
5640:
5641: sub authorspace {
5642: my ($url) = @_;
5643: if ($url ne '') {
5644: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
5645: return $1;
5646: }
5647: }
5648: my $caname = '';
5649: my $cadom = '';
5650: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
5651: ($cadom,$caname) =
5652: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
5653: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
5654: $caname = $env{'user.name'};
5655: $cadom = $env{'user.domain'};
5656: }
5657: if (($caname ne '') && ($cadom ne '')) {
5658: return "/priv/$cadom/$caname/";
5659: }
5660: return;
5661: }
5662:
5663: ##############################################
5664: =pod
5665:
5666: =item * &head_subbox()
5667:
5668: Inputs: $content (contains HTML code with page functions, etc.)
5669:
5670: Returns: HTML div with $content
5671: To be included in page header
5672:
5673: =cut
5674:
5675: sub head_subbox {
5676: my ($content)=@_;
5677: my $output =
5678: '<div class="LC_head_subbox">'
5679: .$content
5680: .'</div>'
5681: }
5682:
5683: ##############################################
5684: =pod
5685:
5686: =item * &CSTR_pageheader()
5687:
5688: Input: (optional) filename from which breadcrumb trail is built.
5689: In most cases no input as needed, as $env{'request.filename'}
5690: is appropriate for use in building the breadcrumb trail.
5691:
5692: Returns: HTML div with CSTR path and recent box
5693: To be included on Authoring Space pages
5694:
5695: =cut
5696:
5697: sub CSTR_pageheader {
5698: my ($trailfile) = @_;
5699: if ($trailfile eq '') {
5700: $trailfile = $env{'request.filename'};
5701: }
5702:
5703: # this is for resources; directories have customtitle, and crumbs
5704: # and select recent are created in lonpubdir.pm
5705:
5706: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
5707: my ($udom,$uname,$thisdisfn)=
5708: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
5709: my $formaction = "/priv/$udom/$uname/$thisdisfn";
5710: $formaction =~ s{/+}{/}g;
5711:
5712: my $parentpath = '';
5713: my $lastitem = '';
5714: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
5715: $parentpath = $1;
5716: $lastitem = $2;
5717: } else {
5718: $lastitem = $thisdisfn;
5719: }
5720:
5721: my ($crsauthor,$title);
5722: if (($env{'request.course.id'}) &&
5723: ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
5724: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
5725: $crsauthor = 1;
5726: $title = &mt('Course Authoring Space');
5727: } else {
5728: $title = &mt('Authoring Space');
5729: }
5730:
5731: my $output =
5732: '<div>'
5733: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
5734: .'<b>'.$title.'</b> '
5735: .'<form name="dirs" method="post" action="'.$formaction
5736: .'" target="_top">' #FIXME lonpubdir: target="_parent"
5737: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
5738:
5739: if ($lastitem) {
5740: $output .=
5741: '<span class="LC_filename">'
5742: .$lastitem
5743: .'</span>';
5744: }
5745:
5746: if ($crsauthor) {
5747: $output .= '</form>'.&Apache::lonmenu::constspaceform();
5748: } else {
5749: $output .=
5750: '<br />'
5751: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
5752: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
5753: .'</form>'
5754: .&Apache::lonmenu::constspaceform();
5755: }
5756: $output .= '</div>';
5757:
5758: return $output;
5759: }
5760:
5761: ###############################################
5762: ###############################################
5763:
5764: =pod
5765:
5766: =back
5767:
5768: =head1 HTML Helpers
5769:
5770: =over 4
5771:
5772: =item * &bodytag()
5773:
5774: Returns a uniform header for LON-CAPA web pages.
5775:
5776: Inputs:
5777:
5778: =over 4
5779:
5780: =item * $title, A title to be displayed on the page.
5781:
5782: =item * $function, the current role (can be undef).
5783:
5784: =item * $addentries, extra parameters for the <body> tag.
5785:
5786: =item * $bodyonly, if defined, only return the <body> tag.
5787:
5788: =item * $domain, if defined, force a given domain.
5789:
5790: =item * $forcereg, if page should register as content page (relevant for
5791: text interface only)
5792:
5793: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
5794: navigational links
5795:
5796: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
5797:
5798: =item * $args, optional argument valid values are
5799: no_auto_mt_title -> prevents &mt()ing the title arg
5800:
5801: =item * $advtoolsref, optional argument, ref to an array containing
5802: inlineremote items to be added in "Functions" menu below
5803: breadcrumbs.
5804:
5805: =back
5806:
5807: Returns: A uniform header for LON-CAPA web pages.
5808: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
5809: If $bodyonly is undef or zero, an html string containing a <body> tag and
5810: other decorations will be returned.
5811:
5812: =cut
5813:
5814: sub bodytag {
5815: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
5816: $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
5817:
5818: my $public;
5819: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
5820: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
5821: $public = 1;
5822: }
5823: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
5824: my $httphost = $args->{'use_absolute'};
5825:
5826: $function = &get_users_function() if (!$function);
5827: my $img = &designparm($function.'.img',$domain);
5828: my $font = &designparm($function.'.font',$domain);
5829: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
5830:
5831: my %design = ( 'style' => 'margin-top: 0',
5832: 'bgcolor' => $pgbg,
5833: 'text' => $font,
5834: 'alink' => &designparm($function.'.alink',$domain),
5835: 'vlink' => &designparm($function.'.vlink',$domain),
5836: 'link' => &designparm($function.'.link',$domain),);
5837: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
5838:
5839: # role and realm
5840: my ($role,$realm) = split(m{\./},$env{'request.role'},2);
5841: if ($realm) {
5842: $realm = '/'.$realm;
5843: }
5844: if ($role eq 'ca') {
5845: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
5846: $realm = &plainname($rname,$rdom);
5847: }
5848: # realm
5849: if ($env{'request.course.id'}) {
5850: if ($env{'request.role'} !~ /^cr/) {
5851: $role = &Apache::lonnet::plaintext($role,&course_type());
5852: }
5853: if ($env{'request.course.sec'}) {
5854: $role .= (' 'x2).'- '.&mt('section:').' '.$env{'request.course.sec'};
5855: }
5856: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
5857: } else {
5858: $role = &Apache::lonnet::plaintext($role);
5859: }
5860:
5861: if (!$realm) { $realm=' '; }
5862:
5863: my $extra_body_attr = &make_attr_string($forcereg,\%design);
5864:
5865: # construct main body tag
5866: my $bodytag = "<body $extra_body_attr>".
5867: &Apache::lontexconvert::init_math_support();
5868:
5869: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
5870:
5871: if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
5872: return $bodytag;
5873: }
5874:
5875: if ($public) {
5876: undef($role);
5877: }
5878:
5879: my $titleinfo = '<h1>'.$title.'</h1>';
5880: #
5881: # Extra info if you are the DC
5882: my $dc_info = '';
5883: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
5884: $env{'course.'.$env{'request.course.id'}.
5885: '.domain'}.'/'})) {
5886: my $cid = $env{'request.course.id'};
5887: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
5888: $dc_info =~ s/\s+$//;
5889: }
5890:
5891: my $crstype;
5892: if ($env{'request.course.id'}) {
5893: $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
5894: } elsif ($args->{'crstype'}) {
5895: $crstype = $args->{'crstype'};
5896: }
5897: if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
5898: undef($role);
5899: } else {
5900: $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
5901: }
5902:
5903: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
5904:
5905: # if ($env{'request.state'} eq 'construct') {
5906: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
5907: # }
5908:
5909: $bodytag .= Apache::lonhtmlcommon::scripttag(
5910: Apache::lonmenu::utilityfunctions($httphost), 'start');
5911:
5912: my ($left,$right) = Apache::lonmenu::primary_menu($crstype);
5913:
5914: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
5915: if ($dc_info) {
5916: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
5917: }
5918: $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
5919: <em>$realm</em> $dc_info</div>|;
5920: return $bodytag;
5921: }
5922:
5923: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
5924: $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
5925: }
5926:
5927: $bodytag .= $right;
5928:
5929: if ($dc_info) {
5930: $dc_info = &dc_courseid_toggle($dc_info);
5931: }
5932: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
5933:
5934: #if directed to not display the secondary menu, don't.
5935: if ($args->{'no_secondary_menu'}) {
5936: return $bodytag;
5937: }
5938: #don't show menus for public users
5939: if (!$public){
5940: $bodytag .= Apache::lonmenu::secondary_menu($httphost);
5941: $bodytag .= Apache::lonmenu::serverform();
5942: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5943: if ($env{'request.state'} eq 'construct') {
5944: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
5945: $args->{'bread_crumbs'});
5946: } elsif ($forcereg) {
5947: $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
5948: $args->{'group'});
5949: } else {
5950: $bodytag .=
5951: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
5952: $forcereg,$args->{'group'},
5953: $args->{'bread_crumbs'},
5954: $advtoolsref);
5955: }
5956: }else{
5957: # this is to seperate menu from content when there's no secondary
5958: # menu. Especially needed for public accessible ressources.
5959: $bodytag .= '<hr style="clear:both" />';
5960: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5961: }
5962:
5963: return $bodytag;
5964: }
5965:
5966: sub dc_courseid_toggle {
5967: my ($dc_info) = @_;
5968: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
5969: '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
5970: &mt('(More ...)').'</a></span>'.
5971: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
5972: }
5973:
5974: sub make_attr_string {
5975: my ($register,$attr_ref) = @_;
5976:
5977: if ($attr_ref && !ref($attr_ref)) {
5978: die("addentries Must be a hash ref ".
5979: join(':',caller(1))." ".
5980: join(':',caller(0))." ");
5981: }
5982:
5983: if ($register) {
5984: my ($on_load,$on_unload);
5985: foreach my $key (keys(%{$attr_ref})) {
5986: if (lc($key) eq 'onload') {
5987: $on_load.=$attr_ref->{$key}.';';
5988: delete($attr_ref->{$key});
5989:
5990: } elsif (lc($key) eq 'onunload') {
5991: $on_unload.=$attr_ref->{$key}.';';
5992: delete($attr_ref->{$key});
5993: }
5994: }
5995: $attr_ref->{'onload'} = $on_load;
5996: $attr_ref->{'onunload'}= $on_unload;
5997: }
5998:
5999: my $attr_string;
6000: foreach my $attr (sort(keys(%$attr_ref))) {
6001: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
6002: }
6003: return $attr_string;
6004: }
6005:
6006:
6007: ###############################################
6008: ###############################################
6009:
6010: =pod
6011:
6012: =item * &endbodytag()
6013:
6014: Returns a uniform footer for LON-CAPA web pages.
6015:
6016: Inputs: 1 - optional reference to an args hash
6017: If in the hash, key for noredirectlink has a value which evaluates to true,
6018: a 'Continue' link is not displayed if the page contains an
6019: internal redirect in the <head></head> section,
6020: i.e., $env{'internal.head.redirect'} exists
6021:
6022: =cut
6023:
6024: sub endbodytag {
6025: my ($args) = @_;
6026: my $endbodytag;
6027: unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
6028: $endbodytag='</body>';
6029: }
6030: if ( exists( $env{'internal.head.redirect'} ) ) {
6031: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
6032: $endbodytag=
6033: "<br /><a href=\"$env{'internal.head.redirect'}\">".
6034: &mt('Continue').'</a>'.
6035: $endbodytag;
6036: }
6037: }
6038: return $endbodytag;
6039: }
6040:
6041: =pod
6042:
6043: =item * &standard_css()
6044:
6045: Returns a style sheet
6046:
6047: Inputs: (all optional)
6048: domain -> force to color decorate a page for a specific
6049: domain
6050: function -> force usage of a specific rolish color scheme
6051: bgcolor -> override the default page bgcolor
6052:
6053: =cut
6054:
6055: sub standard_css {
6056: my ($function,$domain,$bgcolor) = @_;
6057: $function = &get_users_function() if (!$function);
6058: my $img = &designparm($function.'.img', $domain);
6059: my $tabbg = &designparm($function.'.tabbg', $domain);
6060: my $font = &designparm($function.'.font', $domain);
6061: my $fontmenu = &designparm($function.'.fontmenu', $domain);
6062: #second colour for later usage
6063: my $sidebg = &designparm($function.'.sidebg',$domain);
6064: my $pgbg_or_bgcolor =
6065: $bgcolor ||
6066: &designparm($function.'.pgbg', $domain);
6067: my $pgbg = &designparm($function.'.pgbg', $domain);
6068: my $alink = &designparm($function.'.alink', $domain);
6069: my $vlink = &designparm($function.'.vlink', $domain);
6070: my $link = &designparm($function.'.link', $domain);
6071:
6072: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
6073: my $mono = 'monospace';
6074: my $data_table_head = $sidebg;
6075: my $data_table_light = '#FAFAFA';
6076: my $data_table_dark = '#E0E0E0';
6077: my $data_table_darker = '#CCCCCC';
6078: my $data_table_highlight = '#FFFF00';
6079: my $mail_new = '#FFBB77';
6080: my $mail_new_hover = '#DD9955';
6081: my $mail_read = '#BBBB77';
6082: my $mail_read_hover = '#999944';
6083: my $mail_replied = '#AAAA88';
6084: my $mail_replied_hover = '#888855';
6085: my $mail_other = '#99BBBB';
6086: my $mail_other_hover = '#669999';
6087: my $table_header = '#DDDDDD';
6088: my $feedback_link_bg = '#BBBBBB';
6089: my $lg_border_color = '#C8C8C8';
6090: my $button_hover = '#BF2317';
6091:
6092: my $border = ($env{'browser.type'} eq 'explorer' ||
6093: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
6094: : '0 3px 0 4px';
6095:
6096:
6097: return <<END;
6098:
6099: /* needed for iframe to allow 100% height in FF */
6100: body, html {
6101: margin: 0;
6102: padding: 0 0.5%;
6103: height: 99%; /* to avoid scrollbars */
6104: }
6105:
6106: body {
6107: font-family: $sans;
6108: line-height:130%;
6109: font-size:0.83em;
6110: color:$font;
6111: }
6112:
6113: a:focus,
6114: a:focus img {
6115: color: red;
6116: }
6117:
6118: form, .inline {
6119: display: inline;
6120: }
6121:
6122: .LC_right {
6123: text-align:right;
6124: }
6125:
6126: .LC_middle {
6127: vertical-align:middle;
6128: }
6129:
6130: .LC_floatleft {
6131: float: left;
6132: }
6133:
6134: .LC_floatright {
6135: float: right;
6136: }
6137:
6138: .LC_400Box {
6139: width:400px;
6140: }
6141:
6142: .LC_iframecontainer {
6143: width: 98%;
6144: margin: 0;
6145: position: fixed;
6146: top: 8.5em;
6147: bottom: 0;
6148: }
6149:
6150: .LC_iframecontainer iframe{
6151: border: none;
6152: width: 100%;
6153: height: 100%;
6154: }
6155:
6156: .LC_filename {
6157: font-family: $mono;
6158: white-space:pre;
6159: font-size: 120%;
6160: }
6161:
6162: .LC_fileicon {
6163: border: none;
6164: height: 1.3em;
6165: vertical-align: text-bottom;
6166: margin-right: 0.3em;
6167: text-decoration:none;
6168: }
6169:
6170: .LC_setting {
6171: text-decoration:underline;
6172: }
6173:
6174: .LC_error {
6175: color: red;
6176: }
6177:
6178: .LC_warning {
6179: color: darkorange;
6180: }
6181:
6182: .LC_diff_removed {
6183: color: red;
6184: }
6185:
6186: .LC_info,
6187: .LC_success,
6188: .LC_diff_added {
6189: color: green;
6190: }
6191:
6192: div.LC_confirm_box {
6193: background-color: #FAFAFA;
6194: border: 1px solid $lg_border_color;
6195: margin-right: 0;
6196: padding: 5px;
6197: }
6198:
6199: div.LC_confirm_box .LC_error img,
6200: div.LC_confirm_box .LC_success img {
6201: vertical-align: middle;
6202: }
6203:
6204: .LC_maxwidth {
6205: max-width: 100%;
6206: height: auto;
6207: }
6208:
6209: .LC_textsize_mobile {
6210: \@media only screen and (max-device-width: 480px) {
6211: -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
6212: }
6213: }
6214:
6215: .LC_icon {
6216: border: none;
6217: vertical-align: middle;
6218: }
6219:
6220: .LC_docs_spacer {
6221: width: 25px;
6222: height: 1px;
6223: border: none;
6224: }
6225:
6226: .LC_internal_info {
6227: color: #999999;
6228: }
6229:
6230: .LC_discussion {
6231: background: $data_table_dark;
6232: border: 1px solid black;
6233: margin: 2px;
6234: }
6235:
6236: .LC_disc_action_left {
6237: background: $sidebg;
6238: text-align: left;
6239: padding: 4px;
6240: margin: 2px;
6241: }
6242:
6243: .LC_disc_action_right {
6244: background: $sidebg;
6245: text-align: right;
6246: padding: 4px;
6247: margin: 2px;
6248: }
6249:
6250: .LC_disc_new_item {
6251: background: white;
6252: border: 2px solid red;
6253: margin: 4px;
6254: padding: 4px;
6255: }
6256:
6257: .LC_disc_old_item {
6258: background: white;
6259: margin: 4px;
6260: padding: 4px;
6261: }
6262:
6263: table.LC_pastsubmission {
6264: border: 1px solid black;
6265: margin: 2px;
6266: }
6267:
6268: table#LC_menubuttons {
6269: width: 100%;
6270: background: $pgbg;
6271: border: 2px;
6272: border-collapse: separate;
6273: padding: 0;
6274: }
6275:
6276: table#LC_title_bar a {
6277: color: $fontmenu;
6278: }
6279:
6280: table#LC_title_bar {
6281: clear: both;
6282: display: none;
6283: }
6284:
6285: table#LC_title_bar,
6286: table.LC_breadcrumbs, /* obsolete? */
6287: table#LC_title_bar.LC_with_remote {
6288: width: 100%;
6289: border-color: $pgbg;
6290: border-style: solid;
6291: border-width: $border;
6292: background: $pgbg;
6293: color: $fontmenu;
6294: border-collapse: collapse;
6295: padding: 0;
6296: margin: 0;
6297: }
6298:
6299: ul.LC_breadcrumb_tools_outerlist {
6300: margin: 0;
6301: padding: 0;
6302: position: relative;
6303: list-style: none;
6304: }
6305: ul.LC_breadcrumb_tools_outerlist li {
6306: display: inline;
6307: }
6308:
6309: .LC_breadcrumb_tools_navigation {
6310: padding: 0;
6311: margin: 0;
6312: float: left;
6313: }
6314: .LC_breadcrumb_tools_tools {
6315: padding: 0;
6316: margin: 0;
6317: float: right;
6318: }
6319:
6320: .LC_placement_prog {
6321: padding-right: 20px;
6322: font-weight: bold;
6323: font-size: 90%;
6324: }
6325:
6326: table#LC_title_bar td {
6327: background: $tabbg;
6328: }
6329:
6330: table#LC_menubuttons img {
6331: border: none;
6332: }
6333:
6334: .LC_breadcrumbs_component {
6335: float: right;
6336: margin: 0 1em;
6337: }
6338: .LC_breadcrumbs_component img {
6339: vertical-align: middle;
6340: }
6341:
6342: .LC_breadcrumbs_hoverable {
6343: background: $sidebg;
6344: }
6345:
6346: td.LC_table_cell_checkbox {
6347: text-align: center;
6348: }
6349:
6350: .LC_fontsize_small {
6351: font-size: 70%;
6352: }
6353:
6354: #LC_breadcrumbs {
6355: clear:both;
6356: background: $sidebg;
6357: border-bottom: 1px solid $lg_border_color;
6358: line-height: 2.5em;
6359: overflow: hidden;
6360: margin: 0;
6361: padding: 0;
6362: text-align: left;
6363: }
6364:
6365: .LC_head_subbox, .LC_actionbox {
6366: clear:both;
6367: background: #F8F8F8; /* $sidebg; */
6368: border: 1px solid $sidebg;
6369: margin: 0 0 10px 0;
6370: padding: 3px;
6371: text-align: left;
6372: }
6373:
6374: .LC_fontsize_medium {
6375: font-size: 85%;
6376: }
6377:
6378: .LC_fontsize_large {
6379: font-size: 120%;
6380: }
6381:
6382: .LC_menubuttons_inline_text {
6383: color: $font;
6384: font-size: 90%;
6385: padding-left:3px;
6386: }
6387:
6388: .LC_menubuttons_inline_text img{
6389: vertical-align: middle;
6390: }
6391:
6392: li.LC_menubuttons_inline_text img {
6393: cursor:pointer;
6394: text-decoration: none;
6395: }
6396:
6397: .LC_menubuttons_link {
6398: text-decoration: none;
6399: }
6400:
6401: .LC_menubuttons_category {
6402: color: $font;
6403: background: $pgbg;
6404: font-size: larger;
6405: font-weight: bold;
6406: }
6407:
6408: td.LC_menubuttons_text {
6409: color: $font;
6410: }
6411:
6412: .LC_current_location {
6413: background: $tabbg;
6414: }
6415:
6416: table.LC_data_table {
6417: border: 1px solid #000000;
6418: border-collapse: separate;
6419: border-spacing: 1px;
6420: background: $pgbg;
6421: }
6422:
6423: .LC_data_table_dense {
6424: font-size: small;
6425: }
6426:
6427: table.LC_nested_outer {
6428: border: 1px solid #000000;
6429: border-collapse: collapse;
6430: border-spacing: 0;
6431: width: 100%;
6432: }
6433:
6434: table.LC_innerpickbox,
6435: table.LC_nested {
6436: border: none;
6437: border-collapse: collapse;
6438: border-spacing: 0;
6439: width: 100%;
6440: }
6441:
6442: table.LC_data_table tr th,
6443: table.LC_calendar tr th,
6444: table.LC_prior_tries tr th,
6445: table.LC_innerpickbox tr th {
6446: font-weight: bold;
6447: background-color: $data_table_head;
6448: color:$fontmenu;
6449: font-size:90%;
6450: }
6451:
6452: table.LC_innerpickbox tr th,
6453: table.LC_innerpickbox tr td {
6454: vertical-align: top;
6455: }
6456:
6457: table.LC_data_table tr.LC_info_row > td {
6458: background-color: #CCCCCC;
6459: font-weight: bold;
6460: text-align: left;
6461: }
6462:
6463: table.LC_data_table tr.LC_odd_row > td {
6464: background-color: $data_table_light;
6465: padding: 2px;
6466: vertical-align: top;
6467: }
6468:
6469: table.LC_pick_box tr > td.LC_odd_row {
6470: background-color: $data_table_light;
6471: vertical-align: top;
6472: }
6473:
6474: table.LC_data_table tr.LC_even_row > td {
6475: background-color: $data_table_dark;
6476: padding: 2px;
6477: vertical-align: top;
6478: }
6479:
6480: table.LC_pick_box tr > td.LC_even_row {
6481: background-color: $data_table_dark;
6482: vertical-align: top;
6483: }
6484:
6485: table.LC_data_table tr.LC_data_table_highlight td {
6486: background-color: $data_table_darker;
6487: }
6488:
6489: table.LC_data_table tr td.LC_leftcol_header {
6490: background-color: $data_table_head;
6491: font-weight: bold;
6492: }
6493:
6494: table.LC_data_table tr.LC_empty_row td,
6495: table.LC_nested tr.LC_empty_row td {
6496: font-weight: bold;
6497: font-style: italic;
6498: text-align: center;
6499: padding: 8px;
6500: }
6501:
6502: table.LC_data_table tr.LC_empty_row td,
6503: table.LC_data_table tr.LC_footer_row td {
6504: background-color: $sidebg;
6505: }
6506:
6507: table.LC_nested tr.LC_empty_row td {
6508: background-color: #FFFFFF;
6509: }
6510:
6511: table.LC_caption {
6512: }
6513:
6514: table.LC_nested tr.LC_empty_row td {
6515: padding: 4ex
6516: }
6517:
6518: table.LC_nested_outer tr th {
6519: font-weight: bold;
6520: color:$fontmenu;
6521: background-color: $data_table_head;
6522: font-size: small;
6523: border-bottom: 1px solid #000000;
6524: }
6525:
6526: table.LC_nested_outer tr td.LC_subheader {
6527: background-color: $data_table_head;
6528: font-weight: bold;
6529: font-size: small;
6530: border-bottom: 1px solid #000000;
6531: text-align: right;
6532: }
6533:
6534: table.LC_nested tr.LC_info_row td {
6535: background-color: #CCCCCC;
6536: font-weight: bold;
6537: font-size: small;
6538: text-align: center;
6539: }
6540:
6541: table.LC_nested tr.LC_info_row td.LC_left_item,
6542: table.LC_nested_outer tr th.LC_left_item {
6543: text-align: left;
6544: }
6545:
6546: table.LC_nested td {
6547: background-color: #FFFFFF;
6548: font-size: small;
6549: }
6550:
6551: table.LC_nested_outer tr th.LC_right_item,
6552: table.LC_nested tr.LC_info_row td.LC_right_item,
6553: table.LC_nested tr.LC_odd_row td.LC_right_item,
6554: table.LC_nested tr td.LC_right_item {
6555: text-align: right;
6556: }
6557:
6558: table.LC_nested tr.LC_odd_row td {
6559: background-color: #EEEEEE;
6560: }
6561:
6562: table.LC_createuser {
6563: }
6564:
6565: table.LC_createuser tr.LC_section_row td {
6566: font-size: small;
6567: }
6568:
6569: table.LC_createuser tr.LC_info_row td {
6570: background-color: #CCCCCC;
6571: font-weight: bold;
6572: text-align: center;
6573: }
6574:
6575: table.LC_calendar {
6576: border: 1px solid #000000;
6577: border-collapse: collapse;
6578: width: 98%;
6579: }
6580:
6581: table.LC_calendar_pickdate {
6582: font-size: xx-small;
6583: }
6584:
6585: table.LC_calendar tr td {
6586: border: 1px solid #000000;
6587: vertical-align: top;
6588: width: 14%;
6589: }
6590:
6591: table.LC_calendar tr td.LC_calendar_day_empty {
6592: background-color: $data_table_dark;
6593: }
6594:
6595: table.LC_calendar tr td.LC_calendar_day_current {
6596: background-color: $data_table_highlight;
6597: }
6598:
6599: table.LC_data_table tr td.LC_mail_new {
6600: background-color: $mail_new;
6601: }
6602:
6603: table.LC_data_table tr.LC_mail_new:hover {
6604: background-color: $mail_new_hover;
6605: }
6606:
6607: table.LC_data_table tr td.LC_mail_read {
6608: background-color: $mail_read;
6609: }
6610:
6611: /*
6612: table.LC_data_table tr.LC_mail_read:hover {
6613: background-color: $mail_read_hover;
6614: }
6615: */
6616:
6617: table.LC_data_table tr td.LC_mail_replied {
6618: background-color: $mail_replied;
6619: }
6620:
6621: /*
6622: table.LC_data_table tr.LC_mail_replied:hover {
6623: background-color: $mail_replied_hover;
6624: }
6625: */
6626:
6627: table.LC_data_table tr td.LC_mail_other {
6628: background-color: $mail_other;
6629: }
6630:
6631: /*
6632: table.LC_data_table tr.LC_mail_other:hover {
6633: background-color: $mail_other_hover;
6634: }
6635: */
6636:
6637: table.LC_data_table tr > td.LC_browser_file,
6638: table.LC_data_table tr > td.LC_browser_file_published {
6639: background: #AAEE77;
6640: }
6641:
6642: table.LC_data_table tr > td.LC_browser_file_locked,
6643: table.LC_data_table tr > td.LC_browser_file_unpublished {
6644: background: #FFAA99;
6645: }
6646:
6647: table.LC_data_table tr > td.LC_browser_file_obsolete {
6648: background: #888888;
6649: }
6650:
6651: table.LC_data_table tr > td.LC_browser_file_modified,
6652: table.LC_data_table tr > td.LC_browser_file_metamodified {
6653: background: #F8F866;
6654: }
6655:
6656: table.LC_data_table tr.LC_browser_folder > td {
6657: background: #E0E8FF;
6658: }
6659:
6660: table.LC_data_table tr > td.LC_roles_is {
6661: /* background: #77FF77; */
6662: }
6663:
6664: table.LC_data_table tr > td.LC_roles_future {
6665: border-right: 8px solid #FFFF77;
6666: }
6667:
6668: table.LC_data_table tr > td.LC_roles_will {
6669: border-right: 8px solid #FFAA77;
6670: }
6671:
6672: table.LC_data_table tr > td.LC_roles_expired {
6673: border-right: 8px solid #FF7777;
6674: }
6675:
6676: table.LC_data_table tr > td.LC_roles_will_not {
6677: border-right: 8px solid #AAFF77;
6678: }
6679:
6680: table.LC_data_table tr > td.LC_roles_selected {
6681: border-right: 8px solid #11CC55;
6682: }
6683:
6684: span.LC_current_location {
6685: font-size:larger;
6686: background: $pgbg;
6687: }
6688:
6689: span.LC_current_nav_location {
6690: font-weight:bold;
6691: background: $sidebg;
6692: }
6693:
6694: span.LC_parm_menu_item {
6695: font-size: larger;
6696: }
6697:
6698: span.LC_parm_scope_all {
6699: color: red;
6700: }
6701:
6702: span.LC_parm_scope_folder {
6703: color: green;
6704: }
6705:
6706: span.LC_parm_scope_resource {
6707: color: orange;
6708: }
6709:
6710: span.LC_parm_part {
6711: color: blue;
6712: }
6713:
6714: span.LC_parm_folder,
6715: span.LC_parm_symb {
6716: font-size: x-small;
6717: font-family: $mono;
6718: color: #AAAAAA;
6719: }
6720:
6721: ul.LC_parm_parmlist li {
6722: display: inline-block;
6723: padding: 0.3em 0.8em;
6724: vertical-align: top;
6725: width: 150px;
6726: border-top:1px solid $lg_border_color;
6727: }
6728:
6729: td.LC_parm_overview_level_menu,
6730: td.LC_parm_overview_map_menu,
6731: td.LC_parm_overview_parm_selectors,
6732: td.LC_parm_overview_restrictions {
6733: border: 1px solid black;
6734: border-collapse: collapse;
6735: }
6736:
6737: table.LC_parm_overview_restrictions td {
6738: border-width: 1px 4px 1px 4px;
6739: border-style: solid;
6740: border-color: $pgbg;
6741: text-align: center;
6742: }
6743:
6744: table.LC_parm_overview_restrictions th {
6745: background: $tabbg;
6746: border-width: 1px 4px 1px 4px;
6747: border-style: solid;
6748: border-color: $pgbg;
6749: }
6750:
6751: table#LC_helpmenu {
6752: border: none;
6753: height: 55px;
6754: border-spacing: 0;
6755: }
6756:
6757: table#LC_helpmenu fieldset legend {
6758: font-size: larger;
6759: }
6760:
6761: table#LC_helpmenu_links {
6762: width: 100%;
6763: border: 1px solid black;
6764: background: $pgbg;
6765: padding: 0;
6766: border-spacing: 1px;
6767: }
6768:
6769: table#LC_helpmenu_links tr td {
6770: padding: 1px;
6771: background: $tabbg;
6772: text-align: center;
6773: font-weight: bold;
6774: }
6775:
6776: table#LC_helpmenu_links a:link,
6777: table#LC_helpmenu_links a:visited,
6778: table#LC_helpmenu_links a:active {
6779: text-decoration: none;
6780: color: $font;
6781: }
6782:
6783: table#LC_helpmenu_links a:hover {
6784: text-decoration: underline;
6785: color: $vlink;
6786: }
6787:
6788: .LC_chrt_popup_exists {
6789: border: 1px solid #339933;
6790: margin: -1px;
6791: }
6792:
6793: .LC_chrt_popup_up {
6794: border: 1px solid yellow;
6795: margin: -1px;
6796: }
6797:
6798: .LC_chrt_popup {
6799: border: 1px solid #8888FF;
6800: background: #CCCCFF;
6801: }
6802:
6803: table.LC_pick_box {
6804: border-collapse: separate;
6805: background: white;
6806: border: 1px solid black;
6807: border-spacing: 1px;
6808: }
6809:
6810: table.LC_pick_box td.LC_pick_box_title {
6811: background: $sidebg;
6812: font-weight: bold;
6813: text-align: left;
6814: vertical-align: top;
6815: width: 184px;
6816: padding: 8px;
6817: }
6818:
6819: table.LC_pick_box td.LC_pick_box_value {
6820: text-align: left;
6821: padding: 8px;
6822: }
6823:
6824: table.LC_pick_box td.LC_pick_box_select {
6825: text-align: left;
6826: padding: 8px;
6827: }
6828:
6829: table.LC_pick_box td.LC_pick_box_separator {
6830: padding: 0;
6831: height: 1px;
6832: background: black;
6833: }
6834:
6835: table.LC_pick_box td.LC_pick_box_submit {
6836: text-align: right;
6837: }
6838:
6839: table.LC_pick_box td.LC_evenrow_value {
6840: text-align: left;
6841: padding: 8px;
6842: background-color: $data_table_light;
6843: }
6844:
6845: table.LC_pick_box td.LC_oddrow_value {
6846: text-align: left;
6847: padding: 8px;
6848: background-color: $data_table_light;
6849: }
6850:
6851: span.LC_helpform_receipt_cat {
6852: font-weight: bold;
6853: }
6854:
6855: table.LC_group_priv_box {
6856: background: white;
6857: border: 1px solid black;
6858: border-spacing: 1px;
6859: }
6860:
6861: table.LC_group_priv_box td.LC_pick_box_title {
6862: background: $tabbg;
6863: font-weight: bold;
6864: text-align: right;
6865: width: 184px;
6866: }
6867:
6868: table.LC_group_priv_box td.LC_groups_fixed {
6869: background: $data_table_light;
6870: text-align: center;
6871: }
6872:
6873: table.LC_group_priv_box td.LC_groups_optional {
6874: background: $data_table_dark;
6875: text-align: center;
6876: }
6877:
6878: table.LC_group_priv_box td.LC_groups_functionality {
6879: background: $data_table_darker;
6880: text-align: center;
6881: font-weight: bold;
6882: }
6883:
6884: table.LC_group_priv td {
6885: text-align: left;
6886: padding: 0;
6887: }
6888:
6889: .LC_navbuttons {
6890: margin: 2ex 0ex 2ex 0ex;
6891: }
6892:
6893: .LC_topic_bar {
6894: font-weight: bold;
6895: background: $tabbg;
6896: margin: 1em 0em 1em 2em;
6897: padding: 3px;
6898: font-size: 1.2em;
6899: }
6900:
6901: .LC_topic_bar span {
6902: left: 0.5em;
6903: position: absolute;
6904: vertical-align: middle;
6905: font-size: 1.2em;
6906: }
6907:
6908: table.LC_course_group_status {
6909: margin: 20px;
6910: }
6911:
6912: table.LC_status_selector td {
6913: vertical-align: top;
6914: text-align: center;
6915: padding: 4px;
6916: }
6917:
6918: div.LC_feedback_link {
6919: clear: both;
6920: background: $sidebg;
6921: width: 100%;
6922: padding-bottom: 10px;
6923: border: 1px $tabbg solid;
6924: height: 22px;
6925: line-height: 22px;
6926: padding-top: 5px;
6927: }
6928:
6929: div.LC_feedback_link img {
6930: height: 22px;
6931: vertical-align:middle;
6932: }
6933:
6934: div.LC_feedback_link a {
6935: text-decoration: none;
6936: }
6937:
6938: div.LC_comblock {
6939: display:inline;
6940: color:$font;
6941: font-size:90%;
6942: }
6943:
6944: div.LC_feedback_link div.LC_comblock {
6945: padding-left:5px;
6946: }
6947:
6948: div.LC_feedback_link div.LC_comblock a {
6949: color:$font;
6950: }
6951:
6952: span.LC_feedback_link {
6953: /* background: $feedback_link_bg; */
6954: font-size: larger;
6955: }
6956:
6957: span.LC_message_link {
6958: /* background: $feedback_link_bg; */
6959: font-size: larger;
6960: position: absolute;
6961: right: 1em;
6962: }
6963:
6964: table.LC_prior_tries {
6965: border: 1px solid #000000;
6966: border-collapse: separate;
6967: border-spacing: 1px;
6968: }
6969:
6970: table.LC_prior_tries td {
6971: padding: 2px;
6972: }
6973:
6974: .LC_answer_correct {
6975: background: lightgreen;
6976: color: darkgreen;
6977: padding: 6px;
6978: }
6979:
6980: .LC_answer_charged_try {
6981: background: #FFAAAA;
6982: color: darkred;
6983: padding: 6px;
6984: }
6985:
6986: .LC_answer_not_charged_try,
6987: .LC_answer_no_grade,
6988: .LC_answer_late {
6989: background: lightyellow;
6990: color: black;
6991: padding: 6px;
6992: }
6993:
6994: .LC_answer_previous {
6995: background: lightblue;
6996: color: darkblue;
6997: padding: 6px;
6998: }
6999:
7000: .LC_answer_no_message {
7001: background: #FFFFFF;
7002: color: black;
7003: padding: 6px;
7004: }
7005:
7006: .LC_answer_unknown {
7007: background: orange;
7008: color: black;
7009: padding: 6px;
7010: }
7011:
7012: span.LC_prior_numerical,
7013: span.LC_prior_string,
7014: span.LC_prior_custom,
7015: span.LC_prior_reaction,
7016: span.LC_prior_math {
7017: font-family: $mono;
7018: white-space: pre;
7019: }
7020:
7021: span.LC_prior_string {
7022: font-family: $mono;
7023: white-space: pre;
7024: }
7025:
7026: table.LC_prior_option {
7027: width: 100%;
7028: border-collapse: collapse;
7029: }
7030:
7031: table.LC_prior_rank,
7032: table.LC_prior_match {
7033: border-collapse: collapse;
7034: }
7035:
7036: table.LC_prior_option tr td,
7037: table.LC_prior_rank tr td,
7038: table.LC_prior_match tr td {
7039: border: 1px solid #000000;
7040: }
7041:
7042: .LC_nobreak {
7043: white-space: nowrap;
7044: }
7045:
7046: span.LC_cusr_emph {
7047: font-style: italic;
7048: }
7049:
7050: span.LC_cusr_subheading {
7051: font-weight: normal;
7052: font-size: 85%;
7053: }
7054:
7055: div.LC_docs_entry_move {
7056: border: 1px solid #BBBBBB;
7057: background: #DDDDDD;
7058: width: 22px;
7059: padding: 1px;
7060: margin: 0;
7061: }
7062:
7063: table.LC_data_table tr > td.LC_docs_entry_commands,
7064: table.LC_data_table tr > td.LC_docs_entry_parameter {
7065: font-size: x-small;
7066: }
7067:
7068: .LC_docs_entry_parameter {
7069: white-space: nowrap;
7070: }
7071:
7072: .LC_docs_copy {
7073: color: #000099;
7074: }
7075:
7076: .LC_docs_cut {
7077: color: #550044;
7078: }
7079:
7080: .LC_docs_rename {
7081: color: #009900;
7082: }
7083:
7084: .LC_docs_remove {
7085: color: #990000;
7086: }
7087:
7088: .LC_docs_reinit_warn,
7089: .LC_docs_ext_edit {
7090: font-size: x-small;
7091: }
7092:
7093: table.LC_docs_adddocs td,
7094: table.LC_docs_adddocs th {
7095: border: 1px solid #BBBBBB;
7096: padding: 4px;
7097: background: #DDDDDD;
7098: }
7099:
7100: table.LC_sty_begin {
7101: background: #BBFFBB;
7102: }
7103:
7104: table.LC_sty_end {
7105: background: #FFBBBB;
7106: }
7107:
7108: table.LC_double_column {
7109: border-width: 0;
7110: border-collapse: collapse;
7111: width: 100%;
7112: padding: 2px;
7113: }
7114:
7115: table.LC_double_column tr td.LC_left_col {
7116: top: 2px;
7117: left: 2px;
7118: width: 47%;
7119: vertical-align: top;
7120: }
7121:
7122: table.LC_double_column tr td.LC_right_col {
7123: top: 2px;
7124: right: 2px;
7125: width: 47%;
7126: vertical-align: top;
7127: }
7128:
7129: div.LC_left_float {
7130: float: left;
7131: padding-right: 5%;
7132: padding-bottom: 4px;
7133: }
7134:
7135: div.LC_clear_float_header {
7136: padding-bottom: 2px;
7137: }
7138:
7139: div.LC_clear_float_footer {
7140: padding-top: 10px;
7141: clear: both;
7142: }
7143:
7144: div.LC_grade_show_user {
7145: /* border-left: 5px solid $sidebg; */
7146: border-top: 5px solid #000000;
7147: margin: 50px 0 0 0;
7148: padding: 15px 0 5px 10px;
7149: }
7150:
7151: div.LC_grade_show_user_odd_row {
7152: /* border-left: 5px solid #000000; */
7153: }
7154:
7155: div.LC_grade_show_user div.LC_Box {
7156: margin-right: 50px;
7157: }
7158:
7159: div.LC_grade_submissions,
7160: div.LC_grade_message_center,
7161: div.LC_grade_info_links {
7162: margin: 5px;
7163: width: 99%;
7164: background: #FFFFFF;
7165: }
7166:
7167: div.LC_grade_submissions_header,
7168: div.LC_grade_message_center_header {
7169: font-weight: bold;
7170: font-size: large;
7171: }
7172:
7173: div.LC_grade_submissions_body,
7174: div.LC_grade_message_center_body {
7175: border: 1px solid black;
7176: width: 99%;
7177: background: #FFFFFF;
7178: }
7179:
7180: table.LC_scantron_action {
7181: width: 100%;
7182: }
7183:
7184: table.LC_scantron_action tr th {
7185: font-weight:bold;
7186: font-style:normal;
7187: }
7188:
7189: .LC_edit_problem_header,
7190: div.LC_edit_problem_footer {
7191: font-weight: normal;
7192: font-size: medium;
7193: margin: 2px;
7194: background-color: $sidebg;
7195: }
7196:
7197: div.LC_edit_problem_header,
7198: div.LC_edit_problem_header div,
7199: div.LC_edit_problem_footer,
7200: div.LC_edit_problem_footer div,
7201: div.LC_edit_problem_editxml_header,
7202: div.LC_edit_problem_editxml_header div {
7203: z-index: 100;
7204: }
7205:
7206: div.LC_edit_problem_header_title {
7207: font-weight: bold;
7208: font-size: larger;
7209: background: $tabbg;
7210: padding: 3px;
7211: margin: 0 0 5px 0;
7212: }
7213:
7214: table.LC_edit_problem_header_title {
7215: width: 100%;
7216: background: $tabbg;
7217: }
7218:
7219: div.LC_edit_actionbar {
7220: background-color: $sidebg;
7221: margin: 0;
7222: padding: 0;
7223: line-height: 200%;
7224: }
7225:
7226: div.LC_edit_actionbar div{
7227: padding: 0;
7228: margin: 0;
7229: display: inline-block;
7230: }
7231:
7232: .LC_edit_opt {
7233: padding-left: 1em;
7234: white-space: nowrap;
7235: }
7236:
7237: .LC_edit_problem_latexhelper{
7238: text-align: right;
7239: }
7240:
7241: #LC_edit_problem_colorful div{
7242: margin-left: 40px;
7243: }
7244:
7245: #LC_edit_problem_codemirror div{
7246: margin-left: 0px;
7247: }
7248:
7249: img.stift {
7250: border-width: 0;
7251: vertical-align: middle;
7252: }
7253:
7254: table td.LC_mainmenu_col_fieldset {
7255: vertical-align: top;
7256: }
7257:
7258: div.LC_createcourse {
7259: margin: 10px 10px 10px 10px;
7260: }
7261:
7262: .LC_dccid {
7263: float: right;
7264: margin: 0.2em 0 0 0;
7265: padding: 0;
7266: font-size: 90%;
7267: display:none;
7268: }
7269:
7270: ol.LC_primary_menu a:hover,
7271: ol#LC_MenuBreadcrumbs a:hover,
7272: ol#LC_PathBreadcrumbs a:hover,
7273: ul#LC_secondary_menu a:hover,
7274: .LC_FormSectionClearButton input:hover
7275: ul.LC_TabContent li:hover a {
7276: color:$button_hover;
7277: text-decoration:none;
7278: }
7279:
7280: h1 {
7281: padding: 0;
7282: line-height:130%;
7283: }
7284:
7285: h2,
7286: h3,
7287: h4,
7288: h5,
7289: h6 {
7290: margin: 5px 0 5px 0;
7291: padding: 0;
7292: line-height:130%;
7293: }
7294:
7295: .LC_hcell {
7296: padding:3px 15px 3px 15px;
7297: margin: 0;
7298: background-color:$tabbg;
7299: color:$fontmenu;
7300: border-bottom:solid 1px $lg_border_color;
7301: }
7302:
7303: .LC_Box > .LC_hcell {
7304: margin: 0 -10px 10px -10px;
7305: }
7306:
7307: .LC_noBorder {
7308: border: 0;
7309: }
7310:
7311: .LC_FormSectionClearButton input {
7312: background-color:transparent;
7313: border: none;
7314: cursor:pointer;
7315: text-decoration:underline;
7316: }
7317:
7318: .LC_help_open_topic {
7319: color: #FFFFFF;
7320: background-color: #EEEEFF;
7321: margin: 1px;
7322: padding: 4px;
7323: border: 1px solid #000033;
7324: white-space: nowrap;
7325: /* vertical-align: middle; */
7326: }
7327:
7328: dl,
7329: ul,
7330: div,
7331: fieldset {
7332: margin: 10px 10px 10px 0;
7333: /* overflow: hidden; */
7334: }
7335:
7336: article.geogebraweb div {
7337: margin: 0;
7338: }
7339:
7340: fieldset > legend {
7341: font-weight: bold;
7342: padding: 0 5px 0 5px;
7343: }
7344:
7345: #LC_nav_bar {
7346: float: left;
7347: background-color: $pgbg_or_bgcolor;
7348: margin: 0 0 2px 0;
7349: }
7350:
7351: #LC_realm {
7352: margin: 0.2em 0 0 0;
7353: padding: 0;
7354: font-weight: bold;
7355: text-align: center;
7356: background-color: $pgbg_or_bgcolor;
7357: }
7358:
7359: #LC_nav_bar em {
7360: font-weight: bold;
7361: font-style: normal;
7362: }
7363:
7364: ol.LC_primary_menu {
7365: margin: 0;
7366: padding: 0;
7367: }
7368:
7369: ol#LC_PathBreadcrumbs {
7370: margin: 0;
7371: }
7372:
7373: ol.LC_primary_menu li {
7374: color: RGB(80, 80, 80);
7375: vertical-align: middle;
7376: text-align: left;
7377: list-style: none;
7378: position: relative;
7379: float: left;
7380: z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
7381: line-height: 1.5em;
7382: }
7383:
7384: ol.LC_primary_menu li a,
7385: ol.LC_primary_menu li p {
7386: display: block;
7387: margin: 0;
7388: padding: 0 5px 0 10px;
7389: text-decoration: none;
7390: }
7391:
7392: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
7393: display: inline-block;
7394: width: 95%;
7395: text-align: left;
7396: }
7397:
7398: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
7399: display: inline-block;
7400: width: 5%;
7401: float: right;
7402: text-align: right;
7403: font-size: 70%;
7404: }
7405:
7406: ol.LC_primary_menu ul {
7407: display: none;
7408: width: 15em;
7409: background-color: $data_table_light;
7410: position: absolute;
7411: top: 100%;
7412: }
7413:
7414: ol.LC_primary_menu ul ul {
7415: left: 100%;
7416: top: 0;
7417: }
7418:
7419: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
7420: display: block;
7421: position: absolute;
7422: margin: 0;
7423: padding: 0;
7424: z-index: 2;
7425: }
7426:
7427: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
7428: /* First Submenu -> size should be smaller than the menu title of the whole menu */
7429: font-size: 90%;
7430: vertical-align: top;
7431: float: none;
7432: border-left: 1px solid black;
7433: border-right: 1px solid black;
7434: /* A dark bottom border to visualize different menu options;
7435: overwritten in the create_submenu routine for the last border-bottom of the menu */
7436: border-bottom: 1px solid $data_table_dark;
7437: }
7438:
7439: ol.LC_primary_menu li li p:hover {
7440: color:$button_hover;
7441: text-decoration:none;
7442: background-color:$data_table_dark;
7443: }
7444:
7445: ol.LC_primary_menu li li a:hover {
7446: color:$button_hover;
7447: background-color:$data_table_dark;
7448: }
7449:
7450: /* Font-size equal to the size of the predecessors*/
7451: ol.LC_primary_menu li:hover li li {
7452: font-size: 100%;
7453: }
7454:
7455: ol.LC_primary_menu li img {
7456: vertical-align: bottom;
7457: height: 1.1em;
7458: margin: 0.2em 0 0 0;
7459: }
7460:
7461: ol.LC_primary_menu a {
7462: color: RGB(80, 80, 80);
7463: text-decoration: none;
7464: }
7465:
7466: ol.LC_primary_menu a.LC_new_message {
7467: font-weight:bold;
7468: color: darkred;
7469: }
7470:
7471: ol.LC_docs_parameters {
7472: margin-left: 0;
7473: padding: 0;
7474: list-style: none;
7475: }
7476:
7477: ol.LC_docs_parameters li {
7478: margin: 0;
7479: padding-right: 20px;
7480: display: inline;
7481: }
7482:
7483: ol.LC_docs_parameters li:before {
7484: content: "\\002022 \\0020";
7485: }
7486:
7487: li.LC_docs_parameters_title {
7488: font-weight: bold;
7489: }
7490:
7491: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
7492: content: "";
7493: }
7494:
7495: ul#LC_secondary_menu {
7496: clear: right;
7497: color: $fontmenu;
7498: background: $tabbg;
7499: list-style: none;
7500: padding: 0;
7501: margin: 0;
7502: width: 100%;
7503: text-align: left;
7504: float: left;
7505: }
7506:
7507: ul#LC_secondary_menu li {
7508: font-weight: bold;
7509: line-height: 1.8em;
7510: border-right: 1px solid black;
7511: float: left;
7512: }
7513:
7514: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
7515: background-color: $data_table_light;
7516: }
7517:
7518: ul#LC_secondary_menu li a {
7519: padding: 0 0.8em;
7520: }
7521:
7522: ul#LC_secondary_menu li ul {
7523: display: none;
7524: }
7525:
7526: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
7527: display: block;
7528: position: absolute;
7529: margin: 0;
7530: padding: 0;
7531: list-style:none;
7532: float: none;
7533: background-color: $data_table_light;
7534: z-index: 2;
7535: margin-left: -1px;
7536: }
7537:
7538: ul#LC_secondary_menu li ul li {
7539: font-size: 90%;
7540: vertical-align: top;
7541: border-left: 1px solid black;
7542: border-right: 1px solid black;
7543: background-color: $data_table_light;
7544: list-style:none;
7545: float: none;
7546: }
7547:
7548: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
7549: background-color: $data_table_dark;
7550: }
7551:
7552: ul.LC_TabContent {
7553: display:block;
7554: background: $sidebg;
7555: border-bottom: solid 1px $lg_border_color;
7556: list-style:none;
7557: margin: -1px -10px 0 -10px;
7558: padding: 0;
7559: }
7560:
7561: ul.LC_TabContent li,
7562: ul.LC_TabContentBigger li {
7563: float:left;
7564: }
7565:
7566: ul#LC_secondary_menu li a {
7567: color: $fontmenu;
7568: text-decoration: none;
7569: }
7570:
7571: ul.LC_TabContent {
7572: min-height:20px;
7573: }
7574:
7575: ul.LC_TabContent li {
7576: vertical-align:middle;
7577: padding: 0 16px 0 10px;
7578: background-color:$tabbg;
7579: border-bottom:solid 1px $lg_border_color;
7580: border-left: solid 1px $font;
7581: }
7582:
7583: ul.LC_TabContent .right {
7584: float:right;
7585: }
7586:
7587: ul.LC_TabContent li a,
7588: ul.LC_TabContent li {
7589: color:rgb(47,47,47);
7590: text-decoration:none;
7591: font-size:95%;
7592: font-weight:bold;
7593: min-height:20px;
7594: }
7595:
7596: ul.LC_TabContent li a:hover,
7597: ul.LC_TabContent li a:focus {
7598: color: $button_hover;
7599: background:none;
7600: outline:none;
7601: }
7602:
7603: ul.LC_TabContent li:hover {
7604: color: $button_hover;
7605: cursor:pointer;
7606: }
7607:
7608: ul.LC_TabContent li.active {
7609: color: $font;
7610: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
7611: border-bottom:solid 1px #FFFFFF;
7612: cursor: default;
7613: }
7614:
7615: ul.LC_TabContent li.active a {
7616: color:$font;
7617: background:#FFFFFF;
7618: outline: none;
7619: }
7620:
7621: ul.LC_TabContent li.goback {
7622: float: left;
7623: border-left: none;
7624: }
7625:
7626: #maincoursedoc {
7627: clear:both;
7628: }
7629:
7630: ul.LC_TabContentBigger {
7631: display:block;
7632: list-style:none;
7633: padding: 0;
7634: }
7635:
7636: ul.LC_TabContentBigger li {
7637: vertical-align:bottom;
7638: height: 30px;
7639: font-size:110%;
7640: font-weight:bold;
7641: color: #737373;
7642: }
7643:
7644: ul.LC_TabContentBigger li.active {
7645: position: relative;
7646: top: 1px;
7647: }
7648:
7649: ul.LC_TabContentBigger li a {
7650: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
7651: height: 30px;
7652: line-height: 30px;
7653: text-align: center;
7654: display: block;
7655: text-decoration: none;
7656: outline: none;
7657: }
7658:
7659: ul.LC_TabContentBigger li.active a {
7660: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
7661: color:$font;
7662: }
7663:
7664: ul.LC_TabContentBigger li b {
7665: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
7666: display: block;
7667: float: left;
7668: padding: 0 30px;
7669: border-bottom: 1px solid $lg_border_color;
7670: }
7671:
7672: ul.LC_TabContentBigger li:hover b {
7673: color:$button_hover;
7674: }
7675:
7676: ul.LC_TabContentBigger li.active b {
7677: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
7678: color:$font;
7679: border: 0;
7680: }
7681:
7682:
7683: ul.LC_CourseBreadcrumbs {
7684: background: $sidebg;
7685: height: 2em;
7686: padding-left: 10px;
7687: margin: 0;
7688: list-style-position: inside;
7689: }
7690:
7691: ol#LC_MenuBreadcrumbs,
7692: ol#LC_PathBreadcrumbs {
7693: padding-left: 10px;
7694: margin: 0;
7695: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
7696: }
7697:
7698: ol#LC_MenuBreadcrumbs li,
7699: ol#LC_PathBreadcrumbs li,
7700: ul.LC_CourseBreadcrumbs li {
7701: display: inline;
7702: white-space: normal;
7703: }
7704:
7705: ol#LC_MenuBreadcrumbs li a,
7706: ul.LC_CourseBreadcrumbs li a {
7707: text-decoration: none;
7708: font-size:90%;
7709: }
7710:
7711: ol#LC_MenuBreadcrumbs h1 {
7712: display: inline;
7713: font-size: 90%;
7714: line-height: 2.5em;
7715: margin: 0;
7716: padding: 0;
7717: }
7718:
7719: ol#LC_PathBreadcrumbs li a {
7720: text-decoration:none;
7721: font-size:100%;
7722: font-weight:bold;
7723: }
7724:
7725: .LC_Box {
7726: border: solid 1px $lg_border_color;
7727: padding: 0 10px 10px 10px;
7728: }
7729:
7730: .LC_DocsBox {
7731: border: solid 1px $lg_border_color;
7732: padding: 0 0 10px 10px;
7733: }
7734:
7735: .LC_AboutMe_Image {
7736: float:left;
7737: margin-right:10px;
7738: }
7739:
7740: .LC_Clear_AboutMe_Image {
7741: clear:left;
7742: }
7743:
7744: dl.LC_ListStyleClean dt {
7745: padding-right: 5px;
7746: display: table-header-group;
7747: }
7748:
7749: dl.LC_ListStyleClean dd {
7750: display: table-row;
7751: }
7752:
7753: .LC_ListStyleClean,
7754: .LC_ListStyleSimple,
7755: .LC_ListStyleNormal,
7756: .LC_ListStyleSpecial {
7757: /* display:block; */
7758: list-style-position: inside;
7759: list-style-type: none;
7760: overflow: hidden;
7761: padding: 0;
7762: }
7763:
7764: .LC_ListStyleSimple li,
7765: .LC_ListStyleSimple dd,
7766: .LC_ListStyleNormal li,
7767: .LC_ListStyleNormal dd,
7768: .LC_ListStyleSpecial li,
7769: .LC_ListStyleSpecial dd {
7770: margin: 0;
7771: padding: 5px 5px 5px 10px;
7772: clear: both;
7773: }
7774:
7775: .LC_ListStyleClean li,
7776: .LC_ListStyleClean dd {
7777: padding-top: 0;
7778: padding-bottom: 0;
7779: }
7780:
7781: .LC_ListStyleSimple dd,
7782: .LC_ListStyleSimple li {
7783: border-bottom: solid 1px $lg_border_color;
7784: }
7785:
7786: .LC_ListStyleSpecial li,
7787: .LC_ListStyleSpecial dd {
7788: list-style-type: none;
7789: background-color: RGB(220, 220, 220);
7790: margin-bottom: 4px;
7791: }
7792:
7793: table.LC_SimpleTable {
7794: margin:5px;
7795: border:solid 1px $lg_border_color;
7796: }
7797:
7798: table.LC_SimpleTable tr {
7799: padding: 0;
7800: border:solid 1px $lg_border_color;
7801: }
7802:
7803: table.LC_SimpleTable thead {
7804: background:rgb(220,220,220);
7805: }
7806:
7807: div.LC_columnSection {
7808: display: block;
7809: clear: both;
7810: overflow: hidden;
7811: margin: 0;
7812: }
7813:
7814: div.LC_columnSection>* {
7815: float: left;
7816: margin: 10px 20px 10px 0;
7817: overflow:hidden;
7818: }
7819:
7820: table em {
7821: font-weight: bold;
7822: font-style: normal;
7823: }
7824:
7825: table.LC_tableBrowseRes,
7826: table.LC_tableOfContent {
7827: border:none;
7828: border-spacing: 1px;
7829: padding: 3px;
7830: background-color: #FFFFFF;
7831: font-size: 90%;
7832: }
7833:
7834: table.LC_tableOfContent {
7835: border-collapse: collapse;
7836: }
7837:
7838: table.LC_tableBrowseRes a,
7839: table.LC_tableOfContent a {
7840: background-color: transparent;
7841: text-decoration: none;
7842: }
7843:
7844: table.LC_tableOfContent img {
7845: border: none;
7846: height: 1.3em;
7847: vertical-align: text-bottom;
7848: margin-right: 0.3em;
7849: }
7850:
7851: a#LC_content_toolbar_firsthomework {
7852: background-image:url(/res/adm/pages/open-first-problem.gif);
7853: }
7854:
7855: a#LC_content_toolbar_everything {
7856: background-image:url(/res/adm/pages/show-all.gif);
7857: }
7858:
7859: a#LC_content_toolbar_uncompleted {
7860: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
7861: }
7862:
7863: #LC_content_toolbar_clearbubbles {
7864: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
7865: }
7866:
7867: a#LC_content_toolbar_changefolder {
7868: background : url(/res/adm/pages/close-all-folders.gif) top center ;
7869: }
7870:
7871: a#LC_content_toolbar_changefolder_toggled {
7872: background-image:url(/res/adm/pages/open-all-folders.gif);
7873: }
7874:
7875: a#LC_content_toolbar_edittoplevel {
7876: background-image:url(/res/adm/pages/edittoplevel.gif);
7877: }
7878:
7879: ul#LC_toolbar li a:hover {
7880: background-position: bottom center;
7881: }
7882:
7883: ul#LC_toolbar {
7884: padding: 0;
7885: margin: 2px;
7886: list-style:none;
7887: position:relative;
7888: background-color:white;
7889: overflow: auto;
7890: }
7891:
7892: ul#LC_toolbar li {
7893: border:1px solid white;
7894: padding: 0;
7895: margin: 0;
7896: float: left;
7897: display:inline;
7898: vertical-align:middle;
7899: white-space: nowrap;
7900: }
7901:
7902:
7903: a.LC_toolbarItem {
7904: display:block;
7905: padding: 0;
7906: margin: 0;
7907: height: 32px;
7908: width: 32px;
7909: color:white;
7910: border: none;
7911: background-repeat:no-repeat;
7912: background-color:transparent;
7913: }
7914:
7915: ul.LC_funclist {
7916: margin: 0;
7917: padding: 0.5em 1em 0.5em 0;
7918: }
7919:
7920: ul.LC_funclist > li:first-child {
7921: font-weight:bold;
7922: margin-left:0.8em;
7923: }
7924:
7925: ul.LC_funclist + ul.LC_funclist {
7926: /*
7927: left border as a seperator if we have more than
7928: one list
7929: */
7930: border-left: 1px solid $sidebg;
7931: /*
7932: this hides the left border behind the border of the
7933: outer box if element is wrapped to the next 'line'
7934: */
7935: margin-left: -1px;
7936: }
7937:
7938: ul.LC_funclist li {
7939: display: inline;
7940: white-space: nowrap;
7941: margin: 0 0 0 25px;
7942: line-height: 150%;
7943: }
7944:
7945: .LC_hidden {
7946: display: none;
7947: }
7948:
7949: .LCmodal-overlay {
7950: position:fixed;
7951: top:0;
7952: right:0;
7953: bottom:0;
7954: left:0;
7955: height:100%;
7956: width:100%;
7957: margin:0;
7958: padding:0;
7959: background:#999;
7960: opacity:.75;
7961: filter: alpha(opacity=75);
7962: -moz-opacity: 0.75;
7963: z-index:101;
7964: }
7965:
7966: * html .LCmodal-overlay {
7967: position: absolute;
7968: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
7969: }
7970:
7971: .LCmodal-window {
7972: position:fixed;
7973: top:50%;
7974: left:50%;
7975: margin:0;
7976: padding:0;
7977: z-index:102;
7978: }
7979:
7980: * html .LCmodal-window {
7981: position:absolute;
7982: }
7983:
7984: .LCclose-window {
7985: position:absolute;
7986: width:32px;
7987: height:32px;
7988: right:8px;
7989: top:8px;
7990: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
7991: text-indent:-99999px;
7992: overflow:hidden;
7993: cursor:pointer;
7994: }
7995:
7996: /*
7997: styles used for response display
7998: */
7999: div.LC_radiofoil, div.LC_rankfoil {
8000: margin: .5em 0em .5em 0em;
8001: }
8002: table.LC_itemgroup {
8003: margin-top: 1em;
8004: }
8005:
8006: /*
8007: styles used by TTH when "Default set of options to pass to tth/m
8008: when converting TeX" in course settings has been set
8009:
8010: option passed: -t
8011:
8012: */
8013:
8014: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
8015: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
8016: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
8017: td div.norm {line-height:normal;}
8018:
8019: /*
8020: option passed -y3
8021: */
8022:
8023: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
8024: span.overacc2 {position: relative; left: .8em; top: -1.2ex;}
8025: span.overacc1 {position: relative; left: .6em; top: -1.2ex;}
8026:
8027: /*
8028: sections with roles, for content only
8029: */
8030: section[class^="role-"] {
8031: padding-left: 10px;
8032: padding-right: 5px;
8033: margin-top: 8px;
8034: margin-bottom: 8px;
8035: border: 1px solid #2A4;
8036: border-radius: 5px;
8037: box-shadow: 0px 1px 1px #BBB;
8038: }
8039: section[class^="role-"]>h1 {
8040: position: relative;
8041: margin: 0px;
8042: padding-top: 10px;
8043: padding-left: 40px;
8044: }
8045: section[class^="role-"]>h1:before {
8046: position: absolute;
8047: left: -5px;
8048: top: 5px;
8049: }
8050: section.role-activity>h1:before {
8051: content:url('/adm/daxe/images/section_icons/activity.png');
8052: }
8053: section.role-advice>h1:before {
8054: content:url('/adm/daxe/images/section_icons/advice.png');
8055: }
8056: section.role-bibliography>h1:before {
8057: content:url('/adm/daxe/images/section_icons/bibliography.png');
8058: }
8059: section.role-citation>h1:before {
8060: content:url('/adm/daxe/images/section_icons/citation.png');
8061: }
8062: section.role-conclusion>h1:before {
8063: content:url('/adm/daxe/images/section_icons/conclusion.png');
8064: }
8065: section.role-definition>h1:before {
8066: content:url('/adm/daxe/images/section_icons/definition.png');
8067: }
8068: section.role-demonstration>h1:before {
8069: content:url('/adm/daxe/images/section_icons/demonstration.png');
8070: }
8071: section.role-example>h1:before {
8072: content:url('/adm/daxe/images/section_icons/example.png');
8073: }
8074: section.role-explanation>h1:before {
8075: content:url('/adm/daxe/images/section_icons/explanation.png');
8076: }
8077: section.role-introduction>h1:before {
8078: content:url('/adm/daxe/images/section_icons/introduction.png');
8079: }
8080: section.role-method>h1:before {
8081: content:url('/adm/daxe/images/section_icons/method.png');
8082: }
8083: section.role-more_information>h1:before {
8084: content:url('/adm/daxe/images/section_icons/more_information.png');
8085: }
8086: section.role-objectives>h1:before {
8087: content:url('/adm/daxe/images/section_icons/objectives.png');
8088: }
8089: section.role-prerequisites>h1:before {
8090: content:url('/adm/daxe/images/section_icons/prerequisites.png');
8091: }
8092: section.role-remark>h1:before {
8093: content:url('/adm/daxe/images/section_icons/remark.png');
8094: }
8095: section.role-reminder>h1:before {
8096: content:url('/adm/daxe/images/section_icons/reminder.png');
8097: }
8098: section.role-summary>h1:before {
8099: content:url('/adm/daxe/images/section_icons/summary.png');
8100: }
8101: section.role-syntax>h1:before {
8102: content:url('/adm/daxe/images/section_icons/syntax.png');
8103: }
8104: section.role-warning>h1:before {
8105: content:url('/adm/daxe/images/section_icons/warning.png');
8106: }
8107:
8108: END
8109: }
8110:
8111: =pod
8112:
8113: =item * &headtag()
8114:
8115: Returns a uniform footer for LON-CAPA web pages.
8116:
8117: Inputs: $title - optional title for the head
8118: $head_extra - optional extra HTML to put inside the <head>
8119: $args - optional arguments
8120: force_register - if is true call registerurl so the remote is
8121: informed
8122: redirect -> array ref of
8123: 1- seconds before redirect occurs
8124: 2- url to redirect to
8125: 3- whether the side effect should occur
8126: (side effect of setting
8127: $env{'internal.head.redirect'} to the url
8128: redirected too)
8129: domain -> force to color decorate a page for a specific
8130: domain
8131: function -> force usage of a specific rolish color scheme
8132: bgcolor -> override the default page bgcolor
8133: no_auto_mt_title
8134: -> prevent &mt()ing the title arg
8135:
8136: =cut
8137:
8138: sub headtag {
8139: my ($title,$head_extra,$args) = @_;
8140:
8141: my $function = $args->{'function'} || &get_users_function();
8142: my $domain = $args->{'domain'} || &determinedomain();
8143: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
8144: my $httphost = $args->{'use_absolute'};
8145: my $url = join(':',$env{'user.name'},$env{'user.domain'},
8146: $Apache::lonnet::perlvar{'lonVersion'},
8147: #time(),
8148: $env{'environment.color.timestamp'},
8149: $function,$domain,$bgcolor);
8150:
8151: $url = '/adm/css/'.&escape($url).'.css';
8152:
8153: my $result =
8154: '<head>'.
8155: &font_settings($args);
8156:
8157: my $inhibitprint;
8158: if ($args->{'print_suppress'}) {
8159: $inhibitprint = &print_suppression();
8160: }
8161:
8162: if (!$args->{'frameset'}) {
8163: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
8164: }
8165: if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
8166: $result .= Apache::lonxml::display_title();
8167: }
8168: if (!$args->{'no_nav_bar'}
8169: && !$args->{'only_body'}
8170: && !$args->{'frameset'}) {
8171: $result .= &help_menu_js($httphost);
8172: $result.=&modal_window();
8173: $result.=&togglebox_script();
8174: $result.=&wishlist_window();
8175: $result.=&LCprogressbarUpdate_script();
8176: } else {
8177: if ($args->{'add_modal'}) {
8178: $result.=&modal_window();
8179: }
8180: if ($args->{'add_wishlist'}) {
8181: $result.=&wishlist_window();
8182: }
8183: if ($args->{'add_togglebox'}) {
8184: $result.=&togglebox_script();
8185: }
8186: if ($args->{'add_progressbar'}) {
8187: $result.=&LCprogressbarUpdate_script();
8188: }
8189: }
8190: if (ref($args->{'redirect'})) {
8191: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
8192: $url = &Apache::lonenc::check_encrypt($url);
8193: if (!$inhibit_continue) {
8194: $env{'internal.head.redirect'} = $url;
8195: }
8196: $result.=<<ADDMETA
8197: <meta http-equiv="pragma" content="no-cache" />
8198: <meta http-equiv="Refresh" content="$time; url=$url" />
8199: ADDMETA
8200: } else {
8201: unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
8202: my $requrl = $env{'request.uri'};
8203: if ($requrl eq '') {
8204: $requrl = $ENV{'REQUEST_URI'};
8205: $requrl =~ s/\?.+$//;
8206: }
8207: unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
8208: (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
8209: ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
8210: my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
8211: unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
8212: my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
8213: if (ref($domdefs{'offloadnow'}) eq 'HASH') {
8214: my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
8215: if ($domdefs{'offloadnow'}{$lonhost}) {
8216: my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
8217: if (($newserver) && ($newserver ne $lonhost)) {
8218: my $numsec = 5;
8219: my $timeout = $numsec * 1000;
8220: my ($newurl,$locknum,%locks,$msg);
8221: if ($env{'request.role.adv'}) {
8222: ($locknum,%locks) = &Apache::lonnet::get_locks();
8223: }
8224: my $disable_submit = 0;
8225: if ($requrl =~ /$LONCAPA::assess_re/) {
8226: $disable_submit = 1;
8227: }
8228: if ($locknum) {
8229: my @lockinfo = sort(values(%locks));
8230: $msg = &mt('Once the following tasks are complete: ')."\\n".
8231: join(", ",sort(values(%locks)))."\\n".
8232: &mt('your session will be transferred to a different server, after you click "Roles".');
8233: } else {
8234: if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
8235: $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
8236: }
8237: $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
8238: $newurl = '/adm/switchserver?otherserver='.$newserver;
8239: if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
8240: $newurl .= '&role='.$env{'request.role'};
8241: }
8242: if ($env{'request.symb'}) {
8243: $newurl .= '&symb='.$env{'request.symb'};
8244: } else {
8245: $newurl .= '&origurl='.$requrl;
8246: }
8247: }
8248: &js_escape(\$msg);
8249: $result.=<<OFFLOAD
8250: <meta http-equiv="pragma" content="no-cache" />
8251: <script type="text/javascript">
8252: // <![CDATA[
8253: function LC_Offload_Now() {
8254: var dest = "$newurl";
8255: if (dest != '') {
8256: window.location.href="$newurl";
8257: }
8258: }
8259: \$(document).ready(function () {
8260: window.alert('$msg');
8261: if ($disable_submit) {
8262: \$(".LC_hwk_submit").prop("disabled", true);
8263: \$( ".LC_textline" ).prop( "readonly", "readonly");
8264: }
8265: setTimeout('LC_Offload_Now()', $timeout);
8266: });
8267: // ]]>
8268: </script>
8269: OFFLOAD
8270: }
8271: }
8272: }
8273: }
8274: }
8275: }
8276: }
8277: if (!defined($title)) {
8278: $title = 'The LearningOnline Network with CAPA';
8279: }
8280: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
8281: $result .= '<title> LON-CAPA '.$title.'</title>'
8282: .'<link rel="stylesheet" type="text/css" href="'.$url.'"';
8283: if (!$args->{'frameset'}) {
8284: $result .= ' /';
8285: }
8286: $result .= '>'
8287: .$inhibitprint
8288: .$head_extra;
8289: my $clientmobile;
8290: if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
8291: (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
8292: } else {
8293: $clientmobile = $env{'browser.mobile'};
8294: }
8295: if ($clientmobile) {
8296: $result .= '
8297: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
8298: <meta name="apple-mobile-web-app-capable" content="yes" />';
8299: }
8300: return $result.'</head>';
8301: }
8302:
8303: =pod
8304:
8305: =item * &font_settings()
8306:
8307: Returns neccessary <meta> to set the proper encoding
8308:
8309: Inputs: optional reference to HASH -- $args passed to &headtag()
8310:
8311: =cut
8312:
8313: sub font_settings {
8314: my ($args) = @_;
8315: my $headerstring='';
8316: if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
8317: ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
8318: $headerstring.=
8319: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
8320: if (!$args->{'frameset'}) {
8321: $headerstring.= ' /';
8322: }
8323: $headerstring .= '>'."\n";
8324: }
8325: return $headerstring;
8326: }
8327:
8328: =pod
8329:
8330: =item * &print_suppression()
8331:
8332: In course context returns css which causes the body to be blank when media="print",
8333: if printout generation is unavailable for the current resource.
8334:
8335: This could be because:
8336:
8337: (a) printstartdate is in the future
8338:
8339: (b) printenddate is in the past
8340:
8341: (c) there is an active exam block with "printout"
8342: functionality blocked
8343:
8344: Users with pav, pfo or evb privileges are exempt.
8345:
8346: Inputs: none
8347:
8348: =cut
8349:
8350:
8351: sub print_suppression {
8352: my $noprint;
8353: if ($env{'request.course.id'}) {
8354: my $scope = $env{'request.course.id'};
8355: if ((&Apache::lonnet::allowed('pav',$scope)) ||
8356: (&Apache::lonnet::allowed('pfo',$scope))) {
8357: return;
8358: }
8359: if ($env{'request.course.sec'} ne '') {
8360: $scope .= "/$env{'request.course.sec'}";
8361: if ((&Apache::lonnet::allowed('pav',$scope)) ||
8362: (&Apache::lonnet::allowed('pfo',$scope))) {
8363: return;
8364: }
8365: }
8366: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8367: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8368: my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
8369: if ($blocked) {
8370: my $checkrole = "cm./$cdom/$cnum";
8371: if ($env{'request.course.sec'} ne '') {
8372: $checkrole .= "/$env{'request.course.sec'}";
8373: }
8374: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
8375: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
8376: $noprint = 1;
8377: }
8378: }
8379: unless ($noprint) {
8380: my $symb = &Apache::lonnet::symbread();
8381: if ($symb ne '') {
8382: my $navmap = Apache::lonnavmaps::navmap->new();
8383: if (ref($navmap)) {
8384: my $res = $navmap->getBySymb($symb);
8385: if (ref($res)) {
8386: if (!$res->resprintable()) {
8387: $noprint = 1;
8388: }
8389: }
8390: }
8391: }
8392: }
8393: if ($noprint) {
8394: return <<"ENDSTYLE";
8395: <style type="text/css" media="print">
8396: body { display:none }
8397: </style>
8398: ENDSTYLE
8399: }
8400: }
8401: return;
8402: }
8403:
8404: =pod
8405:
8406: =item * &xml_begin()
8407:
8408: Returns the needed doctype and <html>
8409:
8410: Inputs: none
8411:
8412: =cut
8413:
8414: sub xml_begin {
8415: my ($is_frameset) = @_;
8416: my $output='';
8417:
8418: if ($env{'browser.mathml'}) {
8419: $output='<?xml version="1.0"?>'
8420: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
8421: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
8422:
8423: # .'<!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">] >'
8424: .'<!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">'
8425: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
8426: .'xmlns="http://www.w3.org/1999/xhtml">';
8427: } elsif ($is_frameset) {
8428: $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
8429: '<html>'."\n";
8430: } else {
8431: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
8432: '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
8433: }
8434: return $output;
8435: }
8436:
8437: =pod
8438:
8439: =item * &start_page()
8440:
8441: Returns a complete <html> .. <body> section for LON-CAPA web pages.
8442:
8443: Inputs:
8444:
8445: =over 4
8446:
8447: $title - optional title for the page
8448:
8449: $head_extra - optional extra HTML to incude inside the <head>
8450:
8451: $args - additional optional args supported are:
8452:
8453: =over 8
8454:
8455: only_body -> is true will set &bodytag() onlybodytag
8456: arg on
8457: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
8458: add_entries -> additional attributes to add to the <body>
8459: domain -> force to color decorate a page for a
8460: specific domain
8461: function -> force usage of a specific rolish color
8462: scheme
8463: redirect -> see &headtag()
8464: bgcolor -> override the default page bg color
8465: js_ready -> return a string ready for being used in
8466: a javascript writeln
8467: html_encode -> return a string ready for being used in
8468: a html attribute
8469: force_register -> if is true will turn on the &bodytag()
8470: $forcereg arg
8471: frameset -> if true will start with a <frameset>
8472: rather than <body>
8473: skip_phases -> hash ref of
8474: head -> skip the <html><head> generation
8475: body -> skip all <body> generation
8476: no_auto_mt_title -> prevent &mt()ing the title arg
8477: bread_crumbs -> Array containing breadcrumbs
8478: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
8479: group -> includes the current group, if page is for a
8480: specific group
8481:
8482: =back
8483:
8484: =back
8485:
8486: =cut
8487:
8488: sub start_page {
8489: my ($title,$head_extra,$args) = @_;
8490: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
8491:
8492: $env{'internal.start_page'}++;
8493: my ($result,@advtools);
8494:
8495: if (! exists($args->{'skip_phases'}{'head'}) ) {
8496: $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
8497: }
8498:
8499: if (! exists($args->{'skip_phases'}{'body'}) ) {
8500: if ($args->{'frameset'}) {
8501: my $attr_string = &make_attr_string($args->{'force_register'},
8502: $args->{'add_entries'});
8503: $result .= "\n<frameset $attr_string>\n";
8504: } else {
8505: $result .=
8506: &bodytag($title,
8507: $args->{'function'}, $args->{'add_entries'},
8508: $args->{'only_body'}, $args->{'domain'},
8509: $args->{'force_register'}, $args->{'no_nav_bar'},
8510: $args->{'bgcolor'}, $args,
8511: \@advtools);
8512: }
8513: }
8514:
8515: if ($args->{'js_ready'}) {
8516: $result = &js_ready($result);
8517: }
8518: if ($args->{'html_encode'}) {
8519: $result = &html_encode($result);
8520: }
8521:
8522: # Preparation for new and consistent functionlist at top of screen
8523: # if ($args->{'functionlist'}) {
8524: # $result .= &build_functionlist();
8525: #}
8526:
8527: # Don't add anything more if only_body wanted or in const space
8528: return $result if $args->{'only_body'}
8529: || $env{'request.state'} eq 'construct';
8530:
8531: #Breadcrumbs
8532: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
8533: &Apache::lonhtmlcommon::clear_breadcrumbs();
8534: #if any br links exists, add them to the breadcrumbs
8535: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
8536: foreach my $crumb (@{$args->{'bread_crumbs'}}){
8537: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
8538: }
8539: }
8540: # if @advtools array contains items add then to the breadcrumbs
8541: if (@advtools > 0) {
8542: &Apache::lonmenu::advtools_crumbs(@advtools);
8543: }
8544:
8545: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
8546: if(exists($args->{'bread_crumbs_component'})){
8547: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
8548: } elsif ($args->{'crstype'} eq 'Placement') {
8549: $result .= &Apache::lonhtmlcommon::breadcrumbs('','','','','','','','','',
8550: $args->{'crstype'});
8551: } else {
8552: $result .= &Apache::lonhtmlcommon::breadcrumbs();
8553: }
8554: }
8555: return $result;
8556: }
8557:
8558: sub end_page {
8559: my ($args) = @_;
8560: $env{'internal.end_page'}++;
8561: my $result;
8562: if ($args->{'discussion'}) {
8563: my ($target,$parser);
8564: if (ref($args->{'discussion'})) {
8565: ($target,$parser) =($args->{'discussion'}{'target'},
8566: $args->{'discussion'}{'parser'});
8567: }
8568: $result .= &Apache::lonxml::xmlend($target,$parser);
8569: }
8570: if ($args->{'frameset'}) {
8571: $result .= '</frameset>';
8572: } else {
8573: $result .= &endbodytag($args);
8574: }
8575: unless ($args->{'notbody'}) {
8576: $result .= "\n</html>";
8577: }
8578:
8579: if ($args->{'js_ready'}) {
8580: $result = &js_ready($result);
8581: }
8582:
8583: if ($args->{'html_encode'}) {
8584: $result = &html_encode($result);
8585: }
8586:
8587: return $result;
8588: }
8589:
8590: sub wishlist_window {
8591: return(<<'ENDWISHLIST');
8592: <script type="text/javascript">
8593: // <![CDATA[
8594: // <!-- BEGIN LON-CAPA Internal
8595: function set_wishlistlink(title, path) {
8596: if (!title) {
8597: title = document.title;
8598: title = title.replace(/^LON-CAPA /,'');
8599: }
8600: title = encodeURIComponent(title);
8601: title = title.replace("'","\\\'");
8602: if (!path) {
8603: path = location.pathname;
8604: }
8605: path = encodeURIComponent(path);
8606: path = path.replace("'","\\\'");
8607: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
8608: 'wishlistNewLink','width=560,height=350,scrollbars=0');
8609: }
8610: // END LON-CAPA Internal -->
8611: // ]]>
8612: </script>
8613: ENDWISHLIST
8614: }
8615:
8616: sub modal_window {
8617: return(<<'ENDMODAL');
8618: <script type="text/javascript">
8619: // <![CDATA[
8620: // <!-- BEGIN LON-CAPA Internal
8621: var modalWindow = {
8622: parent:"body",
8623: windowId:null,
8624: content:null,
8625: width:null,
8626: height:null,
8627: close:function()
8628: {
8629: $(".LCmodal-window").remove();
8630: $(".LCmodal-overlay").remove();
8631: },
8632: open:function()
8633: {
8634: var modal = "";
8635: modal += "<div class=\"LCmodal-overlay\"></div>";
8636: 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;\">";
8637: modal += this.content;
8638: modal += "</div>";
8639:
8640: $(this.parent).append(modal);
8641:
8642: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
8643: $(".LCclose-window").click(function(){modalWindow.close();});
8644: $(".LCmodal-overlay").click(function(){modalWindow.close();});
8645: }
8646: };
8647: var openMyModal = function(source,width,height,scrolling,transparency,style)
8648: {
8649: source = source.replace("'","'");
8650: modalWindow.windowId = "myModal";
8651: modalWindow.width = width;
8652: modalWindow.height = height;
8653: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
8654: modalWindow.open();
8655: };
8656: // END LON-CAPA Internal -->
8657: // ]]>
8658: </script>
8659: ENDMODAL
8660: }
8661:
8662: sub modal_link {
8663: my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
8664: unless ($width) { $width=480; }
8665: unless ($height) { $height=400; }
8666: unless ($scrolling) { $scrolling='yes'; }
8667: unless ($transparency) { $transparency='true'; }
8668:
8669: my $target_attr;
8670: if (defined($target)) {
8671: $target_attr = 'target="'.$target.'"';
8672: }
8673: return <<"ENDLINK";
8674: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
8675: $linktext</a>
8676: ENDLINK
8677: }
8678:
8679: sub modal_adhoc_script {
8680: my ($funcname,$width,$height,$content)=@_;
8681: return (<<ENDADHOC);
8682: <script type="text/javascript">
8683: // <![CDATA[
8684: var $funcname = function()
8685: {
8686: modalWindow.windowId = "myModal";
8687: modalWindow.width = $width;
8688: modalWindow.height = $height;
8689: modalWindow.content = '$content';
8690: modalWindow.open();
8691: };
8692: // ]]>
8693: </script>
8694: ENDADHOC
8695: }
8696:
8697: sub modal_adhoc_inner {
8698: my ($funcname,$width,$height,$content)=@_;
8699: my $innerwidth=$width-20;
8700: $content=&js_ready(
8701: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
8702: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
8703: $content.
8704: &end_scrollbox().
8705: &end_page()
8706: );
8707: return &modal_adhoc_script($funcname,$width,$height,$content);
8708: }
8709:
8710: sub modal_adhoc_window {
8711: my ($funcname,$width,$height,$content,$linktext)=@_;
8712: return &modal_adhoc_inner($funcname,$width,$height,$content).
8713: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
8714: }
8715:
8716: sub modal_adhoc_launch {
8717: my ($funcname,$width,$height,$content)=@_;
8718: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
8719: <script type="text/javascript">
8720: // <![CDATA[
8721: $funcname();
8722: // ]]>
8723: </script>
8724: ENDLAUNCH
8725: }
8726:
8727: sub modal_adhoc_close {
8728: return (<<ENDCLOSE);
8729: <script type="text/javascript">
8730: // <![CDATA[
8731: modalWindow.close();
8732: // ]]>
8733: </script>
8734: ENDCLOSE
8735: }
8736:
8737: sub togglebox_script {
8738: return(<<ENDTOGGLE);
8739: <script type="text/javascript">
8740: // <![CDATA[
8741: function LCtoggleDisplay(id,hidetext,showtext) {
8742: link = document.getElementById(id + "link").childNodes[0];
8743: with (document.getElementById(id).style) {
8744: if (display == "none" ) {
8745: display = "inline";
8746: link.nodeValue = hidetext;
8747: } else {
8748: display = "none";
8749: link.nodeValue = showtext;
8750: }
8751: }
8752: }
8753: // ]]>
8754: </script>
8755: ENDTOGGLE
8756: }
8757:
8758: sub start_togglebox {
8759: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
8760: unless ($heading) { $heading=''; } else { $heading.=' '; }
8761: unless ($showtext) { $showtext=&mt('show'); }
8762: unless ($hidetext) { $hidetext=&mt('hide'); }
8763: unless ($headerbg) { $headerbg='#FFFFFF'; }
8764: return &start_data_table().
8765: &start_data_table_header_row().
8766: '<td bgcolor="'.$headerbg.'">'.$heading.
8767: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
8768: $showtext.'\')">'.$showtext.'</a>]</td>'.
8769: &end_data_table_header_row().
8770: '<tr id="'.$id.'" style="display:none""><td>';
8771: }
8772:
8773: sub end_togglebox {
8774: return '</td></tr>'.&end_data_table();
8775: }
8776:
8777: sub LCprogressbar_script {
8778: my ($id)=@_;
8779: return(<<ENDPROGRESS);
8780: <script type="text/javascript">
8781: // <![CDATA[
8782: \$('#progressbar$id').progressbar({
8783: value: 0,
8784: change: function(event, ui) {
8785: var newVal = \$(this).progressbar('option', 'value');
8786: \$('.pblabel', this).text(LCprogressTxt);
8787: }
8788: });
8789: // ]]>
8790: </script>
8791: ENDPROGRESS
8792: }
8793:
8794: sub LCprogressbarUpdate_script {
8795: return(<<ENDPROGRESSUPDATE);
8796: <style type="text/css">
8797: .ui-progressbar { position:relative; }
8798: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
8799: </style>
8800: <script type="text/javascript">
8801: // <![CDATA[
8802: var LCprogressTxt='---';
8803:
8804: function LCupdateProgress(percent,progresstext,id) {
8805: LCprogressTxt=progresstext;
8806: \$('#progressbar'+id).progressbar('value',percent);
8807: }
8808: // ]]>
8809: </script>
8810: ENDPROGRESSUPDATE
8811: }
8812:
8813: my $LClastpercent;
8814: my $LCidcnt;
8815: my $LCcurrentid;
8816:
8817: sub LCprogressbar {
8818: my ($r)=(@_);
8819: $LClastpercent=0;
8820: $LCidcnt++;
8821: $LCcurrentid=$$.'_'.$LCidcnt;
8822: my $starting=&mt('Starting');
8823: my $content=(<<ENDPROGBAR);
8824: <div id="progressbar$LCcurrentid">
8825: <span class="pblabel">$starting</span>
8826: </div>
8827: ENDPROGBAR
8828: &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
8829: }
8830:
8831: sub LCprogressbarUpdate {
8832: my ($r,$val,$text)=@_;
8833: unless ($val) {
8834: if ($LClastpercent) {
8835: $val=$LClastpercent;
8836: } else {
8837: $val=0;
8838: }
8839: }
8840: if ($val<0) { $val=0; }
8841: if ($val>100) { $val=0; }
8842: $LClastpercent=$val;
8843: unless ($text) { $text=$val.'%'; }
8844: $text=&js_ready($text);
8845: &r_print($r,<<ENDUPDATE);
8846: <script type="text/javascript">
8847: // <![CDATA[
8848: LCupdateProgress($val,'$text','$LCcurrentid');
8849: // ]]>
8850: </script>
8851: ENDUPDATE
8852: }
8853:
8854: sub LCprogressbarClose {
8855: my ($r)=@_;
8856: $LClastpercent=0;
8857: &r_print($r,<<ENDCLOSE);
8858: <script type="text/javascript">
8859: // <![CDATA[
8860: \$("#progressbar$LCcurrentid").hide('slow');
8861: // ]]>
8862: </script>
8863: ENDCLOSE
8864: }
8865:
8866: sub r_print {
8867: my ($r,$to_print)=@_;
8868: if ($r) {
8869: $r->print($to_print);
8870: $r->rflush();
8871: } else {
8872: print($to_print);
8873: }
8874: }
8875:
8876: sub html_encode {
8877: my ($result) = @_;
8878:
8879: $result = &HTML::Entities::encode($result,'<>&"');
8880:
8881: return $result;
8882: }
8883:
8884: sub js_ready {
8885: my ($result) = @_;
8886:
8887: $result =~ s/[\n\r]/ /xmsg;
8888: $result =~ s/\\/\\\\/xmsg;
8889: $result =~ s/'/\\'/xmsg;
8890: $result =~ s{</}{<\\/}xmsg;
8891:
8892: return $result;
8893: }
8894:
8895: sub validate_page {
8896: if ( exists($env{'internal.start_page'})
8897: && $env{'internal.start_page'} > 1) {
8898: &Apache::lonnet::logthis('start_page called multiple times '.
8899: $env{'internal.start_page'}.' '.
8900: $ENV{'request.filename'});
8901: }
8902: if ( exists($env{'internal.end_page'})
8903: && $env{'internal.end_page'} > 1) {
8904: &Apache::lonnet::logthis('end_page called multiple times '.
8905: $env{'internal.end_page'}.' '.
8906: $env{'request.filename'});
8907: }
8908: if ( exists($env{'internal.start_page'})
8909: && ! exists($env{'internal.end_page'})) {
8910: &Apache::lonnet::logthis('start_page called without end_page '.
8911: $env{'request.filename'});
8912: }
8913: if ( ! exists($env{'internal.start_page'})
8914: && exists($env{'internal.end_page'})) {
8915: &Apache::lonnet::logthis('end_page called without start_page'.
8916: $env{'request.filename'});
8917: }
8918: }
8919:
8920:
8921: sub start_scrollbox {
8922: my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
8923: unless ($outerwidth) { $outerwidth='520px'; }
8924: unless ($width) { $width='500px'; }
8925: unless ($height) { $height='200px'; }
8926: my ($table_id,$div_id,$tdcol);
8927: if ($id ne '') {
8928: $table_id = ' id="table_'.$id.'"';
8929: $div_id = ' id="div_'.$id.'"';
8930: }
8931: if ($bgcolor ne '') {
8932: $tdcol = "background-color: $bgcolor;";
8933: }
8934: my $nicescroll_js;
8935: if ($env{'browser.mobile'}) {
8936: $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
8937: }
8938: return <<"END";
8939: $nicescroll_js
8940:
8941: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
8942: <div style="overflow:auto; width:$width; height:$height;"$div_id>
8943: END
8944: }
8945:
8946: sub end_scrollbox {
8947: return '</div></td></tr></table>';
8948: }
8949:
8950: sub nicescroll_javascript {
8951: my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
8952: my %options;
8953: if (ref($cursor) eq 'HASH') {
8954: %options = %{$cursor};
8955: }
8956: unless ($options{'railalign'} =~ /^left|right$/) {
8957: $options{'railalign'} = 'left';
8958: }
8959: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
8960: my $function = &get_users_function();
8961: $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
8962: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
8963: $options{'cursorcolor'} = '#00F';
8964: }
8965: }
8966: if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
8967: unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
8968: $options{'cursoropacity'}='1.0';
8969: }
8970: } else {
8971: $options{'cursoropacity'}='1.0';
8972: }
8973: if ($options{'cursorfixedheight'} eq 'none') {
8974: delete($options{'cursorfixedheight'});
8975: } else {
8976: unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
8977: }
8978: unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
8979: delete($options{'railoffset'});
8980: }
8981: my @niceoptions;
8982: while (my($key,$value) = each(%options)) {
8983: if ($value =~ /^\{.+\}$/) {
8984: push(@niceoptions,$key.':'.$value);
8985: } else {
8986: push(@niceoptions,$key.':"'.$value.'"');
8987: }
8988: }
8989: my $nicescroll_js = '
8990: $(document).ready(
8991: function() {
8992: $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
8993: }
8994: );
8995: ';
8996: if ($framecheck) {
8997: $nicescroll_js .= '
8998: function expand_div(caller) {
8999: if (top === self) {
9000: document.getElementById("'.$id.'").style.width = "auto";
9001: document.getElementById("'.$id.'").style.height = "auto";
9002: } else {
9003: try {
9004: if (parent.frames) {
9005: if (parent.frames.length > 1) {
9006: var framesrc = parent.frames[1].location.href;
9007: var currsrc = framesrc.replace(/\#.*$/,"");
9008: if ((caller == "search") || (currsrc == "'.$location.'")) {
9009: document.getElementById("'.$id.'").style.width = "auto";
9010: document.getElementById("'.$id.'").style.height = "auto";
9011: }
9012: }
9013: }
9014: } catch (e) {
9015: return;
9016: }
9017: }
9018: return;
9019: }
9020: ';
9021: }
9022: if ($needjsready) {
9023: $nicescroll_js = '
9024: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
9025: } else {
9026: $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
9027: }
9028: return $nicescroll_js;
9029: }
9030:
9031: sub simple_error_page {
9032: my ($r,$title,$msg,$args) = @_;
9033: if (ref($args) eq 'HASH') {
9034: if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
9035: } else {
9036: $msg = &mt($msg);
9037: }
9038:
9039: my $page =
9040: &Apache::loncommon::start_page($title).
9041: '<p class="LC_error">'.$msg.'</p>'.
9042: &Apache::loncommon::end_page();
9043: if (ref($r)) {
9044: $r->print($page);
9045: return;
9046: }
9047: return $page;
9048: }
9049:
9050: {
9051: my @row_count;
9052:
9053: sub start_data_table_count {
9054: unshift(@row_count, 0);
9055: return;
9056: }
9057:
9058: sub end_data_table_count {
9059: shift(@row_count);
9060: return;
9061: }
9062:
9063: sub start_data_table {
9064: my ($add_class,$id) = @_;
9065: my $css_class = (join(' ','LC_data_table',$add_class));
9066: my $table_id;
9067: if (defined($id)) {
9068: $table_id = ' id="'.$id.'"';
9069: }
9070: &start_data_table_count();
9071: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
9072: }
9073:
9074: sub end_data_table {
9075: &end_data_table_count();
9076: return '</table>'."\n";;
9077: }
9078:
9079: sub start_data_table_row {
9080: my ($add_class, $id) = @_;
9081: $row_count[0]++;
9082: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
9083: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
9084: $id = (' id="'.$id.'"') unless ($id eq '');
9085: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
9086: }
9087:
9088: sub continue_data_table_row {
9089: my ($add_class, $id) = @_;
9090: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
9091: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
9092: $id = (' id="'.$id.'"') unless ($id eq '');
9093: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
9094: }
9095:
9096: sub end_data_table_row {
9097: return '</tr>'."\n";;
9098: }
9099:
9100: sub start_data_table_empty_row {
9101: # $row_count[0]++;
9102: return '<tr class="LC_empty_row" >'."\n";;
9103: }
9104:
9105: sub end_data_table_empty_row {
9106: return '</tr>'."\n";;
9107: }
9108:
9109: sub start_data_table_header_row {
9110: return '<tr class="LC_header_row">'."\n";;
9111: }
9112:
9113: sub end_data_table_header_row {
9114: return '</tr>'."\n";;
9115: }
9116:
9117: sub data_table_caption {
9118: my $caption = shift;
9119: return "<caption class=\"LC_caption\">$caption</caption>";
9120: }
9121: }
9122:
9123: =pod
9124:
9125: =item * &inhibit_menu_check($arg)
9126:
9127: Checks for a inhibitmenu state and generates output to preserve it
9128:
9129: Inputs: $arg - can be any of
9130: - undef - in which case the return value is a string
9131: to add into arguments list of a uri
9132: - 'input' - in which case the return value is a HTML
9133: <form> <input> field of type hidden to
9134: preserve the value
9135: - a url - in which case the return value is the url with
9136: the neccesary cgi args added to preserve the
9137: inhibitmenu state
9138: - a ref to a url - no return value, but the string is
9139: updated to include the neccessary cgi
9140: args to preserve the inhibitmenu state
9141:
9142: =cut
9143:
9144: sub inhibit_menu_check {
9145: my ($arg) = @_;
9146: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
9147: if ($arg eq 'input') {
9148: if ($env{'form.inhibitmenu'}) {
9149: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
9150: } else {
9151: return
9152: }
9153: }
9154: if ($env{'form.inhibitmenu'}) {
9155: if (ref($arg)) {
9156: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
9157: } elsif ($arg eq '') {
9158: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
9159: } else {
9160: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
9161: }
9162: }
9163: if (!ref($arg)) {
9164: return $arg;
9165: }
9166: }
9167:
9168: ###############################################
9169:
9170: =pod
9171:
9172: =back
9173:
9174: =head1 User Information Routines
9175:
9176: =over 4
9177:
9178: =item * &get_users_function()
9179:
9180: Used by &bodytag to determine the current users primary role.
9181: Returns either 'student','coordinator','admin', or 'author'.
9182:
9183: =cut
9184:
9185: ###############################################
9186: sub get_users_function {
9187: my $function = 'norole';
9188: if ($env{'request.role'}=~/^(st)/) {
9189: $function='student';
9190: }
9191: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
9192: $function='coordinator';
9193: }
9194: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
9195: $function='admin';
9196: }
9197: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
9198: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
9199: $function='author';
9200: }
9201: return $function;
9202: }
9203:
9204: ###############################################
9205:
9206: =pod
9207:
9208: =item * &show_course()
9209:
9210: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
9211: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
9212:
9213: Inputs:
9214: None
9215:
9216: Outputs:
9217: Scalar: 1 if 'Course' to be used, 0 otherwise.
9218:
9219: =cut
9220:
9221: ###############################################
9222: sub show_course {
9223: my $course = !$env{'user.adv'};
9224: if (!$env{'user.adv'}) {
9225: foreach my $env (keys(%env)) {
9226: next if ($env !~ m/^user\.priv\./);
9227: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
9228: $course = 0;
9229: last;
9230: }
9231: }
9232: }
9233: return $course;
9234: }
9235:
9236: ###############################################
9237:
9238: =pod
9239:
9240: =item * &check_user_status()
9241:
9242: Determines current status of supplied role for a
9243: specific user. Roles can be active, previous or future.
9244:
9245: Inputs:
9246: user's domain, user's username, course's domain,
9247: course's number, optional section ID.
9248:
9249: Outputs:
9250: role status: active, previous or future.
9251:
9252: =cut
9253:
9254: sub check_user_status {
9255: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
9256: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
9257: my @uroles = keys(%userinfo);
9258: my $srchstr;
9259: my $active_chk = 'none';
9260: my $now = time;
9261: if (@uroles > 0) {
9262: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
9263: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
9264: } else {
9265: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
9266: }
9267: if (grep/^\Q$srchstr\E$/,@uroles) {
9268: my $role_end = 0;
9269: my $role_start = 0;
9270: $active_chk = 'active';
9271: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
9272: $role_end = $1;
9273: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
9274: $role_start = $1;
9275: }
9276: }
9277: if ($role_start > 0) {
9278: if ($now < $role_start) {
9279: $active_chk = 'future';
9280: }
9281: }
9282: if ($role_end > 0) {
9283: if ($now > $role_end) {
9284: $active_chk = 'previous';
9285: }
9286: }
9287: }
9288: }
9289: return $active_chk;
9290: }
9291:
9292: ###############################################
9293:
9294: =pod
9295:
9296: =item * &get_sections()
9297:
9298: Determines all the sections for a course including
9299: sections with students and sections containing other roles.
9300: Incoming parameters:
9301:
9302: 1. domain
9303: 2. course number
9304: 3. reference to array containing roles for which sections should
9305: be gathered (optional).
9306: 4. reference to array containing status types for which sections
9307: should be gathered (optional).
9308:
9309: If the third argument is undefined, sections are gathered for any role.
9310: If the fourth argument is undefined, sections are gathered for any status.
9311: Permissible values are 'active' or 'future' or 'previous'.
9312:
9313: Returns section hash (keys are section IDs, values are
9314: number of users in each section), subject to the
9315: optional roles filter, optional status filter
9316:
9317: =cut
9318:
9319: ###############################################
9320: sub get_sections {
9321: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
9322: if (!defined($cdom) || !defined($cnum)) {
9323: my $cid = $env{'request.course.id'};
9324:
9325: return if (!defined($cid));
9326:
9327: $cdom = $env{'course.'.$cid.'.domain'};
9328: $cnum = $env{'course.'.$cid.'.num'};
9329: }
9330:
9331: my %sectioncount;
9332: my $now = time;
9333:
9334: my $check_students = 1;
9335: my $only_students = 0;
9336: if (ref($possible_roles) eq 'ARRAY') {
9337: if (grep(/^st$/,@{$possible_roles})) {
9338: if (@{$possible_roles} == 1) {
9339: $only_students = 1;
9340: }
9341: } else {
9342: $check_students = 0;
9343: }
9344: }
9345:
9346: if ($check_students) {
9347: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
9348: my $sec_index = &Apache::loncoursedata::CL_SECTION();
9349: my $status_index = &Apache::loncoursedata::CL_STATUS();
9350: my $start_index = &Apache::loncoursedata::CL_START();
9351: my $end_index = &Apache::loncoursedata::CL_END();
9352: my $status;
9353: while (my ($student,$data) = each(%$classlist)) {
9354: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
9355: $data->[$status_index],
9356: $data->[$start_index],
9357: $data->[$end_index]);
9358: if ($stu_status eq 'Active') {
9359: $status = 'active';
9360: } elsif ($end < $now) {
9361: $status = 'previous';
9362: } elsif ($start > $now) {
9363: $status = 'future';
9364: }
9365: if ($section ne '-1' && $section !~ /^\s*$/) {
9366: if ((!defined($possible_status)) || (($status ne '') &&
9367: (grep/^\Q$status\E$/,@{$possible_status}))) {
9368: $sectioncount{$section}++;
9369: }
9370: }
9371: }
9372: }
9373: if ($only_students) {
9374: return %sectioncount;
9375: }
9376: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9377: foreach my $user (sort(keys(%courseroles))) {
9378: if ($user !~ /^(\w{2})/) { next; }
9379: my ($role) = ($user =~ /^(\w{2})/);
9380: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
9381: my ($section,$status);
9382: if ($role eq 'cr' &&
9383: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
9384: $section=$1;
9385: }
9386: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
9387: if (!defined($section) || $section eq '-1') { next; }
9388: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
9389: if ($end == -1 && $start == -1) {
9390: next; #deleted role
9391: }
9392: if (!defined($possible_status)) {
9393: $sectioncount{$section}++;
9394: } else {
9395: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
9396: $status = 'active';
9397: } elsif ($end < $now) {
9398: $status = 'future';
9399: } elsif ($start > $now) {
9400: $status = 'previous';
9401: }
9402: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
9403: $sectioncount{$section}++;
9404: }
9405: }
9406: }
9407: return %sectioncount;
9408: }
9409:
9410: ###############################################
9411:
9412: =pod
9413:
9414: =item * &get_course_users()
9415:
9416: Retrieves usernames:domains for users in the specified course
9417: with specific role(s), and access status.
9418:
9419: Incoming parameters:
9420: 1. course domain
9421: 2. course number
9422: 3. access status: users must have - either active,
9423: previous, future, or all.
9424: 4. reference to array of permissible roles
9425: 5. reference to array of section restrictions (optional)
9426: 6. reference to results object (hash of hashes).
9427: 7. reference to optional userdata hash
9428: 8. reference to optional statushash
9429: 9. flag if privileged users (except those set to unhide in
9430: course settings) should be excluded
9431: Keys of top level results hash are roles.
9432: Keys of inner hashes are username:domain, with
9433: values set to access type.
9434: Optional userdata hash returns an array with arguments in the
9435: same order as loncoursedata::get_classlist() for student data.
9436:
9437: Optional statushash returns
9438:
9439: Entries for end, start, section and status are blank because
9440: of the possibility of multiple values for non-student roles.
9441:
9442: =cut
9443:
9444: ###############################################
9445:
9446: sub get_course_users {
9447: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
9448: my %idx = ();
9449: my %seclists;
9450:
9451: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
9452: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
9453: $idx{end} = &Apache::loncoursedata::CL_END();
9454: $idx{start} = &Apache::loncoursedata::CL_START();
9455: $idx{id} = &Apache::loncoursedata::CL_ID();
9456: $idx{section} = &Apache::loncoursedata::CL_SECTION();
9457: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
9458: $idx{status} = &Apache::loncoursedata::CL_STATUS();
9459:
9460: if (grep(/^st$/,@{$roles})) {
9461: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
9462: my $now = time;
9463: foreach my $student (keys(%{$classlist})) {
9464: my $match = 0;
9465: my $secmatch = 0;
9466: my $section = $$classlist{$student}[$idx{section}];
9467: my $status = $$classlist{$student}[$idx{status}];
9468: if ($section eq '') {
9469: $section = 'none';
9470: }
9471: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
9472: if (grep(/^all$/,@{$sections})) {
9473: $secmatch = 1;
9474: } elsif ($$classlist{$student}[$idx{section}] eq '') {
9475: if (grep(/^none$/,@{$sections})) {
9476: $secmatch = 1;
9477: }
9478: } else {
9479: if (grep(/^\Q$section\E$/,@{$sections})) {
9480: $secmatch = 1;
9481: }
9482: }
9483: if (!$secmatch) {
9484: next;
9485: }
9486: }
9487: if (defined($$types{'active'})) {
9488: if ($$classlist{$student}[$idx{status}] eq 'Active') {
9489: push(@{$$users{st}{$student}},'active');
9490: $match = 1;
9491: }
9492: }
9493: if (defined($$types{'previous'})) {
9494: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
9495: push(@{$$users{st}{$student}},'previous');
9496: $match = 1;
9497: }
9498: }
9499: if (defined($$types{'future'})) {
9500: if ($$classlist{$student}[$idx{status}] eq 'Future') {
9501: push(@{$$users{st}{$student}},'future');
9502: $match = 1;
9503: }
9504: }
9505: if ($match) {
9506: push(@{$seclists{$student}},$section);
9507: if (ref($userdata) eq 'HASH') {
9508: $$userdata{$student} = $$classlist{$student};
9509: }
9510: if (ref($statushash) eq 'HASH') {
9511: $statushash->{$student}{'st'}{$section} = $status;
9512: }
9513: }
9514: }
9515: }
9516: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
9517: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9518: my $now = time;
9519: my %displaystatus = ( previous => 'Expired',
9520: active => 'Active',
9521: future => 'Future',
9522: );
9523: my (%nothide,@possdoms);
9524: if ($hidepriv) {
9525: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
9526: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
9527: if ($user !~ /:/) {
9528: $nothide{join(':',split(/[\@]/,$user))}=1;
9529: } else {
9530: $nothide{$user} = 1;
9531: }
9532: }
9533: my @possdoms = ($cdom);
9534: if ($coursehash{'checkforpriv'}) {
9535: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
9536: }
9537: }
9538: foreach my $person (sort(keys(%coursepersonnel))) {
9539: my $match = 0;
9540: my $secmatch = 0;
9541: my $status;
9542: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
9543: $user =~ s/:$//;
9544: my ($end,$start) = split(/:/,$coursepersonnel{$person});
9545: if ($end == -1 || $start == -1) {
9546: next;
9547: }
9548: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
9549: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
9550: my ($uname,$udom) = split(/:/,$user);
9551: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
9552: if (grep(/^all$/,@{$sections})) {
9553: $secmatch = 1;
9554: } elsif ($usec eq '') {
9555: if (grep(/^none$/,@{$sections})) {
9556: $secmatch = 1;
9557: }
9558: } else {
9559: if (grep(/^\Q$usec\E$/,@{$sections})) {
9560: $secmatch = 1;
9561: }
9562: }
9563: if (!$secmatch) {
9564: next;
9565: }
9566: }
9567: if ($usec eq '') {
9568: $usec = 'none';
9569: }
9570: if ($uname ne '' && $udom ne '') {
9571: if ($hidepriv) {
9572: if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
9573: (!$nothide{$uname.':'.$udom})) {
9574: next;
9575: }
9576: }
9577: if ($end > 0 && $end < $now) {
9578: $status = 'previous';
9579: } elsif ($start > $now) {
9580: $status = 'future';
9581: } else {
9582: $status = 'active';
9583: }
9584: foreach my $type (keys(%{$types})) {
9585: if ($status eq $type) {
9586: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
9587: push(@{$$users{$role}{$user}},$type);
9588: }
9589: $match = 1;
9590: }
9591: }
9592: if (($match) && (ref($userdata) eq 'HASH')) {
9593: if (!exists($$userdata{$uname.':'.$udom})) {
9594: &get_user_info($udom,$uname,\%idx,$userdata);
9595: }
9596: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
9597: push(@{$seclists{$uname.':'.$udom}},$usec);
9598: }
9599: if (ref($statushash) eq 'HASH') {
9600: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
9601: }
9602: }
9603: }
9604: }
9605: }
9606: if (grep(/^ow$/,@{$roles})) {
9607: if ((defined($cdom)) && (defined($cnum))) {
9608: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
9609: if ( defined($csettings{'internal.courseowner'}) ) {
9610: my $owner = $csettings{'internal.courseowner'};
9611: next if ($owner eq '');
9612: my ($ownername,$ownerdom);
9613: if ($owner =~ /^([^:]+):([^:]+)$/) {
9614: $ownername = $1;
9615: $ownerdom = $2;
9616: } else {
9617: $ownername = $owner;
9618: $ownerdom = $cdom;
9619: $owner = $ownername.':'.$ownerdom;
9620: }
9621: @{$$users{'ow'}{$owner}} = 'any';
9622: if (defined($userdata) &&
9623: !exists($$userdata{$owner})) {
9624: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
9625: if (!grep(/^none$/,@{$seclists{$owner}})) {
9626: push(@{$seclists{$owner}},'none');
9627: }
9628: if (ref($statushash) eq 'HASH') {
9629: $statushash->{$owner}{'ow'}{'none'} = 'Any';
9630: }
9631: }
9632: }
9633: }
9634: }
9635: foreach my $user (keys(%seclists)) {
9636: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
9637: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
9638: }
9639: }
9640: return;
9641: }
9642:
9643: sub get_user_info {
9644: my ($udom,$uname,$idx,$userdata) = @_;
9645: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
9646: &plainname($uname,$udom,'lastname');
9647: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
9648: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
9649: my %idhash = &Apache::lonnet::idrget($udom,($uname));
9650: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
9651: return;
9652: }
9653:
9654: ###############################################
9655:
9656: =pod
9657:
9658: =item * &get_user_quota()
9659:
9660: Retrieves quota assigned for storage of user files.
9661: Default is to report quota for portfolio files.
9662:
9663: Incoming parameters:
9664: 1. user's username
9665: 2. user's domain
9666: 3. quota name - portfolio, author, or course
9667: (if no quota name provided, defaults to portfolio).
9668: 4. crstype - official, unofficial, textbook, placement or community,
9669: if quota name is course
9670:
9671: Returns:
9672: 1. Disk quota (in MB) assigned to student.
9673: 2. (Optional) Type of setting: custom or default
9674: (individually assigned or default for user's
9675: institutional status).
9676: 3. (Optional) - User's institutional status (e.g., faculty, staff
9677: or student - types as defined in localenroll::inst_usertypes
9678: for user's domain, which determines default quota for user.
9679: 4. (Optional) - Default quota which would apply to the user.
9680:
9681: If a value has been stored in the user's environment,
9682: it will return that, otherwise it returns the maximal default
9683: defined for the user's institutional status(es) in the domain.
9684:
9685: =cut
9686:
9687: ###############################################
9688:
9689:
9690: sub get_user_quota {
9691: my ($uname,$udom,$quotaname,$crstype) = @_;
9692: my ($quota,$quotatype,$settingstatus,$defquota);
9693: if (!defined($udom)) {
9694: $udom = $env{'user.domain'};
9695: }
9696: if (!defined($uname)) {
9697: $uname = $env{'user.name'};
9698: }
9699: if (($udom eq '' || $uname eq '') ||
9700: ($udom eq 'public') && ($uname eq 'public')) {
9701: $quota = 0;
9702: $quotatype = 'default';
9703: $defquota = 0;
9704: } else {
9705: my $inststatus;
9706: if ($quotaname eq 'course') {
9707: if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
9708: ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
9709: $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
9710: } else {
9711: my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
9712: $quota = $cenv{'internal.uploadquota'};
9713: }
9714: } else {
9715: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
9716: if ($quotaname eq 'author') {
9717: $quota = $env{'environment.authorquota'};
9718: } else {
9719: $quota = $env{'environment.portfolioquota'};
9720: }
9721: $inststatus = $env{'environment.inststatus'};
9722: } else {
9723: my %userenv =
9724: &Apache::lonnet::get('environment',['portfolioquota',
9725: 'authorquota','inststatus'],$udom,$uname);
9726: my ($tmp) = keys(%userenv);
9727: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9728: if ($quotaname eq 'author') {
9729: $quota = $userenv{'authorquota'};
9730: } else {
9731: $quota = $userenv{'portfolioquota'};
9732: }
9733: $inststatus = $userenv{'inststatus'};
9734: } else {
9735: undef(%userenv);
9736: }
9737: }
9738: }
9739: if ($quota eq '' || wantarray) {
9740: if ($quotaname eq 'course') {
9741: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
9742: if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
9743: ($crstype eq 'community') || ($crstype eq 'textbook') ||
9744: ($crstype eq 'placement')) {
9745: $defquota = $domdefs{$crstype.'quota'};
9746: }
9747: if ($defquota eq '') {
9748: $defquota = 500;
9749: }
9750: } else {
9751: ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
9752: }
9753: if ($quota eq '') {
9754: $quota = $defquota;
9755: $quotatype = 'default';
9756: } else {
9757: $quotatype = 'custom';
9758: }
9759: }
9760: }
9761: if (wantarray) {
9762: return ($quota,$quotatype,$settingstatus,$defquota);
9763: } else {
9764: return $quota;
9765: }
9766: }
9767:
9768: ###############################################
9769:
9770: =pod
9771:
9772: =item * &default_quota()
9773:
9774: Retrieves default quota assigned for storage of user portfolio files,
9775: given an (optional) user's institutional status.
9776:
9777: Incoming parameters:
9778:
9779: 1. domain
9780: 2. (Optional) institutional status(es). This is a : separated list of
9781: status types (e.g., faculty, staff, student etc.)
9782: which apply to the user for whom the default is being retrieved.
9783: If the institutional status string in undefined, the domain
9784: default quota will be returned.
9785: 3. quota name - portfolio, author, or course
9786: (if no quota name provided, defaults to portfolio).
9787:
9788: Returns:
9789:
9790: 1. Default disk quota (in MB) for user portfolios in the domain.
9791: 2. (Optional) institutional type which determined the value of the
9792: default quota.
9793:
9794: If a value has been stored in the domain's configuration db,
9795: it will return that, otherwise it returns 20 (for backwards
9796: compatibility with domains which have not set up a configuration
9797: db file; the original statically defined portfolio quota was 20 MB).
9798:
9799: If the user's status includes multiple types (e.g., staff and student),
9800: the largest default quota which applies to the user determines the
9801: default quota returned.
9802:
9803: =cut
9804:
9805: ###############################################
9806:
9807:
9808: sub default_quota {
9809: my ($udom,$inststatus,$quotaname) = @_;
9810: my ($defquota,$settingstatus);
9811: my %quotahash = &Apache::lonnet::get_dom('configuration',
9812: ['quotas'],$udom);
9813: my $key = 'defaultquota';
9814: if ($quotaname eq 'author') {
9815: $key = 'authorquota';
9816: }
9817: if (ref($quotahash{'quotas'}) eq 'HASH') {
9818: if ($inststatus ne '') {
9819: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
9820: foreach my $item (@statuses) {
9821: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
9822: if ($quotahash{'quotas'}{$key}{$item} ne '') {
9823: if ($defquota eq '') {
9824: $defquota = $quotahash{'quotas'}{$key}{$item};
9825: $settingstatus = $item;
9826: } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
9827: $defquota = $quotahash{'quotas'}{$key}{$item};
9828: $settingstatus = $item;
9829: }
9830: }
9831: } elsif ($key eq 'defaultquota') {
9832: if ($quotahash{'quotas'}{$item} ne '') {
9833: if ($defquota eq '') {
9834: $defquota = $quotahash{'quotas'}{$item};
9835: $settingstatus = $item;
9836: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
9837: $defquota = $quotahash{'quotas'}{$item};
9838: $settingstatus = $item;
9839: }
9840: }
9841: }
9842: }
9843: }
9844: if ($defquota eq '') {
9845: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
9846: $defquota = $quotahash{'quotas'}{$key}{'default'};
9847: } elsif ($key eq 'defaultquota') {
9848: $defquota = $quotahash{'quotas'}{'default'};
9849: }
9850: $settingstatus = 'default';
9851: if ($defquota eq '') {
9852: if ($quotaname eq 'author') {
9853: $defquota = 500;
9854: }
9855: }
9856: }
9857: } else {
9858: $settingstatus = 'default';
9859: if ($quotaname eq 'author') {
9860: $defquota = 500;
9861: } else {
9862: $defquota = 20;
9863: }
9864: }
9865: if (wantarray) {
9866: return ($defquota,$settingstatus);
9867: } else {
9868: return $defquota;
9869: }
9870: }
9871:
9872: ###############################################
9873:
9874: =pod
9875:
9876: =item * &excess_filesize_warning()
9877:
9878: Returns warning message if upload of file to authoring space, or copying
9879: of existing file within authoring space will cause quota for the authoring
9880: space to be exceeded.
9881:
9882: Same, if upload of a file directly to a course/community via Course Editor
9883: will cause quota for uploaded content for the course to be exceeded.
9884:
9885: Inputs: 7
9886: 1. username or coursenum
9887: 2. domain
9888: 3. context ('author' or 'course')
9889: 4. filename of file for which action is being requested
9890: 5. filesize (kB) of file
9891: 6. action being taken: copy or upload.
9892: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
9893:
9894: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
9895: otherwise return null.
9896:
9897: =back
9898:
9899: =cut
9900:
9901: sub excess_filesize_warning {
9902: my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
9903: my $current_disk_usage = 0;
9904: my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
9905: if ($context eq 'author') {
9906: my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
9907: $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
9908: } else {
9909: foreach my $subdir ('docs','supplemental') {
9910: $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
9911: }
9912: }
9913: $disk_quota = int($disk_quota * 1000);
9914: if (($current_disk_usage + $filesize) > $disk_quota) {
9915: return '<p class="LC_warning">'.
9916: &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
9917: '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
9918: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
9919: $disk_quota,$current_disk_usage).
9920: '</p>';
9921: }
9922: return;
9923: }
9924:
9925: ###############################################
9926:
9927:
9928:
9929:
9930: sub get_secgrprole_info {
9931: my ($cdom,$cnum,$needroles,$type) = @_;
9932: my %sections_count = &get_sections($cdom,$cnum);
9933: my @sections = (sort {$a <=> $b} keys(%sections_count));
9934: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
9935: my @groups = sort(keys(%curr_groups));
9936: my $allroles = [];
9937: my $rolehash;
9938: my $accesshash = {
9939: active => 'Currently has access',
9940: future => 'Will have future access',
9941: previous => 'Previously had access',
9942: };
9943: if ($needroles) {
9944: $rolehash = {'all' => 'all'};
9945: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9946: if (&Apache::lonnet::error(%user_roles)) {
9947: undef(%user_roles);
9948: }
9949: foreach my $item (keys(%user_roles)) {
9950: my ($role)=split(/\:/,$item,2);
9951: if ($role eq 'cr') { next; }
9952: if ($role =~ /^cr/) {
9953: $$rolehash{$role} = (split('/',$role))[3];
9954: } else {
9955: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
9956: }
9957: }
9958: foreach my $key (sort(keys(%{$rolehash}))) {
9959: push(@{$allroles},$key);
9960: }
9961: push (@{$allroles},'st');
9962: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
9963: }
9964: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
9965: }
9966:
9967: sub user_picker {
9968: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom) = @_;
9969: my $currdom = $dom;
9970: my @alldoms = &Apache::lonnet::all_domains();
9971: if (@alldoms == 1) {
9972: my %domsrch = &Apache::lonnet::get_dom('configuration',
9973: ['directorysrch'],$alldoms[0]);
9974: my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
9975: my $showdom = $domdesc;
9976: if ($showdom eq '') {
9977: $showdom = $dom;
9978: }
9979: if (ref($domsrch{'directorysrch'}) eq 'HASH') {
9980: if ((!$domsrch{'directorysrch'}{'available'}) &&
9981: ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
9982: return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
9983: }
9984: }
9985: }
9986: my %curr_selected = (
9987: srchin => 'dom',
9988: srchby => 'lastname',
9989: );
9990: my $srchterm;
9991: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
9992: if ($srch->{'srchby'} ne '') {
9993: $curr_selected{'srchby'} = $srch->{'srchby'};
9994: }
9995: if ($srch->{'srchin'} ne '') {
9996: $curr_selected{'srchin'} = $srch->{'srchin'};
9997: }
9998: if ($srch->{'srchtype'} ne '') {
9999: $curr_selected{'srchtype'} = $srch->{'srchtype'};
10000: }
10001: if ($srch->{'srchdomain'} ne '') {
10002: $currdom = $srch->{'srchdomain'};
10003: }
10004: $srchterm = $srch->{'srchterm'};
10005: }
10006: my %html_lt=&Apache::lonlocal::texthash(
10007: 'usr' => 'Search criteria',
10008: 'doma' => 'Domain/institution to search',
10009: 'uname' => 'username',
10010: 'lastname' => 'last name',
10011: 'lastfirst' => 'last name, first name',
10012: 'crs' => 'in this course',
10013: 'dom' => 'in selected LON-CAPA domain',
10014: 'alc' => 'all LON-CAPA',
10015: 'instd' => 'in institutional directory for selected domain',
10016: 'exact' => 'is',
10017: 'contains' => 'contains',
10018: 'begins' => 'begins with',
10019: );
10020: my %js_lt=&Apache::lonlocal::texthash(
10021: 'youm' => "You must include some text to search for.",
10022: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
10023: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
10024: 'yomc' => "You must choose a domain when using an institutional directory search.",
10025: 'ymcd' => "You must choose a domain when using a domain search.",
10026: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
10027: 'whse' => "When searching by last,first you must include at least one character in the first name.",
10028: 'thfo' => "The following need to be corrected before the search can be run:",
10029: );
10030: &html_escape(\%html_lt);
10031: &js_escape(\%js_lt);
10032: my $domform;
10033: if ($fixeddom) {
10034: $domform = &select_dom_form($currdom,'srchdomain',1,1,undef,[$currdom]);
10035: } else {
10036: $domform = &select_dom_form($currdom,'srchdomain',1,1);
10037: }
10038: my $srchinsel = ' <select name="srchin">';
10039:
10040: my @srchins = ('crs','dom','alc','instd');
10041:
10042: foreach my $option (@srchins) {
10043: # FIXME 'alc' option unavailable until
10044: # loncreateuser::print_user_query_page()
10045: # has been completed.
10046: next if ($option eq 'alc');
10047: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
10048: next if ($option eq 'crs' && !$env{'request.course.id'});
10049: if ($curr_selected{'srchin'} eq $option) {
10050: $srchinsel .= '
10051: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10052: } else {
10053: $srchinsel .= '
10054: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10055: }
10056: }
10057: $srchinsel .= "\n </select>\n";
10058:
10059: my $srchbysel = ' <select name="srchby">';
10060: foreach my $option ('lastname','lastfirst','uname') {
10061: if ($curr_selected{'srchby'} eq $option) {
10062: $srchbysel .= '
10063: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10064: } else {
10065: $srchbysel .= '
10066: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10067: }
10068: }
10069: $srchbysel .= "\n </select>\n";
10070:
10071: my $srchtypesel = ' <select name="srchtype">';
10072: foreach my $option ('begins','contains','exact') {
10073: if ($curr_selected{'srchtype'} eq $option) {
10074: $srchtypesel .= '
10075: <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10076: } else {
10077: $srchtypesel .= '
10078: <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10079: }
10080: }
10081: $srchtypesel .= "\n </select>\n";
10082:
10083: my ($newuserscript,$new_user_create);
10084: my $context_dom = $env{'request.role.domain'};
10085: if ($context eq 'requestcrs') {
10086: if ($env{'form.coursedom'} ne '') {
10087: $context_dom = $env{'form.coursedom'};
10088: }
10089: }
10090: if ($forcenewuser) {
10091: if (ref($srch) eq 'HASH') {
10092: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
10093: if ($cancreate) {
10094: $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>';
10095: } else {
10096: my $helplink = 'javascript:helpMenu('."'display'".')';
10097: my %usertypetext = (
10098: official => 'institutional',
10099: unofficial => 'non-institutional',
10100: );
10101: $new_user_create = '<p class="LC_warning">'
10102: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
10103: .' '
10104: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
10105: ,'<a href="'.$helplink.'">','</a>')
10106: .'</p><br />';
10107: }
10108: }
10109: }
10110:
10111: $newuserscript = <<"ENDSCRIPT";
10112:
10113: function setSearch(createnew,callingForm) {
10114: if (createnew == 1) {
10115: for (var i=0; i<callingForm.srchby.length; i++) {
10116: if (callingForm.srchby.options[i].value == 'uname') {
10117: callingForm.srchby.selectedIndex = i;
10118: }
10119: }
10120: for (var i=0; i<callingForm.srchin.length; i++) {
10121: if ( callingForm.srchin.options[i].value == 'dom') {
10122: callingForm.srchin.selectedIndex = i;
10123: }
10124: }
10125: for (var i=0; i<callingForm.srchtype.length; i++) {
10126: if (callingForm.srchtype.options[i].value == 'exact') {
10127: callingForm.srchtype.selectedIndex = i;
10128: }
10129: }
10130: for (var i=0; i<callingForm.srchdomain.length; i++) {
10131: if (callingForm.srchdomain.options[i].value == '$context_dom') {
10132: callingForm.srchdomain.selectedIndex = i;
10133: }
10134: }
10135: }
10136: }
10137: ENDSCRIPT
10138:
10139: }
10140:
10141: my $output = <<"END_BLOCK";
10142: <script type="text/javascript">
10143: // <![CDATA[
10144: function validateEntry(callingForm) {
10145:
10146: var checkok = 1;
10147: var srchin;
10148: for (var i=0; i<callingForm.srchin.length; i++) {
10149: if ( callingForm.srchin[i].checked ) {
10150: srchin = callingForm.srchin[i].value;
10151: }
10152: }
10153:
10154: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10155: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10156: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10157: var srchterm = callingForm.srchterm.value;
10158: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10159: var msg = "";
10160:
10161: if (srchterm == "") {
10162: checkok = 0;
10163: msg += "$js_lt{'youm'}\\n";
10164: }
10165:
10166: if (srchtype== 'begins') {
10167: if (srchterm.length < 2) {
10168: checkok = 0;
10169: msg += "$js_lt{'thte'}\\n";
10170: }
10171: }
10172:
10173: if (srchtype== 'contains') {
10174: if (srchterm.length < 3) {
10175: checkok = 0;
10176: msg += "$js_lt{'thet'}\\n";
10177: }
10178: }
10179: if (srchin == 'instd') {
10180: if (srchdomain == '') {
10181: checkok = 0;
10182: msg += "$js_lt{'yomc'}\\n";
10183: }
10184: }
10185: if (srchin == 'dom') {
10186: if (srchdomain == '') {
10187: checkok = 0;
10188: msg += "$js_lt{'ymcd'}\\n";
10189: }
10190: }
10191: if (srchby == 'lastfirst') {
10192: if (srchterm.indexOf(",") == -1) {
10193: checkok = 0;
10194: msg += "$js_lt{'whus'}\\n";
10195: }
10196: if (srchterm.indexOf(",") == srchterm.length -1) {
10197: checkok = 0;
10198: msg += "$js_lt{'whse'}\\n";
10199: }
10200: }
10201: if (checkok == 0) {
10202: alert("$js_lt{'thfo'}\\n"+msg);
10203: return;
10204: }
10205: if (checkok == 1) {
10206: callingForm.submit();
10207: }
10208: }
10209:
10210: $newuserscript
10211:
10212: // ]]>
10213: </script>
10214:
10215: $new_user_create
10216:
10217: END_BLOCK
10218:
10219: $output .= &Apache::lonhtmlcommon::start_pick_box().
10220: &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10221: $domform.
10222: &Apache::lonhtmlcommon::row_closure().
10223: &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10224: $srchbysel.
10225: $srchtypesel.
10226: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10227: $srchinsel.
10228: &Apache::lonhtmlcommon::row_closure(1).
10229: &Apache::lonhtmlcommon::end_pick_box().
10230: '<br />';
10231: return ($output,1);
10232: }
10233:
10234: sub user_rule_check {
10235: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10236: my ($response,%inst_response);
10237: if (ref($usershash) eq 'HASH') {
10238: if (keys(%{$usershash}) > 1) {
10239: my (%by_username,%by_id,%userdoms);
10240: my $checkid;
10241: if (ref($checks) eq 'HASH') {
10242: if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10243: $checkid = 1;
10244: }
10245: }
10246: foreach my $user (keys(%{$usershash})) {
10247: my ($uname,$udom) = split(/:/,$user);
10248: if ($checkid) {
10249: if (ref($usershash->{$user}) eq 'HASH') {
10250: if ($usershash->{$user}->{'id'} ne '') {
10251: $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
10252: $userdoms{$udom} = 1;
10253: if (ref($inst_results) eq 'HASH') {
10254: $inst_results->{$uname.':'.$udom} = {};
10255: }
10256: }
10257: }
10258: } else {
10259: $by_username{$udom}{$uname} = 1;
10260: $userdoms{$udom} = 1;
10261: if (ref($inst_results) eq 'HASH') {
10262: $inst_results->{$uname.':'.$udom} = {};
10263: }
10264: }
10265: }
10266: foreach my $udom (keys(%userdoms)) {
10267: if (!$got_rules->{$udom}) {
10268: my %domconfig = &Apache::lonnet::get_dom('configuration',
10269: ['usercreation'],$udom);
10270: if (ref($domconfig{'usercreation'}) eq 'HASH') {
10271: foreach my $item ('username','id') {
10272: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10273: $$curr_rules{$udom}{$item} =
10274: $domconfig{'usercreation'}{$item.'_rule'};
10275: }
10276: }
10277: }
10278: $got_rules->{$udom} = 1;
10279: }
10280: }
10281: if ($checkid) {
10282: foreach my $udom (keys(%by_id)) {
10283: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10284: if ($outcome eq 'ok') {
10285: foreach my $id (keys(%{$by_id{$udom}})) {
10286: my $uname = $by_id{$udom}{$id};
10287: $inst_response{$uname.':'.$udom} = $outcome;
10288: }
10289: if (ref($results) eq 'HASH') {
10290: foreach my $uname (keys(%{$results})) {
10291: if (exists($inst_response{$uname.':'.$udom})) {
10292: $inst_response{$uname.':'.$udom} = $outcome;
10293: $inst_results->{$uname.':'.$udom} = $results->{$uname};
10294: }
10295: }
10296: }
10297: }
10298: }
10299: } else {
10300: foreach my $udom (keys(%by_username)) {
10301: my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10302: if ($outcome eq 'ok') {
10303: foreach my $uname (keys(%{$by_username{$udom}})) {
10304: $inst_response{$uname.':'.$udom} = $outcome;
10305: }
10306: if (ref($results) eq 'HASH') {
10307: foreach my $uname (keys(%{$results})) {
10308: $inst_results->{$uname.':'.$udom} = $results->{$uname};
10309: }
10310: }
10311: }
10312: }
10313: }
10314: } elsif (keys(%{$usershash}) == 1) {
10315: my $user = (keys(%{$usershash}))[0];
10316: my ($uname,$udom) = split(/:/,$user);
10317: if (($udom ne '') && ($uname ne '')) {
10318: if (ref($usershash->{$user}) eq 'HASH') {
10319: if (ref($checks) eq 'HASH') {
10320: if (defined($checks->{'username'})) {
10321: ($inst_response{$user},%{$inst_results->{$user}}) =
10322: &Apache::lonnet::get_instuser($udom,$uname);
10323: } elsif (defined($checks->{'id'})) {
10324: if ($usershash->{$user}->{'id'} ne '') {
10325: ($inst_response{$user},%{$inst_results->{$user}}) =
10326: &Apache::lonnet::get_instuser($udom,undef,
10327: $usershash->{$user}->{'id'});
10328: } else {
10329: ($inst_response{$user},%{$inst_results->{$user}}) =
10330: &Apache::lonnet::get_instuser($udom,$uname);
10331: }
10332: }
10333: } else {
10334: ($inst_response{$user},%{$inst_results->{$user}}) =
10335: &Apache::lonnet::get_instuser($udom,$uname);
10336: return;
10337: }
10338: if (!$got_rules->{$udom}) {
10339: my %domconfig = &Apache::lonnet::get_dom('configuration',
10340: ['usercreation'],$udom);
10341: if (ref($domconfig{'usercreation'}) eq 'HASH') {
10342: foreach my $item ('username','id') {
10343: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10344: $$curr_rules{$udom}{$item} =
10345: $domconfig{'usercreation'}{$item.'_rule'};
10346: }
10347: }
10348: }
10349: $got_rules->{$udom} = 1;
10350: }
10351: }
10352: } else {
10353: return;
10354: }
10355: } else {
10356: return;
10357: }
10358: foreach my $user (keys(%{$usershash})) {
10359: my ($uname,$udom) = split(/:/,$user);
10360: next if (($udom eq '') || ($uname eq ''));
10361: my $id;
10362: if (ref($inst_results) eq 'HASH') {
10363: if (ref($inst_results->{$user}) eq 'HASH') {
10364: $id = $inst_results->{$user}->{'id'};
10365: }
10366: }
10367: if ($id eq '') {
10368: if (ref($usershash->{$user})) {
10369: $id = $usershash->{$user}->{'id'};
10370: }
10371: }
10372: foreach my $item (keys(%{$checks})) {
10373: if (ref($$curr_rules{$udom}) eq 'HASH') {
10374: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10375: if (@{$$curr_rules{$udom}{$item}} > 0) {
10376: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10377: $$curr_rules{$udom}{$item});
10378: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10379: if ($rule_check{$rule}) {
10380: $$rulematch{$user}{$item} = $rule;
10381: if ($inst_response{$user} eq 'ok') {
10382: if (ref($inst_results) eq 'HASH') {
10383: if (ref($inst_results->{$user}) eq 'HASH') {
10384: if (keys(%{$inst_results->{$user}}) == 0) {
10385: $$alerts{$item}{$udom}{$uname} = 1;
10386: } elsif ($item eq 'id') {
10387: if ($inst_results->{$user}->{'id'} eq '') {
10388: $$alerts{$item}{$udom}{$uname} = 1;
10389: }
10390: }
10391: }
10392: }
10393: }
10394: last;
10395: }
10396: }
10397: }
10398: }
10399: }
10400: }
10401: }
10402: }
10403: return;
10404: }
10405:
10406: sub user_rule_formats {
10407: my ($domain,$domdesc,$curr_rules,$check) = @_;
10408: my %text = (
10409: 'username' => 'Usernames',
10410: 'id' => 'IDs',
10411: );
10412: my $output;
10413: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10414: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10415: if (@{$ruleorder} > 0) {
10416: $output = '<br />'.
10417: &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10418: '<span class="LC_cusr_emph">','</span>',$domdesc).
10419: ' <ul>';
10420: foreach my $rule (@{$ruleorder}) {
10421: if (ref($curr_rules) eq 'ARRAY') {
10422: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10423: if (ref($rules->{$rule}) eq 'HASH') {
10424: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10425: $rules->{$rule}{'desc'}.'</li>';
10426: }
10427: }
10428: }
10429: }
10430: $output .= '</ul>';
10431: }
10432: }
10433: return $output;
10434: }
10435:
10436: sub instrule_disallow_msg {
10437: my ($checkitem,$domdesc,$count,$mode) = @_;
10438: my $response;
10439: my %text = (
10440: item => 'username',
10441: items => 'usernames',
10442: match => 'matches',
10443: do => 'does',
10444: action => 'a username',
10445: one => 'one',
10446: );
10447: if ($count > 1) {
10448: $text{'item'} = 'usernames';
10449: $text{'match'} ='match';
10450: $text{'do'} = 'do';
10451: $text{'action'} = 'usernames',
10452: $text{'one'} = 'ones';
10453: }
10454: if ($checkitem eq 'id') {
10455: $text{'items'} = 'IDs';
10456: $text{'item'} = 'ID';
10457: $text{'action'} = 'an ID';
10458: if ($count > 1) {
10459: $text{'item'} = 'IDs';
10460: $text{'action'} = 'IDs';
10461: }
10462: }
10463: $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 />';
10464: if ($mode eq 'upload') {
10465: if ($checkitem eq 'username') {
10466: $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'}.");
10467: } elsif ($checkitem eq 'id') {
10468: $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.");
10469: }
10470: } elsif ($mode eq 'selfcreate') {
10471: if ($checkitem eq 'id') {
10472: $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.");
10473: }
10474: } else {
10475: if ($checkitem eq 'username') {
10476: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10477: } elsif ($checkitem eq 'id') {
10478: $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.");
10479: }
10480: }
10481: return $response;
10482: }
10483:
10484: sub personal_data_fieldtitles {
10485: my %fieldtitles = &Apache::lonlocal::texthash (
10486: id => 'Student/Employee ID',
10487: permanentemail => 'E-mail address',
10488: lastname => 'Last Name',
10489: firstname => 'First Name',
10490: middlename => 'Middle Name',
10491: generation => 'Generation',
10492: gen => 'Generation',
10493: inststatus => 'Affiliation',
10494: );
10495: return %fieldtitles;
10496: }
10497:
10498: sub sorted_inst_types {
10499: my ($dom) = @_;
10500: my ($usertypes,$order);
10501: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10502: if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10503: $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10504: $order = $domdefaults{'inststatus'}{'inststatusorder'};
10505: } else {
10506: ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10507: }
10508: my $othertitle = &mt('All users');
10509: if ($env{'request.course.id'}) {
10510: $othertitle = &mt('Any users');
10511: }
10512: my @types;
10513: if (ref($order) eq 'ARRAY') {
10514: @types = @{$order};
10515: }
10516: if (@types == 0) {
10517: if (ref($usertypes) eq 'HASH') {
10518: @types = sort(keys(%{$usertypes}));
10519: }
10520: }
10521: if (keys(%{$usertypes}) > 0) {
10522: $othertitle = &mt('Other users');
10523: }
10524: return ($othertitle,$usertypes,\@types);
10525: }
10526:
10527: sub get_institutional_codes {
10528: my ($settings,$allcourses,$LC_code) = @_;
10529: # Get complete list of course sections to update
10530: my @currsections = ();
10531: my @currxlists = ();
10532: my $coursecode = $$settings{'internal.coursecode'};
10533:
10534: if ($$settings{'internal.sectionnums'} ne '') {
10535: @currsections = split(/,/,$$settings{'internal.sectionnums'});
10536: }
10537:
10538: if ($$settings{'internal.crosslistings'} ne '') {
10539: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10540: }
10541:
10542: if (@currxlists > 0) {
10543: foreach (@currxlists) {
10544: if (m/^([^:]+):(\w*)$/) {
10545: unless (grep/^$1$/,@{$allcourses}) {
10546: push @{$allcourses},$1;
10547: $$LC_code{$1} = $2;
10548: }
10549: }
10550: }
10551: }
10552:
10553: if (@currsections > 0) {
10554: foreach (@currsections) {
10555: if (m/^(\w+):(\w*)$/) {
10556: my $sec = $coursecode.$1;
10557: my $lc_sec = $2;
10558: unless (grep/^$sec$/,@{$allcourses}) {
10559: push @{$allcourses},$sec;
10560: $$LC_code{$sec} = $lc_sec;
10561: }
10562: }
10563: }
10564: }
10565: return;
10566: }
10567:
10568: sub get_standard_codeitems {
10569: return ('Year','Semester','Department','Number','Section');
10570: }
10571:
10572: =pod
10573:
10574: =head1 Slot Helpers
10575:
10576: =over 4
10577:
10578: =item * sorted_slots()
10579:
10580: Sorts an array of slot names in order of an optional sort key,
10581: default sort is by slot start time (earliest first).
10582:
10583: Inputs:
10584:
10585: =over 4
10586:
10587: slotsarr - Reference to array of unsorted slot names.
10588:
10589: slots - Reference to hash of hash, where outer hash keys are slot names.
10590:
10591: sortkey - Name of key in inner hash to be sorted on (e.g., starttime).
10592:
10593: =back
10594:
10595: Returns:
10596:
10597: =over 4
10598:
10599: sorted - An array of slot names sorted by a specified sort key
10600: (default sort key is start time of the slot).
10601:
10602: =back
10603:
10604: =cut
10605:
10606:
10607: sub sorted_slots {
10608: my ($slotsarr,$slots,$sortkey) = @_;
10609: if ($sortkey eq '') {
10610: $sortkey = 'starttime';
10611: }
10612: my @sorted;
10613: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10614: @sorted =
10615: sort {
10616: if (ref($slots->{$a}) && ref($slots->{$b})) {
10617: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10618: }
10619: if (ref($slots->{$a})) { return -1;}
10620: if (ref($slots->{$b})) { return 1;}
10621: return 0;
10622: } @{$slotsarr};
10623: }
10624: return @sorted;
10625: }
10626:
10627: =pod
10628:
10629: =item * get_future_slots()
10630:
10631: Inputs:
10632:
10633: =over 4
10634:
10635: cnum - course number
10636:
10637: cdom - course domain
10638:
10639: now - current UNIX time
10640:
10641: symb - optional symb
10642:
10643: =back
10644:
10645: Returns:
10646:
10647: =over 4
10648:
10649: sorted_reservable - ref to array of student_schedulable slots currently
10650: reservable, ordered by end date of reservation period.
10651:
10652: reservable_now - ref to hash of student_schedulable slots currently
10653: reservable.
10654:
10655: Keys in inner hash are:
10656: (a) symb: either blank or symb to which slot use is restricted.
10657: (b) endreserve: end date of reservation period.
10658: (c) uniqueperiod: start,end dates when slot is to be uniquely
10659: selected.
10660:
10661: sorted_future - ref to array of student_schedulable slots reservable in
10662: the future, ordered by start date of reservation period.
10663:
10664: future_reservable - ref to hash of student_schedulable slots reservable
10665: in the future.
10666:
10667: Keys in inner hash are:
10668: (a) symb: either blank or symb to which slot use is restricted.
10669: (b) startreserve: start date of reservation period.
10670: (c) uniqueperiod: start,end dates when slot is to be uniquely
10671: selected.
10672:
10673: =back
10674:
10675: =cut
10676:
10677: sub get_future_slots {
10678: my ($cnum,$cdom,$now,$symb) = @_;
10679: my $map;
10680: if ($symb) {
10681: ($map) = &Apache::lonnet::decode_symb($symb);
10682: }
10683: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10684: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10685: foreach my $slot (keys(%slots)) {
10686: next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10687: if ($symb) {
10688: if ($slots{$slot}->{'symb'} ne '') {
10689: my $canuse;
10690: my %oksymbs;
10691: my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
10692: map { $oksymbs{$_} = 1; } @slotsymbs;
10693: if ($oksymbs{$symb}) {
10694: $canuse = 1;
10695: } else {
10696: foreach my $item (@slotsymbs) {
10697: if ($item =~ /\.(page|sequence)$/) {
10698: (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
10699: if (($map ne '') && ($map eq $sloturl)) {
10700: $canuse = 1;
10701: last;
10702: }
10703: }
10704: }
10705: }
10706: next unless ($canuse);
10707: }
10708: }
10709: if (($slots{$slot}->{'starttime'} > $now) &&
10710: ($slots{$slot}->{'endtime'} > $now)) {
10711: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10712: my $userallowed = 0;
10713: if ($slots{$slot}->{'allowedsections'}) {
10714: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10715: if (!defined($env{'request.role.sec'})
10716: && grep(/^No section assigned$/,@allowed_sec)) {
10717: $userallowed=1;
10718: } else {
10719: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10720: $userallowed=1;
10721: }
10722: }
10723: unless ($userallowed) {
10724: if (defined($env{'request.course.groups'})) {
10725: my @groups = split(/:/,$env{'request.course.groups'});
10726: foreach my $group (@groups) {
10727: if (grep(/^\Q$group\E$/,@allowed_sec)) {
10728: $userallowed=1;
10729: last;
10730: }
10731: }
10732: }
10733: }
10734: }
10735: if ($slots{$slot}->{'allowedusers'}) {
10736: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10737: my $user = $env{'user.name'}.':'.$env{'user.domain'};
10738: if (grep(/^\Q$user\E$/,@allowed_users)) {
10739: $userallowed = 1;
10740: }
10741: }
10742: next unless($userallowed);
10743: }
10744: my $startreserve = $slots{$slot}->{'startreserve'};
10745: my $endreserve = $slots{$slot}->{'endreserve'};
10746: my $symb = $slots{$slot}->{'symb'};
10747: my $uniqueperiod;
10748: if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
10749: $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
10750: }
10751: if (($startreserve < $now) &&
10752: (!$endreserve || $endreserve > $now)) {
10753: my $lastres = $endreserve;
10754: if (!$lastres) {
10755: $lastres = $slots{$slot}->{'starttime'};
10756: }
10757: $reservable_now{$slot} = {
10758: symb => $symb,
10759: endreserve => $lastres,
10760: uniqueperiod => $uniqueperiod,
10761: };
10762: } elsif (($startreserve > $now) &&
10763: (!$endreserve || $endreserve > $startreserve)) {
10764: $future_reservable{$slot} = {
10765: symb => $symb,
10766: startreserve => $startreserve,
10767: uniqueperiod => $uniqueperiod,
10768: };
10769: }
10770: }
10771: }
10772: my @unsorted_reservable = keys(%reservable_now);
10773: if (@unsorted_reservable > 0) {
10774: @sorted_reservable =
10775: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10776: }
10777: my @unsorted_future = keys(%future_reservable);
10778: if (@unsorted_future > 0) {
10779: @sorted_future =
10780: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10781: }
10782: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10783: }
10784:
10785: =pod
10786:
10787: =back
10788:
10789: =head1 HTTP Helpers
10790:
10791: =over 4
10792:
10793: =item * &get_unprocessed_cgi($query,$possible_names)
10794:
10795: Modify the %env hash to contain unprocessed CGI form parameters held in
10796: $query. The parameters listed in $possible_names (an array reference),
10797: will be set in $env{'form.name'} if they do not already exist.
10798:
10799: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
10800: $possible_names is an ref to an array of form element names. As an example:
10801: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10802: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10803:
10804: =cut
10805:
10806: sub get_unprocessed_cgi {
10807: my ($query,$possible_names)= @_;
10808: # $Apache::lonxml::debug=1;
10809: foreach my $pair (split(/&/,$query)) {
10810: my ($name, $value) = split(/=/,$pair);
10811: $name = &unescape($name);
10812: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10813: $value =~ tr/+/ /;
10814: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10815: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10816: }
10817: }
10818: }
10819:
10820: =pod
10821:
10822: =item * &cacheheader()
10823:
10824: returns cache-controlling header code
10825:
10826: =cut
10827:
10828: sub cacheheader {
10829: unless ($env{'request.method'} eq 'GET') { return ''; }
10830: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10831: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10832: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10833: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10834: return $output;
10835: }
10836:
10837: =pod
10838:
10839: =item * &no_cache($r)
10840:
10841: specifies header code to not have cache
10842:
10843: =cut
10844:
10845: sub no_cache {
10846: my ($r) = @_;
10847: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10848: $env{'request.method'} ne 'GET') { return ''; }
10849: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10850: $r->no_cache(1);
10851: $r->header_out("Expires" => $date);
10852: $r->header_out("Pragma" => "no-cache");
10853: }
10854:
10855: sub content_type {
10856: my ($r,$type,$charset) = @_;
10857: if ($r) {
10858: # Note that printout.pl calls this with undef for $r.
10859: &no_cache($r);
10860: }
10861: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10862: unless ($charset) {
10863: $charset=&Apache::lonlocal::current_encoding;
10864: }
10865: if ($charset) { $type.='; charset='.$charset; }
10866: if ($r) {
10867: $r->content_type($type);
10868: } else {
10869: print("Content-type: $type\n\n");
10870: }
10871: }
10872:
10873: =pod
10874:
10875: =item * &add_to_env($name,$value)
10876:
10877: adds $name to the %env hash with value
10878: $value, if $name already exists, the entry is converted to an array
10879: reference and $value is added to the array.
10880:
10881: =cut
10882:
10883: sub add_to_env {
10884: my ($name,$value)=@_;
10885: if (defined($env{$name})) {
10886: if (ref($env{$name})) {
10887: #already have multiple values
10888: push(@{ $env{$name} },$value);
10889: } else {
10890: #first time seeing multiple values, convert hash entry to an arrayref
10891: my $first=$env{$name};
10892: undef($env{$name});
10893: push(@{ $env{$name} },$first,$value);
10894: }
10895: } else {
10896: $env{$name}=$value;
10897: }
10898: }
10899:
10900: =pod
10901:
10902: =item * &get_env_multiple($name)
10903:
10904: gets $name from the %env hash, it seemlessly handles the cases where multiple
10905: values may be defined and end up as an array ref.
10906:
10907: returns an array of values
10908:
10909: =cut
10910:
10911: sub get_env_multiple {
10912: my ($name) = @_;
10913: my @values;
10914: if (defined($env{$name})) {
10915: # exists is it an array
10916: if (ref($env{$name})) {
10917: @values=@{ $env{$name} };
10918: } else {
10919: $values[0]=$env{$name};
10920: }
10921: }
10922: return(@values);
10923: }
10924:
10925: # Looks at given dependencies, and returns something depending on the context.
10926: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
10927: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
10928: # For all other contexts, returns ($output, $counter, $numpathchg).
10929: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
10930: # $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.
10931: # $numpathchg: integer with the number of cleaned up dependency paths.
10932: # \%existing: hash reference clean path -> 1 only for existing dependencies.
10933: # \%mapping: hash reference clean path -> original path for all dependencies.
10934: # @param {string} actionurl - The path to the handler, indicative of the context.
10935: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
10936: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
10937: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
10938: # @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)
10939: # @return {Array} - array depending on the context (not a reference)
10940: sub ask_for_embedded_content {
10941: # NOTE: documentation was added afterwards, it could be wrong
10942: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
10943: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
10944: %currsubfile,%unused,$rem);
10945: my $counter = 0;
10946: my $numnew = 0;
10947: my $numremref = 0;
10948: my $numinvalid = 0;
10949: my $numpathchg = 0;
10950: my $numexisting = 0;
10951: my $numunused = 0;
10952: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10953: $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10954: my $heading = &mt('Upload embedded files');
10955: my $buttontext = &mt('Upload');
10956:
10957: # fills these variables based on the context:
10958: # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
10959: # $path, $fileloc, $title, $rem, $filename
10960: if ($env{'request.course.id'}) {
10961: if ($actionurl eq '/adm/dependencies') {
10962: $navmap = Apache::lonnavmaps::navmap->new();
10963: }
10964: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10965: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10966: }
10967: if (($actionurl eq '/adm/portfolio') ||
10968: ($actionurl eq '/adm/coursegrp_portfolio')) {
10969: my $current_path='/';
10970: if ($env{'form.currentpath'}) {
10971: $current_path = $env{'form.currentpath'};
10972: }
10973: if ($actionurl eq '/adm/coursegrp_portfolio') {
10974: $udom = $cdom;
10975: $uname = $cnum;
10976: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10977: } else {
10978: $udom = $env{'user.domain'};
10979: $uname = $env{'user.name'};
10980: $url = '/userfiles/portfolio';
10981: }
10982: $toplevel = $url.'/';
10983: $url .= $current_path;
10984: $getpropath = 1;
10985: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10986: ($actionurl eq '/adm/imsimport')) {
10987: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
10988: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
10989: $toplevel = $url;
10990: if ($rest ne '') {
10991: $url .= $rest;
10992: }
10993: } elsif ($actionurl eq '/adm/coursedocs') {
10994: if (ref($args) eq 'HASH') {
10995: $url = $args->{'docs_url'};
10996: $toplevel = $url;
10997: if ($args->{'context'} eq 'paste') {
10998: ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
10999: ($path) =
11000: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11001: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11002: $fileloc =~ s{^/}{};
11003: }
11004: }
11005: } elsif ($actionurl eq '/adm/dependencies') {
11006: if ($env{'request.course.id'} ne '') {
11007: if (ref($args) eq 'HASH') {
11008: $url = $args->{'docs_url'};
11009: $title = $args->{'docs_title'};
11010: $toplevel = $url;
11011: unless ($toplevel =~ m{^/}) {
11012: $toplevel = "/$url";
11013: }
11014: ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
11015: if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
11016: $path = $1;
11017: } else {
11018: ($path) =
11019: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11020: }
11021: if ($toplevel=~/^\/*(uploaded|editupload)/) {
11022: $fileloc = $toplevel;
11023: $fileloc=~ s/^\s*(\S+)\s*$/$1/;
11024: my ($udom,$uname,$fname) =
11025: ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
11026: $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
11027: } else {
11028: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11029: }
11030: $fileloc =~ s{^/}{};
11031: ($filename) = ($fileloc =~ m{.+/([^/]+)$});
11032: $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
11033: }
11034: }
11035: } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11036: $udom = $cdom;
11037: $uname = $cnum;
11038: $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
11039: $toplevel = $url;
11040: $path = $url;
11041: $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
11042: $fileloc =~ s{^/}{};
11043: }
11044:
11045: # parses the dependency paths to get some info
11046: # fills $newfiles, $mapping, $subdependencies, $dependencies
11047: # $newfiles: hash URL -> 1 for new files or external URLs
11048: # (will be completed later)
11049: # $mapping:
11050: # for external URLs: external URL -> external URL
11051: # for relative paths: clean path -> original path
11052: # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
11053: # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
11054: foreach my $file (keys(%{$allfiles})) {
11055: my $embed_file;
11056: if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
11057: $embed_file = $1;
11058: } else {
11059: $embed_file = $file;
11060: }
11061: my ($absolutepath,$cleaned_file);
11062: if ($embed_file =~ m{^\w+://}) {
11063: $cleaned_file = $embed_file;
11064: $newfiles{$cleaned_file} = 1;
11065: $mapping{$cleaned_file} = $embed_file;
11066: } else {
11067: $cleaned_file = &clean_path($embed_file);
11068: if ($embed_file =~ m{^/}) {
11069: $absolutepath = $embed_file;
11070: }
11071: if ($cleaned_file =~ m{/}) {
11072: my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
11073: $path = &check_for_traversal($path,$url,$toplevel);
11074: my $item = $fname;
11075: if ($path ne '') {
11076: $item = $path.'/'.$fname;
11077: $subdependencies{$path}{$fname} = 1;
11078: } else {
11079: $dependencies{$item} = 1;
11080: }
11081: if ($absolutepath) {
11082: $mapping{$item} = $absolutepath;
11083: } else {
11084: $mapping{$item} = $embed_file;
11085: }
11086: } else {
11087: $dependencies{$embed_file} = 1;
11088: if ($absolutepath) {
11089: $mapping{$cleaned_file} = $absolutepath;
11090: } else {
11091: $mapping{$cleaned_file} = $embed_file;
11092: }
11093: }
11094: }
11095: }
11096:
11097: # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
11098: # and lists
11099: # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
11100: # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
11101: # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
11102: # the path had to be cleaned up
11103: # $existing: hash clean path -> 1 if the file exists
11104: # $numexisting: number of keys in $existing
11105: # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
11106: # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
11107: # dependency subdirectories that are
11108: # not listed as dependencies, with some exceptions using $rem
11109: my $dirptr = 16384;
11110: foreach my $path (keys(%subdependencies)) {
11111: $currsubfile{$path} = {};
11112: if (($actionurl eq '/adm/portfolio') ||
11113: ($actionurl eq '/adm/coursegrp_portfolio')) {
11114: my ($sublistref,$listerror) =
11115: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
11116: if (ref($sublistref) eq 'ARRAY') {
11117: foreach my $line (@{$sublistref}) {
11118: my ($file_name,$rest) = split(/\&/,$line,2);
11119: $currsubfile{$path}{$file_name} = 1;
11120: }
11121: }
11122: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11123: if (opendir(my $dir,$url.'/'.$path)) {
11124: my @subdir_list = grep(!/^\./,readdir($dir));
11125: map {$currsubfile{$path}{$_} = 1;} @subdir_list;
11126: }
11127: } elsif (($actionurl eq '/adm/dependencies') ||
11128: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11129: ($args->{'context'} eq 'paste')) ||
11130: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11131: if ($env{'request.course.id'} ne '') {
11132: my $dir;
11133: if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11134: $dir = $fileloc;
11135: } else {
11136: ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11137: }
11138: if ($dir ne '') {
11139: my ($sublistref,$listerror) =
11140: &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
11141: if (ref($sublistref) eq 'ARRAY') {
11142: foreach my $line (@{$sublistref}) {
11143: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
11144: undef,$mtime)=split(/\&/,$line,12);
11145: unless (($testdir&$dirptr) ||
11146: ($file_name =~ /^\.\.?$/)) {
11147: $currsubfile{$path}{$file_name} = [$size,$mtime];
11148: }
11149: }
11150: }
11151: }
11152: }
11153: }
11154: foreach my $file (keys(%{$subdependencies{$path}})) {
11155: if (exists($currsubfile{$path}{$file})) {
11156: my $item = $path.'/'.$file;
11157: unless ($mapping{$item} eq $item) {
11158: $pathchanges{$item} = 1;
11159: }
11160: $existing{$item} = 1;
11161: $numexisting ++;
11162: } else {
11163: $newfiles{$path.'/'.$file} = 1;
11164: }
11165: }
11166: if ($actionurl eq '/adm/dependencies') {
11167: foreach my $path (keys(%currsubfile)) {
11168: if (ref($currsubfile{$path}) eq 'HASH') {
11169: foreach my $file (keys(%{$currsubfile{$path}})) {
11170: unless ($subdependencies{$path}{$file}) {
11171: next if (($rem ne '') &&
11172: (($env{"httpref.$rem"."$path/$file"} ne '') ||
11173: (ref($navmap) &&
11174: (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
11175: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11176: ($navmap->getResourceByUrl($rem."$path/$1")))))));
11177: $unused{$path.'/'.$file} = 1;
11178: }
11179: }
11180: }
11181: }
11182: }
11183: }
11184:
11185: # fills $currfile, hash file name -> 1 or [$size,$mtime]
11186: # for files in $url or $fileloc (target directory) in some contexts
11187: my %currfile;
11188: if (($actionurl eq '/adm/portfolio') ||
11189: ($actionurl eq '/adm/coursegrp_portfolio')) {
11190: my ($dirlistref,$listerror) =
11191: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
11192: if (ref($dirlistref) eq 'ARRAY') {
11193: foreach my $line (@{$dirlistref}) {
11194: my ($file_name,$rest) = split(/\&/,$line,2);
11195: $currfile{$file_name} = 1;
11196: }
11197: }
11198: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11199: if (opendir(my $dir,$url)) {
11200: my @dir_list = grep(!/^\./,readdir($dir));
11201: map {$currfile{$_} = 1;} @dir_list;
11202: }
11203: } elsif (($actionurl eq '/adm/dependencies') ||
11204: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11205: ($args->{'context'} eq 'paste')) ||
11206: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11207: if ($env{'request.course.id'} ne '') {
11208: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11209: if ($dir ne '') {
11210: my ($dirlistref,$listerror) =
11211: &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11212: if (ref($dirlistref) eq 'ARRAY') {
11213: foreach my $line (@{$dirlistref}) {
11214: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11215: $size,undef,$mtime)=split(/\&/,$line,12);
11216: unless (($testdir&$dirptr) ||
11217: ($file_name =~ /^\.\.?$/)) {
11218: $currfile{$file_name} = [$size,$mtime];
11219: }
11220: }
11221: }
11222: }
11223: }
11224: }
11225: # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
11226: # are not in subdirectories, using $currfile
11227: foreach my $file (keys(%dependencies)) {
11228: if (exists($currfile{$file})) {
11229: unless ($mapping{$file} eq $file) {
11230: $pathchanges{$file} = 1;
11231: }
11232: $existing{$file} = 1;
11233: $numexisting ++;
11234: } else {
11235: $newfiles{$file} = 1;
11236: }
11237: }
11238: foreach my $file (keys(%currfile)) {
11239: unless (($file eq $filename) ||
11240: ($file eq $filename.'.bak') ||
11241: ($dependencies{$file})) {
11242: if ($actionurl eq '/adm/dependencies') {
11243: unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
11244: next if (($rem ne '') &&
11245: (($env{"httpref.$rem".$file} ne '') ||
11246: (ref($navmap) &&
11247: (($navmap->getResourceByUrl($rem.$file) ne '') ||
11248: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11249: ($navmap->getResourceByUrl($rem.$1)))))));
11250: }
11251: }
11252: $unused{$file} = 1;
11253: }
11254: }
11255:
11256: # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
11257: if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11258: ($args->{'context'} eq 'paste')) {
11259: $counter = scalar(keys(%existing));
11260: $numpathchg = scalar(keys(%pathchanges));
11261: return ($output,$counter,$numpathchg,\%existing);
11262: } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
11263: (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
11264: $counter = scalar(keys(%existing));
11265: $numpathchg = scalar(keys(%pathchanges));
11266: return ($output,$counter,$numpathchg,\%existing,\%mapping);
11267: }
11268:
11269: # returns HTML otherwise, with dependency results and to ask for more uploads
11270:
11271: # $upload_output: missing dependencies (with upload form)
11272: # $modify_output: uploaded dependencies (in use)
11273: # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
11274: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
11275: if ($actionurl eq '/adm/dependencies') {
11276: next if ($embed_file =~ m{^\w+://});
11277: }
11278: $upload_output .= &start_data_table_row().
11279: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
11280: '<span class="LC_filename">'.$embed_file.'</span>';
11281: unless ($mapping{$embed_file} eq $embed_file) {
11282: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
11283: &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
11284: }
11285: $upload_output .= '</td>';
11286: if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) {
11287: $upload_output.='<td align="right">'.
11288: '<span class="LC_info LC_fontsize_medium">'.
11289: &mt("URL points to web address").'</span>';
11290: $numremref++;
11291: } elsif ($args->{'error_on_invalid_names'}
11292: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
11293: $upload_output.='<td align="right"><span class="LC_warning">'.
11294: &mt('Invalid characters').'</span>';
11295: $numinvalid++;
11296: } else {
11297: $upload_output .= '<td>'.
11298: &embedded_file_element('upload_embedded',$counter,
11299: $embed_file,\%mapping,
11300: $allfiles,$codebase,'upload');
11301: $counter ++;
11302: $numnew ++;
11303: }
11304: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
11305: }
11306: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
11307: if ($actionurl eq '/adm/dependencies') {
11308: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
11309: $modify_output .= &start_data_table_row().
11310: '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
11311: '<img src="'.&icon($embed_file).'" border="0" />'.
11312: ' <span class="LC_filename">'.$embed_file.'</span></a></td>'.
11313: '<td>'.$size.'</td>'.
11314: '<td>'.$mtime.'</td>'.
11315: '<td><label><input type="checkbox" name="mod_upload_dep" '.
11316: 'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
11317: $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11318: '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11319: &embedded_file_element('upload_embedded',$counter,
11320: $embed_file,\%mapping,
11321: $allfiles,$codebase,'modify').
11322: '</div></td>'.
11323: &end_data_table_row()."\n";
11324: $counter ++;
11325: } else {
11326: $upload_output .= &start_data_table_row().
11327: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
11328: '<span class="LC_filename">'.$embed_file.'</span></td>'.
11329: '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11330: &Apache::loncommon::end_data_table_row()."\n";
11331: }
11332: }
11333: my $delidx = $counter;
11334: foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11335: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11336: $delete_output .= &start_data_table_row().
11337: '<td><img src="'.&icon($oldfile).'" />'.
11338: ' <span class="LC_filename">'.$oldfile.'</span></td>'.
11339: '<td>'.$size.'</td>'.
11340: '<td>'.$mtime.'</td>'.
11341: '<td><label><input type="checkbox" name="del_upload_dep" '.
11342: ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11343: &embedded_file_element('upload_embedded',$delidx,
11344: $oldfile,\%mapping,$allfiles,
11345: $codebase,'delete').'</td>'.
11346: &end_data_table_row()."\n";
11347: $numunused ++;
11348: $delidx ++;
11349: }
11350: if ($upload_output) {
11351: $upload_output = &start_data_table().
11352: $upload_output.
11353: &end_data_table()."\n";
11354: }
11355: if ($modify_output) {
11356: $modify_output = &start_data_table().
11357: &start_data_table_header_row().
11358: '<th>'.&mt('File').'</th>'.
11359: '<th>'.&mt('Size (KB)').'</th>'.
11360: '<th>'.&mt('Modified').'</th>'.
11361: '<th>'.&mt('Upload replacement?').'</th>'.
11362: &end_data_table_header_row().
11363: $modify_output.
11364: &end_data_table()."\n";
11365: }
11366: if ($delete_output) {
11367: $delete_output = &start_data_table().
11368: &start_data_table_header_row().
11369: '<th>'.&mt('File').'</th>'.
11370: '<th>'.&mt('Size (KB)').'</th>'.
11371: '<th>'.&mt('Modified').'</th>'.
11372: '<th>'.&mt('Delete?').'</th>'.
11373: &end_data_table_header_row().
11374: $delete_output.
11375: &end_data_table()."\n";
11376: }
11377: my $applies = 0;
11378: if ($numremref) {
11379: $applies ++;
11380: }
11381: if ($numinvalid) {
11382: $applies ++;
11383: }
11384: if ($numexisting) {
11385: $applies ++;
11386: }
11387: if ($counter || $numunused) {
11388: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11389: ' method="post" enctype="multipart/form-data">'."\n".
11390: $state.'<h3>'.$heading.'</h3>';
11391: if ($actionurl eq '/adm/dependencies') {
11392: if ($numnew) {
11393: $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11394: '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11395: $upload_output.'<br />'."\n";
11396: }
11397: if ($numexisting) {
11398: $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11399: '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11400: $modify_output.'<br />'."\n";
11401: $buttontext = &mt('Save changes');
11402: }
11403: if ($numunused) {
11404: $output .= '<h4>'.&mt('Unused files').'</h4>'.
11405: '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11406: $delete_output.'<br />'."\n";
11407: $buttontext = &mt('Save changes');
11408: }
11409: } else {
11410: $output .= $upload_output.'<br />'."\n";
11411: }
11412: $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11413: $counter.'" />'."\n";
11414: if ($actionurl eq '/adm/dependencies') {
11415: $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11416: $numnew.'" />'."\n";
11417: } elsif ($actionurl eq '') {
11418: $output .= '<input type="hidden" name="phase" value="three" />';
11419: }
11420: } elsif ($applies) {
11421: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11422: if ($applies > 1) {
11423: $output .=
11424: &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11425: if ($numremref) {
11426: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11427: }
11428: if ($numinvalid) {
11429: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11430: }
11431: if ($numexisting) {
11432: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11433: }
11434: $output .= '</ul><br />';
11435: } elsif ($numremref) {
11436: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11437: } elsif ($numinvalid) {
11438: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11439: } elsif ($numexisting) {
11440: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11441: }
11442: $output .= $upload_output.'<br />';
11443: }
11444: my ($pathchange_output,$chgcount);
11445: $chgcount = $counter;
11446: if (keys(%pathchanges) > 0) {
11447: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11448: if ($counter) {
11449: $output .= &embedded_file_element('pathchange',$chgcount,
11450: $embed_file,\%mapping,
11451: $allfiles,$codebase,'change');
11452: } else {
11453: $pathchange_output .=
11454: &start_data_table_row().
11455: '<td><input type ="checkbox" name="namechange" value="'.
11456: $chgcount.'" checked="checked" /></td>'.
11457: '<td>'.$mapping{$embed_file}.'</td>'.
11458: '<td>'.$embed_file.
11459: &embedded_file_element('pathchange',$numpathchg,$embed_file,
11460: \%mapping,$allfiles,$codebase,'change').
11461: '</td>'.&end_data_table_row();
11462: }
11463: $numpathchg ++;
11464: $chgcount ++;
11465: }
11466: }
11467: if (($counter) || ($numunused)) {
11468: if ($numpathchg) {
11469: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11470: $numpathchg.'" />'."\n";
11471: }
11472: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11473: ($actionurl eq '/adm/imsimport')) {
11474: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11475: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11476: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11477: } elsif ($actionurl eq '/adm/dependencies') {
11478: $output .= '<input type="hidden" name="action" value="process_changes" />';
11479: }
11480: $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11481: } elsif ($numpathchg) {
11482: my %pathchange = ();
11483: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11484: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11485: $output .= '<p>'.&mt('or').'</p>';
11486: }
11487: }
11488: return ($output,$counter,$numpathchg);
11489: }
11490:
11491: =pod
11492:
11493: =item * clean_path($name)
11494:
11495: Performs clean-up of directories, subdirectories and filename in an
11496: embedded object, referenced in an HTML file which is being uploaded
11497: to a course or portfolio, where
11498: "Upload embedded images/multimedia files if HTML file" checkbox was
11499: checked.
11500:
11501: Clean-up is similar to replacements in lonnet::clean_filename()
11502: except each / between sub-directory and next level is preserved.
11503:
11504: =cut
11505:
11506: sub clean_path {
11507: my ($embed_file) = @_;
11508: $embed_file =~s{^/+}{};
11509: my @contents;
11510: if ($embed_file =~ m{/}) {
11511: @contents = split(/\//,$embed_file);
11512: } else {
11513: @contents = ($embed_file);
11514: }
11515: my $lastidx = scalar(@contents)-1;
11516: for (my $i=0; $i<=$lastidx; $i++) {
11517: $contents[$i]=~s{\\}{/}g;
11518: $contents[$i]=~s/\s+/\_/g;
11519: $contents[$i]=~s{[^/\w\.\-]}{}g;
11520: if ($i == $lastidx) {
11521: $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11522: }
11523: }
11524: if ($lastidx > 0) {
11525: return join('/',@contents);
11526: } else {
11527: return $contents[0];
11528: }
11529: }
11530:
11531: sub embedded_file_element {
11532: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11533: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11534: (ref($codebase) eq 'HASH'));
11535: my $output;
11536: if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11537: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11538: }
11539: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11540: &escape($embed_file).'" />';
11541: unless (($context eq 'upload_embedded') &&
11542: ($mapping->{$embed_file} eq $embed_file)) {
11543: $output .='
11544: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11545: }
11546: my $attrib;
11547: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11548: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11549: }
11550: $output .=
11551: "\n\t\t".
11552: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11553: $attrib.'" />';
11554: if (exists($codebase->{$mapping->{$embed_file}})) {
11555: $output .=
11556: "\n\t\t".
11557: '<input name="codebase_'.$num.'" type="hidden" value="'.
11558: &escape($codebase->{$mapping->{$embed_file}}).'" />';
11559: }
11560: return $output;
11561: }
11562:
11563: sub get_dependency_details {
11564: my ($currfile,$currsubfile,$embed_file) = @_;
11565: my ($size,$mtime,$showsize,$showmtime);
11566: if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11567: if ($embed_file =~ m{/}) {
11568: my ($path,$fname) = split(/\//,$embed_file);
11569: if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11570: ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11571: }
11572: } else {
11573: if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11574: ($size,$mtime) = @{$currfile->{$embed_file}};
11575: }
11576: }
11577: $showsize = $size/1024.0;
11578: $showsize = sprintf("%.1f",$showsize);
11579: if ($mtime > 0) {
11580: $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11581: }
11582: }
11583: return ($showsize,$showmtime);
11584: }
11585:
11586: sub ask_embedded_js {
11587: return <<"END";
11588: <script type="text/javascript"">
11589: // <![CDATA[
11590: function toggleBrowse(counter) {
11591: var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11592: var fileid = document.getElementById('embedded_item_'+counter);
11593: var uploaddivid = document.getElementById('moduploaddep_'+counter);
11594: if (chkboxid.checked == true) {
11595: uploaddivid.style.display='block';
11596: } else {
11597: uploaddivid.style.display='none';
11598: fileid.value = '';
11599: }
11600: }
11601: // ]]>
11602: </script>
11603:
11604: END
11605: }
11606:
11607: sub upload_embedded {
11608: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11609: $current_disk_usage,$hiddenstate,$actionurl) = @_;
11610: my (%pathchange,$output,$modifyform,$footer,$returnflag);
11611: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11612: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11613: my $orig_uploaded_filename =
11614: $env{'form.embedded_item_'.$i.'.filename'};
11615: foreach my $type ('orig','ref','attrib','codebase') {
11616: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11617: $env{'form.embedded_'.$type.'_'.$i} =
11618: &unescape($env{'form.embedded_'.$type.'_'.$i});
11619: }
11620: }
11621: my ($path,$fname) =
11622: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11623: # no path, whole string is fname
11624: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11625: $fname = &Apache::lonnet::clean_filename($fname);
11626: # See if there is anything left
11627: next if ($fname eq '');
11628:
11629: # Check if file already exists as a file or directory.
11630: my ($state,$msg);
11631: if ($context eq 'portfolio') {
11632: my $port_path = $dirpath;
11633: if ($group ne '') {
11634: $port_path = "groups/$group/$port_path";
11635: }
11636: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11637: $fname,$group,'embedded_item_'.$i,
11638: $dir_root,$port_path,$disk_quota,
11639: $current_disk_usage,$uname,$udom);
11640: if ($state eq 'will_exceed_quota'
11641: || $state eq 'file_locked') {
11642: $output .= $msg;
11643: next;
11644: }
11645: } elsif (($context eq 'author') || ($context eq 'testbank')) {
11646: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11647: if ($state eq 'exists') {
11648: $output .= $msg;
11649: next;
11650: }
11651: }
11652: # Check if extension is valid
11653: if (($fname =~ /\.(\w+)$/) &&
11654: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11655: $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11656: .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11657: next;
11658: } elsif (($fname =~ /\.(\w+)$/) &&
11659: (!defined(&Apache::loncommon::fileembstyle($1)))) {
11660: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11661: next;
11662: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11663: $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11664: next;
11665: }
11666: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11667: my $subdir = $path;
11668: $subdir =~ s{/+$}{};
11669: if ($context eq 'portfolio') {
11670: my $result;
11671: if ($state eq 'existingfile') {
11672: $result=
11673: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11674: $dirpath.$env{'form.currentpath'}.$subdir);
11675: } else {
11676: $result=
11677: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11678: $dirpath.
11679: $env{'form.currentpath'}.$subdir);
11680: if ($result !~ m|^/uploaded/|) {
11681: $output .= '<span class="LC_error">'
11682: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11683: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11684: .'</span><br />';
11685: next;
11686: } else {
11687: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11688: $path.$fname.'</span>').'<br />';
11689: }
11690: }
11691: } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11692: my $extendedsubdir = $dirpath.'/'.$subdir;
11693: $extendedsubdir =~ s{/+$}{};
11694: my $result =
11695: &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11696: if ($result !~ m|^/uploaded/|) {
11697: $output .= '<span class="LC_error">'
11698: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11699: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11700: .'</span><br />';
11701: next;
11702: } else {
11703: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11704: $path.$fname.'</span>').'<br />';
11705: if ($context eq 'syllabus') {
11706: &Apache::lonnet::make_public_indefinitely($result);
11707: }
11708: }
11709: } else {
11710: # Save the file
11711: my $target = $env{'form.embedded_item_'.$i};
11712: my $fullpath = $dir_root.$dirpath.'/'.$path;
11713: my $dest = $fullpath.$fname;
11714: my $url = $url_root.$dirpath.'/'.$path.$fname;
11715: my @parts=split(/\//,"$dirpath/$path");
11716: my $count;
11717: my $filepath = $dir_root;
11718: foreach my $subdir (@parts) {
11719: $filepath .= "/$subdir";
11720: if (!-e $filepath) {
11721: mkdir($filepath,0770);
11722: }
11723: }
11724: my $fh;
11725: if (!open($fh,'>'.$dest)) {
11726: &Apache::lonnet::logthis('Failed to create '.$dest);
11727: $output .= '<span class="LC_error">'.
11728: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11729: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11730: '</span><br />';
11731: } else {
11732: if (!print $fh $env{'form.embedded_item_'.$i}) {
11733: &Apache::lonnet::logthis('Failed to write to '.$dest);
11734: $output .= '<span class="LC_error">'.
11735: &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11736: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11737: '</span><br />';
11738: } else {
11739: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11740: $url.'</span>').'<br />';
11741: unless ($context eq 'testbank') {
11742: $footer .= &mt('View embedded file: [_1]',
11743: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11744: }
11745: }
11746: close($fh);
11747: }
11748: }
11749: if ($env{'form.embedded_ref_'.$i}) {
11750: $pathchange{$i} = 1;
11751: }
11752: }
11753: if ($output) {
11754: $output = '<p>'.$output.'</p>';
11755: }
11756: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11757: $returnflag = 'ok';
11758: my $numpathchgs = scalar(keys(%pathchange));
11759: if ($numpathchgs > 0) {
11760: if ($context eq 'portfolio') {
11761: $output .= '<p>'.&mt('or').'</p>';
11762: } elsif ($context eq 'testbank') {
11763: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11764: '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11765: $returnflag = 'modify_orightml';
11766: }
11767: }
11768: return ($output.$footer,$returnflag,$numpathchgs);
11769: }
11770:
11771: sub modify_html_form {
11772: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11773: my $end = 0;
11774: my $modifyform;
11775: if ($context eq 'upload_embedded') {
11776: return unless (ref($pathchange) eq 'HASH');
11777: if ($env{'form.number_embedded_items'}) {
11778: $end += $env{'form.number_embedded_items'};
11779: }
11780: if ($env{'form.number_pathchange_items'}) {
11781: $end += $env{'form.number_pathchange_items'};
11782: }
11783: if ($end) {
11784: for (my $i=0; $i<$end; $i++) {
11785: if ($i < $env{'form.number_embedded_items'}) {
11786: next unless($pathchange->{$i});
11787: }
11788: $modifyform .=
11789: &start_data_table_row().
11790: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11791: 'checked="checked" /></td>'.
11792: '<td>'.$env{'form.embedded_ref_'.$i}.
11793: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11794: &escape($env{'form.embedded_ref_'.$i}).'" />'.
11795: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11796: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11797: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11798: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11799: '<td>'.$env{'form.embedded_orig_'.$i}.
11800: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11801: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11802: &end_data_table_row();
11803: }
11804: }
11805: } else {
11806: $modifyform = $pathchgtable;
11807: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11808: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11809: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11810: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11811: }
11812: }
11813: if ($modifyform) {
11814: if ($actionurl eq '/adm/dependencies') {
11815: $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11816: }
11817: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11818: '<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".
11819: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11820: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11821: '</ol></p>'."\n".'<p>'.
11822: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11823: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11824: &start_data_table()."\n".
11825: &start_data_table_header_row().
11826: '<th>'.&mt('Change?').'</th>'.
11827: '<th>'.&mt('Current reference').'</th>'.
11828: '<th>'.&mt('Required reference').'</th>'.
11829: &end_data_table_header_row()."\n".
11830: $modifyform.
11831: &end_data_table().'<br />'."\n".$hiddenstate.
11832: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11833: '</form>'."\n";
11834: }
11835: return;
11836: }
11837:
11838: sub modify_html_refs {
11839: my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11840: my $container;
11841: if ($context eq 'portfolio') {
11842: $container = $env{'form.container'};
11843: } elsif ($context eq 'coursedoc') {
11844: $container = $env{'form.primaryurl'};
11845: } elsif ($context eq 'manage_dependencies') {
11846: (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11847: $container = "/$container";
11848: } elsif ($context eq 'syllabus') {
11849: $container = $url;
11850: } else {
11851: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11852: }
11853: my (%allfiles,%codebase,$output,$content);
11854: my @changes = &get_env_multiple('form.namechange');
11855: unless ((@changes > 0) || ($context eq 'syllabus')) {
11856: if (wantarray) {
11857: return ('',0,0);
11858: } else {
11859: return;
11860: }
11861: }
11862: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
11863: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11864: unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11865: if (wantarray) {
11866: return ('',0,0);
11867: } else {
11868: return;
11869: }
11870: }
11871: $content = &Apache::lonnet::getfile($container);
11872: if ($content eq '-1') {
11873: if (wantarray) {
11874: return ('',0,0);
11875: } else {
11876: return;
11877: }
11878: }
11879: } else {
11880: unless ($container =~ /^\Q$dir_root\E/) {
11881: if (wantarray) {
11882: return ('',0,0);
11883: } else {
11884: return;
11885: }
11886: }
11887: if (open(my $fh,"<$container")) {
11888: $content = join('', <$fh>);
11889: close($fh);
11890: } else {
11891: if (wantarray) {
11892: return ('',0,0);
11893: } else {
11894: return;
11895: }
11896: }
11897: }
11898: my ($count,$codebasecount) = (0,0);
11899: my $mm = new File::MMagic;
11900: my $mime_type = $mm->checktype_contents($content);
11901: if ($mime_type eq 'text/html') {
11902: my $parse_result =
11903: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11904: \%codebase,\$content);
11905: if ($parse_result eq 'ok') {
11906: foreach my $i (@changes) {
11907: my $orig = &unescape($env{'form.embedded_orig_'.$i});
11908: my $ref = &unescape($env{'form.embedded_ref_'.$i});
11909: if ($allfiles{$ref}) {
11910: my $newname = $orig;
11911: my ($attrib_regexp,$codebase);
11912: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11913: if ($attrib_regexp =~ /:/) {
11914: $attrib_regexp =~ s/\:/|/g;
11915: }
11916: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11917: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11918: $count += $numchg;
11919: $allfiles{$newname} = $allfiles{$ref};
11920: delete($allfiles{$ref});
11921: }
11922: if ($env{'form.embedded_codebase_'.$i} ne '') {
11923: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11924: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
11925: $codebasecount ++;
11926: }
11927: }
11928: }
11929: my $skiprewrites;
11930: if ($count || $codebasecount) {
11931: my $saveresult;
11932: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
11933: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11934: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11935: if ($url eq $container) {
11936: my ($fname) = ($container =~ m{/([^/]+)$});
11937: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11938: $count,'<span class="LC_filename">'.
11939: $fname.'</span>').'</p>';
11940: } else {
11941: $output = '<p class="LC_error">'.
11942: &mt('Error: update failed for: [_1].',
11943: '<span class="LC_filename">'.
11944: $container.'</span>').'</p>';
11945: }
11946: if ($context eq 'syllabus') {
11947: unless ($saveresult eq 'ok') {
11948: $skiprewrites = 1;
11949: }
11950: }
11951: } else {
11952: if (open(my $fh,">$container")) {
11953: print $fh $content;
11954: close($fh);
11955: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11956: $count,'<span class="LC_filename">'.
11957: $container.'</span>').'</p>';
11958: } else {
11959: $output = '<p class="LC_error">'.
11960: &mt('Error: could not update [_1].',
11961: '<span class="LC_filename">'.
11962: $container.'</span>').'</p>';
11963: }
11964: }
11965: }
11966: if (($context eq 'syllabus') && (!$skiprewrites)) {
11967: my ($actionurl,$state);
11968: $actionurl = "/public/$udom/$uname/syllabus";
11969: my ($ignore,$num,$numpathchanges,$existing,$mapping) =
11970: &ask_for_embedded_content($actionurl,$state,\%allfiles,
11971: \%codebase,
11972: {'context' => 'rewrites',
11973: 'ignore_remote_references' => 1,});
11974: if (ref($mapping) eq 'HASH') {
11975: my $rewrites = 0;
11976: foreach my $key (keys(%{$mapping})) {
11977: next if ($key =~ m{^https?://});
11978: my $ref = $mapping->{$key};
11979: my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
11980: my $attrib;
11981: if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
11982: $attrib = join('|',@{$allfiles{$mapping->{$key}}});
11983: }
11984: if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11985: my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11986: $rewrites += $numchg;
11987: }
11988: }
11989: if ($rewrites) {
11990: my $saveresult;
11991: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11992: if ($url eq $container) {
11993: my ($fname) = ($container =~ m{/([^/]+)$});
11994: $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11995: $count,'<span class="LC_filename">'.
11996: $fname.'</span>').'</p>';
11997: } else {
11998: $output .= '<p class="LC_error">'.
11999: &mt('Error: could not update links in [_1].',
12000: '<span class="LC_filename">'.
12001: $container.'</span>').'</p>';
12002:
12003: }
12004: }
12005: }
12006: }
12007: } else {
12008: &logthis('Failed to parse '.$container.
12009: ' to modify references: '.$parse_result);
12010: }
12011: }
12012: if (wantarray) {
12013: return ($output,$count,$codebasecount);
12014: } else {
12015: return $output;
12016: }
12017: }
12018:
12019: sub check_for_existing {
12020: my ($path,$fname,$element) = @_;
12021: my ($state,$msg);
12022: if (-d $path.'/'.$fname) {
12023: $state = 'exists';
12024: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12025: } elsif (-e $path.'/'.$fname) {
12026: $state = 'exists';
12027: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12028: }
12029: if ($state eq 'exists') {
12030: $msg = '<span class="LC_error">'.$msg.'</span><br />';
12031: }
12032: return ($state,$msg);
12033: }
12034:
12035: sub check_for_upload {
12036: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
12037: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
12038: my $filesize = length($env{'form.'.$element});
12039: if (!$filesize) {
12040: my $msg = '<span class="LC_error">'.
12041: &mt('Unable to upload [_1]. (size = [_2] bytes)',
12042: '<span class="LC_filename">'.$fname.'</span>',
12043: $filesize).'<br />'.
12044: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
12045: '</span>';
12046: return ('zero_bytes',$msg);
12047: }
12048: $filesize = $filesize/1000; #express in k (1024?)
12049: my $getpropath = 1;
12050: my ($dirlistref,$listerror) =
12051: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
12052: my $found_file = 0;
12053: my $locked_file = 0;
12054: my @lockers;
12055: my $navmap;
12056: if ($env{'request.course.id'}) {
12057: $navmap = Apache::lonnavmaps::navmap->new();
12058: }
12059: if (ref($dirlistref) eq 'ARRAY') {
12060: foreach my $line (@{$dirlistref}) {
12061: my ($file_name,$rest)=split(/\&/,$line,2);
12062: if ($file_name eq $fname){
12063: $file_name = $path.$file_name;
12064: if ($group ne '') {
12065: $file_name = $group.$file_name;
12066: }
12067: $found_file = 1;
12068: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
12069: foreach my $lock (@lockers) {
12070: if (ref($lock) eq 'ARRAY') {
12071: my ($symb,$crsid) = @{$lock};
12072: if ($crsid eq $env{'request.course.id'}) {
12073: if (ref($navmap)) {
12074: my $res = $navmap->getBySymb($symb);
12075: foreach my $part (@{$res->parts()}) {
12076: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
12077: unless (($slot_status == $res->RESERVED) ||
12078: ($slot_status == $res->RESERVED_LOCATION)) {
12079: $locked_file = 1;
12080: }
12081: }
12082: } else {
12083: $locked_file = 1;
12084: }
12085: } else {
12086: $locked_file = 1;
12087: }
12088: }
12089: }
12090: } else {
12091: my @info = split(/\&/,$rest);
12092: my $currsize = $info[6]/1000;
12093: if ($currsize < $filesize) {
12094: my $extra = $filesize - $currsize;
12095: if (($current_disk_usage + $extra) > $disk_quota) {
12096: my $msg = '<p class="LC_warning">'.
12097: &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.',
12098: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
12099: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
12100: $disk_quota,$current_disk_usage).'</p>';
12101: return ('will_exceed_quota',$msg);
12102: }
12103: }
12104: }
12105: }
12106: }
12107: }
12108: if (($current_disk_usage + $filesize) > $disk_quota){
12109: my $msg = '<p class="LC_warning">'.
12110: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
12111: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
12112: return ('will_exceed_quota',$msg);
12113: } elsif ($found_file) {
12114: if ($locked_file) {
12115: my $msg = '<p class="LC_warning">';
12116: $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>');
12117: $msg .= '</p>';
12118: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
12119: return ('file_locked',$msg);
12120: } else {
12121: my $msg = '<p class="LC_error">';
12122: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
12123: $msg .= '</p>';
12124: return ('existingfile',$msg);
12125: }
12126: }
12127: }
12128:
12129: sub check_for_traversal {
12130: my ($path,$url,$toplevel) = @_;
12131: my @parts=split(/\//,$path);
12132: my $cleanpath;
12133: my $fullpath = $url;
12134: for (my $i=0;$i<@parts;$i++) {
12135: next if ($parts[$i] eq '.');
12136: if ($parts[$i] eq '..') {
12137: $fullpath =~ s{([^/]+/)$}{};
12138: } else {
12139: $fullpath .= $parts[$i].'/';
12140: }
12141: }
12142: if ($fullpath =~ /^\Q$url\E(.*)$/) {
12143: $cleanpath = $1;
12144: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
12145: my $curr_toprel = $1;
12146: my @parts = split(/\//,$curr_toprel);
12147: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
12148: my @urlparts = split(/\//,$url_toprel);
12149: my $doubledots;
12150: my $startdiff = -1;
12151: for (my $i=0; $i<@urlparts; $i++) {
12152: if ($startdiff == -1) {
12153: unless ($urlparts[$i] eq $parts[$i]) {
12154: $startdiff = $i;
12155: $doubledots .= '../';
12156: }
12157: } else {
12158: $doubledots .= '../';
12159: }
12160: }
12161: if ($startdiff > -1) {
12162: $cleanpath = $doubledots;
12163: for (my $i=$startdiff; $i<@parts; $i++) {
12164: $cleanpath .= $parts[$i].'/';
12165: }
12166: }
12167: }
12168: $cleanpath =~ s{(/)$}{};
12169: return $cleanpath;
12170: }
12171:
12172: sub is_archive_file {
12173: my ($mimetype) = @_;
12174: if (($mimetype eq 'application/octet-stream') ||
12175: ($mimetype eq 'application/x-stuffit') ||
12176: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
12177: return 1;
12178: }
12179: return;
12180: }
12181:
12182: sub decompress_form {
12183: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
12184: my %lt = &Apache::lonlocal::texthash (
12185: this => 'This file is an archive file.',
12186: camt => 'This file is a Camtasia archive file.',
12187: itsc => 'Its contents are as follows:',
12188: youm => 'You may wish to extract its contents.',
12189: extr => 'Extract contents',
12190: auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
12191: proa => 'Process automatically?',
12192: yes => 'Yes',
12193: no => 'No',
12194: fold => 'Title for folder containing movie',
12195: movi => 'Title for page containing embedded movie',
12196: );
12197: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
12198: my ($is_camtasia,$topdir,%toplevel,@paths);
12199: my $info = &list_archive_contents($fileloc,\@paths);
12200: if (@paths) {
12201: foreach my $path (@paths) {
12202: $path =~ s{^/}{};
12203: if ($path =~ m{^([^/]+)/$}) {
12204: $topdir = $1;
12205: }
12206: if ($path =~ m{^([^/]+)/}) {
12207: $toplevel{$1} = $path;
12208: } else {
12209: $toplevel{$path} = $path;
12210: }
12211: }
12212: }
12213: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12214: my @camtasia6 = ("$topdir/","$topdir/index.html",
12215: "$topdir/media/",
12216: "$topdir/media/$topdir.mp4",
12217: "$topdir/media/FirstFrame.png",
12218: "$topdir/media/player.swf",
12219: "$topdir/media/swfobject.js",
12220: "$topdir/media/expressInstall.swf");
12221: my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12222: "$topdir/$topdir.mp4",
12223: "$topdir/$topdir\_config.xml",
12224: "$topdir/$topdir\_controller.swf",
12225: "$topdir/$topdir\_embed.css",
12226: "$topdir/$topdir\_First_Frame.png",
12227: "$topdir/$topdir\_player.html",
12228: "$topdir/$topdir\_Thumbnails.png",
12229: "$topdir/playerProductInstall.swf",
12230: "$topdir/scripts/",
12231: "$topdir/scripts/config_xml.js",
12232: "$topdir/scripts/handlebars.js",
12233: "$topdir/scripts/jquery-1.7.1.min.js",
12234: "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12235: "$topdir/scripts/modernizr.js",
12236: "$topdir/scripts/player-min.js",
12237: "$topdir/scripts/swfobject.js",
12238: "$topdir/skins/",
12239: "$topdir/skins/configuration_express.xml",
12240: "$topdir/skins/express_show/",
12241: "$topdir/skins/express_show/player-min.css",
12242: "$topdir/skins/express_show/spritesheet.png");
12243: my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
12244: "$topdir/$topdir.mp4",
12245: "$topdir/$topdir\_config.xml",
12246: "$topdir/$topdir\_controller.swf",
12247: "$topdir/$topdir\_embed.css",
12248: "$topdir/$topdir\_First_Frame.png",
12249: "$topdir/$topdir\_player.html",
12250: "$topdir/$topdir\_Thumbnails.png",
12251: "$topdir/playerProductInstall.swf",
12252: "$topdir/scripts/",
12253: "$topdir/scripts/config_xml.js",
12254: "$topdir/scripts/techsmith-smart-player.min.js",
12255: "$topdir/skins/",
12256: "$topdir/skins/configuration_express.xml",
12257: "$topdir/skins/express_show/",
12258: "$topdir/skins/express_show/spritesheet.min.css",
12259: "$topdir/skins/express_show/spritesheet.png",
12260: "$topdir/skins/express_show/techsmith-smart-player.min.css");
12261: my @diffs = &compare_arrays(\@paths,\@camtasia6);
12262: if (@diffs == 0) {
12263: $is_camtasia = 6;
12264: } else {
12265: @diffs = &compare_arrays(\@paths,\@camtasia8_1);
12266: if (@diffs == 0) {
12267: $is_camtasia = 8;
12268: } else {
12269: @diffs = &compare_arrays(\@paths,\@camtasia8_4);
12270: if (@diffs == 0) {
12271: $is_camtasia = 8;
12272: }
12273: }
12274: }
12275: }
12276: my $output;
12277: if ($is_camtasia) {
12278: $output = <<"ENDCAM";
12279: <script type="text/javascript" language="Javascript">
12280: // <![CDATA[
12281:
12282: function camtasiaToggle() {
12283: for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
12284: if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
12285: if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
12286: document.getElementById('camtasia_titles').style.display='block';
12287: } else {
12288: document.getElementById('camtasia_titles').style.display='none';
12289: }
12290: }
12291: }
12292: return;
12293: }
12294:
12295: // ]]>
12296: </script>
12297: <p>$lt{'camt'}</p>
12298: ENDCAM
12299: } else {
12300: $output = '<p>'.$lt{'this'};
12301: if ($info eq '') {
12302: $output .= ' '.$lt{'youm'}.'</p>'."\n";
12303: } else {
12304: $output .= ' '.$lt{'itsc'}.'</p>'."\n".
12305: '<div><pre>'.$info.'</pre></div>';
12306: }
12307: }
12308: $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
12309: my $duplicates;
12310: my $num = 0;
12311: if (ref($dirlist) eq 'ARRAY') {
12312: foreach my $item (@{$dirlist}) {
12313: if (ref($item) eq 'ARRAY') {
12314: if (exists($toplevel{$item->[0]})) {
12315: $duplicates .=
12316: &start_data_table_row().
12317: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12318: 'value="0" checked="checked" />'.&mt('No').'</label>'.
12319: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '.
12320: 'value="1" />'.&mt('Yes').'</label>'.
12321: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12322: '<td>'.$item->[0].'</td>';
12323: if ($item->[2]) {
12324: $duplicates .= '<td>'.&mt('Directory').'</td>';
12325: } else {
12326: $duplicates .= '<td>'.&mt('File').'</td>';
12327: }
12328: $duplicates .= '<td>'.$item->[3].'</td>'.
12329: '<td>'.
12330: &Apache::lonlocal::locallocaltime($item->[4]).
12331: '</td>'.
12332: &end_data_table_row();
12333: $num ++;
12334: }
12335: }
12336: }
12337: }
12338: my $itemcount;
12339: if (@paths > 0) {
12340: $itemcount = scalar(@paths);
12341: } else {
12342: $itemcount = 1;
12343: }
12344: if ($is_camtasia) {
12345: $output .= $lt{'auto'}.'<br />'.
12346: '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12347: '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12348: $lt{'yes'}.'</label> <label>'.
12349: '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12350: $lt{'no'}.'</label></span><br />'.
12351: '<div id="camtasia_titles" style="display:block">'.
12352: &Apache::lonhtmlcommon::start_pick_box().
12353: &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12354: '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12355: &Apache::lonhtmlcommon::row_closure().
12356: &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12357: '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12358: &Apache::lonhtmlcommon::row_closure(1).
12359: &Apache::lonhtmlcommon::end_pick_box().
12360: '</div>';
12361: }
12362: $output .=
12363: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12364: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12365: "\n";
12366: if ($duplicates ne '') {
12367: $output .= '<p><span class="LC_warning">'.
12368: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.
12369: &start_data_table().
12370: &start_data_table_header_row().
12371: '<th>'.&mt('Overwrite?').'</th>'.
12372: '<th>'.&mt('Name').'</th>'.
12373: '<th>'.&mt('Type').'</th>'.
12374: '<th>'.&mt('Size').'</th>'.
12375: '<th>'.&mt('Last modified').'</th>'.
12376: &end_data_table_header_row().
12377: $duplicates.
12378: &end_data_table().
12379: '</p>';
12380: }
12381: $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12382: if (ref($hiddenelements) eq 'HASH') {
12383: foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12384: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12385: }
12386: }
12387: $output .= <<"END";
12388: <br />
12389: <input type="submit" name="decompress" value="$lt{'extr'}" />
12390: </form>
12391: $noextract
12392: END
12393: return $output;
12394: }
12395:
12396: sub decompression_utility {
12397: my ($program) = @_;
12398: my @utilities = ('tar','gunzip','bunzip2','unzip');
12399: my $location;
12400: if (grep(/^\Q$program\E$/,@utilities)) {
12401: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12402: '/usr/sbin/') {
12403: if (-x $dir.$program) {
12404: $location = $dir.$program;
12405: last;
12406: }
12407: }
12408: }
12409: return $location;
12410: }
12411:
12412: sub list_archive_contents {
12413: my ($file,$pathsref) = @_;
12414: my (@cmd,$output);
12415: my $needsregexp;
12416: if ($file =~ /\.zip$/) {
12417: @cmd = (&decompression_utility('unzip'),"-l");
12418: $needsregexp = 1;
12419: } elsif (($file =~ m/\.tar\.gz$/) ||
12420: ($file =~ /\.tgz$/)) {
12421: @cmd = (&decompression_utility('tar'),"-ztf");
12422: } elsif ($file =~ /\.tar\.bz2$/) {
12423: @cmd = (&decompression_utility('tar'),"-jtf");
12424: } elsif ($file =~ m|\.tar$|) {
12425: @cmd = (&decompression_utility('tar'),"-tf");
12426: }
12427: if (@cmd) {
12428: undef($!);
12429: undef($@);
12430: if (open(my $fh,"-|", @cmd, $file)) {
12431: while (my $line = <$fh>) {
12432: $output .= $line;
12433: chomp($line);
12434: my $item;
12435: if ($needsregexp) {
12436: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/);
12437: } else {
12438: $item = $line;
12439: }
12440: if ($item ne '') {
12441: unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12442: push(@{$pathsref},$item);
12443: }
12444: }
12445: }
12446: close($fh);
12447: }
12448: }
12449: return $output;
12450: }
12451:
12452: sub decompress_uploaded_file {
12453: my ($file,$dir) = @_;
12454: &Apache::lonnet::appenv({'cgi.file' => $file});
12455: &Apache::lonnet::appenv({'cgi.dir' => $dir});
12456: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12457: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12458: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12459: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12460: my $decompressed = $env{'cgi.decompressed'};
12461: &Apache::lonnet::delenv('cgi.file');
12462: &Apache::lonnet::delenv('cgi.dir');
12463: &Apache::lonnet::delenv('cgi.decompressed');
12464: return ($decompressed,$result);
12465: }
12466:
12467: sub process_decompression {
12468: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12469: my ($dir,$error,$warning,$output);
12470: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12471: $error = &mt('Filename not a supported archive file type.').
12472: '<br />'.&mt('Filename should end with one of: [_1].',
12473: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12474: } else {
12475: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12476: if ($docuhome eq 'no_host') {
12477: $error = &mt('Could not determine home server for course.');
12478: } else {
12479: my @ids=&Apache::lonnet::current_machine_ids();
12480: my $currdir = "$dir_root/$destination";
12481: if (grep(/^\Q$docuhome\E$/,@ids)) {
12482: $dir = &LONCAPA::propath($docudom,$docuname).
12483: "$dir_root/$destination";
12484: } else {
12485: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12486: "$dir_root/$docudom/$docuname/$destination";
12487: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12488: $error = &mt('Archive file not found.');
12489: }
12490: }
12491: my (@to_overwrite,@to_skip);
12492: if ($env{'form.archive_overwrite_total'} > 0) {
12493: my $total = $env{'form.archive_overwrite_total'};
12494: for (my $i=0; $i<$total; $i++) {
12495: if ($env{'form.archive_overwrite_'.$i} == 1) {
12496: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12497: } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12498: push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12499: }
12500: }
12501: }
12502: my $numskip = scalar(@to_skip);
12503: if (($numskip > 0) &&
12504: ($numskip == $env{'form.archive_itemcount'})) {
12505: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');
12506: } elsif ($dir eq '') {
12507: $error = &mt('Directory containing archive file unavailable.');
12508: } elsif (!$error) {
12509: my ($decompressed,$display);
12510: if ($numskip > 0) {
12511: my $tempdir = time.'_'.$$.int(rand(10000));
12512: mkdir("$dir/$tempdir",0755);
12513: system("mv $dir/$file $dir/$tempdir/$file");
12514: ($decompressed,$display) =
12515: &decompress_uploaded_file($file,"$dir/$tempdir");
12516: foreach my $item (@to_skip) {
12517: if (($item ne '') && ($item !~ /\.\./)) {
12518: if (-f "$dir/$tempdir/$item") {
12519: unlink("$dir/$tempdir/$item");
12520: } elsif (-d "$dir/$tempdir/$item") {
12521: system("rm -rf $dir/$tempdir/$item");
12522: }
12523: }
12524: }
12525: system("mv $dir/$tempdir/* $dir");
12526: rmdir("$dir/$tempdir");
12527: } else {
12528: ($decompressed,$display) =
12529: &decompress_uploaded_file($file,$dir);
12530: }
12531: if ($decompressed eq 'ok') {
12532: $output = '<p class="LC_info">'.
12533: &mt('Files extracted successfully from archive.').
12534: '</p>'."\n";
12535: my ($warning,$result,@contents);
12536: my ($newdirlistref,$newlisterror) =
12537: &Apache::lonnet::dirlist($currdir,$docudom,
12538: $docuname,1);
12539: my (%is_dir,%changes,@newitems);
12540: my $dirptr = 16384;
12541: if (ref($newdirlistref) eq 'ARRAY') {
12542: foreach my $dir_line (@{$newdirlistref}) {
12543: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12544: unless (($item =~ /^\.+$/) || ($item eq $file) ||
12545: ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
12546: push(@newitems,$item);
12547: if ($dirptr&$testdir) {
12548: $is_dir{$item} = 1;
12549: }
12550: $changes{$item} = 1;
12551: }
12552: }
12553: }
12554: if (keys(%changes) > 0) {
12555: foreach my $item (sort(@newitems)) {
12556: if ($changes{$item}) {
12557: push(@contents,$item);
12558: }
12559: }
12560: }
12561: if (@contents > 0) {
12562: my $wantform;
12563: unless ($env{'form.autoextract_camtasia'}) {
12564: $wantform = 1;
12565: }
12566: my (%children,%parent,%dirorder,%titles);
12567: my ($count,$datatable) = &get_extracted($docudom,$docuname,
12568: $currdir,\%is_dir,
12569: \%children,\%parent,
12570: \@contents,\%dirorder,
12571: \%titles,$wantform);
12572: if ($datatable ne '') {
12573: $output .= &archive_options_form('decompressed',$datatable,
12574: $count,$hiddenelem);
12575: my $startcount = 6;
12576: $output .= &archive_javascript($startcount,$count,
12577: \%titles,\%children);
12578: }
12579: if ($env{'form.autoextract_camtasia'}) {
12580: my $version = $env{'form.autoextract_camtasia'};
12581: my %displayed;
12582: my $total = 1;
12583: $env{'form.archive_directory'} = [];
12584: foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12585: my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12586: $path =~ s{/$}{};
12587: my $item;
12588: if ($path ne '') {
12589: $item = "$path/$titles{$i}";
12590: } else {
12591: $item = $titles{$i};
12592: }
12593: $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12594: if ($item eq $contents[0]) {
12595: push(@{$env{'form.archive_directory'}},$i);
12596: $env{'form.archive_'.$i} = 'display';
12597: $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12598: $displayed{'folder'} = $i;
12599: } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12600: (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
12601: $env{'form.archive_'.$i} = 'display';
12602: $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12603: $displayed{'web'} = $i;
12604: } else {
12605: if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12606: ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12607: ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12608: push(@{$env{'form.archive_directory'}},$i);
12609: }
12610: $env{'form.archive_'.$i} = 'dependency';
12611: }
12612: $total ++;
12613: }
12614: for (my $i=1; $i<$total; $i++) {
12615: next if ($i == $displayed{'web'});
12616: next if ($i == $displayed{'folder'});
12617: $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12618: }
12619: $env{'form.phase'} = 'decompress_cleanup';
12620: $env{'form.archivedelete'} = 1;
12621: $env{'form.archive_count'} = $total-1;
12622: $output .=
12623: &process_extracted_files('coursedocs',$docudom,
12624: $docuname,$destination,
12625: $dir_root,$hiddenelem);
12626: }
12627: } else {
12628: $warning = &mt('No new items extracted from archive file.');
12629: }
12630: } else {
12631: $output = $display;
12632: $error = &mt('An error occurred during extraction from the archive file.');
12633: }
12634: }
12635: }
12636: }
12637: if ($error) {
12638: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12639: $error.'</p>'."\n";
12640: }
12641: if ($warning) {
12642: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12643: }
12644: return $output;
12645: }
12646:
12647: sub get_extracted {
12648: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12649: $titles,$wantform) = @_;
12650: my $count = 0;
12651: my $depth = 0;
12652: my $datatable;
12653: my @hierarchy;
12654: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12655: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12656: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12657: foreach my $item (@{$contents}) {
12658: $count ++;
12659: @{$dirorder->{$count}} = @hierarchy;
12660: $titles->{$count} = $item;
12661: &archive_hierarchy($depth,$count,$parent,$children);
12662: if ($wantform) {
12663: $datatable .= &archive_row($is_dir->{$item},$item,
12664: $currdir,$depth,$count);
12665: }
12666: if ($is_dir->{$item}) {
12667: $depth ++;
12668: push(@hierarchy,$count);
12669: $parent->{$depth} = $count;
12670: $datatable .=
12671: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12672: \$depth,\$count,\@hierarchy,$dirorder,
12673: $children,$parent,$titles,$wantform);
12674: $depth --;
12675: pop(@hierarchy);
12676: }
12677: }
12678: return ($count,$datatable);
12679: }
12680:
12681: sub recurse_extracted_archive {
12682: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12683: $children,$parent,$titles,$wantform) = @_;
12684: my $result='';
12685: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12686: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12687: (ref($dirorder) eq 'HASH')) {
12688: return $result;
12689: }
12690: my $dirptr = 16384;
12691: my ($newdirlistref,$newlisterror) =
12692: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12693: if (ref($newdirlistref) eq 'ARRAY') {
12694: foreach my $dir_line (@{$newdirlistref}) {
12695: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12696: unless ($item =~ /^\.+$/) {
12697: $$count ++;
12698: @{$dirorder->{$$count}} = @{$hierarchy};
12699: $titles->{$$count} = $item;
12700: &archive_hierarchy($$depth,$$count,$parent,$children);
12701:
12702: my $is_dir;
12703: if ($dirptr&$testdir) {
12704: $is_dir = 1;
12705: }
12706: if ($wantform) {
12707: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12708: }
12709: if ($is_dir) {
12710: $$depth ++;
12711: push(@{$hierarchy},$$count);
12712: $parent->{$$depth} = $$count;
12713: $result .=
12714: &recurse_extracted_archive("$currdir/$item",$docudom,
12715: $docuname,$depth,$count,
12716: $hierarchy,$dirorder,$children,
12717: $parent,$titles,$wantform);
12718: $$depth --;
12719: pop(@{$hierarchy});
12720: }
12721: }
12722: }
12723: }
12724: return $result;
12725: }
12726:
12727: sub archive_hierarchy {
12728: my ($depth,$count,$parent,$children) =@_;
12729: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12730: if (exists($parent->{$depth})) {
12731: $children->{$parent->{$depth}} .= $count.':';
12732: }
12733: }
12734: return;
12735: }
12736:
12737: sub archive_row {
12738: my ($is_dir,$item,$currdir,$depth,$count) = @_;
12739: my ($name) = ($item =~ m{([^/]+)$});
12740: my %choices = &Apache::lonlocal::texthash (
12741: 'display' => 'Add as file',
12742: 'dependency' => 'Include as dependency',
12743: 'discard' => 'Discard',
12744: );
12745: if ($is_dir) {
12746: $choices{'display'} = &mt('Add as folder');
12747: }
12748: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12749: my $offset = 0;
12750: foreach my $action ('display','dependency','discard') {
12751: $offset ++;
12752: if ($action ne 'display') {
12753: $offset ++;
12754: }
12755: $output .= '<td><span class="LC_nobreak">'.
12756: '<label><input type="radio" name="archive_'.$count.
12757: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12758: my $text = $choices{$action};
12759: if ($is_dir) {
12760: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12761: if ($action eq 'display') {
12762: $text = &mt('Add as folder');
12763: }
12764: } else {
12765: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12766:
12767: }
12768: $output .= ' /> '.$choices{$action}.'</label></span>';
12769: if ($action eq 'dependency') {
12770: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12771: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '.
12772: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12773: '<option value=""></option>'."\n".
12774: '</select>'."\n".
12775: '</div>';
12776: } elsif ($action eq 'display') {
12777: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12778: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12779: '</div>';
12780: }
12781: $output .= '</td>';
12782: }
12783: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12784: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2);
12785: for (my $i=0; $i<$depth; $i++) {
12786: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12787: }
12788: if ($is_dir) {
12789: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n".
12790: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12791: } else {
12792: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12793: }
12794: $output .= ' '.$name.'</td>'."\n".
12795: &end_data_table_row();
12796: return $output;
12797: }
12798:
12799: sub archive_options_form {
12800: my ($form,$display,$count,$hiddenelem) = @_;
12801: my %lt = &Apache::lonlocal::texthash(
12802: perm => 'Permanently remove archive file?',
12803: hows => 'How should each extracted item be incorporated in the course?',
12804: cont => 'Content actions for all',
12805: addf => 'Add as folder/file',
12806: incd => 'Include as dependency for a displayed file',
12807: disc => 'Discard',
12808: no => 'No',
12809: yes => 'Yes',
12810: save => 'Save',
12811: );
12812: my $output = <<"END";
12813: <form name="$form" method="post" action="">
12814: <p><span class="LC_nobreak">$lt{'perm'}
12815: <label>
12816: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12817: </label>
12818:
12819: <label>
12820: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12821: </span>
12822: </p>
12823: <input type="hidden" name="phase" value="decompress_cleanup" />
12824: <br />$lt{'hows'}
12825: <div class="LC_columnSection">
12826: <fieldset>
12827: <legend>$lt{'cont'}</legend>
12828: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" />
12829: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12830: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12831: </fieldset>
12832: </div>
12833: END
12834: return $output.
12835: &start_data_table()."\n".
12836: $display."\n".
12837: &end_data_table()."\n".
12838: '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12839: $hiddenelem.
12840: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12841: '</form>';
12842: }
12843:
12844: sub archive_javascript {
12845: my ($startcount,$numitems,$titles,$children) = @_;
12846: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12847: my $maintitle = $env{'form.comment'};
12848: my $scripttag = <<START;
12849: <script type="text/javascript">
12850: // <![CDATA[
12851:
12852: function checkAll(form,prefix) {
12853: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$");
12854: for (var i=0; i < form.elements.length; i++) {
12855: var id = form.elements[i].id;
12856: if ((id != '') && (id != undefined)) {
12857: if (idstr.test(id)) {
12858: if (form.elements[i].type == 'radio') {
12859: form.elements[i].checked = true;
12860: var nostart = i-$startcount;
12861: var offset = nostart%7;
12862: var count = (nostart-offset)/7;
12863: dependencyCheck(form,count,offset);
12864: }
12865: }
12866: }
12867: }
12868: }
12869:
12870: function propagateCheck(form,count) {
12871: if (count > 0) {
12872: var startelement = $startcount + ((count-1) * 7);
12873: for (var j=1; j<6; j++) {
12874: if ((j != 2) && (j != 4)) {
12875: var item = startelement + j;
12876: if (form.elements[item].type == 'radio') {
12877: if (form.elements[item].checked) {
12878: containerCheck(form,count,j);
12879: break;
12880: }
12881: }
12882: }
12883: }
12884: }
12885: }
12886:
12887: numitems = $numitems
12888: var titles = new Array(numitems);
12889: var parents = new Array(numitems);
12890: for (var i=0; i<numitems; i++) {
12891: parents[i] = new Array;
12892: }
12893: var maintitle = '$maintitle';
12894:
12895: START
12896:
12897: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12898: my @contents = split(/:/,$children->{$container});
12899: for (my $i=0; $i<@contents; $i ++) {
12900: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12901: }
12902: }
12903:
12904: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12905: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12906: }
12907:
12908: $scripttag .= <<END;
12909:
12910: function containerCheck(form,count,offset) {
12911: if (count > 0) {
12912: dependencyCheck(form,count,offset);
12913: var item = (offset+$startcount)+7*(count-1);
12914: form.elements[item].checked = true;
12915: if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12916: if (parents[count].length > 0) {
12917: for (var j=0; j<parents[count].length; j++) {
12918: containerCheck(form,parents[count][j],offset);
12919: }
12920: }
12921: }
12922: }
12923: }
12924:
12925: function dependencyCheck(form,count,offset) {
12926: if (count > 0) {
12927: var chosen = (offset+$startcount)+7*(count-1);
12928: var depitem = $startcount + ((count-1) * 7) + 4;
12929: var currtype = form.elements[depitem].type;
12930: if (form.elements[chosen].value == 'dependency') {
12931: document.getElementById('arc_depon_'+count).style.display='block';
12932: form.elements[depitem].options.length = 0;
12933: form.elements[depitem].options[0] = new Option('Select','',true,true);
12934: for (var i=1; i<=numitems; i++) {
12935: if (i == count) {
12936: continue;
12937: }
12938: var startelement = $startcount + (i-1) * 7;
12939: for (var j=1; j<6; j++) {
12940: if ((j != 2) && (j!= 4)) {
12941: var item = startelement + j;
12942: if (form.elements[item].type == 'radio') {
12943: if (form.elements[item].checked) {
12944: if (form.elements[item].value == 'display') {
12945: var n = form.elements[depitem].options.length;
12946: form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
12947: }
12948: }
12949: }
12950: }
12951: }
12952: }
12953: } else {
12954: document.getElementById('arc_depon_'+count).style.display='none';
12955: form.elements[depitem].options.length = 0;
12956: form.elements[depitem].options[0] = new Option('Select','',true,true);
12957: }
12958: titleCheck(form,count,offset);
12959: }
12960: }
12961:
12962: function propagateSelect(form,count,offset) {
12963: if (count > 0) {
12964: var item = (1+offset+$startcount)+7*(count-1);
12965: var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
12966: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12967: if (parents[count].length > 0) {
12968: for (var j=0; j<parents[count].length; j++) {
12969: containerSelect(form,parents[count][j],offset,picked);
12970: }
12971: }
12972: }
12973: }
12974: }
12975:
12976: function containerSelect(form,count,offset,picked) {
12977: if (count > 0) {
12978: var item = (offset+$startcount)+7*(count-1);
12979: if (form.elements[item].type == 'radio') {
12980: if (form.elements[item].value == 'dependency') {
12981: if (form.elements[item+1].type == 'select-one') {
12982: for (var i=0; i<form.elements[item+1].options.length; i++) {
12983: if (form.elements[item+1].options[i].value == picked) {
12984: form.elements[item+1].selectedIndex = i;
12985: break;
12986: }
12987: }
12988: }
12989: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12990: if (parents[count].length > 0) {
12991: for (var j=0; j<parents[count].length; j++) {
12992: containerSelect(form,parents[count][j],offset,picked);
12993: }
12994: }
12995: }
12996: }
12997: }
12998: }
12999: }
13000:
13001: function titleCheck(form,count,offset) {
13002: if (count > 0) {
13003: var chosen = (offset+$startcount)+7*(count-1);
13004: var depitem = $startcount + ((count-1) * 7) + 2;
13005: var currtype = form.elements[depitem].type;
13006: if (form.elements[chosen].value == 'display') {
13007: document.getElementById('arc_title_'+count).style.display='block';
13008: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
13009: document.getElementById('archive_title_'+count).value=maintitle;
13010: }
13011: } else {
13012: document.getElementById('arc_title_'+count).style.display='none';
13013: if (currtype == 'text') {
13014: document.getElementById('archive_title_'+count).value='';
13015: }
13016: }
13017: }
13018: return;
13019: }
13020:
13021: // ]]>
13022: </script>
13023: END
13024: return $scripttag;
13025: }
13026:
13027: sub process_extracted_files {
13028: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
13029: my $numitems = $env{'form.archive_count'};
13030: return unless ($numitems);
13031: my @ids=&Apache::lonnet::current_machine_ids();
13032: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
13033: %folders,%containers,%mapinner,%prompttofetch);
13034: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13035: if (grep(/^\Q$docuhome\E$/,@ids)) {
13036: $prefix = &LONCAPA::propath($docudom,$docuname);
13037: $pathtocheck = "$dir_root/$destination";
13038: $dir = $dir_root;
13039: $ishome = 1;
13040: } else {
13041: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
13042: $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
13043: $dir = "$dir_root/$docudom/$docuname";
13044: }
13045: my $currdir = "$dir_root/$destination";
13046: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
13047: if ($env{'form.folderpath'}) {
13048: my @items = split('&',$env{'form.folderpath'});
13049: $folders{'0'} = $items[-2];
13050: if ($env{'form.folderpath'} =~ /\:1$/) {
13051: $containers{'0'}='page';
13052: } else {
13053: $containers{'0'}='sequence';
13054: }
13055: }
13056: my @archdirs = &get_env_multiple('form.archive_directory');
13057: if ($numitems) {
13058: for (my $i=1; $i<=$numitems; $i++) {
13059: my $path = $env{'form.archive_content_'.$i};
13060: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
13061: my $item = $1;
13062: $toplevelitems{$item} = $i;
13063: if (grep(/^\Q$i\E$/,@archdirs)) {
13064: $is_dir{$item} = 1;
13065: }
13066: }
13067: }
13068: }
13069: my ($output,%children,%parent,%titles,%dirorder,$result);
13070: if (keys(%toplevelitems) > 0) {
13071: my @contents = sort(keys(%toplevelitems));
13072: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
13073: \%parent,\@contents,\%dirorder,\%titles);
13074: }
13075: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
13076: if ($numitems) {
13077: for (my $i=1; $i<=$numitems; $i++) {
13078: next if ($env{'form.archive_'.$i} eq 'dependency');
13079: my $path = $env{'form.archive_content_'.$i};
13080: if ($path =~ /^\Q$pathtocheck\E/) {
13081: if ($env{'form.archive_'.$i} eq 'discard') {
13082: if ($prefix ne '' && $path ne '') {
13083: if (-e $prefix.$path) {
13084: if ((@archdirs > 0) &&
13085: (grep(/^\Q$i\E$/,@archdirs))) {
13086: $todeletedir{$prefix.$path} = 1;
13087: } else {
13088: $todelete{$prefix.$path} = 1;
13089: }
13090: }
13091: }
13092: } elsif ($env{'form.archive_'.$i} eq 'display') {
13093: my ($docstitle,$title,$url,$outer);
13094: ($title) = ($path =~ m{/([^/]+)$});
13095: $docstitle = $env{'form.archive_title_'.$i};
13096: if ($docstitle eq '') {
13097: $docstitle = $title;
13098: }
13099: $outer = 0;
13100: if (ref($dirorder{$i}) eq 'ARRAY') {
13101: if (@{$dirorder{$i}} > 0) {
13102: foreach my $item (reverse(@{$dirorder{$i}})) {
13103: if ($env{'form.archive_'.$item} eq 'display') {
13104: $outer = $item;
13105: last;
13106: }
13107: }
13108: }
13109: }
13110: my ($errtext,$fatal) =
13111: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
13112: '/'.$folders{$outer}.'.'.
13113: $containers{$outer});
13114: next if ($fatal);
13115: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
13116: if ($context eq 'coursedocs') {
13117: $mapinner{$i} = time;
13118: $folders{$i} = 'default_'.$mapinner{$i};
13119: $containers{$i} = 'sequence';
13120: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13121: $folders{$i}.'.'.$containers{$i};
13122: my $newidx = &LONCAPA::map::getresidx();
13123: $LONCAPA::map::resources[$newidx]=
13124: $docstitle.':'.$url.':false:normal:res';
13125: push(@LONCAPA::map::order,$newidx);
13126: my ($outtext,$errtext) =
13127: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13128: $docuname.'/'.$folders{$outer}.
13129: '.'.$containers{$outer},1,1);
13130: $newseqid{$i} = $newidx;
13131: unless ($errtext) {
13132: $result .= '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
13133: }
13134: }
13135: } else {
13136: if ($context eq 'coursedocs') {
13137: my $newidx=&LONCAPA::map::getresidx();
13138: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13139: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
13140: $title;
13141: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
13142: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
13143: }
13144: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13145: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
13146: }
13147: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13148: system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
13149: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
13150: unless ($ishome) {
13151: my $fetch = "$newdest{$i}/$title";
13152: $fetch =~ s/^\Q$prefix$dir\E//;
13153: $prompttofetch{$fetch} = 1;
13154: }
13155: }
13156: $LONCAPA::map::resources[$newidx]=
13157: $docstitle.':'.$url.':false:normal:res';
13158: push(@LONCAPA::map::order, $newidx);
13159: my ($outtext,$errtext)=
13160: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13161: $docuname.'/'.$folders{$outer}.
13162: '.'.$containers{$outer},1,1);
13163: unless ($errtext) {
13164: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
13165: $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
13166: }
13167: }
13168: }
13169: }
13170: }
13171: } else {
13172: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
13173: }
13174: }
13175: for (my $i=1; $i<=$numitems; $i++) {
13176: next unless ($env{'form.archive_'.$i} eq 'dependency');
13177: my $path = $env{'form.archive_content_'.$i};
13178: if ($path =~ /^\Q$pathtocheck\E/) {
13179: my ($title) = ($path =~ m{/([^/]+)$});
13180: $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13181: if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13182: if (ref($dirorder{$i}) eq 'ARRAY') {
13183: my ($itemidx,$fullpath,$relpath);
13184: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13185: my $container = $dirorder{$referrer{$i}}->[-1];
13186: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13187: if ($dirorder{$i}->[$j] eq $container) {
13188: $itemidx = $j;
13189: }
13190: }
13191: }
13192: if ($itemidx eq '') {
13193: $itemidx = 0;
13194: }
13195: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13196: if ($mapinner{$referrer{$i}}) {
13197: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13198: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13199: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13200: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13201: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13202: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13203: if (!-e $fullpath) {
13204: mkdir($fullpath,0755);
13205: }
13206: }
13207: } else {
13208: last;
13209: }
13210: }
13211: }
13212: } elsif ($newdest{$referrer{$i}}) {
13213: $fullpath = $newdest{$referrer{$i}};
13214: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13215: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
13216: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
13217: last;
13218: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13219: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13220: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13221: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13222: if (!-e $fullpath) {
13223: mkdir($fullpath,0755);
13224: }
13225: }
13226: } else {
13227: last;
13228: }
13229: }
13230: }
13231: if ($fullpath ne '') {
13232: if (-e "$prefix$path") {
13233: system("mv $prefix$path $fullpath/$title");
13234: }
13235: if (-e "$fullpath/$title") {
13236: my $showpath;
13237: if ($relpath ne '') {
13238: $showpath = "$relpath/$title";
13239: } else {
13240: $showpath = "/$title";
13241: }
13242: $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
13243: }
13244: unless ($ishome) {
13245: my $fetch = "$fullpath/$title";
13246: $fetch =~ s/^\Q$prefix$dir\E//;
13247: $prompttofetch{$fetch} = 1;
13248: }
13249: }
13250: }
13251: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
13252: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
13253: $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
13254: }
13255: } else {
13256: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
13257: }
13258: }
13259: if (keys(%todelete)) {
13260: foreach my $key (keys(%todelete)) {
13261: unlink($key);
13262: }
13263: }
13264: if (keys(%todeletedir)) {
13265: foreach my $key (keys(%todeletedir)) {
13266: rmdir($key);
13267: }
13268: }
13269: foreach my $dir (sort(keys(%is_dir))) {
13270: if (($pathtocheck ne '') && ($dir ne '')) {
13271: &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
13272: }
13273: }
13274: if ($result ne '') {
13275: $output .= '<ul>'."\n".
13276: $result."\n".
13277: '</ul>';
13278: }
13279: unless ($ishome) {
13280: my $replicationfail;
13281: foreach my $item (keys(%prompttofetch)) {
13282: my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13283: unless ($fetchresult eq 'ok') {
13284: $replicationfail .= '<li>'.$item.'</li>'."\n";
13285: }
13286: }
13287: if ($replicationfail) {
13288: $output .= '<p class="LC_error">'.
13289: &mt('Course home server failed to retrieve:').'<ul>'.
13290: $replicationfail.
13291: '</ul></p>';
13292: }
13293: }
13294: } else {
13295: $warning = &mt('No items found in archive.');
13296: }
13297: if ($error) {
13298: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13299: $error.'</p>'."\n";
13300: }
13301: if ($warning) {
13302: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13303: }
13304: return $output;
13305: }
13306:
13307: sub cleanup_empty_dirs {
13308: my ($path) = @_;
13309: if (($path ne '') && (-d $path)) {
13310: if (opendir(my $dirh,$path)) {
13311: my @dircontents = grep(!/^\./,readdir($dirh));
13312: my $numitems = 0;
13313: foreach my $item (@dircontents) {
13314: if (-d "$path/$item") {
13315: &cleanup_empty_dirs("$path/$item");
13316: if (-e "$path/$item") {
13317: $numitems ++;
13318: }
13319: } else {
13320: $numitems ++;
13321: }
13322: }
13323: if ($numitems == 0) {
13324: rmdir($path);
13325: }
13326: closedir($dirh);
13327: }
13328: }
13329: return;
13330: }
13331:
13332: =pod
13333:
13334: =item * &get_folder_hierarchy()
13335:
13336: Provides hierarchy of names of folders/sub-folders containing the current
13337: item,
13338:
13339: Inputs: 3
13340: - $navmap - navmaps object
13341:
13342: - $map - url for map (either the trigger itself, or map containing
13343: the resource, which is the trigger).
13344:
13345: - $showitem - 1 => show title for map itself; 0 => do not show.
13346:
13347: Outputs: 1 @pathitems - array of folder/subfolder names.
13348:
13349: =cut
13350:
13351: sub get_folder_hierarchy {
13352: my ($navmap,$map,$showitem) = @_;
13353: my @pathitems;
13354: if (ref($navmap)) {
13355: my $mapres = $navmap->getResourceByUrl($map);
13356: if (ref($mapres)) {
13357: my $pcslist = $mapres->map_hierarchy();
13358: if ($pcslist ne '') {
13359: my @pcs = split(/,/,$pcslist);
13360: foreach my $pc (@pcs) {
13361: if ($pc == 1) {
13362: push(@pathitems,&mt('Main Content'));
13363: } else {
13364: my $res = $navmap->getByMapPc($pc);
13365: if (ref($res)) {
13366: my $title = $res->compTitle();
13367: $title =~ s/\W+/_/g;
13368: if ($title ne '') {
13369: push(@pathitems,$title);
13370: }
13371: }
13372: }
13373: }
13374: }
13375: if ($showitem) {
13376: if ($mapres->{ID} eq '0.0') {
13377: push(@pathitems,&mt('Main Content'));
13378: } else {
13379: my $maptitle = $mapres->compTitle();
13380: $maptitle =~ s/\W+/_/g;
13381: if ($maptitle ne '') {
13382: push(@pathitems,$maptitle);
13383: }
13384: }
13385: }
13386: }
13387: }
13388: return @pathitems;
13389: }
13390:
13391: =pod
13392:
13393: =item * &get_turnedin_filepath()
13394:
13395: Determines path in a user's portfolio file for storage of files uploaded
13396: to a specific essayresponse or dropbox item.
13397:
13398: Inputs: 3 required + 1 optional.
13399: $symb is symb for resource, $uname and $udom are for current user (required).
13400: $caller is optional (can be "submission", if routine is called when storing
13401: an upoaded file when "Submit Answer" button was pressed).
13402:
13403: Returns array containing $path and $multiresp.
13404: $path is path in portfolio. $multiresp is 1 if this resource contains more
13405: than one file upload item. Callers of routine should append partid as a
13406: subdirectory to $path in cases where $multiresp is 1.
13407:
13408: Called by: homework/essayresponse.pm and homework/structuretags.pm
13409:
13410: =cut
13411:
13412: sub get_turnedin_filepath {
13413: my ($symb,$uname,$udom,$caller) = @_;
13414: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13415: my $turnindir;
13416: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13417: $turnindir = $userhash{'turnindir'};
13418: my ($path,$multiresp);
13419: if ($turnindir eq '') {
13420: if ($caller eq 'submission') {
13421: $turnindir = &mt('turned in');
13422: $turnindir =~ s/\W+/_/g;
13423: my %newhash = (
13424: 'turnindir' => $turnindir,
13425: );
13426: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13427: }
13428: }
13429: if ($turnindir ne '') {
13430: $path = '/'.$turnindir.'/';
13431: my ($multipart,$turnin,@pathitems);
13432: my $navmap = Apache::lonnavmaps::navmap->new();
13433: if (defined($navmap)) {
13434: my $mapres = $navmap->getResourceByUrl($map);
13435: if (ref($mapres)) {
13436: my $pcslist = $mapres->map_hierarchy();
13437: if ($pcslist ne '') {
13438: foreach my $pc (split(/,/,$pcslist)) {
13439: my $res = $navmap->getByMapPc($pc);
13440: if (ref($res)) {
13441: my $title = $res->compTitle();
13442: $title =~ s/\W+/_/g;
13443: if ($title ne '') {
13444: if (($pc > 1) && (length($title) > 12)) {
13445: $title = substr($title,0,12);
13446: }
13447: push(@pathitems,$title);
13448: }
13449: }
13450: }
13451: }
13452: my $maptitle = $mapres->compTitle();
13453: $maptitle =~ s/\W+/_/g;
13454: if ($maptitle ne '') {
13455: if (length($maptitle) > 12) {
13456: $maptitle = substr($maptitle,0,12);
13457: }
13458: push(@pathitems,$maptitle);
13459: }
13460: unless ($env{'request.state'} eq 'construct') {
13461: my $res = $navmap->getBySymb($symb);
13462: if (ref($res)) {
13463: my $partlist = $res->parts();
13464: my $totaluploads = 0;
13465: if (ref($partlist) eq 'ARRAY') {
13466: foreach my $part (@{$partlist}) {
13467: my @types = $res->responseType($part);
13468: my @ids = $res->responseIds($part);
13469: for (my $i=0; $i < scalar(@ids); $i++) {
13470: if ($types[$i] eq 'essay') {
13471: my $partid = $part.'_'.$ids[$i];
13472: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13473: $totaluploads ++;
13474: }
13475: }
13476: }
13477: }
13478: if ($totaluploads > 1) {
13479: $multiresp = 1;
13480: }
13481: }
13482: }
13483: }
13484: } else {
13485: return;
13486: }
13487: } else {
13488: return;
13489: }
13490: my $restitle=&Apache::lonnet::gettitle($symb);
13491: $restitle =~ s/\W+/_/g;
13492: if ($restitle eq '') {
13493: $restitle = ($resurl =~ m{/[^/]+$});
13494: if ($restitle eq '') {
13495: $restitle = time;
13496: }
13497: }
13498: if (length($restitle) > 12) {
13499: $restitle = substr($restitle,0,12);
13500: }
13501: push(@pathitems,$restitle);
13502: $path .= join('/',@pathitems);
13503: }
13504: return ($path,$multiresp);
13505: }
13506:
13507: =pod
13508:
13509: =back
13510:
13511: =head1 CSV Upload/Handling functions
13512:
13513: =over 4
13514:
13515: =item * &upfile_store($r)
13516:
13517: Store uploaded file, $r should be the HTTP Request object,
13518: needs $env{'form.upfile'}
13519: returns $datatoken to be put into hidden field
13520:
13521: =cut
13522:
13523: sub upfile_store {
13524: my $r=shift;
13525: $env{'form.upfile'}=~s/\r/\n/gs;
13526: $env{'form.upfile'}=~s/\f/\n/gs;
13527: $env{'form.upfile'}=~s/\n+/\n/gs;
13528: $env{'form.upfile'}=~s/\n+$//gs;
13529:
13530: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
13531: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
13532: {
13533: my $datafile = $r->dir_config('lonDaemons').
13534: '/tmp/'.$datatoken.'.tmp';
13535: if ( open(my $fh,">$datafile") ) {
13536: print $fh $env{'form.upfile'};
13537: close($fh);
13538: }
13539: }
13540: return $datatoken;
13541: }
13542:
13543: =pod
13544:
13545: =item * &load_tmp_file($r)
13546:
13547: Load uploaded file from tmp, $r should be the HTTP Request object,
13548: needs $env{'form.datatoken'},
13549: sets $env{'form.upfile'} to the contents of the file
13550:
13551: =cut
13552:
13553: sub load_tmp_file {
13554: my $r=shift;
13555: my @studentdata=();
13556: {
13557: my $studentfile = $r->dir_config('lonDaemons').
13558: '/tmp/'.$env{'form.datatoken'}.'.tmp';
13559: if ( open(my $fh,"<$studentfile") ) {
13560: @studentdata=<$fh>;
13561: close($fh);
13562: }
13563: }
13564: $env{'form.upfile'}=join('',@studentdata);
13565: }
13566:
13567: =pod
13568:
13569: =item * &upfile_record_sep()
13570:
13571: Separate uploaded file into records
13572: returns array of records,
13573: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13574:
13575: =cut
13576:
13577: sub upfile_record_sep {
13578: if ($env{'form.upfiletype'} eq 'xml') {
13579: } else {
13580: my @records;
13581: foreach my $line (split(/\n/,$env{'form.upfile'})) {
13582: if ($line=~/^\s*$/) { next; }
13583: push(@records,$line);
13584: }
13585: return @records;
13586: }
13587: }
13588:
13589: =pod
13590:
13591: =item * &record_sep($record)
13592:
13593: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13594:
13595: =cut
13596:
13597: sub takeleft {
13598: my $index=shift;
13599: return substr('0000'.$index,-4,4);
13600: }
13601:
13602: sub record_sep {
13603: my $record=shift;
13604: my %components=();
13605: if ($env{'form.upfiletype'} eq 'xml') {
13606: } elsif ($env{'form.upfiletype'} eq 'space') {
13607: my $i=0;
13608: foreach my $field (split(/\s+/,$record)) {
13609: $field=~s/^(\"|\')//;
13610: $field=~s/(\"|\')$//;
13611: $components{&takeleft($i)}=$field;
13612: $i++;
13613: }
13614: } elsif ($env{'form.upfiletype'} eq 'tab') {
13615: my $i=0;
13616: foreach my $field (split(/\t/,$record)) {
13617: $field=~s/^(\"|\')//;
13618: $field=~s/(\"|\')$//;
13619: $components{&takeleft($i)}=$field;
13620: $i++;
13621: }
13622: } else {
13623: my $separator=',';
13624: if ($env{'form.upfiletype'} eq 'semisv') {
13625: $separator=';';
13626: }
13627: my $i=0;
13628: # the character we are looking for to indicate the end of a quote or a record
13629: my $looking_for=$separator;
13630: # do not add the characters to the fields
13631: my $ignore=0;
13632: # we just encountered a separator (or the beginning of the record)
13633: my $just_found_separator=1;
13634: # store the field we are working on here
13635: my $field='';
13636: # work our way through all characters in record
13637: foreach my $character ($record=~/(.)/g) {
13638: if ($character eq $looking_for) {
13639: if ($character ne $separator) {
13640: # Found the end of a quote, again looking for separator
13641: $looking_for=$separator;
13642: $ignore=1;
13643: } else {
13644: # Found a separator, store away what we got
13645: $components{&takeleft($i)}=$field;
13646: $i++;
13647: $just_found_separator=1;
13648: $ignore=0;
13649: $field='';
13650: }
13651: next;
13652: }
13653: # single or double quotation marks after a separator indicate beginning of a quote
13654: # we are now looking for the end of the quote and need to ignore separators
13655: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
13656: $looking_for=$character;
13657: next;
13658: }
13659: # ignore would be true after we reached the end of a quote
13660: if ($ignore) { next; }
13661: if (($just_found_separator) && ($character=~/\s/)) { next; }
13662: $field.=$character;
13663: $just_found_separator=0;
13664: }
13665: # catch the very last entry, since we never encountered the separator
13666: $components{&takeleft($i)}=$field;
13667: }
13668: return %components;
13669: }
13670:
13671: ######################################################
13672: ######################################################
13673:
13674: =pod
13675:
13676: =item * &upfile_select_html()
13677:
13678: Return HTML code to select a file from the users machine and specify
13679: the file type.
13680:
13681: =cut
13682:
13683: ######################################################
13684: ######################################################
13685: sub upfile_select_html {
13686: my %Types = (
13687: csv => &mt('CSV (comma separated values, spreadsheet)'),
13688: semisv => &mt('Semicolon separated values'),
13689: space => &mt('Space separated'),
13690: tab => &mt('Tabulator separated'),
13691: # xml => &mt('HTML/XML'),
13692: );
13693: my $Str = '<input type="file" name="upfile" size="50" />'.
13694: '<br />'.&mt('Type').': <select name="upfiletype">';
13695: foreach my $type (sort(keys(%Types))) {
13696: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13697: }
13698: $Str .= "</select>\n";
13699: return $Str;
13700: }
13701:
13702: sub get_samples {
13703: my ($records,$toget) = @_;
13704: my @samples=({});
13705: my $got=0;
13706: foreach my $rec (@$records) {
13707: my %temp = &record_sep($rec);
13708: if (! grep(/\S/, values(%temp))) { next; }
13709: if (%temp) {
13710: $samples[$got]=\%temp;
13711: $got++;
13712: if ($got == $toget) { last; }
13713: }
13714: }
13715: return \@samples;
13716: }
13717:
13718: ######################################################
13719: ######################################################
13720:
13721: =pod
13722:
13723: =item * &csv_print_samples($r,$records)
13724:
13725: Prints a table of sample values from each column uploaded $r is an
13726: Apache Request ref, $records is an arrayref from
13727: &Apache::loncommon::upfile_record_sep
13728:
13729: =cut
13730:
13731: ######################################################
13732: ######################################################
13733: sub csv_print_samples {
13734: my ($r,$records) = @_;
13735: my $samples = &get_samples($records,5);
13736:
13737: $r->print(&mt('Samples').'<br />'.&start_data_table().
13738: &start_data_table_header_row());
13739: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13740: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13741: $r->print(&end_data_table_header_row());
13742: foreach my $hash (@$samples) {
13743: $r->print(&start_data_table_row());
13744: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13745: $r->print('<td>');
13746: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13747: $r->print('</td>');
13748: }
13749: $r->print(&end_data_table_row());
13750: }
13751: $r->print(&end_data_table().'<br />'."\n");
13752: }
13753:
13754: ######################################################
13755: ######################################################
13756:
13757: =pod
13758:
13759: =item * &csv_print_select_table($r,$records,$d)
13760:
13761: Prints a table to create associations between values and table columns.
13762:
13763: $r is an Apache Request ref,
13764: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13765: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13766:
13767: =cut
13768:
13769: ######################################################
13770: ######################################################
13771: sub csv_print_select_table {
13772: my ($r,$records,$d) = @_;
13773: my $i=0;
13774: my $samples = &get_samples($records,1);
13775: $r->print(&mt('Associate columns with student attributes.')."\n".
13776: &start_data_table().&start_data_table_header_row().
13777: '<th>'.&mt('Attribute').'</th>'.
13778: '<th>'.&mt('Column').'</th>'.
13779: &end_data_table_header_row()."\n");
13780: foreach my $array_ref (@$d) {
13781: my ($value,$display,$defaultcol)=@{ $array_ref };
13782: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
13783:
13784: $r->print('<td><select name="f'.$i.'"'.
13785: ' onchange="javascript:flip(this.form,'.$i.');">');
13786: $r->print('<option value="none"></option>');
13787: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13788: $r->print('<option value="'.$sample.'"'.
13789: ($sample eq $defaultcol ? ' selected="selected" ' : '').
13790: '>'.&mt('Column [_1]',($sample+1)).'</option>');
13791: }
13792: $r->print('</select></td>'.&end_data_table_row()."\n");
13793: $i++;
13794: }
13795: $r->print(&end_data_table());
13796: $i--;
13797: return $i;
13798: }
13799:
13800: ######################################################
13801: ######################################################
13802:
13803: =pod
13804:
13805: =item * &csv_samples_select_table($r,$records,$d)
13806:
13807: Prints a table of sample values from the upload and can make associate samples to internal names.
13808:
13809: $r is an Apache Request ref,
13810: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13811: $d is an array of 2 element arrays (internal name, displayed name)
13812:
13813: =cut
13814:
13815: ######################################################
13816: ######################################################
13817: sub csv_samples_select_table {
13818: my ($r,$records,$d) = @_;
13819: my $i=0;
13820: #
13821: my $max_samples = 5;
13822: my $samples = &get_samples($records,$max_samples);
13823: $r->print(&start_data_table().
13824: &start_data_table_header_row().'<th>'.
13825: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13826: &end_data_table_header_row());
13827:
13828: foreach my $key (sort(keys(%{ $samples->[0] }))) {
13829: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13830: ' onchange="javascript:flip(this.form,'.$i.');">');
13831: foreach my $option (@$d) {
13832: my ($value,$display,$defaultcol)=@{ $option };
13833: $r->print('<option value="'.$value.'"'.
13834: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13835: $display.'</option>');
13836: }
13837: $r->print('</select></td><td>');
13838: foreach my $line (0..($max_samples-1)) {
13839: if (defined($samples->[$line]{$key})) {
13840: $r->print($samples->[$line]{$key}."<br />\n");
13841: }
13842: }
13843: $r->print('</td>'.&end_data_table_row());
13844: $i++;
13845: }
13846: $r->print(&end_data_table());
13847: $i--;
13848: return($i);
13849: }
13850:
13851: ######################################################
13852: ######################################################
13853:
13854: =pod
13855:
13856: =item * &clean_excel_name($name)
13857:
13858: Returns a replacement for $name which does not contain any illegal characters.
13859:
13860: =cut
13861:
13862: ######################################################
13863: ######################################################
13864: sub clean_excel_name {
13865: my ($name) = @_;
13866: $name =~ s/[:\*\?\/\\]//g;
13867: if (length($name) > 31) {
13868: $name = substr($name,0,31);
13869: }
13870: return $name;
13871: }
13872:
13873: =pod
13874:
13875: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13876:
13877: Returns either 1 or undef
13878:
13879: 1 if the part is to be hidden, undef if it is to be shown
13880:
13881: Arguments are:
13882:
13883: $id the id of the part to be checked
13884: $symb, optional the symb of the resource to check
13885: $udom, optional the domain of the user to check for
13886: $uname, optional the username of the user to check for
13887:
13888: =cut
13889:
13890: sub check_if_partid_hidden {
13891: my ($id,$symb,$udom,$uname) = @_;
13892: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13893: $symb,$udom,$uname);
13894: my $truth=1;
13895: #if the string starts with !, then the list is the list to show not hide
13896: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13897: my @hiddenlist=split(/,/,$hiddenparts);
13898: foreach my $checkid (@hiddenlist) {
13899: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13900: }
13901: return !$truth;
13902: }
13903:
13904:
13905: ############################################################
13906: ############################################################
13907:
13908: =pod
13909:
13910: =back
13911:
13912: =head1 cgi-bin script and graphing routines
13913:
13914: =over 4
13915:
13916: =item * &get_cgi_id()
13917:
13918: Inputs: none
13919:
13920: Returns an id which can be used to pass environment variables
13921: to various cgi-bin scripts. These environment variables will
13922: be removed from the users environment after a given time by
13923: the routine &Apache::lonnet::transfer_profile_to_env.
13924:
13925: =cut
13926:
13927: ############################################################
13928: ############################################################
13929: my $uniq=0;
13930: sub get_cgi_id {
13931: $uniq=($uniq+1)%100000;
13932: return (time.'_'.$$.'_'.$uniq);
13933: }
13934:
13935: ############################################################
13936: ############################################################
13937:
13938: =pod
13939:
13940: =item * &DrawBarGraph()
13941:
13942: Facilitates the plotting of data in a (stacked) bar graph.
13943: Puts plot definition data into the users environment in order for
13944: graph.png to plot it. Returns an <img> tag for the plot.
13945: The bars on the plot are labeled '1','2',...,'n'.
13946:
13947: Inputs:
13948:
13949: =over 4
13950:
13951: =item $Title: string, the title of the plot
13952:
13953: =item $xlabel: string, text describing the X-axis of the plot
13954:
13955: =item $ylabel: string, text describing the Y-axis of the plot
13956:
13957: =item $Max: scalar, the maximum Y value to use in the plot
13958: If $Max is < any data point, the graph will not be rendered.
13959:
13960: =item $colors: array ref holding the colors to be used for the data sets when
13961: they are plotted. If undefined, default values will be used.
13962:
13963: =item $labels: array ref holding the labels to use on the x-axis for the bars.
13964:
13965: =item @Values: An array of array references. Each array reference holds data
13966: to be plotted in a stacked bar chart.
13967:
13968: =item If the final element of @Values is a hash reference the key/value
13969: pairs will be added to the graph definition.
13970:
13971: =back
13972:
13973: Returns:
13974:
13975: An <img> tag which references graph.png and the appropriate identifying
13976: information for the plot.
13977:
13978: =cut
13979:
13980: ############################################################
13981: ############################################################
13982: sub DrawBarGraph {
13983: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
13984: #
13985: if (! defined($colors)) {
13986: $colors = ['#33ff00',
13987: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
13988: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
13989: ];
13990: }
13991: my $extra_settings = {};
13992: if (ref($Values[-1]) eq 'HASH') {
13993: $extra_settings = pop(@Values);
13994: }
13995: #
13996: my $identifier = &get_cgi_id();
13997: my $id = 'cgi.'.$identifier;
13998: if (! @Values || ref($Values[0]) ne 'ARRAY') {
13999: return '';
14000: }
14001: #
14002: my @Labels;
14003: if (defined($labels)) {
14004: @Labels = @$labels;
14005: } else {
14006: for (my $i=0;$i<@{$Values[0]};$i++) {
14007: push (@Labels,$i+1);
14008: }
14009: }
14010: #
14011: my $NumBars = scalar(@{$Values[0]});
14012: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
14013: my %ValuesHash;
14014: my $NumSets=1;
14015: foreach my $array (@Values) {
14016: next if (! ref($array));
14017: $ValuesHash{$id.'.data.'.$NumSets++} =
14018: join(',',@$array);
14019: }
14020: #
14021: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
14022: if ($NumBars < 3) {
14023: $width = 120+$NumBars*32;
14024: $xskip = 1;
14025: $bar_width = 30;
14026: } elsif ($NumBars < 5) {
14027: $width = 120+$NumBars*20;
14028: $xskip = 1;
14029: $bar_width = 20;
14030: } elsif ($NumBars < 10) {
14031: $width = 120+$NumBars*15;
14032: $xskip = 1;
14033: $bar_width = 15;
14034: } elsif ($NumBars <= 25) {
14035: $width = 120+$NumBars*11;
14036: $xskip = 5;
14037: $bar_width = 8;
14038: } elsif ($NumBars <= 50) {
14039: $width = 120+$NumBars*8;
14040: $xskip = 5;
14041: $bar_width = 4;
14042: } else {
14043: $width = 120+$NumBars*8;
14044: $xskip = 5;
14045: $bar_width = 4;
14046: }
14047: #
14048: $Max = 1 if ($Max < 1);
14049: if ( int($Max) < $Max ) {
14050: $Max++;
14051: $Max = int($Max);
14052: }
14053: $Title = '' if (! defined($Title));
14054: $xlabel = '' if (! defined($xlabel));
14055: $ylabel = '' if (! defined($ylabel));
14056: $ValuesHash{$id.'.title'} = &escape($Title);
14057: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
14058: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
14059: $ValuesHash{$id.'.y_max_value'} = $Max;
14060: $ValuesHash{$id.'.NumBars'} = $NumBars;
14061: $ValuesHash{$id.'.NumSets'} = $NumSets;
14062: $ValuesHash{$id.'.PlotType'} = 'bar';
14063: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
14064: $ValuesHash{$id.'.height'} = $height;
14065: $ValuesHash{$id.'.width'} = $width;
14066: $ValuesHash{$id.'.xskip'} = $xskip;
14067: $ValuesHash{$id.'.bar_width'} = $bar_width;
14068: $ValuesHash{$id.'.labels'} = join(',',@Labels);
14069: #
14070: # Deal with other parameters
14071: while (my ($key,$value) = each(%$extra_settings)) {
14072: $ValuesHash{$id.'.'.$key} = $value;
14073: }
14074: #
14075: &Apache::lonnet::appenv(\%ValuesHash);
14076: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14077: }
14078:
14079: ############################################################
14080: ############################################################
14081:
14082: =pod
14083:
14084: =item * &DrawXYGraph()
14085:
14086: Facilitates the plotting of data in an XY graph.
14087: Puts plot definition data into the users environment in order for
14088: graph.png to plot it. Returns an <img> tag for the plot.
14089:
14090: Inputs:
14091:
14092: =over 4
14093:
14094: =item $Title: string, the title of the plot
14095:
14096: =item $xlabel: string, text describing the X-axis of the plot
14097:
14098: =item $ylabel: string, text describing the Y-axis of the plot
14099:
14100: =item $Max: scalar, the maximum Y value to use in the plot
14101: If $Max is < any data point, the graph will not be rendered.
14102:
14103: =item $colors: Array ref containing the hex color codes for the data to be
14104: plotted in. If undefined, default values will be used.
14105:
14106: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14107:
14108: =item $Ydata: Array ref containing Array refs.
14109: Each of the contained arrays will be plotted as a separate curve.
14110:
14111: =item %Values: hash indicating or overriding any default values which are
14112: passed to graph.png.
14113: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14114:
14115: =back
14116:
14117: Returns:
14118:
14119: An <img> tag which references graph.png and the appropriate identifying
14120: information for the plot.
14121:
14122: =cut
14123:
14124: ############################################################
14125: ############################################################
14126: sub DrawXYGraph {
14127: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
14128: #
14129: # Create the identifier for the graph
14130: my $identifier = &get_cgi_id();
14131: my $id = 'cgi.'.$identifier;
14132: #
14133: $Title = '' if (! defined($Title));
14134: $xlabel = '' if (! defined($xlabel));
14135: $ylabel = '' if (! defined($ylabel));
14136: my %ValuesHash =
14137: (
14138: $id.'.title' => &escape($Title),
14139: $id.'.xlabel' => &escape($xlabel),
14140: $id.'.ylabel' => &escape($ylabel),
14141: $id.'.y_max_value'=> $Max,
14142: $id.'.labels' => join(',',@$Xlabels),
14143: $id.'.PlotType' => 'XY',
14144: );
14145: #
14146: if (defined($colors) && ref($colors) eq 'ARRAY') {
14147: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
14148: }
14149: #
14150: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
14151: return '';
14152: }
14153: my $NumSets=1;
14154: foreach my $array (@{$Ydata}){
14155: next if (! ref($array));
14156: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14157: }
14158: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14159: #
14160: # Deal with other parameters
14161: while (my ($key,$value) = each(%Values)) {
14162: $ValuesHash{$id.'.'.$key} = $value;
14163: }
14164: #
14165: &Apache::lonnet::appenv(\%ValuesHash);
14166: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14167: }
14168:
14169: ############################################################
14170: ############################################################
14171:
14172: =pod
14173:
14174: =item * &DrawXYYGraph()
14175:
14176: Facilitates the plotting of data in an XY graph with two Y axes.
14177: Puts plot definition data into the users environment in order for
14178: graph.png to plot it. Returns an <img> tag for the plot.
14179:
14180: Inputs:
14181:
14182: =over 4
14183:
14184: =item $Title: string, the title of the plot
14185:
14186: =item $xlabel: string, text describing the X-axis of the plot
14187:
14188: =item $ylabel: string, text describing the Y-axis of the plot
14189:
14190: =item $colors: Array ref containing the hex color codes for the data to be
14191: plotted in. If undefined, default values will be used.
14192:
14193: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14194:
14195: =item $Ydata1: The first data set
14196:
14197: =item $Min1: The minimum value of the left Y-axis
14198:
14199: =item $Max1: The maximum value of the left Y-axis
14200:
14201: =item $Ydata2: The second data set
14202:
14203: =item $Min2: The minimum value of the right Y-axis
14204:
14205: =item $Max2: The maximum value of the left Y-axis
14206:
14207: =item %Values: hash indicating or overriding any default values which are
14208: passed to graph.png.
14209: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14210:
14211: =back
14212:
14213: Returns:
14214:
14215: An <img> tag which references graph.png and the appropriate identifying
14216: information for the plot.
14217:
14218: =cut
14219:
14220: ############################################################
14221: ############################################################
14222: sub DrawXYYGraph {
14223: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
14224: $Ydata2,$Min2,$Max2,%Values)=@_;
14225: #
14226: # Create the identifier for the graph
14227: my $identifier = &get_cgi_id();
14228: my $id = 'cgi.'.$identifier;
14229: #
14230: $Title = '' if (! defined($Title));
14231: $xlabel = '' if (! defined($xlabel));
14232: $ylabel = '' if (! defined($ylabel));
14233: my %ValuesHash =
14234: (
14235: $id.'.title' => &escape($Title),
14236: $id.'.xlabel' => &escape($xlabel),
14237: $id.'.ylabel' => &escape($ylabel),
14238: $id.'.labels' => join(',',@$Xlabels),
14239: $id.'.PlotType' => 'XY',
14240: $id.'.NumSets' => 2,
14241: $id.'.two_axes' => 1,
14242: $id.'.y1_max_value' => $Max1,
14243: $id.'.y1_min_value' => $Min1,
14244: $id.'.y2_max_value' => $Max2,
14245: $id.'.y2_min_value' => $Min2,
14246: );
14247: #
14248: if (defined($colors) && ref($colors) eq 'ARRAY') {
14249: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
14250: }
14251: #
14252: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
14253: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
14254: return '';
14255: }
14256: my $NumSets=1;
14257: foreach my $array ($Ydata1,$Ydata2){
14258: next if (! ref($array));
14259: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14260: }
14261: #
14262: # Deal with other parameters
14263: while (my ($key,$value) = each(%Values)) {
14264: $ValuesHash{$id.'.'.$key} = $value;
14265: }
14266: #
14267: &Apache::lonnet::appenv(\%ValuesHash);
14268: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14269: }
14270:
14271: ############################################################
14272: ############################################################
14273:
14274: =pod
14275:
14276: =back
14277:
14278: =head1 Statistics helper routines?
14279:
14280: Bad place for them but what the hell.
14281:
14282: =over 4
14283:
14284: =item * &chartlink()
14285:
14286: Returns a link to the chart for a specific student.
14287:
14288: Inputs:
14289:
14290: =over 4
14291:
14292: =item $linktext: The text of the link
14293:
14294: =item $sname: The students username
14295:
14296: =item $sdomain: The students domain
14297:
14298: =back
14299:
14300: =back
14301:
14302: =cut
14303:
14304: ############################################################
14305: ############################################################
14306: sub chartlink {
14307: my ($linktext, $sname, $sdomain) = @_;
14308: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14309: '&SelectedStudent='.&escape($sname.':'.$sdomain).
14310: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
14311: '">'.$linktext.'</a>';
14312: }
14313:
14314: #######################################################
14315: #######################################################
14316:
14317: =pod
14318:
14319: =head1 Course Environment Routines
14320:
14321: =over 4
14322:
14323: =item * &restore_course_settings()
14324:
14325: =item * &store_course_settings()
14326:
14327: Restores/Store indicated form parameters from the course environment.
14328: Will not overwrite existing values of the form parameters.
14329:
14330: Inputs:
14331: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14332:
14333: a hash ref describing the data to be stored. For example:
14334:
14335: %Save_Parameters = ('Status' => 'scalar',
14336: 'chartoutputmode' => 'scalar',
14337: 'chartoutputdata' => 'scalar',
14338: 'Section' => 'array',
14339: 'Group' => 'array',
14340: 'StudentData' => 'array',
14341: 'Maps' => 'array');
14342:
14343: Returns: both routines return nothing
14344:
14345: =back
14346:
14347: =cut
14348:
14349: #######################################################
14350: #######################################################
14351: sub store_course_settings {
14352: return &store_settings($env{'request.course.id'},@_);
14353: }
14354:
14355: sub store_settings {
14356: # save to the environment
14357: # appenv the same items, just to be safe
14358: my $udom = $env{'user.domain'};
14359: my $uname = $env{'user.name'};
14360: my ($context,$prefix,$Settings) = @_;
14361: my %SaveHash;
14362: my %AppHash;
14363: while (my ($setting,$type) = each(%$Settings)) {
14364: my $basename = join('.','internal',$context,$prefix,$setting);
14365: my $envname = 'environment.'.$basename;
14366: if (exists($env{'form.'.$setting})) {
14367: # Save this value away
14368: if ($type eq 'scalar' &&
14369: (! exists($env{$envname}) ||
14370: $env{$envname} ne $env{'form.'.$setting})) {
14371: $SaveHash{$basename} = $env{'form.'.$setting};
14372: $AppHash{$envname} = $env{'form.'.$setting};
14373: } elsif ($type eq 'array') {
14374: my $stored_form;
14375: if (ref($env{'form.'.$setting})) {
14376: $stored_form = join(',',
14377: map {
14378: &escape($_);
14379: } sort(@{$env{'form.'.$setting}}));
14380: } else {
14381: $stored_form =
14382: &escape($env{'form.'.$setting});
14383: }
14384: # Determine if the array contents are the same.
14385: if ($stored_form ne $env{$envname}) {
14386: $SaveHash{$basename} = $stored_form;
14387: $AppHash{$envname} = $stored_form;
14388: }
14389: }
14390: }
14391: }
14392: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14393: $udom,$uname);
14394: if ($put_result !~ /^(ok|delayed)/) {
14395: &Apache::lonnet::logthis('unable to save form parameters, '.
14396: 'got error:'.$put_result);
14397: }
14398: # Make sure these settings stick around in this session, too
14399: &Apache::lonnet::appenv(\%AppHash);
14400: return;
14401: }
14402:
14403: sub restore_course_settings {
14404: return &restore_settings($env{'request.course.id'},@_);
14405: }
14406:
14407: sub restore_settings {
14408: my ($context,$prefix,$Settings) = @_;
14409: while (my ($setting,$type) = each(%$Settings)) {
14410: next if (exists($env{'form.'.$setting}));
14411: my $envname = 'environment.internal.'.$context.'.'.$prefix.
14412: '.'.$setting;
14413: if (exists($env{$envname})) {
14414: if ($type eq 'scalar') {
14415: $env{'form.'.$setting} = $env{$envname};
14416: } elsif ($type eq 'array') {
14417: $env{'form.'.$setting} = [
14418: map {
14419: &unescape($_);
14420: } split(',',$env{$envname})
14421: ];
14422: }
14423: }
14424: }
14425: }
14426:
14427: #######################################################
14428: #######################################################
14429:
14430: =pod
14431:
14432: =head1 Domain E-mail Routines
14433:
14434: =over 4
14435:
14436: =item * &build_recipient_list()
14437:
14438: Build recipient lists for following types of e-mail:
14439: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14440: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14441: module change checking, student/employee ID conflict checks, as
14442: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14443: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14444:
14445: Inputs:
14446: defmail (scalar - email address of default recipient),
14447: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14448: requestsmail, updatesmail, or idconflictsmail).
14449:
14450: defdom (domain for which to retrieve configuration settings),
14451:
14452: origmail (scalar - email address of recipient from loncapa.conf,
14453: i.e., predates configuration by DC via domainprefs.pm
14454:
14455: Returns: comma separated list of addresses to which to send e-mail.
14456:
14457: =back
14458:
14459: =cut
14460:
14461: ############################################################
14462: ############################################################
14463: sub build_recipient_list {
14464: my ($defmail,$mailing,$defdom,$origmail) = @_;
14465: my @recipients;
14466: my $otheremails;
14467: my %domconfig =
14468: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14469: if (ref($domconfig{'contacts'}) eq 'HASH') {
14470: if (exists($domconfig{'contacts'}{$mailing})) {
14471: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14472: my @contacts = ('adminemail','supportemail');
14473: foreach my $item (@contacts) {
14474: if ($domconfig{'contacts'}{$mailing}{$item}) {
14475: my $addr = $domconfig{'contacts'}{$item};
14476: if (!grep(/^\Q$addr\E$/,@recipients)) {
14477: push(@recipients,$addr);
14478: }
14479: }
14480: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14481: }
14482: }
14483: } elsif ($origmail ne '') {
14484: push(@recipients,$origmail);
14485: }
14486: } elsif ($origmail ne '') {
14487: push(@recipients,$origmail);
14488: }
14489: if (defined($defmail)) {
14490: if ($defmail ne '') {
14491: push(@recipients,$defmail);
14492: }
14493: }
14494: if ($otheremails) {
14495: my @others;
14496: if ($otheremails =~ /,/) {
14497: @others = split(/,/,$otheremails);
14498: } else {
14499: push(@others,$otheremails);
14500: }
14501: foreach my $addr (@others) {
14502: if (!grep(/^\Q$addr\E$/,@recipients)) {
14503: push(@recipients,$addr);
14504: }
14505: }
14506: }
14507: my $recipientlist = join(',',@recipients);
14508: return $recipientlist;
14509: }
14510:
14511: ############################################################
14512: ############################################################
14513:
14514: =pod
14515:
14516: =over 4
14517:
14518: =item * &mime_email()
14519:
14520: Sends an email with a possible attachment
14521:
14522: Inputs:
14523:
14524: =over 4
14525:
14526: from - Sender's email address
14527:
14528: to - Email address of recipient
14529:
14530: subject - Subject of email
14531:
14532: body - Body of email
14533:
14534: cc_string - Carbon copy email address
14535:
14536: bcc - Blind carbon copy email address
14537:
14538: type - File type of attachment
14539:
14540: attachment_path - Path of file to be attached
14541:
14542: file_name - Name of file to be attached
14543:
14544: attachment_text - The body of an attachment of type "TEXT"
14545:
14546: =back
14547:
14548: =back
14549:
14550: =cut
14551:
14552: ############################################################
14553: ############################################################
14554:
14555: sub mime_email {
14556: my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path,
14557: $file_name, $attachment_text) = @_;
14558: my $msg = MIME::Lite->new(
14559: From => $from,
14560: To => $to,
14561: Subject => $subject,
14562: Type =>'TEXT',
14563: Data => $body,
14564: );
14565: if ($cc_string ne '') {
14566: $msg->add("Cc" => $cc_string);
14567: }
14568: if ($bcc ne '') {
14569: $msg->add("Bcc" => $bcc);
14570: }
14571: $msg->attr("content-type" => "text/plain");
14572: $msg->attr("content-type.charset" => "UTF-8");
14573: # Attach file if given
14574: if ($attachment_path) {
14575: unless ($file_name) {
14576: if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
14577: }
14578: my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
14579: $msg->attach(Type => $type,
14580: Path => $attachment_path,
14581: Filename => $file_name
14582: );
14583: # Otherwise attach text if given
14584: } elsif ($attachment_text) {
14585: $msg->attach(Type => 'TEXT',
14586: Data => $attachment_text);
14587: }
14588: # Send it
14589: $msg->send('sendmail');
14590: }
14591:
14592: ############################################################
14593: ############################################################
14594:
14595: =pod
14596:
14597: =head1 Course Catalog Routines
14598:
14599: =over 4
14600:
14601: =item * &gather_categories()
14602:
14603: Converts category definitions - keys of categories hash stored in
14604: coursecategories in configuration.db on the primary library server in a
14605: domain - to an array. Also generates javascript and idx hash used to
14606: generate Domain Coordinator interface for editing Course Categories.
14607:
14608: Inputs:
14609:
14610: categories (reference to hash of category definitions).
14611:
14612: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14613: categories and subcategories).
14614:
14615: idx (reference to hash of counters used in Domain Coordinator interface for
14616: editing Course Categories).
14617:
14618: jsarray (reference to array of categories used to create Javascript arrays for
14619: Domain Coordinator interface for editing Course Categories).
14620:
14621: Returns: nothing
14622:
14623: Side effects: populates cats, idx and jsarray.
14624:
14625: =cut
14626:
14627: sub gather_categories {
14628: my ($categories,$cats,$idx,$jsarray) = @_;
14629: my %counters;
14630: my $num = 0;
14631: foreach my $item (keys(%{$categories})) {
14632: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
14633: if ($container eq '' && $depth == 0) {
14634: $cats->[$depth][$categories->{$item}] = $cat;
14635: } else {
14636: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
14637: }
14638: my ($escitem,$tail) = split(/:/,$item,2);
14639: if ($counters{$tail} eq '') {
14640: $counters{$tail} = $num;
14641: $num ++;
14642: }
14643: if (ref($idx) eq 'HASH') {
14644: $idx->{$item} = $counters{$tail};
14645: }
14646: if (ref($jsarray) eq 'ARRAY') {
14647: push(@{$jsarray->[$counters{$tail}]},$item);
14648: }
14649: }
14650: return;
14651: }
14652:
14653: =pod
14654:
14655: =item * &extract_categories()
14656:
14657: Used to generate breadcrumb trails for course categories.
14658:
14659: Inputs:
14660:
14661: categories (reference to hash of category definitions).
14662:
14663: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14664: categories and subcategories).
14665:
14666: trails (reference to array of breacrumb trails for each category).
14667:
14668: allitems (reference to hash - key is category key
14669: (format: escaped(name):escaped(parent category):depth in hierarchy).
14670:
14671: idx (reference to hash of counters used in Domain Coordinator interface for
14672: editing Course Categories).
14673:
14674: jsarray (reference to array of categories used to create Javascript arrays for
14675: Domain Coordinator interface for editing Course Categories).
14676:
14677: subcats (reference to hash of arrays containing all subcategories within each
14678: category, -recursive)
14679:
14680: Returns: nothing
14681:
14682: Side effects: populates trails and allitems hash references.
14683:
14684: =cut
14685:
14686: sub extract_categories {
14687: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
14688: if (ref($categories) eq 'HASH') {
14689: &gather_categories($categories,$cats,$idx,$jsarray);
14690: if (ref($cats->[0]) eq 'ARRAY') {
14691: for (my $i=0; $i<@{$cats->[0]}; $i++) {
14692: my $name = $cats->[0][$i];
14693: my $item = &escape($name).'::0';
14694: my $trailstr;
14695: if ($name eq 'instcode') {
14696: $trailstr = &mt('Official courses (with institutional codes)');
14697: } elsif ($name eq 'communities') {
14698: $trailstr = &mt('Communities');
14699: } elsif ($name eq 'placement') {
14700: $trailstr = &mt('Placement Tests');
14701: } else {
14702: $trailstr = $name;
14703: }
14704: if ($allitems->{$item} eq '') {
14705: push(@{$trails},$trailstr);
14706: $allitems->{$item} = scalar(@{$trails})-1;
14707: }
14708: my @parents = ($name);
14709: if (ref($cats->[1]{$name}) eq 'ARRAY') {
14710: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
14711: my $category = $cats->[1]{$name}[$j];
14712: if (ref($subcats) eq 'HASH') {
14713: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
14714: }
14715: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
14716: }
14717: } else {
14718: if (ref($subcats) eq 'HASH') {
14719: $subcats->{$item} = [];
14720: }
14721: }
14722: }
14723: }
14724: }
14725: return;
14726: }
14727:
14728: =pod
14729:
14730: =item * &recurse_categories()
14731:
14732: Recursively used to generate breadcrumb trails for course categories.
14733:
14734: Inputs:
14735:
14736: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14737: categories and subcategories).
14738:
14739: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
14740:
14741: category (current course category, for which breadcrumb trail is being generated).
14742:
14743: trails (reference to array of breadcrumb trails for each category).
14744:
14745: allitems (reference to hash - key is category key
14746: (format: escaped(name):escaped(parent category):depth in hierarchy).
14747:
14748: parents (array containing containers directories for current category,
14749: back to top level).
14750:
14751: Returns: nothing
14752:
14753: Side effects: populates trails and allitems hash references
14754:
14755: =cut
14756:
14757: sub recurse_categories {
14758: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
14759: my $shallower = $depth - 1;
14760: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
14761: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
14762: my $name = $cats->[$depth]{$category}[$k];
14763: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14764: my $trailstr = join(' -> ',(@{$parents},$category));
14765: if ($allitems->{$item} eq '') {
14766: push(@{$trails},$trailstr);
14767: $allitems->{$item} = scalar(@{$trails})-1;
14768: }
14769: my $deeper = $depth+1;
14770: push(@{$parents},$category);
14771: if (ref($subcats) eq 'HASH') {
14772: my $subcat = &escape($name).':'.$category.':'.$depth;
14773: for (my $j=@{$parents}; $j>=0; $j--) {
14774: my $higher;
14775: if ($j > 0) {
14776: $higher = &escape($parents->[$j]).':'.
14777: &escape($parents->[$j-1]).':'.$j;
14778: } else {
14779: $higher = &escape($parents->[$j]).'::'.$j;
14780: }
14781: push(@{$subcats->{$higher}},$subcat);
14782: }
14783: }
14784: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14785: $subcats);
14786: pop(@{$parents});
14787: }
14788: } else {
14789: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14790: my $trailstr = join(' -> ',(@{$parents},$category));
14791: if ($allitems->{$item} eq '') {
14792: push(@{$trails},$trailstr);
14793: $allitems->{$item} = scalar(@{$trails})-1;
14794: }
14795: }
14796: return;
14797: }
14798:
14799: =pod
14800:
14801: =item * &assign_categories_table()
14802:
14803: Create a datatable for display of hierarchical categories in a domain,
14804: with checkboxes to allow a course to be categorized.
14805:
14806: Inputs:
14807:
14808: cathash - reference to hash of categories defined for the domain (from
14809: configuration.db)
14810:
14811: currcat - scalar with an & separated list of categories assigned to a course.
14812:
14813: type - scalar contains course type (Course or Community).
14814:
14815: Returns: $output (markup to be displayed)
14816:
14817: =cut
14818:
14819: sub assign_categories_table {
14820: my ($cathash,$currcat,$type) = @_;
14821: my $output;
14822: if (ref($cathash) eq 'HASH') {
14823: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
14824: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
14825: $maxdepth = scalar(@cats);
14826: if (@cats > 0) {
14827: my $itemcount = 0;
14828: if (ref($cats[0]) eq 'ARRAY') {
14829: my @currcategories;
14830: if ($currcat ne '') {
14831: @currcategories = split('&',$currcat);
14832: }
14833: my $table;
14834: for (my $i=0; $i<@{$cats[0]}; $i++) {
14835: my $parent = $cats[0][$i];
14836: next if ($parent eq 'instcode');
14837: if ($type eq 'Community') {
14838: next unless ($parent eq 'communities');
14839: } elsif ($type eq 'Placement') {
14840: next unless ($parent eq 'placement');
14841: } else {
14842: next if (($parent eq 'communities') || ($parent eq 'placement'));
14843: }
14844: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14845: my $item = &escape($parent).'::0';
14846: my $checked = '';
14847: if (@currcategories > 0) {
14848: if (grep(/^\Q$item\E$/,@currcategories)) {
14849: $checked = ' checked="checked"';
14850: }
14851: }
14852: my $parent_title = $parent;
14853: if ($parent eq 'communities') {
14854: $parent_title = &mt('Communities');
14855: } elsif ($parent eq 'placement') {
14856: $parent_title = &mt('Placement Tests');
14857: }
14858: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
14859: '<input type="checkbox" name="usecategory" value="'.
14860: $item.'"'.$checked.' />'.$parent_title.'</span>'.
14861: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
14862: my $depth = 1;
14863: push(@path,$parent);
14864: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
14865: pop(@path);
14866: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
14867: $itemcount ++;
14868: }
14869: if ($itemcount) {
14870: $output = &Apache::loncommon::start_data_table().
14871: $table.
14872: &Apache::loncommon::end_data_table();
14873: }
14874: }
14875: }
14876: }
14877: return $output;
14878: }
14879:
14880: =pod
14881:
14882: =item * &assign_category_rows()
14883:
14884: Create a datatable row for display of nested categories in a domain,
14885: with checkboxes to allow a course to be categorized,called recursively.
14886:
14887: Inputs:
14888:
14889: itemcount - track row number for alternating colors
14890:
14891: cats - reference to array of arrays/hashes which encapsulates hierarchy of
14892: categories and subcategories.
14893:
14894: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
14895:
14896: parent - parent of current category item
14897:
14898: path - Array containing all categories back up through the hierarchy from the
14899: current category to the top level.
14900:
14901: currcategories - reference to array of current categories assigned to the course
14902:
14903: Returns: $output (markup to be displayed).
14904:
14905: =cut
14906:
14907: sub assign_category_rows {
14908: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
14909: my ($text,$name,$item,$chgstr);
14910: if (ref($cats) eq 'ARRAY') {
14911: my $maxdepth = scalar(@{$cats});
14912: if (ref($cats->[$depth]) eq 'HASH') {
14913: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
14914: my $numchildren = @{$cats->[$depth]{$parent}};
14915: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14916: $text .= '<td><table class="LC_data_table">';
14917: for (my $j=0; $j<$numchildren; $j++) {
14918: $name = $cats->[$depth]{$parent}[$j];
14919: $item = &escape($name).':'.&escape($parent).':'.$depth;
14920: my $deeper = $depth+1;
14921: my $checked = '';
14922: if (ref($currcategories) eq 'ARRAY') {
14923: if (@{$currcategories} > 0) {
14924: if (grep(/^\Q$item\E$/,@{$currcategories})) {
14925: $checked = ' checked="checked"';
14926: }
14927: }
14928: }
14929: $text .= '<tr><td><span class="LC_nobreak"><label>'.
14930: '<input type="checkbox" name="usecategory" value="'.
14931: $item.'"'.$checked.' />'.$name.'</label></span>'.
14932: '<input type="hidden" name="catname" value="'.$name.'" />'.
14933: '</td><td>';
14934: if (ref($path) eq 'ARRAY') {
14935: push(@{$path},$name);
14936: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
14937: pop(@{$path});
14938: }
14939: $text .= '</td></tr>';
14940: }
14941: $text .= '</table></td>';
14942: }
14943: }
14944: }
14945: return $text;
14946: }
14947:
14948: =pod
14949:
14950: =back
14951:
14952: =cut
14953:
14954: ############################################################
14955: ############################################################
14956:
14957:
14958: sub commit_customrole {
14959: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
14960: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
14961: ($start?', '.&mt('starting').' '.localtime($start):'').
14962: ($end?', ending '.localtime($end):'').': <b>'.
14963: &Apache::lonnet::assigncustomrole(
14964: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
14965: '</b><br />';
14966: return $output;
14967: }
14968:
14969: sub commit_standardrole {
14970: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
14971: my ($output,$logmsg,$linefeed);
14972: if ($context eq 'auto') {
14973: $linefeed = "\n";
14974: } else {
14975: $linefeed = "<br />\n";
14976: }
14977: if ($three eq 'st') {
14978: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
14979: $one,$two,$sec,$context,$credits);
14980: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
14981: ($result eq 'unknown_course') || ($result eq 'refused')) {
14982: $output = $logmsg.' '.&mt('Error: ').$result."\n";
14983: } else {
14984: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
14985: ($start?', '.&mt('starting').' '.localtime($start):'').
14986: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14987: if ($context eq 'auto') {
14988: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
14989: } else {
14990: $output .= '<b>'.$result.'</b>'.$linefeed.
14991: &mt('Add to classlist').': <b>ok</b>';
14992: }
14993: $output .= $linefeed;
14994: }
14995: } else {
14996: $output = &mt('Assigning').' '.$three.' in '.$url.
14997: ($start?', '.&mt('starting').' '.localtime($start):'').
14998: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14999: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
15000: if ($context eq 'auto') {
15001: $output .= $result.$linefeed;
15002: } else {
15003: $output .= '<b>'.$result.'</b>'.$linefeed;
15004: }
15005: }
15006: return $output;
15007: }
15008:
15009: sub commit_studentrole {
15010: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
15011: $credits) = @_;
15012: my ($result,$linefeed,$oldsecurl,$newsecurl);
15013: if ($context eq 'auto') {
15014: $linefeed = "\n";
15015: } else {
15016: $linefeed = '<br />'."\n";
15017: }
15018: if (defined($one) && defined($two)) {
15019: my $cid=$one.'_'.$two;
15020: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
15021: my $secchange = 0;
15022: my $expire_role_result;
15023: my $modify_section_result;
15024: if ($oldsec ne '-1') {
15025: if ($oldsec ne $sec) {
15026: $secchange = 1;
15027: my $now = time;
15028: my $uurl='/'.$cid;
15029: $uurl=~s/\_/\//g;
15030: if ($oldsec) {
15031: $uurl.='/'.$oldsec;
15032: }
15033: $oldsecurl = $uurl;
15034: $expire_role_result =
15035: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
15036: if ($env{'request.course.sec'} ne '') {
15037: if ($expire_role_result eq 'refused') {
15038: my @roles = ('st');
15039: my @statuses = ('previous');
15040: my @roledoms = ($one);
15041: my $withsec = 1;
15042: my %roleshash =
15043: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
15044: \@statuses,\@roles,\@roledoms,$withsec);
15045: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
15046: my ($oldstart,$oldend) =
15047: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
15048: if ($oldend > 0 && $oldend <= $now) {
15049: $expire_role_result = 'ok';
15050: }
15051: }
15052: }
15053: }
15054: $result = $expire_role_result;
15055: }
15056: }
15057: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
15058: $modify_section_result =
15059: &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
15060: undef,undef,undef,$sec,
15061: $end,$start,'','',$cid,
15062: '',$context,$credits);
15063: if ($modify_section_result =~ /^ok/) {
15064: if ($secchange == 1) {
15065: if ($sec eq '') {
15066: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
15067: } else {
15068: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
15069: }
15070: } elsif ($oldsec eq '-1') {
15071: if ($sec eq '') {
15072: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
15073: } else {
15074: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15075: }
15076: } else {
15077: if ($sec eq '') {
15078: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
15079: } else {
15080: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15081: }
15082: }
15083: } else {
15084: if ($secchange) {
15085: $$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;
15086: } else {
15087: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
15088: }
15089: }
15090: $result = $modify_section_result;
15091: } elsif ($secchange == 1) {
15092: if ($oldsec eq '') {
15093: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
15094: } else {
15095: $$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;
15096: }
15097: if ($expire_role_result eq 'refused') {
15098: my $newsecurl = '/'.$cid;
15099: $newsecurl =~ s/\_/\//g;
15100: if ($sec ne '') {
15101: $newsecurl.='/'.$sec;
15102: }
15103: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
15104: if ($sec eq '') {
15105: $$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;
15106: } else {
15107: $$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;
15108: }
15109: }
15110: }
15111: }
15112: } else {
15113: $$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;
15114: $result = "error: incomplete course id\n";
15115: }
15116: return $result;
15117: }
15118:
15119: sub show_role_extent {
15120: my ($scope,$context,$role) = @_;
15121: $scope =~ s{^/}{};
15122: my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
15123: push(@courseroles,'co');
15124: my @authorroles = &Apache::lonuserutils::roles_by_context('author');
15125: if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
15126: $scope =~ s{/}{_};
15127: return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
15128: } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
15129: my ($audom,$auname) = split(/\//,$scope);
15130: return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
15131: &Apache::loncommon::plainname($auname,$audom).'</span>');
15132: } else {
15133: $scope =~ s{/$}{};
15134: return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
15135: &Apache::lonnet::domain($scope,'description').'</span>');
15136: }
15137: }
15138:
15139: ############################################################
15140: ############################################################
15141:
15142: sub check_clone {
15143: my ($args,$linefeed) = @_;
15144: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
15145: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15146: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15147: my $clonemsg;
15148: my $can_clone = 0;
15149: my $lctype = lc($args->{'crstype'});
15150: if ($lctype ne 'community') {
15151: $lctype = 'course';
15152: }
15153: if ($clonehome eq 'no_host') {
15154: if ($args->{'crstype'} eq 'Community') {
15155: $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'});
15156: } else {
15157: $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'});
15158: }
15159: } else {
15160: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15161: if ($args->{'crstype'} eq 'Community') {
15162: if ($clonedesc{'type'} ne 'Community') {
15163: $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'});
15164: return ($can_clone, $clonemsg, $cloneid, $clonehome);
15165: }
15166: }
15167: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
15168: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15169: $can_clone = 1;
15170: } else {
15171: my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15172: $args->{'clonedomain'},$args->{'clonecourse'});
15173: if ($clonehash{'cloners'} eq '') {
15174: my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15175: if ($domdefs{'canclone'}) {
15176: unless ($domdefs{'canclone'} eq 'none') {
15177: if ($domdefs{'canclone'} eq 'domain') {
15178: if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15179: $can_clone = 1;
15180: }
15181: } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15182: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
15183: if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
15184: $clonehash{'internal.coursecode'},$args->{'crscode'})) {
15185: $can_clone = 1;
15186: }
15187: }
15188: }
15189: }
15190: } else {
15191: my @cloners = split(/,/,$clonehash{'cloners'});
15192: if (grep(/^\*$/,@cloners)) {
15193: $can_clone = 1;
15194: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15195: $can_clone = 1;
15196: } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15197: $can_clone = 1;
15198: }
15199: unless ($can_clone) {
15200: if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15201: ($args->{'clonedomain'} eq $args->{'course_domain'})) {
15202: my (%gotdomdefaults,%gotcodedefaults);
15203: foreach my $cloner (@cloners) {
15204: if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
15205: ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
15206: my (%codedefaults,@code_order);
15207: if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
15208: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
15209: %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15210: }
15211: if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15212: @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15213: }
15214: } else {
15215: &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15216: \%codedefaults,
15217: \@code_order);
15218: $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15219: $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15220: }
15221: if (@code_order > 0) {
15222: if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15223: $cloner,$clonehash{'internal.coursecode'},
15224: $args->{'crscode'})) {
15225: $can_clone = 1;
15226: last;
15227: }
15228: }
15229: }
15230: }
15231: }
15232: }
15233: }
15234: unless ($can_clone) {
15235: my $ccrole = 'cc';
15236: if ($args->{'crstype'} eq 'Community') {
15237: $ccrole = 'co';
15238: }
15239: my %roleshash =
15240: &Apache::lonnet::get_my_roles($args->{'ccuname'},
15241: $args->{'ccdomain'},
15242: 'userroles',['active'],[$ccrole],
15243: [$args->{'clonedomain'}]);
15244: if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15245: $can_clone = 1;
15246: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15247: $args->{'ccuname'},$args->{'ccdomain'})) {
15248: $can_clone = 1;
15249: }
15250: }
15251: unless ($can_clone) {
15252: if ($args->{'crstype'} eq 'Community') {
15253: $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'});
15254: } else {
15255: $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'});
15256: }
15257: }
15258: }
15259: }
15260: return ($can_clone, $clonemsg, $cloneid, $clonehome);
15261: }
15262:
15263: sub construct_course {
15264: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
15265: my $outcome;
15266: my $linefeed = '<br />'."\n";
15267: if ($context eq 'auto') {
15268: $linefeed = "\n";
15269: }
15270:
15271: #
15272: # Are we cloning?
15273: #
15274: my ($can_clone, $clonemsg, $cloneid, $clonehome);
15275: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
15276: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
15277: if ($context ne 'auto') {
15278: if ($clonemsg ne '') {
15279: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
15280: }
15281: }
15282: $outcome .= $clonemsg.$linefeed;
15283:
15284: if (!$can_clone) {
15285: return (0,$outcome);
15286: }
15287: }
15288:
15289: #
15290: # Open course
15291: #
15292: my $showncrstype;
15293: if ($args->{'crstype'} eq 'Placement') {
15294: $showncrstype = 'placement test';
15295: } else {
15296: $showncrstype = lc($args->{'crstype'});
15297: }
15298: my %cenv=();
15299: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
15300: $args->{'cdescr'},
15301: $args->{'curl'},
15302: $args->{'course_home'},
15303: $args->{'nonstandard'},
15304: $args->{'crscode'},
15305: $args->{'ccuname'}.':'.
15306: $args->{'ccdomain'},
15307: $args->{'crstype'},
15308: $cnum,$context,$category);
15309:
15310: # Note: The testing routines depend on this being output; see
15311: # Utils::Course. This needs to at least be output as a comment
15312: # if anyone ever decides to not show this, and Utils::Course::new
15313: # will need to be suitably modified.
15314: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
15315: if ($$courseid =~ /^error:/) {
15316: return (0,$outcome);
15317: }
15318:
15319: #
15320: # Check if created correctly
15321: #
15322: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
15323: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
15324: if ($crsuhome eq 'no_host') {
15325: $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
15326: return (0,$outcome);
15327: }
15328: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
15329:
15330: #
15331: # Do the cloning
15332: #
15333: if ($can_clone && $cloneid) {
15334: $clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
15335: if ($context ne 'auto') {
15336: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
15337: }
15338: $outcome .= $clonemsg.$linefeed;
15339: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
15340: # Copy all files
15341: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
15342: # Restore URL
15343: $cenv{'url'}=$oldcenv{'url'};
15344: # Restore title
15345: $cenv{'description'}=$oldcenv{'description'};
15346: # Restore creation date, creator and creation context.
15347: $cenv{'internal.created'}=$oldcenv{'internal.created'};
15348: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
15349: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
15350: # Mark as cloned
15351: $cenv{'clonedfrom'}=$cloneid;
15352: # Need to clone grading mode
15353: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
15354: $cenv{'grading'}=$newenv{'grading'};
15355: # Do not clone these environment entries
15356: &Apache::lonnet::del('environment',
15357: ['default_enrollment_start_date',
15358: 'default_enrollment_end_date',
15359: 'question.email',
15360: 'policy.email',
15361: 'comment.email',
15362: 'pch.users.denied',
15363: 'plc.users.denied',
15364: 'hidefromcat',
15365: 'checkforpriv',
15366: 'categories',
15367: 'internal.uniquecode'],
15368: $$crsudom,$$crsunum);
15369: if ($args->{'textbook'}) {
15370: $cenv{'internal.textbook'} = $args->{'textbook'};
15371: }
15372: }
15373:
15374: #
15375: # Set environment (will override cloned, if existing)
15376: #
15377: my @sections = ();
15378: my @xlists = ();
15379: if ($args->{'crstype'}) {
15380: $cenv{'type'}=$args->{'crstype'};
15381: }
15382: if ($args->{'crsid'}) {
15383: $cenv{'courseid'}=$args->{'crsid'};
15384: }
15385: if ($args->{'crscode'}) {
15386: $cenv{'internal.coursecode'}=$args->{'crscode'};
15387: }
15388: if ($args->{'crsquota'} ne '') {
15389: $cenv{'internal.coursequota'}=$args->{'crsquota'};
15390: } else {
15391: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
15392: }
15393: if ($args->{'ccuname'}) {
15394: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
15395: ':'.$args->{'ccdomain'};
15396: } else {
15397: $cenv{'internal.courseowner'} = $args->{'curruser'};
15398: }
15399: if ($args->{'defaultcredits'}) {
15400: $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
15401: }
15402: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
15403: if ($args->{'crssections'}) {
15404: $cenv{'internal.sectionnums'} = '';
15405: if ($args->{'crssections'} =~ m/,/) {
15406: @sections = split/,/,$args->{'crssections'};
15407: } else {
15408: $sections[0] = $args->{'crssections'};
15409: }
15410: if (@sections > 0) {
15411: foreach my $item (@sections) {
15412: my ($sec,$gp) = split/:/,$item;
15413: my $class = $args->{'crscode'}.$sec;
15414: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
15415: $cenv{'internal.sectionnums'} .= $item.',';
15416: unless ($addcheck eq 'ok') {
15417: push @badclasses, $class;
15418: }
15419: }
15420: $cenv{'internal.sectionnums'} =~ s/,$//;
15421: }
15422: }
15423: # do not hide course coordinator from staff listing,
15424: # even if privileged
15425: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15426: # add course coordinator's domain to domains to check for privileged users
15427: # if different to course domain
15428: if ($$crsudom ne $args->{'ccdomain'}) {
15429: $cenv{'checkforpriv'} = $args->{'ccdomain'};
15430: }
15431: # add crosslistings
15432: if ($args->{'crsxlist'}) {
15433: $cenv{'internal.crosslistings'}='';
15434: if ($args->{'crsxlist'} =~ m/,/) {
15435: @xlists = split/,/,$args->{'crsxlist'};
15436: } else {
15437: $xlists[0] = $args->{'crsxlist'};
15438: }
15439: if (@xlists > 0) {
15440: foreach my $item (@xlists) {
15441: my ($xl,$gp) = split/:/,$item;
15442: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15443: $cenv{'internal.crosslistings'} .= $item.',';
15444: unless ($addcheck eq 'ok') {
15445: push @badclasses, $xl;
15446: }
15447: }
15448: $cenv{'internal.crosslistings'} =~ s/,$//;
15449: }
15450: }
15451: if ($args->{'autoadds'}) {
15452: $cenv{'internal.autoadds'}=$args->{'autoadds'};
15453: }
15454: if ($args->{'autodrops'}) {
15455: $cenv{'internal.autodrops'}=$args->{'autodrops'};
15456: }
15457: # check for notification of enrollment changes
15458: my @notified = ();
15459: if ($args->{'notify_owner'}) {
15460: if ($args->{'ccuname'} ne '') {
15461: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15462: }
15463: }
15464: if ($args->{'notify_dc'}) {
15465: if ($uname ne '') {
15466: push(@notified,$uname.':'.$udom);
15467: }
15468: }
15469: if (@notified > 0) {
15470: my $notifylist;
15471: if (@notified > 1) {
15472: $notifylist = join(',',@notified);
15473: } else {
15474: $notifylist = $notified[0];
15475: }
15476: $cenv{'internal.notifylist'} = $notifylist;
15477: }
15478: if (@badclasses > 0) {
15479: my %lt=&Apache::lonlocal::texthash(
15480: 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course. However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
15481: 'dnhr' => 'does not have rights to access enrollment in these classes',
15482: 'adby' => 'as determined by the policies of your institution on access to official classlists'
15483: );
15484: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
15485: ' ('.$lt{'adby'}.')';
15486: if ($context eq 'auto') {
15487: $outcome .= $badclass_msg.$linefeed;
15488: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15489: foreach my $item (@badclasses) {
15490: if ($context eq 'auto') {
15491: $outcome .= " - $item\n";
15492: } else {
15493: $outcome .= "<li>$item</li>\n";
15494: }
15495: }
15496: if ($context eq 'auto') {
15497: $outcome .= $linefeed;
15498: } else {
15499: $outcome .= "</ul><br /><br /></div>\n";
15500: }
15501: }
15502: }
15503: if ($args->{'no_end_date'}) {
15504: $args->{'endaccess'} = 0;
15505: }
15506: $cenv{'internal.autostart'}=$args->{'enrollstart'};
15507: $cenv{'internal.autoend'}=$args->{'enrollend'};
15508: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15509: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15510: if ($args->{'showphotos'}) {
15511: $cenv{'internal.showphotos'}=$args->{'showphotos'};
15512: }
15513: $cenv{'internal.authtype'} = $args->{'authtype'};
15514: $cenv{'internal.autharg'} = $args->{'autharg'};
15515: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15516: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
15517: 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');
15518: if ($context eq 'auto') {
15519: $outcome .= $krb_msg;
15520: } else {
15521: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15522: }
15523: $outcome .= $linefeed;
15524: }
15525: }
15526: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15527: if ($args->{'setpolicy'}) {
15528: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15529: }
15530: if ($args->{'setcontent'}) {
15531: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15532: }
15533: if ($args->{'setcomment'}) {
15534: $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15535: }
15536: }
15537: if ($args->{'reshome'}) {
15538: $cenv{'reshome'}=$args->{'reshome'}.'/';
15539: $cenv{'reshome'}=~s/\/+$/\//;
15540: }
15541: #
15542: # course has keyed access
15543: #
15544: if ($args->{'setkeys'}) {
15545: $cenv{'keyaccess'}='yes';
15546: }
15547: # if specified, key authority is not course, but user
15548: # only active if keyaccess is yes
15549: if ($args->{'keyauth'}) {
15550: my ($user,$domain) = split(':',$args->{'keyauth'});
15551: $user = &LONCAPA::clean_username($user);
15552: $domain = &LONCAPA::clean_username($domain);
15553: if ($user ne '' && $domain ne '') {
15554: $cenv{'keyauth'}=$user.':'.$domain;
15555: }
15556: }
15557:
15558: #
15559: # generate and store uniquecode (available to course requester), if course should have one.
15560: #
15561: if ($args->{'uniquecode'}) {
15562: my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
15563: if ($code) {
15564: $cenv{'internal.uniquecode'} = $code;
15565: my %crsinfo =
15566: &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
15567: if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
15568: $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
15569: my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
15570: }
15571: if (ref($coderef)) {
15572: $$coderef = $code;
15573: }
15574: }
15575: }
15576:
15577: if ($args->{'disresdis'}) {
15578: $cenv{'pch.roles.denied'}='st';
15579: }
15580: if ($args->{'disablechat'}) {
15581: $cenv{'plc.roles.denied'}='st';
15582: }
15583:
15584: # Record we've not yet viewed the Course Initialization Helper for this
15585: # course
15586: $cenv{'course.helper.not.run'} = 1;
15587: #
15588: # Use new Randomseed
15589: #
15590: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
15591: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
15592: #
15593: # The encryption code and receipt prefix for this course
15594: #
15595: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
15596: $cenv{'internal.encpref'}=100+int(9*rand(99));
15597: #
15598: # By default, use standard grading
15599: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
15600:
15601: $outcome .= $linefeed.&mt('Setting environment').': '.
15602: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
15603: #
15604: # Open all assignments
15605: #
15606: if ($args->{'openall'}) {
15607: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
15608: my %storecontent = ($storeunder => time,
15609: $storeunder.'.type' => 'date_start');
15610:
15611: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
15612: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
15613: }
15614: #
15615: # Set first page
15616: #
15617: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
15618: || ($cloneid)) {
15619: use LONCAPA::map;
15620: $outcome .= &mt('Setting first resource').': ';
15621:
15622: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
15623: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
15624:
15625: $outcome .= ($fatal?$errtext:'read ok').' - ';
15626: my $title; my $url;
15627: if ($args->{'firstres'} eq 'syl') {
15628: $title=&mt('Syllabus');
15629: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
15630: } else {
15631: $title=&mt('Table of Contents');
15632: $url='/adm/navmaps';
15633: }
15634:
15635: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
15636: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
15637:
15638: if ($errtext) { $fatal=2; }
15639: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
15640: }
15641:
15642: #
15643: # Set params for Placement Tests
15644: #
15645: if ($args->{'crstype'} eq 'Placement') {
15646: my %storecontent;
15647: my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
15648: my %defaults = (
15649: buttonshide => { value => 'yes',
15650: type => 'string_yesno',},
15651: type => { value => 'randomizetry',
15652: type => 'string_questiontype',},
15653: maxtries => { value => 1,
15654: type => 'int_pos',},
15655: problemstatus => { value => 'no',
15656: type => 'string_problemstatus',},
15657: );
15658: foreach my $key (keys(%defaults)) {
15659: $storecontent{$prefix.$key} = $defaults{$key}{'value'};
15660: $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
15661: }
15662: &Apache::lonnet::cput
15663: ('resourcedata',\%storecontent,$$crsudom,$$crsunum);
15664: }
15665:
15666: return (1,$outcome);
15667: }
15668:
15669: sub make_unique_code {
15670: my ($cdom,$cnum) = @_;
15671: # get lock on uniquecodes db
15672: my $lockhash = {
15673: $cnum."\0".'uniquecodes' => $env{'user.name'}.
15674: ':'.$env{'user.domain'},
15675: };
15676: my $tries = 0;
15677: my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15678: my ($code,$error);
15679:
15680: while (($gotlock ne 'ok') && ($tries<3)) {
15681: $tries ++;
15682: sleep 1;
15683: $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15684: }
15685: if ($gotlock eq 'ok') {
15686: my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
15687: my $gotcode;
15688: my $attempts = 0;
15689: while ((!$gotcode) && ($attempts < 100)) {
15690: $code = &generate_code();
15691: if (!exists($currcodes{$code})) {
15692: $gotcode = 1;
15693: unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
15694: $error = 'nostore';
15695: }
15696: }
15697: $attempts ++;
15698: }
15699: my @del_lock = ($cnum."\0".'uniquecodes');
15700: my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
15701: } else {
15702: $error = 'nolock';
15703: }
15704: return ($code,$error);
15705: }
15706:
15707: sub generate_code {
15708: my $code;
15709: my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
15710: for (my $i=0; $i<6; $i++) {
15711: my $lettnum = int (rand 2);
15712: my $item = '';
15713: if ($lettnum) {
15714: $item = $letts[int( rand(18) )];
15715: } else {
15716: $item = 1+int( rand(8) );
15717: }
15718: $code .= $item;
15719: }
15720: return $code;
15721: }
15722:
15723: ############################################################
15724: ############################################################
15725:
15726: # Community, Course and Placement Test
15727: sub course_type {
15728: my ($cid) = @_;
15729: if (!defined($cid)) {
15730: $cid = $env{'request.course.id'};
15731: }
15732: if (defined($env{'course.'.$cid.'.type'})) {
15733: return $env{'course.'.$cid.'.type'};
15734: } else {
15735: return 'Course';
15736: }
15737: }
15738:
15739: sub group_term {
15740: my $crstype = &course_type();
15741: my %names = (
15742: 'Course' => 'group',
15743: 'Community' => 'group',
15744: 'Placement' => 'group',
15745: );
15746: return $names{$crstype};
15747: }
15748:
15749: sub course_types {
15750: my @types = ('official','unofficial','community','textbook','placement');
15751: my %typename = (
15752: official => 'Official course',
15753: unofficial => 'Unofficial course',
15754: community => 'Community',
15755: textbook => 'Textbook course',
15756: placement => 'Placement test',
15757: );
15758: return (\@types,\%typename);
15759: }
15760:
15761: sub icon {
15762: my ($file)=@_;
15763: my $curfext = lc((split(/\./,$file))[-1]);
15764: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
15765: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
15766: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
15767: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
15768: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15769: $curfext.".gif") {
15770: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15771: $curfext.".gif";
15772: }
15773: }
15774: return &lonhttpdurl($iconname);
15775: }
15776:
15777: sub lonhttpdurl {
15778: #
15779: # Had been used for "small fry" static images on separate port 8080.
15780: # Modify here if lightweight http functionality desired again.
15781: # Currently eliminated due to increasing firewall issues.
15782: #
15783: my ($url)=@_;
15784: return $url;
15785: }
15786:
15787: sub connection_aborted {
15788: my ($r)=@_;
15789: $r->print(" ");$r->rflush();
15790: my $c = $r->connection;
15791: return $c->aborted();
15792: }
15793:
15794: # Escapes strings that may have embedded 's that will be put into
15795: # strings as 'strings'.
15796: sub escape_single {
15797: my ($input) = @_;
15798: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
15799: $input =~ s/\'/\\\'/g; # Esacpe the 's....
15800: return $input;
15801: }
15802:
15803: # Same as escape_single, but escape's "'s This
15804: # can be used for "strings"
15805: sub escape_double {
15806: my ($input) = @_;
15807: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
15808: $input =~ s/\"/\\\"/g; # Esacpe the "s....
15809: return $input;
15810: }
15811:
15812: # Escapes the last element of a full URL.
15813: sub escape_url {
15814: my ($url) = @_;
15815: my @urlslices = split(/\//, $url,-1);
15816: my $lastitem = &escape(pop(@urlslices));
15817: return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
15818: }
15819:
15820: sub compare_arrays {
15821: my ($arrayref1,$arrayref2) = @_;
15822: my (@difference,%count);
15823: @difference = ();
15824: %count = ();
15825: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
15826: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
15827: foreach my $element (keys(%count)) {
15828: if ($count{$element} == 1) {
15829: push(@difference,$element);
15830: }
15831: }
15832: }
15833: return @difference;
15834: }
15835:
15836: # -------------------------------------------------------- Initialize user login
15837: sub init_user_environment {
15838: my ($r, $username, $domain, $authhost, $form, $args) = @_;
15839: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
15840:
15841: my $public=($username eq 'public' && $domain eq 'public');
15842:
15843: # See if old ID present, if so, remove
15844:
15845: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
15846: my $now=time;
15847:
15848: if ($public) {
15849: my $max_public=100;
15850: my $oldest;
15851: my $oldest_time=0;
15852: for(my $next=1;$next<=$max_public;$next++) {
15853: if (-e $lonids."/publicuser_$next.id") {
15854: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
15855: if ($mtime<$oldest_time || !$oldest_time) {
15856: $oldest_time=$mtime;
15857: $oldest=$next;
15858: }
15859: } else {
15860: $cookie="publicuser_$next";
15861: last;
15862: }
15863: }
15864: if (!$cookie) { $cookie="publicuser_$oldest"; }
15865: } else {
15866: # if this isn't a robot, kill any existing non-robot sessions
15867: if (!$args->{'robot'}) {
15868: opendir(DIR,$lonids);
15869: while ($filename=readdir(DIR)) {
15870: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
15871: unlink($lonids.'/'.$filename);
15872: }
15873: }
15874: closedir(DIR);
15875: # If there is a undeleted lockfile for the user's paste buffer remove it.
15876: my $namespace = 'nohist_courseeditor';
15877: my $lockingkey = 'paste'."\0".'locked_num';
15878: my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
15879: $domain,$username);
15880: if (exists($lockhash{$lockingkey})) {
15881: my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
15882: unless ($delresult eq 'ok') {
15883: &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
15884: }
15885: }
15886: }
15887: # Give them a new cookie
15888: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
15889: : $now.$$.int(rand(10000)));
15890: $cookie="$username\_$id\_$domain\_$authhost";
15891:
15892: # Initialize roles
15893:
15894: ($userroles,$firstaccenv,$timerintenv) =
15895: &Apache::lonnet::rolesinit($domain,$username,$authhost);
15896: }
15897: # ------------------------------------ Check browser type and MathML capability
15898:
15899: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
15900: $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
15901:
15902: # ------------------------------------------------------------- Get environment
15903:
15904: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
15905: my ($tmp) = keys(%userenv);
15906: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
15907: } else {
15908: undef(%userenv);
15909: }
15910: if (($userenv{'interface'}) && (!$form->{'interface'})) {
15911: $form->{'interface'}=$userenv{'interface'};
15912: }
15913: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
15914:
15915: # --------------- Do not trust query string to be put directly into environment
15916: foreach my $option ('interface','localpath','localres') {
15917: $form->{$option}=~s/[\n\r\=]//gs;
15918: }
15919: # --------------------------------------------------------- Write first profile
15920:
15921: {
15922: my %initial_env =
15923: ("user.name" => $username,
15924: "user.domain" => $domain,
15925: "user.home" => $authhost,
15926: "browser.type" => $clientbrowser,
15927: "browser.version" => $clientversion,
15928: "browser.mathml" => $clientmathml,
15929: "browser.unicode" => $clientunicode,
15930: "browser.os" => $clientos,
15931: "browser.mobile" => $clientmobile,
15932: "browser.info" => $clientinfo,
15933: "browser.osversion" => $clientosversion,
15934: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
15935: "request.course.fn" => '',
15936: "request.course.uri" => '',
15937: "request.course.sec" => '',
15938: "request.role" => 'cm',
15939: "request.role.adv" => $env{'user.adv'},
15940: "request.host" => $ENV{'REMOTE_ADDR'},);
15941:
15942: if ($form->{'localpath'}) {
15943: $initial_env{"browser.localpath"} = $form->{'localpath'};
15944: $initial_env{"browser.localres"} = $form->{'localres'};
15945: }
15946:
15947: if ($form->{'interface'}) {
15948: $form->{'interface'}=~s/\W//gs;
15949: $initial_env{"browser.interface"} = $form->{'interface'};
15950: $env{'browser.interface'}=$form->{'interface'};
15951: }
15952:
15953: if ($form->{'iptoken'}) {
15954: my $lonhost = $r->dir_config('lonHostID');
15955: $initial_env{"user.noloadbalance"} = $lonhost;
15956: $env{'user.noloadbalance'} = $lonhost;
15957: }
15958:
15959: my %is_adv = ( is_adv => $env{'user.adv'} );
15960: my %domdef;
15961: unless ($domain eq 'public') {
15962: %domdef = &Apache::lonnet::get_domain_defaults($domain);
15963: }
15964:
15965: foreach my $tool ('aboutme','blog','webdav','portfolio') {
15966: $userenv{'availabletools.'.$tool} =
15967: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
15968: undef,\%userenv,\%domdef,\%is_adv);
15969: }
15970:
15971: foreach my $crstype ('official','unofficial','community','textbook','placement') {
15972: $userenv{'canrequest.'.$crstype} =
15973: &Apache::lonnet::usertools_access($username,$domain,$crstype,
15974: 'reload','requestcourses',
15975: \%userenv,\%domdef,\%is_adv);
15976: }
15977:
15978: $userenv{'canrequest.author'} =
15979: &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
15980: 'reload','requestauthor',
15981: \%userenv,\%domdef,\%is_adv);
15982: my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
15983: $domain,$username);
15984: my $reqstatus = $reqauthor{'author_status'};
15985: if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
15986: if (ref($reqauthor{'author'}) eq 'HASH') {
15987: $userenv{'requestauthorqueued'} = $reqstatus.':'.
15988: $reqauthor{'author'}{'timestamp'};
15989: }
15990: }
15991:
15992: $env{'user.environment'} = "$lonids/$cookie.id";
15993:
15994: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
15995: &GDBM_WRCREAT(),0640)) {
15996: &_add_to_env(\%disk_env,\%initial_env);
15997: &_add_to_env(\%disk_env,\%userenv,'environment.');
15998: &_add_to_env(\%disk_env,$userroles);
15999: if (ref($firstaccenv) eq 'HASH') {
16000: &_add_to_env(\%disk_env,$firstaccenv);
16001: }
16002: if (ref($timerintenv) eq 'HASH') {
16003: &_add_to_env(\%disk_env,$timerintenv);
16004: }
16005: if (ref($args->{'extra_env'})) {
16006: &_add_to_env(\%disk_env,$args->{'extra_env'});
16007: }
16008: untie(%disk_env);
16009: } else {
16010: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
16011: 'Could not create environment storage in lonauth: '.$!.'</span>');
16012: return 'error: '.$!;
16013: }
16014: }
16015: $env{'request.role'}='cm';
16016: $env{'request.role.adv'}=$env{'user.adv'};
16017: $env{'browser.type'}=$clientbrowser;
16018:
16019: return $cookie;
16020:
16021: }
16022:
16023: sub _add_to_env {
16024: my ($idf,$env_data,$prefix) = @_;
16025: if (ref($env_data) eq 'HASH') {
16026: while (my ($key,$value) = each(%$env_data)) {
16027: $idf->{$prefix.$key} = $value;
16028: $env{$prefix.$key} = $value;
16029: }
16030: }
16031: }
16032:
16033: # --- Get the symbolic name of a problem and the url
16034: sub get_symb {
16035: my ($request,$silent) = @_;
16036: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
16037: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
16038: if ($symb eq '') {
16039: if (!$silent) {
16040: if (ref($request)) {
16041: $request->print("Unable to handle ambiguous references:$url:.");
16042: }
16043: return ();
16044: }
16045: }
16046: &Apache::lonenc::check_decrypt(\$symb);
16047: return ($symb);
16048: }
16049:
16050: # --------------------------------------------------------------Get annotation
16051:
16052: sub get_annotation {
16053: my ($symb,$enc) = @_;
16054:
16055: my $key = $symb;
16056: if (!$enc) {
16057: $key =
16058: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
16059: }
16060: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
16061: return $annotation{$key};
16062: }
16063:
16064: sub clean_symb {
16065: my ($symb,$delete_enc) = @_;
16066:
16067: &Apache::lonenc::check_decrypt(\$symb);
16068: my $enc = $env{'request.enc'};
16069: if ($delete_enc) {
16070: delete($env{'request.enc'});
16071: }
16072:
16073: return ($symb,$enc);
16074: }
16075:
16076: ############################################################
16077: ############################################################
16078:
16079: =pod
16080:
16081: =head1 Routines for building display used to search for courses
16082:
16083:
16084: =over 4
16085:
16086: =item * &build_filters()
16087:
16088: Create markup for a table used to set filters to use when selecting
16089: courses in a domain. Used by lonpickcourse.pm, lonmodifycourse.pm
16090: and quotacheck.pl
16091:
16092:
16093: Inputs:
16094:
16095: filterlist - anonymous array of fields to include as potential filters
16096:
16097: crstype - course type
16098:
16099: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
16100: to pop-open a course selector (will contain "extra element").
16101:
16102: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
16103:
16104: filter - anonymous hash of criteria and their values
16105:
16106: action - form action
16107:
16108: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
16109:
16110: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
16111:
16112: cloneruname - username of owner of new course who wants to clone
16113:
16114: clonerudom - domain of owner of new course who wants to clone
16115:
16116: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
16117:
16118: codetitlesref - reference to array of titles of components in institutional codes (official courses)
16119:
16120: codedom - domain
16121:
16122: formname - value of form element named "form".
16123:
16124: fixeddom - domain, if fixed.
16125:
16126: prevphase - value to assign to form element named "phase" when going back to the previous screen
16127:
16128: cnameelement - name of form element in form on opener page which will receive title of selected course
16129:
16130: cnumelement - name of form element in form on opener page which will receive courseID of selected course
16131:
16132: cdomelement - name of form element in form on opener page which will receive domain of selected course
16133:
16134: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
16135:
16136: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
16137:
16138: clonewarning - warning message about missing information for intended course owner when DC creates a course
16139:
16140:
16141: Returns: $output - HTML for display of search criteria, and hidden form elements.
16142:
16143:
16144: Side Effects: None
16145:
16146: =cut
16147:
16148: # ---------------------------------------------- search for courses based on last activity etc.
16149:
16150: sub build_filters {
16151: my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
16152: $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
16153: $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
16154: $cnameelement,$cnumelement,$cdomelement,$setroles,
16155: $clonetext,$clonewarning) = @_;
16156: my ($list,$jscript);
16157: my $onchange = 'javascript:updateFilters(this)';
16158: my ($domainselectform,$sincefilterform,$createdfilterform,
16159: $ownerdomselectform,$persondomselectform,$instcodeform,
16160: $typeselectform,$instcodetitle);
16161: if ($formname eq '') {
16162: $formname = $caller;
16163: }
16164: foreach my $item (@{$filterlist}) {
16165: unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
16166: ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
16167: if ($item eq 'domainfilter') {
16168: $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
16169: } elsif ($item eq 'coursefilter') {
16170: $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
16171: } elsif ($item eq 'ownerfilter') {
16172: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16173: } elsif ($item eq 'ownerdomfilter') {
16174: $filter->{'ownerdomfilter'} =
16175: &LONCAPA::clean_domain($filter->{$item});
16176: $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
16177: 'ownerdomfilter',1);
16178: } elsif ($item eq 'personfilter') {
16179: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16180: } elsif ($item eq 'persondomfilter') {
16181: $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
16182: 'persondomfilter',1);
16183: } else {
16184: $filter->{$item} =~ s/\W//g;
16185: }
16186: if (!$filter->{$item}) {
16187: $filter->{$item} = '';
16188: }
16189: }
16190: if ($item eq 'domainfilter') {
16191: my $allow_blank = 1;
16192: if ($formname eq 'portform') {
16193: $allow_blank=0;
16194: } elsif ($formname eq 'studentform') {
16195: $allow_blank=0;
16196: }
16197: if ($fixeddom) {
16198: $domainselectform = '<input type="hidden" name="domainfilter"'.
16199: ' value="'.$codedom.'" />'.
16200: &Apache::lonnet::domain($codedom,'description');
16201: } else {
16202: $domainselectform = &select_dom_form($filter->{$item},
16203: 'domainfilter',
16204: $allow_blank,'',$onchange);
16205: }
16206: } else {
16207: $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
16208: }
16209: }
16210:
16211: # last course activity filter and selection
16212: $sincefilterform = &timebased_select_form('sincefilter',$filter);
16213:
16214: # course created filter and selection
16215: if (exists($filter->{'createdfilter'})) {
16216: $createdfilterform = &timebased_select_form('createdfilter',$filter);
16217: }
16218:
16219: my $prefix = $crstype;
16220: if ($crstype eq 'Placement') {
16221: $prefix = 'Placement Test'
16222: }
16223: my %lt = &Apache::lonlocal::texthash(
16224: 'cac' => "$prefix Activity",
16225: 'ccr' => "$prefix Created",
16226: 'cde' => "$prefix Title",
16227: 'cdo' => "$prefix Domain",
16228: 'ins' => 'Institutional Code',
16229: 'inc' => 'Institutional Categorization',
16230: 'cow' => "$prefix Owner/Co-owner",
16231: 'cop' => "$prefix Personnel Includes",
16232: 'cog' => 'Type',
16233: );
16234:
16235: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16236: my $typeval = 'Course';
16237: if ($crstype eq 'Community') {
16238: $typeval = 'Community';
16239: } elsif ($crstype eq 'Placement') {
16240: $typeval = 'Placement';
16241: }
16242: $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
16243: } else {
16244: $typeselectform = '<select name="type" size="1"';
16245: if ($onchange) {
16246: $typeselectform .= ' onchange="'.$onchange.'"';
16247: }
16248: $typeselectform .= '>'."\n";
16249: foreach my $posstype ('Course','Community','Placement') {
16250: my $shown;
16251: if ($posstype eq 'Placement') {
16252: $shown = &mt('Placement Test');
16253: } else {
16254: $shown = &mt($posstype);
16255: }
16256: $typeselectform.='<option value="'.$posstype.'"'.
16257: ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
16258: }
16259: $typeselectform.="</select>";
16260: }
16261:
16262: my ($cloneableonlyform,$cloneabletitle);
16263: if (exists($filter->{'cloneableonly'})) {
16264: my $cloneableon = '';
16265: my $cloneableoff = ' checked="checked"';
16266: if ($filter->{'cloneableonly'}) {
16267: $cloneableon = $cloneableoff;
16268: $cloneableoff = '';
16269: }
16270: $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>';
16271: if ($formname eq 'ccrs') {
16272: $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
16273: } else {
16274: $cloneabletitle = &mt('Cloneable by you');
16275: }
16276: }
16277: my $officialjs;
16278: if ($crstype eq 'Course') {
16279: if (exists($filter->{'instcodefilter'})) {
16280: # if (($fixeddom) || ($formname eq 'requestcrs') ||
16281: # ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
16282: if ($codedom) {
16283: $officialjs = 1;
16284: ($instcodeform,$jscript,$$numtitlesref) =
16285: &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
16286: $officialjs,$codetitlesref);
16287: if ($jscript) {
16288: $jscript = '<script type="text/javascript">'."\n".
16289: '// <![CDATA['."\n".
16290: $jscript."\n".
16291: '// ]]>'."\n".
16292: '</script>'."\n";
16293: }
16294: }
16295: if ($instcodeform eq '') {
16296: $instcodeform =
16297: '<input type="text" name="instcodefilter" size="10" value="'.
16298: $list->{'instcodefilter'}.'" />';
16299: $instcodetitle = $lt{'ins'};
16300: } else {
16301: $instcodetitle = $lt{'inc'};
16302: }
16303: if ($fixeddom) {
16304: $instcodetitle .= '<br />('.$codedom.')';
16305: }
16306: }
16307: }
16308: my $output = qq|
16309: <form method="post" name="filterpicker" action="$action">
16310: <input type="hidden" name="form" value="$formname" />
16311: |;
16312: if ($formname eq 'modifycourse') {
16313: $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
16314: '<input type="hidden" name="prevphase" value="'.
16315: $prevphase.'" />'."\n";
16316: } elsif ($formname eq 'quotacheck') {
16317: $output .= qq|
16318: <input type="hidden" name="sortby" value="" />
16319: <input type="hidden" name="sortorder" value="" />
16320: |;
16321: } else {
16322: my $name_input;
16323: if ($cnameelement ne '') {
16324: $name_input = '<input type="hidden" name="cnameelement" value="'.
16325: $cnameelement.'" />';
16326: }
16327: $output .= qq|
16328: <input type="hidden" name="cnumelement" value="$cnumelement" />
16329: <input type="hidden" name="cdomelement" value="$cdomelement" />
16330: $name_input
16331: $roleelement
16332: $multelement
16333: $typeelement
16334: |;
16335: if ($formname eq 'portform') {
16336: $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
16337: }
16338: }
16339: if ($fixeddom) {
16340: $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
16341: }
16342: $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
16343: if ($sincefilterform) {
16344: $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
16345: .$sincefilterform
16346: .&Apache::lonhtmlcommon::row_closure();
16347: }
16348: if ($createdfilterform) {
16349: $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
16350: .$createdfilterform
16351: .&Apache::lonhtmlcommon::row_closure();
16352: }
16353: if ($domainselectform) {
16354: $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
16355: .$domainselectform
16356: .&Apache::lonhtmlcommon::row_closure();
16357: }
16358: if ($typeselectform) {
16359: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16360: $output .= $typeselectform;
16361: } else {
16362: $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
16363: .$typeselectform
16364: .&Apache::lonhtmlcommon::row_closure();
16365: }
16366: }
16367: if ($instcodeform) {
16368: $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
16369: .$instcodeform
16370: .&Apache::lonhtmlcommon::row_closure();
16371: }
16372: if (exists($filter->{'ownerfilter'})) {
16373: $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
16374: '<table><tr><td>'.&mt('Username').'<br />'.
16375: '<input type="text" name="ownerfilter" size="20" value="'.
16376: $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16377: $ownerdomselectform.'</td></tr></table>'.
16378: &Apache::lonhtmlcommon::row_closure();
16379: }
16380: if (exists($filter->{'personfilter'})) {
16381: $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
16382: '<table><tr><td>'.&mt('Username').'<br />'.
16383: '<input type="text" name="personfilter" size="20" value="'.
16384: $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16385: $persondomselectform.'</td></tr></table>'.
16386: &Apache::lonhtmlcommon::row_closure();
16387: }
16388: if (exists($filter->{'coursefilter'})) {
16389: $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
16390: .'<input type="text" name="coursefilter" size="25" value="'
16391: .$list->{'coursefilter'}.'" />'
16392: .&Apache::lonhtmlcommon::row_closure();
16393: }
16394: if ($cloneableonlyform) {
16395: $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
16396: $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
16397: }
16398: if (exists($filter->{'descriptfilter'})) {
16399: $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
16400: .'<input type="text" name="descriptfilter" size="40" value="'
16401: .$list->{'descriptfilter'}.'" />'
16402: .&Apache::lonhtmlcommon::row_closure(1);
16403: }
16404: $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
16405: '<input type="hidden" name="updater" value="" />'."\n".
16406: '<input type="submit" name="gosearch" value="'.
16407: &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
16408: return $jscript.$clonewarning.$output;
16409: }
16410:
16411: =pod
16412:
16413: =item * &timebased_select_form()
16414:
16415: Create markup for a dropdown list used to select a time-based
16416: filter e.g., Course Activity, Course Created, when searching for courses
16417: or communities
16418:
16419: Inputs:
16420:
16421: item - name of form element (sincefilter or createdfilter)
16422:
16423: filter - anonymous hash of criteria and their values
16424:
16425: Returns: HTML for a select box contained a blank, then six time selections,
16426: with value set in incoming form variables currently selected.
16427:
16428: Side Effects: None
16429:
16430: =cut
16431:
16432: sub timebased_select_form {
16433: my ($item,$filter) = @_;
16434: if (ref($filter) eq 'HASH') {
16435: $filter->{$item} =~ s/[^\d-]//g;
16436: if (!$filter->{$item}) { $filter->{$item}=-1; }
16437: return &select_form(
16438: $filter->{$item},
16439: $item,
16440: { '-1' => '',
16441: '86400' => &mt('today'),
16442: '604800' => &mt('last week'),
16443: '2592000' => &mt('last month'),
16444: '7776000' => &mt('last three months'),
16445: '15552000' => &mt('last six months'),
16446: '31104000' => &mt('last year'),
16447: 'select_form_order' =>
16448: ['-1','86400','604800','2592000','7776000',
16449: '15552000','31104000']});
16450: }
16451: }
16452:
16453: =pod
16454:
16455: =item * &js_changer()
16456:
16457: Create script tag containing Javascript used to submit course search form
16458: when course type or domain is changed, and also to hide 'Searching ...' on
16459: page load completion for page showing search result.
16460:
16461: Inputs: None
16462:
16463: Returns: markup containing updateFilters() and hideSearching() javascript functions.
16464:
16465: Side Effects: None
16466:
16467: =cut
16468:
16469: sub js_changer {
16470: return <<ENDJS;
16471: <script type="text/javascript">
16472: // <![CDATA[
16473: function updateFilters(caller) {
16474: if (typeof(caller) != "undefined") {
16475: document.filterpicker.updater.value = caller.name;
16476: }
16477: document.filterpicker.submit();
16478: }
16479:
16480: function hideSearching() {
16481: if (document.getElementById('searching')) {
16482: document.getElementById('searching').style.display = 'none';
16483: }
16484: return;
16485: }
16486:
16487: // ]]>
16488: </script>
16489:
16490: ENDJS
16491: }
16492:
16493: =pod
16494:
16495: =item * &search_courses()
16496:
16497: Process selected filters form course search form and pass to lonnet::courseiddump
16498: to retrieve a hash for which keys are courseIDs which match the selected filters.
16499:
16500: Inputs:
16501:
16502: dom - domain being searched
16503:
16504: type - course type ('Course' or 'Community' or '.' if any).
16505:
16506: filter - anonymous hash of criteria and their values
16507:
16508: numtitles - for institutional codes - number of categories
16509:
16510: cloneruname - optional username of new course owner
16511:
16512: clonerudom - optional domain of new course owner
16513:
16514: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
16515: (used when DC is using course creation form)
16516:
16517: codetitles - reference to array of titles of components in institutional codes (official courses).
16518:
16519: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16520: (and so can clone automatically)
16521:
16522: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16523:
16524: reqinstcode - institutional code of new course, where search_courses is used to identify potential
16525: courses to clone
16526:
16527: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
16528:
16529:
16530: Side Effects: None
16531:
16532: =cut
16533:
16534:
16535: sub search_courses {
16536: my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
16537: $cc_clone,$reqcrsdom,$reqinstcode) = @_;
16538: my (%courses,%showcourses,$cloner);
16539: if (($filter->{'ownerfilter'} ne '') ||
16540: ($filter->{'ownerdomfilter'} ne '')) {
16541: $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
16542: $filter->{'ownerdomfilter'};
16543: }
16544: foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
16545: if (!$filter->{$item}) {
16546: $filter->{$item}='.';
16547: }
16548: }
16549: my $now = time;
16550: my $timefilter =
16551: ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
16552: my ($createdbefore,$createdafter);
16553: if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
16554: $createdbefore = $now;
16555: $createdafter = $now-$filter->{'createdfilter'};
16556: }
16557: my ($instcodefilter,$regexpok);
16558: if ($numtitles) {
16559: if ($env{'form.official'} eq 'on') {
16560: $instcodefilter =
16561: &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16562: $regexpok = 1;
16563: } elsif ($env{'form.official'} eq 'off') {
16564: $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16565: unless ($instcodefilter eq '') {
16566: $regexpok = -1;
16567: }
16568: }
16569: } else {
16570: $instcodefilter = $filter->{'instcodefilter'};
16571: }
16572: if ($instcodefilter eq '') { $instcodefilter = '.'; }
16573: if ($type eq '') { $type = '.'; }
16574:
16575: if (($clonerudom ne '') && ($cloneruname ne '')) {
16576: $cloner = $cloneruname.':'.$clonerudom;
16577: }
16578: %courses = &Apache::lonnet::courseiddump($dom,
16579: $filter->{'descriptfilter'},
16580: $timefilter,
16581: $instcodefilter,
16582: $filter->{'combownerfilter'},
16583: $filter->{'coursefilter'},
16584: undef,undef,$type,$regexpok,undef,undef,
16585: undef,undef,$cloner,$cc_clone,
16586: $filter->{'cloneableonly'},
16587: $createdbefore,$createdafter,undef,
16588: $domcloner,undef,$reqcrsdom,$reqinstcode);
16589: if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
16590: my $ccrole;
16591: if ($type eq 'Community') {
16592: $ccrole = 'co';
16593: } else {
16594: $ccrole = 'cc';
16595: }
16596: my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
16597: $filter->{'persondomfilter'},
16598: 'userroles',undef,
16599: [$ccrole,'in','ad','ep','ta','cr'],
16600: $dom);
16601: foreach my $role (keys(%rolehash)) {
16602: my ($cnum,$cdom,$courserole) = split(':',$role);
16603: my $cid = $cdom.'_'.$cnum;
16604: if (exists($courses{$cid})) {
16605: if (ref($courses{$cid}) eq 'HASH') {
16606: if (ref($courses{$cid}{roles}) eq 'ARRAY') {
16607: if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
16608: push (@{$courses{$cid}{roles}},$courserole);
16609: }
16610: } else {
16611: $courses{$cid}{roles} = [$courserole];
16612: }
16613: $showcourses{$cid} = $courses{$cid};
16614: }
16615: }
16616: }
16617: %courses = %showcourses;
16618: }
16619: return %courses;
16620: }
16621:
16622: =pod
16623:
16624: =back
16625:
16626: =head1 Routines for version requirements for current course.
16627:
16628: =over 4
16629:
16630: =item * &check_release_required()
16631:
16632: Compares required LON-CAPA version with version on server, and
16633: if required version is newer looks for a server with the required version.
16634:
16635: Looks first at servers in user's owen domain; if none suitable, looks at
16636: servers in course's domain are permitted to host sessions for user's domain.
16637:
16638: Inputs:
16639:
16640: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16641:
16642: $courseid - Course ID of current course
16643:
16644: $rolecode - User's current role in course (for switchserver query string).
16645:
16646: $required - LON-CAPA version needed by course (format: Major.Minor).
16647:
16648:
16649: Returns:
16650:
16651: $switchserver - query string tp append to /adm/switchserver call (if
16652: current server's LON-CAPA version is too old.
16653:
16654: $warning - Message is displayed if no suitable server could be found.
16655:
16656: =cut
16657:
16658: sub check_release_required {
16659: my ($loncaparev,$courseid,$rolecode,$required) = @_;
16660: my ($switchserver,$warning);
16661: if ($required ne '') {
16662: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
16663: my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16664: if ($reqdmajor ne '' && $reqdminor ne '') {
16665: my $otherserver;
16666: if (($major eq '' && $minor eq '') ||
16667: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
16668: my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
16669: my $switchlcrev =
16670: &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
16671: $userdomserver);
16672: my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16673: if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
16674: (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
16675: my $cdom = $env{'course.'.$courseid.'.domain'};
16676: if ($cdom ne $env{'user.domain'}) {
16677: my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
16678: my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
16679: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16680: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
16681: my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
16682: my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
16683: my $canhost =
16684: &Apache::lonnet::can_host_session($env{'user.domain'},
16685: $coursedomserver,
16686: $remoterev,
16687: $udomdefaults{'remotesessions'},
16688: $defdomdefaults{'hostedsessions'});
16689:
16690: if ($canhost) {
16691: $otherserver = $coursedomserver;
16692: } else {
16693: $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.");
16694: }
16695: } else {
16696: $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).");
16697: }
16698: } else {
16699: $otherserver = $userdomserver;
16700: }
16701: }
16702: if ($otherserver ne '') {
16703: $switchserver = 'otherserver='.$otherserver.'&role='.$rolecode;
16704: }
16705: }
16706: }
16707: return ($switchserver,$warning);
16708: }
16709:
16710: =pod
16711:
16712: =item * &check_release_result()
16713:
16714: Inputs:
16715:
16716: $switchwarning - Warning message if no suitable server found to host session.
16717:
16718: $switchserver - query string to append to /adm/switchserver containing lonHostID
16719: and current role.
16720:
16721: Returns: HTML to display with information about requirement to switch server.
16722: Either displaying warning with link to Roles/Courses screen or
16723: display link to switchserver.
16724:
16725: =cut
16726:
16727: sub check_release_result {
16728: my ($switchwarning,$switchserver) = @_;
16729: my $output = &start_page('Selected course unavailable on this server').
16730: '<p class="LC_warning">';
16731: if ($switchwarning) {
16732: $output .= $switchwarning.'<br /><a href="/adm/roles">';
16733: if (&show_course()) {
16734: $output .= &mt('Display courses');
16735: } else {
16736: $output .= &mt('Display roles');
16737: }
16738: $output .= '</a>';
16739: } elsif ($switchserver) {
16740: $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
16741: '<br />'.
16742: '<a href="/adm/switchserver?'.$switchserver.'">'.
16743: &mt('Switch Server').
16744: '</a>';
16745: }
16746: $output .= '</p>'.&end_page();
16747: return $output;
16748: }
16749:
16750: =pod
16751:
16752: =item * &needs_coursereinit()
16753:
16754: Determine if course contents stored for user's session needs to be
16755: refreshed, because content has changed since "Big Hash" last tied.
16756:
16757: Check for change is made if time last checked is more than 10 minutes ago
16758: (by default).
16759:
16760: Inputs:
16761:
16762: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16763:
16764: $interval (optional) - Time which may elapse (in s) between last check for content
16765: change in current course. (default: 600 s).
16766:
16767: Returns: an array; first element is:
16768:
16769: =over 4
16770:
16771: 'switch' - if content updates mean user's session
16772: needs to be switched to a server running a newer LON-CAPA version
16773:
16774: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
16775: on current server hosting user's session
16776:
16777: '' - if no action required.
16778:
16779: =back
16780:
16781: If first item element is 'switch':
16782:
16783: second item is $switchwarning - Warning message if no suitable server found to host session.
16784:
16785: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
16786: and current role.
16787:
16788: otherwise: no other elements returned.
16789:
16790: =back
16791:
16792: =cut
16793:
16794: sub needs_coursereinit {
16795: my ($loncaparev,$interval) = @_;
16796: return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
16797: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
16798: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
16799: my $now = time;
16800: if ($interval eq '') {
16801: $interval = 600;
16802: }
16803: if (($now-$env{'request.course.timechecked'})>$interval) {
16804: my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
16805: &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
16806: if ($lastchange > $env{'request.course.tied'}) {
16807: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16808: if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
16809: my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
16810: if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
16811: &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
16812: $curr_reqd_hash{'internal.releaserequired'}});
16813: my ($switchserver,$switchwarning) =
16814: &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
16815: $curr_reqd_hash{'internal.releaserequired'});
16816: if ($switchwarning ne '' || $switchserver ne '') {
16817: return ('switch',$switchwarning,$switchserver);
16818: }
16819: }
16820: }
16821: return ('update');
16822: }
16823: }
16824: return ();
16825: }
16826:
16827: sub update_content_constraints {
16828: my ($cdom,$cnum,$chome,$cid) = @_;
16829: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16830: my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
16831: my %checkresponsetypes;
16832: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
16833: my ($item,$name,$value) = split(/:/,$key);
16834: if ($item eq 'resourcetag') {
16835: if ($name eq 'responsetype') {
16836: $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
16837: }
16838: }
16839: }
16840: my $navmap = Apache::lonnavmaps::navmap->new();
16841: if (defined($navmap)) {
16842: my %allresponses;
16843: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
16844: my %responses = $res->responseTypes();
16845: foreach my $key (keys(%responses)) {
16846: next unless(exists($checkresponsetypes{$key}));
16847: $allresponses{$key} += $responses{$key};
16848: }
16849: }
16850: foreach my $key (keys(%allresponses)) {
16851: my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
16852: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
16853: ($reqdmajor,$reqdminor) = ($major,$minor);
16854: }
16855: }
16856: undef($navmap);
16857: }
16858: unless (($reqdmajor eq '') && ($reqdminor eq '')) {
16859: &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
16860: }
16861: return;
16862: }
16863:
16864: sub allmaps_incourse {
16865: my ($cdom,$cnum,$chome,$cid) = @_;
16866: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
16867: $cid = $env{'request.course.id'};
16868: $cdom = $env{'course.'.$cid.'.domain'};
16869: $cnum = $env{'course.'.$cid.'.num'};
16870: $chome = $env{'course.'.$cid.'.home'};
16871: }
16872: my %allmaps = ();
16873: my $lastchange =
16874: &Apache::lonnet::get_coursechange($cdom,$cnum);
16875: if ($lastchange > $env{'request.course.tied'}) {
16876: my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
16877: unless ($ferr) {
16878: &update_content_constraints($cdom,$cnum,$chome,$cid);
16879: }
16880: }
16881: my $navmap = Apache::lonnavmaps::navmap->new();
16882: if (defined($navmap)) {
16883: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
16884: $allmaps{$res->src()} = 1;
16885: }
16886: }
16887: return \%allmaps;
16888: }
16889:
16890: sub parse_supplemental_title {
16891: my ($title) = @_;
16892:
16893: my ($foldertitle,$renametitle);
16894: if ($title =~ /&&&/) {
16895: $title = &HTML::Entites::decode($title);
16896: }
16897: if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
16898: $renametitle=$4;
16899: my ($time,$uname,$udom) = ($1,$2,$3);
16900: $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
16901: my $name = &plainname($uname,$udom);
16902: $name = &HTML::Entities::encode($name,'"<>&\'');
16903: $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
16904: $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
16905: $name.': <br />'.$foldertitle;
16906: }
16907: if (wantarray) {
16908: return ($title,$foldertitle,$renametitle);
16909: }
16910: return $title;
16911: }
16912:
16913: sub recurse_supplemental {
16914: my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
16915: if ($suppmap) {
16916: my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
16917: if ($fatal) {
16918: $errors ++;
16919: } else {
16920: if ($#LONCAPA::map::resources > 0) {
16921: foreach my $res (@LONCAPA::map::resources) {
16922: my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
16923: if (($src ne '') && ($status eq 'res')) {
16924: if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
16925: ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
16926: } else {
16927: $numfiles ++;
16928: }
16929: }
16930: }
16931: }
16932: }
16933: }
16934: return ($numfiles,$errors);
16935: }
16936:
16937: sub symb_to_docspath {
16938: my ($symb) = @_;
16939: return unless ($symb);
16940: my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
16941: if ($resurl=~/\.(sequence|page)$/) {
16942: $mapurl=$resurl;
16943: } elsif ($resurl eq 'adm/navmaps') {
16944: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
16945: }
16946: my $mapresobj;
16947: my $navmap = Apache::lonnavmaps::navmap->new();
16948: if (ref($navmap)) {
16949: $mapresobj = $navmap->getResourceByUrl($mapurl);
16950: }
16951: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
16952: my $type=$2;
16953: my $path;
16954: if (ref($mapresobj)) {
16955: my $pcslist = $mapresobj->map_hierarchy();
16956: if ($pcslist ne '') {
16957: foreach my $pc (split(/,/,$pcslist)) {
16958: next if ($pc <= 1);
16959: my $res = $navmap->getByMapPc($pc);
16960: if (ref($res)) {
16961: my $thisurl = $res->src();
16962: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
16963: my $thistitle = $res->title();
16964: $path .= '&'.
16965: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
16966: &escape($thistitle).
16967: ':'.$res->randompick().
16968: ':'.$res->randomout().
16969: ':'.$res->encrypted().
16970: ':'.$res->randomorder().
16971: ':'.$res->is_page();
16972: }
16973: }
16974: }
16975: $path =~ s/^\&//;
16976: my $maptitle = $mapresobj->title();
16977: if ($mapurl eq 'default') {
16978: $maptitle = 'Main Content';
16979: }
16980: $path .= (($path ne '')? '&' : '').
16981: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16982: &escape($maptitle).
16983: ':'.$mapresobj->randompick().
16984: ':'.$mapresobj->randomout().
16985: ':'.$mapresobj->encrypted().
16986: ':'.$mapresobj->randomorder().
16987: ':'.$mapresobj->is_page();
16988: } else {
16989: my $maptitle = &Apache::lonnet::gettitle($mapurl);
16990: my $ispage = (($type eq 'page')? 1 : '');
16991: if ($mapurl eq 'default') {
16992: $maptitle = 'Main Content';
16993: }
16994: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16995: &escape($maptitle).':::::'.$ispage;
16996: }
16997: unless ($mapurl eq 'default') {
16998: $path = 'default&'.
16999: &escape('Main Content').
17000: ':::::&'.$path;
17001: }
17002: return $path;
17003: }
17004:
17005: sub captcha_display {
17006: my ($context,$lonhost) = @_;
17007: my ($output,$error);
17008: my ($captcha,$pubkey,$privkey,$version) =
17009: &get_captcha_config($context,$lonhost);
17010: if ($captcha eq 'original') {
17011: $output = &create_captcha();
17012: unless ($output) {
17013: $error = 'captcha';
17014: }
17015: } elsif ($captcha eq 'recaptcha') {
17016: $output = &create_recaptcha($pubkey,$version);
17017: unless ($output) {
17018: $error = 'recaptcha';
17019: }
17020: }
17021: return ($output,$error,$captcha,$version);
17022: }
17023:
17024: sub captcha_response {
17025: my ($context,$lonhost) = @_;
17026: my ($captcha_chk,$captcha_error);
17027: my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
17028: if ($captcha eq 'original') {
17029: ($captcha_chk,$captcha_error) = &check_captcha();
17030: } elsif ($captcha eq 'recaptcha') {
17031: $captcha_chk = &check_recaptcha($privkey,$version);
17032: } else {
17033: $captcha_chk = 1;
17034: }
17035: return ($captcha_chk,$captcha_error);
17036: }
17037:
17038: sub get_captcha_config {
17039: my ($context,$lonhost) = @_;
17040: my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
17041: my $hostname = &Apache::lonnet::hostname($lonhost);
17042: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
17043: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17044: if ($context eq 'usercreation') {
17045: my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
17046: if (ref($domconfig{$context}) eq 'HASH') {
17047: $hashtocheck = $domconfig{$context}{'cancreate'};
17048: if (ref($hashtocheck) eq 'HASH') {
17049: if ($hashtocheck->{'captcha'} eq 'recaptcha') {
17050: if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
17051: $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
17052: $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
17053: }
17054: if ($privkey && $pubkey) {
17055: $captcha = 'recaptcha';
17056: $version = $hashtocheck->{'recaptchaversion'};
17057: if ($version ne '2') {
17058: $version = 1;
17059: }
17060: } else {
17061: $captcha = 'original';
17062: }
17063: } elsif ($hashtocheck->{'captcha'} ne 'notused') {
17064: $captcha = 'original';
17065: }
17066: }
17067: } else {
17068: $captcha = 'captcha';
17069: }
17070: } elsif ($context eq 'login') {
17071: my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
17072: if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
17073: $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
17074: $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
17075: if ($privkey && $pubkey) {
17076: $captcha = 'recaptcha';
17077: $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
17078: if ($version ne '2') {
17079: $version = 1;
17080: }
17081: } else {
17082: $captcha = 'original';
17083: }
17084: } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
17085: $captcha = 'original';
17086: }
17087: }
17088: return ($captcha,$pubkey,$privkey,$version);
17089: }
17090:
17091: sub create_captcha {
17092: my %captcha_params = &captcha_settings();
17093: my ($output,$maxtries,$tries) = ('',10,0);
17094: while ($tries < $maxtries) {
17095: $tries ++;
17096: my $captcha = Authen::Captcha->new (
17097: output_folder => $captcha_params{'output_dir'},
17098: data_folder => $captcha_params{'db_dir'},
17099: );
17100: my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
17101:
17102: if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
17103: $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
17104: &mt('Type in the letters/numbers shown below').' '.
17105: '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
17106: '<br />'.
17107: '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
17108: last;
17109: }
17110: }
17111: return $output;
17112: }
17113:
17114: sub captcha_settings {
17115: my %captcha_params = (
17116: output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'},
17117: www_output_dir => "/captchaspool",
17118: db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'},
17119: numchars => '5',
17120: );
17121: return %captcha_params;
17122: }
17123:
17124: sub check_captcha {
17125: my ($captcha_chk,$captcha_error);
17126: my $code = $env{'form.code'};
17127: my $md5sum = $env{'form.crypt'};
17128: my %captcha_params = &captcha_settings();
17129: my $captcha = Authen::Captcha->new(
17130: output_folder => $captcha_params{'output_dir'},
17131: data_folder => $captcha_params{'db_dir'},
17132: );
17133: $captcha_chk = $captcha->check_code($code,$md5sum);
17134: my %captcha_hash = (
17135: 0 => 'Code not checked (file error)',
17136: -1 => 'Failed: code expired',
17137: -2 => 'Failed: invalid code (not in database)',
17138: -3 => 'Failed: invalid code (code does not match crypt)',
17139: );
17140: if ($captcha_chk != 1) {
17141: $captcha_error = $captcha_hash{$captcha_chk}
17142: }
17143: return ($captcha_chk,$captcha_error);
17144: }
17145:
17146: sub create_recaptcha {
17147: my ($pubkey,$version) = @_;
17148: if ($version >= 2) {
17149: return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
17150: } else {
17151: my $use_ssl;
17152: if ($ENV{'SERVER_PORT'} == 443) {
17153: $use_ssl = 1;
17154: }
17155: my $captcha = Captcha::reCAPTCHA->new;
17156: return $captcha->get_options_setter({theme => 'white'})."\n".
17157: $captcha->get_html($pubkey,undef,$use_ssl).
17158: &mt('If the text is hard to read, [_1] will replace them.',
17159: '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
17160: '<br /><br />';
17161: }
17162: }
17163:
17164: sub check_recaptcha {
17165: my ($privkey,$version) = @_;
17166: my $captcha_chk;
17167: if ($version >= 2) {
17168: my $ua = LWP::UserAgent->new;
17169: $ua->timeout(10);
17170: my %info = (
17171: secret => $privkey,
17172: response => $env{'form.g-recaptcha-response'},
17173: remoteip => $ENV{'REMOTE_ADDR'},
17174: );
17175: my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
17176: if ($response->is_success) {
17177: my $data = JSON::DWIW->from_json($response->decoded_content);
17178: if (ref($data) eq 'HASH') {
17179: if ($data->{'success'}) {
17180: $captcha_chk = 1;
17181: }
17182: }
17183: }
17184: } else {
17185: my $captcha = Captcha::reCAPTCHA->new;
17186: my $captcha_result =
17187: $captcha->check_answer(
17188: $privkey,
17189: $ENV{'REMOTE_ADDR'},
17190: $env{'form.recaptcha_challenge_field'},
17191: $env{'form.recaptcha_response_field'},
17192: );
17193: if ($captcha_result->{is_valid}) {
17194: $captcha_chk = 1;
17195: }
17196: }
17197: return $captcha_chk;
17198: }
17199:
17200: sub emailusername_info {
17201: my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
17202: my %titles = &Apache::lonlocal::texthash (
17203: lastname => 'Last Name',
17204: firstname => 'First Name',
17205: institution => 'School/college/university',
17206: location => "School's city, state/province, country",
17207: web => "School's web address",
17208: officialemail => 'E-mail address at institution (if different)',
17209: id => 'Student/Employee ID',
17210: );
17211: return (\@fields,\%titles);
17212: }
17213:
17214: sub cleanup_html {
17215: my ($incoming) = @_;
17216: my $outgoing;
17217: if ($incoming ne '') {
17218: $outgoing = $incoming;
17219: $outgoing =~ s/;/;/g;
17220: $outgoing =~ s/\#/#/g;
17221: $outgoing =~ s/\&/&/g;
17222: $outgoing =~ s/</</g;
17223: $outgoing =~ s/>/>/g;
17224: $outgoing =~ s/\(/(/g;
17225: $outgoing =~ s/\)/)/g;
17226: $outgoing =~ s/"/"/g;
17227: $outgoing =~ s/'/'/g;
17228: $outgoing =~ s/\$/$/g;
17229: $outgoing =~ s{/}{/}g;
17230: $outgoing =~ s/=/=/g;
17231: $outgoing =~ s/\\/\/g
17232: }
17233: return $outgoing;
17234: }
17235:
17236: # Checks for critical messages and returns a redirect url if one exists.
17237: # $interval indicates how often to check for messages.
17238: sub critical_redirect {
17239: my ($interval) = @_;
17240: if ((time-$env{'user.criticalcheck.time'})>$interval) {
17241: my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
17242: $env{'user.name'});
17243: &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
17244: my $redirecturl;
17245: if ($what[0]) {
17246: if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
17247: $redirecturl='/adm/email?critical=display';
17248: my $url=&Apache::lonnet::absolute_url().$redirecturl;
17249: return (1, $url);
17250: }
17251: }
17252: }
17253: return ();
17254: }
17255:
17256: # Use:
17257: # my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
17258: #
17259: ##################################################
17260: # password associated functions #
17261: ##################################################
17262: sub des_keys {
17263: # Make a new key for DES encryption.
17264: # Each key has two parts which are returned separately.
17265: # Please note: Each key must be passed through the &hex function
17266: # before it is output to the web browser. The hex versions cannot
17267: # be used to decrypt.
17268: my @hexstr=('0','1','2','3','4','5','6','7',
17269: '8','9','a','b','c','d','e','f');
17270: my $lkey='';
17271: for (0..7) {
17272: $lkey.=$hexstr[rand(15)];
17273: }
17274: my $ukey='';
17275: for (0..7) {
17276: $ukey.=$hexstr[rand(15)];
17277: }
17278: return ($lkey,$ukey);
17279: }
17280:
17281: sub des_decrypt {
17282: my ($key,$cyphertext) = @_;
17283: my $keybin=pack("H16",$key);
17284: my $cypher;
17285: if ($Crypt::DES::VERSION>=2.03) {
17286: $cypher=new Crypt::DES $keybin;
17287: } else {
17288: $cypher=new DES $keybin;
17289: }
17290: my $plaintext='';
17291: my $cypherlength = length($cyphertext);
17292: my $numchunks = int($cypherlength/32);
17293: for (my $j=0; $j<$numchunks; $j++) {
17294: my $start = $j*32;
17295: my $cypherblock = substr($cyphertext,$start,32);
17296: my $chunk =
17297: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
17298: $chunk .=
17299: $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
17300: $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
17301: $plaintext .= $chunk;
17302: }
17303: return $plaintext;
17304: }
17305:
17306: 1;
17307: __END__;
17308:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>