File:
[LON-CAPA] /
loncom /
interface /
loncommon.pm
Revision
1.1115:
download - view:
text,
annotated -
select for diffs
Tue Feb 19 17:30:35 2013 UTC (11 years, 7 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Changes for Domain Coordinator's user listings screen
- "extent" column
- not shown/selectable if role type is domain.
- text for checkbox changed dynamically by javascript when role type of
course, community, or author selected.
- "status column"
- not selectable if role type is course or community.
1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1115 2013/02/19 17:30:35 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: # Makes a table out of the previous attempts
30: # Inputs result_from_symbread, user, domain, course_id
31: # Reads in non-network-related .tab files
32:
33: # POD header:
34:
35: =pod
36:
37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
45:
46: =head1 OVERVIEW
47:
48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
55: package Apache::loncommon;
56:
57: use strict;
58: use Apache::lonnet;
59: use GDBM_File;
60: use POSIX qw(strftime mktime);
61: use Apache::lonmenu();
62: use Apache::lonenc();
63: use Apache::lonlocal;
64: use Apache::lonnet();
65: use HTML::Entities;
66: use Apache::lonhtmlcommon();
67: use Apache::loncoursedata();
68: use Apache::lontexconvert();
69: use Apache::lonclonecourse();
70: use Apache::lonuserutils();
71: use Apache::lonuserstate();
72: use LONCAPA qw(:DEFAULT :match);
73: use DateTime::TimeZone;
74: use DateTime::Locale::Catalog;
75: use Text::Aspell;
76: use Authen::Captcha;
77: use Captcha::reCAPTCHA;
78:
79: # ---------------------------------------------- Designs
80: use vars qw(%defaultdesign);
81:
82: my $readit;
83:
84:
85: ##
86: ## Global Variables
87: ##
88:
89:
90: # ----------------------------------------------- SSI with retries:
91: #
92:
93: =pod
94:
95: =head1 Server Side include with retries:
96:
97: =over 4
98:
99: =item * &ssi_with_retries(resource,retries form)
100:
101: Performs an ssi with some number of retries. Retries continue either
102: until the result is ok or until the retry count supplied by the
103: caller is exhausted.
104:
105: Inputs:
106:
107: =over 4
108:
109: resource - Identifies the resource to insert.
110:
111: retries - Count of the number of retries allowed.
112:
113: form - Hash that identifies the rendering options.
114:
115: =back
116:
117: Returns:
118:
119: =over 4
120:
121: content - The content of the response. If retries were exhausted this is empty.
122:
123: response - The response from the last attempt (which may or may not have been successful.
124:
125: =back
126:
127: =back
128:
129: =cut
130:
131: sub ssi_with_retries {
132: my ($resource, $retries, %form) = @_;
133:
134:
135: my $ok = 0; # True if we got a good response.
136: my $content;
137: my $response;
138:
139: # Try to get the ssi done. within the retries count:
140:
141: do {
142: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
143: $ok = $response->is_success;
144: if (!$ok) {
145: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
146: }
147: $retries--;
148: } while (!$ok && ($retries > 0));
149:
150: if (!$ok) {
151: $content = ''; # On error return an empty content.
152: }
153: return ($content, $response);
154:
155: }
156:
157:
158:
159: # ----------------------------------------------- Filetypes/Languages/Copyright
160: my %language;
161: my %supported_language;
162: my %supported_codes;
163: my %latex_language; # For choosing hyphenation in <transl..>
164: my %latex_language_bykey; # for choosing hyphenation from metadata
165: my %cprtag;
166: my %scprtag;
167: my %fe; my %fd; my %fm;
168: my %category_extensions;
169:
170: # ---------------------------------------------- Thesaurus variables
171: #
172: # %Keywords:
173: # A hash used by &keyword to determine if a word is considered a keyword.
174: # $thesaurus_db_file
175: # Scalar containing the full path to the thesaurus database.
176:
177: my %Keywords;
178: my $thesaurus_db_file;
179:
180: #
181: # Initialize values from language.tab, copyright.tab, filetypes.tab,
182: # thesaurus.tab, and filecategories.tab.
183: #
184: BEGIN {
185: # Variable initialization
186: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
187: #
188: unless ($readit) {
189: # ------------------------------------------------------------------- languages
190: {
191: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
192: '/language.tab';
193: if ( open(my $fh,"<$langtabfile") ) {
194: while (my $line = <$fh>) {
195: next if ($line=~/^\#/);
196: chomp($line);
197: my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
198: $language{$key}=$val.' - '.$enc;
199: if ($sup) {
200: $supported_language{$key}=$sup;
201: $supported_codes{$key} = $code;
202: }
203: if ($latex) {
204: $latex_language_bykey{$key} = $latex;
205: $latex_language{$code} = $latex;
206: }
207: }
208: close($fh);
209: }
210: }
211: # ------------------------------------------------------------------ copyrights
212: {
213: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
214: '/copyright.tab';
215: if ( open (my $fh,"<$copyrightfile") ) {
216: while (my $line = <$fh>) {
217: next if ($line=~/^\#/);
218: chomp($line);
219: my ($key,$val)=(split(/\s+/,$line,2));
220: $cprtag{$key}=$val;
221: }
222: close($fh);
223: }
224: }
225: # ----------------------------------------------------------- source copyrights
226: {
227: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
228: '/source_copyright.tab';
229: if ( open (my $fh,"<$sourcecopyrightfile") ) {
230: while (my $line = <$fh>) {
231: next if ($line =~ /^\#/);
232: chomp($line);
233: my ($key,$val)=(split(/\s+/,$line,2));
234: $scprtag{$key}=$val;
235: }
236: close($fh);
237: }
238: }
239:
240: # -------------------------------------------------------------- default domain designs
241: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
242: my $designfile = $designdir.'/default.tab';
243: if ( open (my $fh,"<$designfile") ) {
244: while (my $line = <$fh>) {
245: next if ($line =~ /^\#/);
246: chomp($line);
247: my ($key,$val)=(split(/\=/,$line));
248: if ($val) { $defaultdesign{$key}=$val; }
249: }
250: close($fh);
251: }
252:
253: # ------------------------------------------------------------- file categories
254: {
255: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
256: '/filecategories.tab';
257: if ( open (my $fh,"<$categoryfile") ) {
258: while (my $line = <$fh>) {
259: next if ($line =~ /^\#/);
260: chomp($line);
261: my ($extension,$category)=(split(/\s+/,$line,2));
262: push @{$category_extensions{lc($category)}},$extension;
263: }
264: close($fh);
265: }
266:
267: }
268: # ------------------------------------------------------------------ file types
269: {
270: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
271: '/filetypes.tab';
272: if ( open (my $fh,"<$typesfile") ) {
273: while (my $line = <$fh>) {
274: next if ($line =~ /^\#/);
275: chomp($line);
276: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
277: if ($descr ne '') {
278: $fe{$ending}=lc($emb);
279: $fd{$ending}=$descr;
280: if ($mime ne 'unk') { $fm{$ending}=$mime; }
281: }
282: }
283: close($fh);
284: }
285: }
286: &Apache::lonnet::logthis(
287: "<span style='color:yellow;'>INFO: Read file types</span>");
288: $readit=1;
289: } # end of unless($readit)
290:
291: }
292:
293: ###############################################################
294: ## HTML and Javascript Helper Functions ##
295: ###############################################################
296:
297: =pod
298:
299: =head1 HTML and Javascript Functions
300:
301: =over 4
302:
303: =item * &browser_and_searcher_javascript()
304:
305: X<browsing, javascript>X<searching, javascript>Returns a string
306: containing javascript with two functions, C<openbrowser> and
307: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
308: tags.
309:
310: =item * &openbrowser(formname,elementname,only,omit) [javascript]
311:
312: inputs: formname, elementname, only, omit
313:
314: formname and elementname indicate the name of the html form and name of
315: the element that the results of the browsing selection are to be placed in.
316:
317: Specifying 'only' will restrict the browser to displaying only files
318: with the given extension. Can be a comma separated list.
319:
320: Specifying 'omit' will restrict the browser to NOT displaying files
321: with the given extension. Can be a comma separated list.
322:
323: =item * &opensearcher(formname,elementname) [javascript]
324:
325: Inputs: formname, elementname
326:
327: formname and elementname specify the name of the html form and the name
328: of the element the selection from the search results will be placed in.
329:
330: =cut
331:
332: sub browser_and_searcher_javascript {
333: my ($mode)=@_;
334: if (!defined($mode)) { $mode='edit'; }
335: my $resurl=&escape_single(&lastresurl());
336: return <<END;
337: // <!-- BEGIN LON-CAPA Internal
338: var editbrowser = null;
339: function openbrowser(formname,elementname,only,omit,titleelement) {
340: var url = '$resurl/?';
341: if (editbrowser == null) {
342: url += 'launch=1&';
343: }
344: url += 'catalogmode=interactive&';
345: url += 'mode=$mode&';
346: url += 'inhibitmenu=yes&';
347: url += 'form=' + formname + '&';
348: if (only != null) {
349: url += 'only=' + only + '&';
350: } else {
351: url += 'only=&';
352: }
353: if (omit != null) {
354: url += 'omit=' + omit + '&';
355: } else {
356: url += 'omit=&';
357: }
358: if (titleelement != null) {
359: url += 'titleelement=' + titleelement + '&';
360: } else {
361: url += 'titleelement=&';
362: }
363: url += 'element=' + elementname + '';
364: var title = 'Browser';
365: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
366: options += ',width=700,height=600';
367: editbrowser = open(url,title,options,'1');
368: editbrowser.focus();
369: }
370: var editsearcher;
371: function opensearcher(formname,elementname,titleelement) {
372: var url = '/adm/searchcat?';
373: if (editsearcher == null) {
374: url += 'launch=1&';
375: }
376: url += 'catalogmode=interactive&';
377: url += 'mode=$mode&';
378: url += 'form=' + formname + '&';
379: if (titleelement != null) {
380: url += 'titleelement=' + titleelement + '&';
381: } else {
382: url += 'titleelement=&';
383: }
384: url += 'element=' + elementname + '';
385: var title = 'Search';
386: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
387: options += ',width=700,height=600';
388: editsearcher = open(url,title,options,'1');
389: editsearcher.focus();
390: }
391: // END LON-CAPA Internal -->
392: END
393: }
394:
395: sub lastresurl {
396: if ($env{'environment.lastresurl'}) {
397: return $env{'environment.lastresurl'}
398: } else {
399: return '/res';
400: }
401: }
402:
403: sub storeresurl {
404: my $resurl=&Apache::lonnet::clutter(shift);
405: unless ($resurl=~/^\/res/) { return 0; }
406: $resurl=~s/\/$//;
407: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
408: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
409: return 1;
410: }
411:
412: sub studentbrowser_javascript {
413: unless (
414: (($env{'request.course.id'}) &&
415: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
416: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
417: '/'.$env{'request.course.sec'})
418: ))
419: || ($env{'request.role'}=~/^(au|dc|su)/)
420: ) { return ''; }
421: return (<<'ENDSTDBRW');
422: <script type="text/javascript" language="Javascript">
423: // <![CDATA[
424: var stdeditbrowser;
425: function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
426: var url = '/adm/pickstudent?';
427: var filter;
428: if (!ignorefilter) {
429: eval('filter=document.'+formname+'.'+uname+'.value;');
430: }
431: if (filter != null) {
432: if (filter != '') {
433: url += 'filter='+filter+'&';
434: }
435: }
436: url += 'form=' + formname + '&unameelement='+uname+
437: '&udomelement='+udom+
438: '&clicker='+clicker;
439: if (roleflag) { url+="&roles=1"; }
440: if (courseadvonly) { url+="&courseadvonly=1"; }
441: var title = 'Student_Browser';
442: var options = 'scrollbars=1,resizable=1,menubar=0';
443: options += ',width=700,height=600';
444: stdeditbrowser = open(url,title,options,'1');
445: stdeditbrowser.focus();
446: }
447: // ]]>
448: </script>
449: ENDSTDBRW
450: }
451:
452: sub resourcebrowser_javascript {
453: unless ($env{'request.course.id'}) { return ''; }
454: return (<<'ENDRESBRW');
455: <script type="text/javascript" language="Javascript">
456: // <![CDATA[
457: var reseditbrowser;
458: function openresbrowser(formname,reslink) {
459: var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
460: var title = 'Resource_Browser';
461: var options = 'scrollbars=1,resizable=1,menubar=0';
462: options += ',width=700,height=500';
463: reseditbrowser = open(url,title,options,'1');
464: reseditbrowser.focus();
465: }
466: // ]]>
467: </script>
468: ENDRESBRW
469: }
470:
471: sub selectstudent_link {
472: my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
473: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
474: &Apache::lonhtmlcommon::entity_encode($unameele)."','".
475: &Apache::lonhtmlcommon::entity_encode($udomele)."'";
476: if ($env{'request.course.id'}) {
477: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
478: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
479: '/'.$env{'request.course.sec'})) {
480: return '';
481: }
482: $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
483: if ($courseadvonly) {
484: $callargs .= ",'',1,1";
485: }
486: return '<span class="LC_nobreak">'.
487: '<a href="javascript:openstdbrowser('.$callargs.');">'.
488: &mt('Select User').'</a></span>';
489: }
490: if ($env{'request.role'}=~/^(au|dc|su)/) {
491: $callargs .= ",'',1";
492: return '<span class="LC_nobreak">'.
493: '<a href="javascript:openstdbrowser('.$callargs.');">'.
494: &mt('Select User').'</a></span>';
495: }
496: return '';
497: }
498:
499: sub selectresource_link {
500: my ($form,$reslink,$arg)=@_;
501:
502: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
503: &Apache::lonhtmlcommon::entity_encode($reslink)."'";
504: unless ($env{'request.course.id'}) { return $arg; }
505: return '<span class="LC_nobreak">'.
506: '<a href="javascript:openresbrowser('.$callargs.');">'.
507: $arg.'</a></span>';
508: }
509:
510:
511:
512: sub authorbrowser_javascript {
513: return <<"ENDAUTHORBRW";
514: <script type="text/javascript" language="JavaScript">
515: // <![CDATA[
516: var stdeditbrowser;
517:
518: function openauthorbrowser(formname,udom) {
519: var url = '/adm/pickauthor?';
520: url += 'form='+formname+'&roledom='+udom;
521: var title = 'Author_Browser';
522: var options = 'scrollbars=1,resizable=1,menubar=0';
523: options += ',width=700,height=600';
524: stdeditbrowser = open(url,title,options,'1');
525: stdeditbrowser.focus();
526: }
527:
528: // ]]>
529: </script>
530: ENDAUTHORBRW
531: }
532:
533: sub coursebrowser_javascript {
534: my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
535: my $wintitle = 'Course_Browser';
536: if ($crstype eq 'Community') {
537: $wintitle = 'Community_Browser';
538: }
539: my $id_functions = &javascript_index_functions();
540: my $output = '
541: <script type="text/javascript" language="JavaScript">
542: // <![CDATA[
543: var stdeditbrowser;'."\n";
544:
545: $output .= <<"ENDSTDBRW";
546: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
547: var url = '/adm/pickcourse?';
548: var formid = getFormIdByName(formname);
549: var domainfilter = getDomainFromSelectbox(formname,udom);
550: if (domainfilter != null) {
551: if (domainfilter != '') {
552: url += 'domainfilter='+domainfilter+'&';
553: }
554: }
555: url += 'form=' + formname + '&cnumelement='+uname+
556: '&cdomelement='+udom+
557: '&cnameelement='+desc;
558: if (extra_element !=null && extra_element != '') {
559: if (formname == 'rolechoice' || formname == 'studentform') {
560: url += '&roleelement='+extra_element;
561: if (domainfilter == null || domainfilter == '') {
562: url += '&domainfilter='+extra_element;
563: }
564: }
565: else {
566: if (formname == 'portform') {
567: url += '&setroles='+extra_element;
568: } else {
569: if (formname == 'rules') {
570: url += '&fixeddom='+extra_element;
571: }
572: }
573: }
574: }
575: if (type != null && type != '') {
576: url += '&type='+type;
577: }
578: if (type_elem != null && type_elem != '') {
579: url += '&typeelement='+type_elem;
580: }
581: if (formname == 'ccrs') {
582: var ownername = document.forms[formid].ccuname.value;
583: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
584: url += '&cloner='+ownername+':'+ownerdom;
585: }
586: if (multflag !=null && multflag != '') {
587: url += '&multiple='+multflag;
588: }
589: var title = '$wintitle';
590: var options = 'scrollbars=1,resizable=1,menubar=0';
591: options += ',width=700,height=600';
592: stdeditbrowser = open(url,title,options,'1');
593: stdeditbrowser.focus();
594: }
595: $id_functions
596: ENDSTDBRW
597: if (($sec_element ne '') || ($role_element ne '')) {
598: $output .= &setsec_javascript($sec_element,$formname,$role_element);
599: }
600: $output .= '
601: // ]]>
602: </script>';
603: return $output;
604: }
605:
606: sub javascript_index_functions {
607: return <<"ENDJS";
608:
609: function getFormIdByName(formname) {
610: for (var i=0;i<document.forms.length;i++) {
611: if (document.forms[i].name == formname) {
612: return i;
613: }
614: }
615: return -1;
616: }
617:
618: function getIndexByName(formid,item) {
619: for (var i=0;i<document.forms[formid].elements.length;i++) {
620: if (document.forms[formid].elements[i].name == item) {
621: return i;
622: }
623: }
624: return -1;
625: }
626:
627: function getDomainFromSelectbox(formname,udom) {
628: var userdom;
629: var formid = getFormIdByName(formname);
630: if (formid > -1) {
631: var domid = getIndexByName(formid,udom);
632: if (domid > -1) {
633: if (document.forms[formid].elements[domid].type == 'select-one') {
634: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
635: }
636: if (document.forms[formid].elements[domid].type == 'hidden') {
637: userdom=document.forms[formid].elements[domid].value;
638: }
639: }
640: }
641: return userdom;
642: }
643:
644: ENDJS
645:
646: }
647:
648: sub javascript_array_indexof {
649: return <<ENDJS;
650: <script type="text/javascript" language="JavaScript">
651: // <![CDATA[
652:
653: if (!Array.prototype.indexOf) {
654: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
655: "use strict";
656: if (this === void 0 || this === null) {
657: throw new TypeError();
658: }
659: var t = Object(this);
660: var len = t.length >>> 0;
661: if (len === 0) {
662: return -1;
663: }
664: var n = 0;
665: if (arguments.length > 0) {
666: n = Number(arguments[1]);
667: if (n !== n) { // shortcut for verifying if it is NaN
668: n = 0;
669: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
670: n = (n > 0 || -1) * Math.floor(Math.abs(n));
671: }
672: }
673: if (n >= len) {
674: return -1;
675: }
676: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
677: for (; k < len; k++) {
678: if (k in t && t[k] === searchElement) {
679: return k;
680: }
681: }
682: return -1;
683: }
684: }
685:
686: // ]]>
687: </script>
688:
689: ENDJS
690:
691: }
692:
693: sub userbrowser_javascript {
694: my $id_functions = &javascript_index_functions();
695: return <<"ENDUSERBRW";
696:
697: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
698: var url = '/adm/pickuser?';
699: var userdom = getDomainFromSelectbox(formname,udom);
700: if (userdom != null) {
701: if (userdom != '') {
702: url += 'srchdom='+userdom+'&';
703: }
704: }
705: url += 'form=' + formname + '&unameelement='+uname+
706: '&udomelement='+udom+
707: '&ulastelement='+ulast+
708: '&ufirstelement='+ufirst+
709: '&uemailelement='+uemail+
710: '&hideudomelement='+hideudom+
711: '&coursedom='+crsdom;
712: if ((caller != null) && (caller != undefined)) {
713: url += '&caller='+caller;
714: }
715: var title = 'User_Browser';
716: var options = 'scrollbars=1,resizable=1,menubar=0';
717: options += ',width=700,height=600';
718: var stdeditbrowser = open(url,title,options,'1');
719: stdeditbrowser.focus();
720: }
721:
722: function fix_domain (formname,udom,origdom,uname) {
723: var formid = getFormIdByName(formname);
724: if (formid > -1) {
725: var unameid = getIndexByName(formid,uname);
726: var domid = getIndexByName(formid,udom);
727: var hidedomid = getIndexByName(formid,origdom);
728: if (hidedomid > -1) {
729: var fixeddom = document.forms[formid].elements[hidedomid].value;
730: var unameval = document.forms[formid].elements[unameid].value;
731: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
732: if (domid > -1) {
733: var slct = document.forms[formid].elements[domid];
734: if (slct.type == 'select-one') {
735: var i;
736: for (i=0;i<slct.length;i++) {
737: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
738: }
739: }
740: if (slct.type == 'hidden') {
741: slct.value = fixeddom;
742: }
743: }
744: }
745: }
746: }
747: return;
748: }
749:
750: $id_functions
751: ENDUSERBRW
752: }
753:
754: sub setsec_javascript {
755: my ($sec_element,$formname,$role_element) = @_;
756: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
757: $communityrolestr);
758: if ($role_element ne '') {
759: my @allroles = ('st','ta','ep','in','ad');
760: foreach my $crstype ('Course','Community') {
761: if ($crstype eq 'Community') {
762: foreach my $role (@allroles) {
763: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
764: }
765: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
766: } else {
767: foreach my $role (@allroles) {
768: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
769: }
770: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
771: }
772: }
773: $rolestr = '"'.join('","',@allroles).'"';
774: $courserolestr = '"'.join('","',@courserolenames).'"';
775: $communityrolestr = '"'.join('","',@communityrolenames).'"';
776: }
777: my $setsections = qq|
778: function setSect(sectionlist) {
779: var sectionsArray = new Array();
780: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
781: sectionsArray = sectionlist.split(",");
782: }
783: var numSections = sectionsArray.length;
784: document.$formname.$sec_element.length = 0;
785: if (numSections == 0) {
786: document.$formname.$sec_element.multiple=false;
787: document.$formname.$sec_element.size=1;
788: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
789: } else {
790: if (numSections == 1) {
791: document.$formname.$sec_element.multiple=false;
792: document.$formname.$sec_element.size=1;
793: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
794: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
795: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
796: } else {
797: for (var i=0; i<numSections; i++) {
798: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
799: }
800: document.$formname.$sec_element.multiple=true
801: if (numSections < 3) {
802: document.$formname.$sec_element.size=numSections;
803: } else {
804: document.$formname.$sec_element.size=3;
805: }
806: document.$formname.$sec_element.options[0].selected = false
807: }
808: }
809: }
810:
811: function setRole(crstype) {
812: |;
813: if ($role_element eq '') {
814: $setsections .= ' return;
815: }
816: ';
817: } else {
818: $setsections .= qq|
819: var elementLength = document.$formname.$role_element.length;
820: var allroles = Array($rolestr);
821: var courserolenames = Array($courserolestr);
822: var communityrolenames = Array($communityrolestr);
823: if (elementLength != undefined) {
824: if (document.$formname.$role_element.options[5].value == 'cc') {
825: if (crstype == 'Course') {
826: return;
827: } else {
828: allroles[5] = 'co';
829: for (var i=0; i<6; i++) {
830: document.$formname.$role_element.options[i].value = allroles[i];
831: document.$formname.$role_element.options[i].text = communityrolenames[i];
832: }
833: }
834: } else {
835: if (crstype == 'Community') {
836: return;
837: } else {
838: allroles[5] = 'cc';
839: for (var i=0; i<6; i++) {
840: document.$formname.$role_element.options[i].value = allroles[i];
841: document.$formname.$role_element.options[i].text = courserolenames[i];
842: }
843: }
844: }
845: }
846: return;
847: }
848: |;
849: }
850: return $setsections;
851: }
852:
853: sub selectcourse_link {
854: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
855: $typeelement) = @_;
856: my $type = $selecttype;
857: my $linktext = &mt('Select Course');
858: if ($selecttype eq 'Community') {
859: $linktext = &mt('Select Community');
860: } elsif ($selecttype eq 'Course/Community') {
861: $linktext = &mt('Select Course/Community');
862: $type = '';
863: } elsif ($selecttype eq 'Select') {
864: $linktext = &mt('Select');
865: $type = '';
866: }
867: return '<span class="LC_nobreak">'
868: ."<a href='"
869: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
870: .'","'.$udomele.'","'.$desc.'","'.$extra_element
871: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
872: ."'>".$linktext.'</a>'
873: .'</span>';
874: }
875:
876: sub selectauthor_link {
877: my ($form,$udom)=@_;
878: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
879: &mt('Select Author').'</a>';
880: }
881:
882: sub selectuser_link {
883: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
884: $coursedom,$linktext,$caller) = @_;
885: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
886: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
887: ');">'.$linktext.'</a>';
888: }
889:
890: sub check_uncheck_jscript {
891: my $jscript = <<"ENDSCRT";
892: function checkAll(field) {
893: if (field.length > 0) {
894: for (i = 0; i < field.length; i++) {
895: if (!field[i].disabled) {
896: field[i].checked = true;
897: }
898: }
899: } else {
900: if (!field.disabled) {
901: field.checked = true;
902: }
903: }
904: }
905:
906: function uncheckAll(field) {
907: if (field.length > 0) {
908: for (i = 0; i < field.length; i++) {
909: field[i].checked = false ;
910: }
911: } else {
912: field.checked = false ;
913: }
914: }
915: ENDSCRT
916: return $jscript;
917: }
918:
919: sub select_timezone {
920: my ($name,$selected,$onchange,$includeempty)=@_;
921: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
922: if ($includeempty) {
923: $output .= '<option value=""';
924: if (($selected eq '') || ($selected eq 'local')) {
925: $output .= ' selected="selected" ';
926: }
927: $output .= '> </option>';
928: }
929: my @timezones = DateTime::TimeZone->all_names;
930: foreach my $tzone (@timezones) {
931: $output.= '<option value="'.$tzone.'"';
932: if ($tzone eq $selected) {
933: $output.=' selected="selected"';
934: }
935: $output.=">$tzone</option>\n";
936: }
937: $output.="</select>";
938: return $output;
939: }
940:
941: sub select_datelocale {
942: my ($name,$selected,$onchange,$includeempty)=@_;
943: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
944: if ($includeempty) {
945: $output .= '<option value=""';
946: if ($selected eq '') {
947: $output .= ' selected="selected" ';
948: }
949: $output .= '> </option>';
950: }
951: my (@possibles,%locale_names);
952: my @locales = DateTime::Locale::Catalog::Locales;
953: foreach my $locale (@locales) {
954: if (ref($locale) eq 'HASH') {
955: my $id = $locale->{'id'};
956: if ($id ne '') {
957: my $en_terr = $locale->{'en_territory'};
958: my $native_terr = $locale->{'native_territory'};
959: my @languages = &Apache::lonlocal::preferred_languages();
960: if (grep(/^en$/,@languages) || !@languages) {
961: if ($en_terr ne '') {
962: $locale_names{$id} = '('.$en_terr.')';
963: } elsif ($native_terr ne '') {
964: $locale_names{$id} = $native_terr;
965: }
966: } else {
967: if ($native_terr ne '') {
968: $locale_names{$id} = $native_terr.' ';
969: } elsif ($en_terr ne '') {
970: $locale_names{$id} = '('.$en_terr.')';
971: }
972: }
973: push (@possibles,$id);
974: }
975: }
976: }
977: foreach my $item (sort(@possibles)) {
978: $output.= '<option value="'.$item.'"';
979: if ($item eq $selected) {
980: $output.=' selected="selected"';
981: }
982: $output.=">$item";
983: if ($locale_names{$item} ne '') {
984: $output.=" $locale_names{$item}</option>\n";
985: }
986: $output.="</option>\n";
987: }
988: $output.="</select>";
989: return $output;
990: }
991:
992: sub select_language {
993: my ($name,$selected,$includeempty) = @_;
994: my %langchoices;
995: if ($includeempty) {
996: %langchoices = ('' => &mt('No language preference'));
997: }
998: foreach my $id (&languageids()) {
999: my $code = &supportedlanguagecode($id);
1000: if ($code) {
1001: $langchoices{$code} = &plainlanguagedescription($id);
1002: }
1003: }
1004: return &select_form($selected,$name,\%langchoices);
1005: }
1006:
1007: =pod
1008:
1009:
1010: =item * &list_languages()
1011:
1012: Returns an array reference that is suitable for use in language prompters.
1013: Each array element is itself a two element array. The first element
1014: is the language code. The second element a descsriptiuon of the
1015: language itself. This is suitable for use in e.g.
1016: &Apache::edit::select_arg (once dereferenced that is).
1017:
1018: =cut
1019:
1020: sub list_languages {
1021: my @lang_choices;
1022:
1023: foreach my $id (&languageids()) {
1024: my $code = &supportedlanguagecode($id);
1025: if ($code) {
1026: my $selector = $supported_codes{$id};
1027: my $description = &plainlanguagedescription($id);
1028: push (@lang_choices, [$selector, $description]);
1029: }
1030: }
1031: return \@lang_choices;
1032: }
1033:
1034: =pod
1035:
1036: =item * &linked_select_forms(...)
1037:
1038: linked_select_forms returns a string containing a <script></script> block
1039: and html for two <select> menus. The select menus will be linked in that
1040: changing the value of the first menu will result in new values being placed
1041: in the second menu. The values in the select menu will appear in alphabetical
1042: order unless a defined order is provided.
1043:
1044: linked_select_forms takes the following ordered inputs:
1045:
1046: =over 4
1047:
1048: =item * $formname, the name of the <form> tag
1049:
1050: =item * $middletext, the text which appears between the <select> tags
1051:
1052: =item * $firstdefault, the default value for the first menu
1053:
1054: =item * $firstselectname, the name of the first <select> tag
1055:
1056: =item * $secondselectname, the name of the second <select> tag
1057:
1058: =item * $hashref, a reference to a hash containing the data for the menus.
1059:
1060: =item * $menuorder, the order of values in the first menu
1061:
1062: =item * $onchangefirst, additional javascript call to execute for an onchange
1063: event for the first <select> tag
1064:
1065: =item * $onchangesecond, additional javascript call to execute for an onchange
1066: event for the second <select> tag
1067:
1068: =back
1069:
1070: Below is an example of such a hash. Only the 'text', 'default', and
1071: 'select2' keys must appear as stated. keys(%menu) are the possible
1072: values for the first select menu. The text that coincides with the
1073: first menu value is given in $menu{$choice1}->{'text'}. The values
1074: and text for the second menu are given in the hash pointed to by
1075: $menu{$choice1}->{'select2'}.
1076:
1077: my %menu = ( A1 => { text =>"Choice A1" ,
1078: default => "B3",
1079: select2 => {
1080: B1 => "Choice B1",
1081: B2 => "Choice B2",
1082: B3 => "Choice B3",
1083: B4 => "Choice B4"
1084: },
1085: order => ['B4','B3','B1','B2'],
1086: },
1087: A2 => { text =>"Choice A2" ,
1088: default => "C2",
1089: select2 => {
1090: C1 => "Choice C1",
1091: C2 => "Choice C2",
1092: C3 => "Choice C3"
1093: },
1094: order => ['C2','C1','C3'],
1095: },
1096: A3 => { text =>"Choice A3" ,
1097: default => "D6",
1098: select2 => {
1099: D1 => "Choice D1",
1100: D2 => "Choice D2",
1101: D3 => "Choice D3",
1102: D4 => "Choice D4",
1103: D5 => "Choice D5",
1104: D6 => "Choice D6",
1105: D7 => "Choice D7"
1106: },
1107: order => ['D4','D3','D2','D1','D7','D6','D5'],
1108: }
1109: );
1110:
1111: =cut
1112:
1113: sub linked_select_forms {
1114: my ($formname,
1115: $middletext,
1116: $firstdefault,
1117: $firstselectname,
1118: $secondselectname,
1119: $hashref,
1120: $menuorder,
1121: $onchangefirst,
1122: $onchangesecond
1123: ) = @_;
1124: my $second = "document.$formname.$secondselectname";
1125: my $first = "document.$formname.$firstselectname";
1126: # output the javascript to do the changing
1127: my $result = '';
1128: $result.='<script type="text/javascript" language="JavaScript">'."\n";
1129: $result.="// <![CDATA[\n";
1130: $result.="var select2data = new Object();\n";
1131: $" = '","';
1132: my $debug = '';
1133: foreach my $s1 (sort(keys(%$hashref))) {
1134: $result.="select2data.d_$s1 = new Object();\n";
1135: $result.="select2data.d_$s1.def = new String('".
1136: $hashref->{$s1}->{'default'}."');\n";
1137: $result.="select2data.d_$s1.values = new Array(";
1138: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1139: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1140: @s2values = @{$hashref->{$s1}->{'order'}};
1141: }
1142: $result.="\"@s2values\");\n";
1143: $result.="select2data.d_$s1.texts = new Array(";
1144: my @s2texts;
1145: foreach my $value (@s2values) {
1146: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
1147: }
1148: $result.="\"@s2texts\");\n";
1149: }
1150: $"=' ';
1151: $result.= <<"END";
1152:
1153: function select1_changed() {
1154: // Determine new choice
1155: var newvalue = "d_" + $first.value;
1156: // update select2
1157: var values = select2data[newvalue].values;
1158: var texts = select2data[newvalue].texts;
1159: var select2def = select2data[newvalue].def;
1160: var i;
1161: // out with the old
1162: for (i = 0; i < $second.options.length; i++) {
1163: $second.options[i] = null;
1164: }
1165: // in with the nuclear
1166: for (i=0;i<values.length; i++) {
1167: $second.options[i] = new Option(values[i]);
1168: $second.options[i].value = values[i];
1169: $second.options[i].text = texts[i];
1170: if (values[i] == select2def) {
1171: $second.options[i].selected = true;
1172: }
1173: }
1174: }
1175: // ]]>
1176: </script>
1177: END
1178: # output the initial values for the selection lists
1179: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1180: my @order = sort(keys(%{$hashref}));
1181: if (ref($menuorder) eq 'ARRAY') {
1182: @order = @{$menuorder};
1183: }
1184: foreach my $value (@order) {
1185: $result.=" <option value=\"$value\" ";
1186: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1187: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1188: }
1189: $result .= "</select>\n";
1190: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1191: $result .= $middletext;
1192: $result .= "<select size=\"1\" name=\"$secondselectname\"";
1193: if ($onchangesecond) {
1194: $result .= ' onchange="'.$onchangesecond.'"';
1195: }
1196: $result .= ">\n";
1197: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1198:
1199: my @secondorder = sort(keys(%select2));
1200: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1201: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1202: }
1203: foreach my $value (@secondorder) {
1204: $result.=" <option value=\"$value\" ";
1205: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1206: $result.=">".&mt($select2{$value})."</option>\n";
1207: }
1208: $result .= "</select>\n";
1209: # return $debug;
1210: return $result;
1211: } # end of sub linked_select_forms {
1212:
1213: =pod
1214:
1215: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1216:
1217: Returns a string corresponding to an HTML link to the given help
1218: $topic, where $topic corresponds to the name of a .tex file in
1219: /home/httpd/html/adm/help/tex, with underscores replaced by
1220: spaces.
1221:
1222: $text will optionally be linked to the same topic, allowing you to
1223: link text in addition to the graphic. If you do not want to link
1224: text, but wish to specify one of the later parameters, pass an
1225: empty string.
1226:
1227: $stayOnPage is a value that will be interpreted as a boolean. If true,
1228: the link will not open a new window. If false, the link will open
1229: a new window using Javascript. (Default is false.)
1230:
1231: $width and $height are optional numerical parameters that will
1232: override the width and height of the popped up window, which may
1233: be useful for certain help topics with big pictures included.
1234:
1235: $imgid is the id of the img tag used for the help icon. This may be
1236: used in a javascript call to switch the image src. See
1237: lonhtmlcommon::htmlareaselectactive() for an example.
1238:
1239: =cut
1240:
1241: sub help_open_topic {
1242: my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1243: $text = "" if (not defined $text);
1244: $stayOnPage = 0 if (not defined $stayOnPage);
1245: $width = 500 if (not defined $width);
1246: $height = 400 if (not defined $height);
1247: my $filename = $topic;
1248: $filename =~ s/ /_/g;
1249:
1250: my $template = "";
1251: my $link;
1252:
1253: $topic=~s/\W/\_/g;
1254:
1255: if (!$stayOnPage) {
1256: $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1257: } elsif ($stayOnPage eq 'popup') {
1258: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1259: } else {
1260: $link = "/adm/help/${filename}.hlp";
1261: }
1262:
1263: # Add the text
1264: if ($text ne "") {
1265: $template.='<span class="LC_help_open_topic">'
1266: .'<a target="_top" href="'.$link.'">'
1267: .$text.'</a>';
1268: }
1269:
1270: # (Always) Add the graphic
1271: my $title = &mt('Online Help');
1272: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1273: if ($imgid ne '') {
1274: $imgid = ' id="'.$imgid.'"';
1275: }
1276: $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
1277: .'<img src="'.$helpicon.'" border="0"'
1278: .' alt="'.&mt('Help: [_1]',$topic).'"'
1279: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
1280: .' /></a>';
1281: if ($text ne "") {
1282: $template.='</span>';
1283: }
1284: return $template;
1285:
1286: }
1287:
1288: # This is a quicky function for Latex cheatsheet editing, since it
1289: # appears in at least four places
1290: sub helpLatexCheatsheet {
1291: my ($topic,$text,$not_author,$stayOnPage) = @_;
1292: my $out;
1293: my $addOther = '';
1294: if ($topic) {
1295: $addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1296: }
1297: $out = '<span>' # Start cheatsheet
1298: .$addOther
1299: .'<span>'
1300: .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1301: .'</span> <span>'
1302: .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1303: .'</span>';
1304: unless ($not_author) {
1305: $out .= ' <span>'
1306: .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1307: .'</span>';
1308: }
1309: $out .= '</span>'; # End cheatsheet
1310: return $out;
1311: }
1312:
1313: sub general_help {
1314: my $helptopic='Student_Intro';
1315: if ($env{'request.role'}=~/^(ca|au)/) {
1316: $helptopic='Authoring_Intro';
1317: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1318: $helptopic='Course_Coordination_Intro';
1319: } elsif ($env{'request.role'}=~/^dc/) {
1320: $helptopic='Domain_Coordination_Intro';
1321: }
1322: return $helptopic;
1323: }
1324:
1325: sub update_help_link {
1326: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1327: my $origurl = $ENV{'REQUEST_URI'};
1328: $origurl=~s|^/~|/priv/|;
1329: my $timestamp = time;
1330: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1331: $$datum = &escape($$datum);
1332: }
1333:
1334: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1335: my $output .= <<"ENDOUTPUT";
1336: <script type="text/javascript">
1337: // <![CDATA[
1338: banner_link = '$banner_link';
1339: // ]]>
1340: </script>
1341: ENDOUTPUT
1342: return $output;
1343: }
1344:
1345: # now just updates the help link and generates a blue icon
1346: sub help_open_menu {
1347: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
1348: = @_;
1349: $stayOnPage = 1;
1350: my $output;
1351: if ($component_help) {
1352: if (!$text) {
1353: $output=&help_open_topic($component_help,undef,$stayOnPage,
1354: $width,$height);
1355: } else {
1356: my $help_text;
1357: $help_text=&unescape($topic);
1358: $output='<table><tr><td>'.
1359: &help_open_topic($component_help,$help_text,$stayOnPage,
1360: $width,$height).'</td></tr></table>';
1361: }
1362: }
1363: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1364: return $output.$banner_link;
1365: }
1366:
1367: sub top_nav_help {
1368: my ($text) = @_;
1369: $text = &mt($text);
1370: my $stay_on_page = 1;
1371:
1372: my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1373: : "javascript:helpMenu('open')";
1374: my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1375:
1376: my $title = &mt('Get help');
1377:
1378: return <<"END";
1379: $banner_link
1380: <a href="$link" title="$title">$text</a>
1381: END
1382: }
1383:
1384: sub help_menu_js {
1385: my ($text) = @_;
1386: my $stayOnPage = 1;
1387: my $width = 620;
1388: my $height = 600;
1389: my $helptopic=&general_help();
1390: my $details_link = '/adm/help/'.$helptopic.'.hlp';
1391: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1392: my $start_page =
1393: &Apache::loncommon::start_page('Help Menu', undef,
1394: {'frameset' => 1,
1395: 'js_ready' => 1,
1396: 'add_entries' => {
1397: 'border' => '0',
1398: 'rows' => "110,*",},});
1399: my $end_page =
1400: &Apache::loncommon::end_page({'frameset' => 1,
1401: 'js_ready' => 1,});
1402:
1403: my $template .= <<"ENDTEMPLATE";
1404: <script type="text/javascript">
1405: // <![CDATA[
1406: // <!-- BEGIN LON-CAPA Internal
1407: var banner_link = '';
1408: function helpMenu(target) {
1409: var caller = this;
1410: if (target == 'open') {
1411: var newWindow = null;
1412: try {
1413: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1414: }
1415: catch(error) {
1416: writeHelp(caller);
1417: return;
1418: }
1419: if (newWindow) {
1420: caller = newWindow;
1421: }
1422: }
1423: writeHelp(caller);
1424: return;
1425: }
1426: function writeHelp(caller) {
1427: caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page')
1428: caller.document.close()
1429: caller.focus()
1430: }
1431: // END LON-CAPA Internal -->
1432: // ]]>
1433: </script>
1434: ENDTEMPLATE
1435: return $template;
1436: }
1437:
1438: sub help_open_bug {
1439: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1440: unless ($env{'user.adv'}) { return ''; }
1441: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1442: $text = "" if (not defined $text);
1443: $stayOnPage=1;
1444: $width = 600 if (not defined $width);
1445: $height = 600 if (not defined $height);
1446:
1447: $topic=~s/\W+/\+/g;
1448: my $link='';
1449: my $template='';
1450: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1451: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1452: if (!$stayOnPage)
1453: {
1454: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1455: }
1456: else
1457: {
1458: $link = $url;
1459: }
1460: # Add the text
1461: if ($text ne "")
1462: {
1463: $template .=
1464: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1465: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1466: }
1467:
1468: # Add the graphic
1469: my $title = &mt('Report a Bug');
1470: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1471: $template .= <<"ENDTEMPLATE";
1472: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1473: ENDTEMPLATE
1474: if ($text ne '') { $template.='</td></tr></table>' };
1475: return $template;
1476:
1477: }
1478:
1479: sub help_open_faq {
1480: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1481: unless ($env{'user.adv'}) { return ''; }
1482: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1483: $text = "" if (not defined $text);
1484: $stayOnPage=1;
1485: $width = 350 if (not defined $width);
1486: $height = 400 if (not defined $height);
1487:
1488: $topic=~s/\W+/\+/g;
1489: my $link='';
1490: my $template='';
1491: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1492: if (!$stayOnPage)
1493: {
1494: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1495: }
1496: else
1497: {
1498: $link = $url;
1499: }
1500:
1501: # Add the text
1502: if ($text ne "")
1503: {
1504: $template .=
1505: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1506: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1507: }
1508:
1509: # Add the graphic
1510: my $title = &mt('View the FAQ');
1511: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1512: $template .= <<"ENDTEMPLATE";
1513: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1514: ENDTEMPLATE
1515: if ($text ne '') { $template.='</td></tr></table>' };
1516: return $template;
1517:
1518: }
1519:
1520: ###############################################################
1521: ###############################################################
1522:
1523: =pod
1524:
1525: =item * &change_content_javascript():
1526:
1527: This and the next function allow you to create small sections of an
1528: otherwise static HTML page that you can update on the fly with
1529: Javascript, even in Netscape 4.
1530:
1531: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1532: must be written to the HTML page once. It will prove the Javascript
1533: function "change(name, content)". Calling the change function with the
1534: name of the section
1535: you want to update, matching the name passed to C<changable_area>, and
1536: the new content you want to put in there, will put the content into
1537: that area.
1538:
1539: B<Note>: Netscape 4 only reserves enough space for the changable area
1540: to contain room for the original contents. You need to "make space"
1541: for whatever changes you wish to make, and be B<sure> to check your
1542: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1543: it's adequate for updating a one-line status display, but little more.
1544: This script will set the space to 100% width, so you only need to
1545: worry about height in Netscape 4.
1546:
1547: Modern browsers are much less limiting, and if you can commit to the
1548: user not using Netscape 4, this feature may be used freely with
1549: pretty much any HTML.
1550:
1551: =cut
1552:
1553: sub change_content_javascript {
1554: # If we're on Netscape 4, we need to use Layer-based code
1555: if ($env{'browser.type'} eq 'netscape' &&
1556: $env{'browser.version'} =~ /^4\./) {
1557: return (<<NETSCAPE4);
1558: function change(name, content) {
1559: doc = document.layers[name+"___escape"].layers[0].document;
1560: doc.open();
1561: doc.write(content);
1562: doc.close();
1563: }
1564: NETSCAPE4
1565: } else {
1566: # Otherwise, we need to use semi-standards-compliant code
1567: # (technically, "innerHTML" isn't standard but the equivalent
1568: # is really scary, and every useful browser supports it
1569: return (<<DOMBASED);
1570: function change(name, content) {
1571: element = document.getElementById(name);
1572: element.innerHTML = content;
1573: }
1574: DOMBASED
1575: }
1576: }
1577:
1578: =pod
1579:
1580: =item * &changable_area($name,$origContent):
1581:
1582: This provides a "changable area" that can be modified on the fly via
1583: the Javascript code provided in C<change_content_javascript>. $name is
1584: the name you will use to reference the area later; do not repeat the
1585: same name on a given HTML page more then once. $origContent is what
1586: the area will originally contain, which can be left blank.
1587:
1588: =cut
1589:
1590: sub changable_area {
1591: my ($name, $origContent) = @_;
1592:
1593: if ($env{'browser.type'} eq 'netscape' &&
1594: $env{'browser.version'} =~ /^4\./) {
1595: # If this is netscape 4, we need to use the Layer tag
1596: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1597: } else {
1598: return "<span id='$name'>$origContent</span>";
1599: }
1600: }
1601:
1602: =pod
1603:
1604: =item * &viewport_geometry_js
1605:
1606: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1607:
1608: =cut
1609:
1610:
1611: sub viewport_geometry_js {
1612: return <<"GEOMETRY";
1613: var Geometry = {};
1614: function init_geometry() {
1615: if (Geometry.init) { return };
1616: Geometry.init=1;
1617: if (window.innerHeight) {
1618: Geometry.getViewportHeight = function() { return window.innerHeight; };
1619: Geometry.getViewportWidth = function() { return window.innerWidth; };
1620: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1621: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1622: }
1623: else if (document.documentElement && document.documentElement.clientHeight) {
1624: Geometry.getViewportHeight =
1625: function() { return document.documentElement.clientHeight; };
1626: Geometry.getViewportWidth =
1627: function() { return document.documentElement.clientWidth; };
1628:
1629: Geometry.getHorizontalScroll =
1630: function() { return document.documentElement.scrollLeft; };
1631: Geometry.getVerticalScroll =
1632: function() { return document.documentElement.scrollTop; };
1633: }
1634: else if (document.body.clientHeight) {
1635: Geometry.getViewportHeight =
1636: function() { return document.body.clientHeight; };
1637: Geometry.getViewportWidth =
1638: function() { return document.body.clientWidth; };
1639: Geometry.getHorizontalScroll =
1640: function() { return document.body.scrollLeft; };
1641: Geometry.getVerticalScroll =
1642: function() { return document.body.scrollTop; };
1643: }
1644: }
1645:
1646: GEOMETRY
1647: }
1648:
1649: =pod
1650:
1651: =item * &viewport_size_js()
1652:
1653: 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.
1654:
1655: =cut
1656:
1657: sub viewport_size_js {
1658: my $geometry = &viewport_geometry_js();
1659: return <<"DIMS";
1660:
1661: $geometry
1662:
1663: function getViewportDims(width,height) {
1664: init_geometry();
1665: width.value = Geometry.getViewportWidth();
1666: height.value = Geometry.getViewportHeight();
1667: return;
1668: }
1669:
1670: DIMS
1671: }
1672:
1673: =pod
1674:
1675: =item * &resize_textarea_js()
1676:
1677: emits the needed javascript to resize a textarea to be as big as possible
1678:
1679: creates a function resize_textrea that takes two IDs first should be
1680: the id of the element to resize, second should be the id of a div that
1681: surrounds everything that comes after the textarea, this routine needs
1682: to be attached to the <body> for the onload and onresize events.
1683:
1684: =back
1685:
1686: =cut
1687:
1688: sub resize_textarea_js {
1689: my $geometry = &viewport_geometry_js();
1690: return <<"RESIZE";
1691: <script type="text/javascript">
1692: // <![CDATA[
1693: $geometry
1694:
1695: function getX(element) {
1696: var x = 0;
1697: while (element) {
1698: x += element.offsetLeft;
1699: element = element.offsetParent;
1700: }
1701: return x;
1702: }
1703: function getY(element) {
1704: var y = 0;
1705: while (element) {
1706: y += element.offsetTop;
1707: element = element.offsetParent;
1708: }
1709: return y;
1710: }
1711:
1712:
1713: function resize_textarea(textarea_id,bottom_id) {
1714: init_geometry();
1715: var textarea = document.getElementById(textarea_id);
1716: //alert(textarea);
1717:
1718: var textarea_top = getY(textarea);
1719: var textarea_height = textarea.offsetHeight;
1720: var bottom = document.getElementById(bottom_id);
1721: var bottom_top = getY(bottom);
1722: var bottom_height = bottom.offsetHeight;
1723: var window_height = Geometry.getViewportHeight();
1724: var fudge = 23;
1725: var new_height = window_height-fudge-textarea_top-bottom_height;
1726: if (new_height < 300) {
1727: new_height = 300;
1728: }
1729: textarea.style.height=new_height+'px';
1730: }
1731: // ]]>
1732: </script>
1733: RESIZE
1734:
1735: }
1736:
1737: =pod
1738:
1739: =head1 Excel and CSV file utility routines
1740:
1741: =over 4
1742:
1743: =cut
1744:
1745: ###############################################################
1746: ###############################################################
1747:
1748: =pod
1749:
1750: =item * &csv_translate($text)
1751:
1752: Translate $text to allow it to be output as a 'comma separated values'
1753: format.
1754:
1755: =cut
1756:
1757: ###############################################################
1758: ###############################################################
1759: sub csv_translate {
1760: my $text = shift;
1761: $text =~ s/\"/\"\"/g;
1762: $text =~ s/\n/ /g;
1763: return $text;
1764: }
1765:
1766: ###############################################################
1767: ###############################################################
1768:
1769: =pod
1770:
1771: =item * &define_excel_formats()
1772:
1773: Define some commonly used Excel cell formats.
1774:
1775: Currently supported formats:
1776:
1777: =over 4
1778:
1779: =item header
1780:
1781: =item bold
1782:
1783: =item h1
1784:
1785: =item h2
1786:
1787: =item h3
1788:
1789: =item h4
1790:
1791: =item i
1792:
1793: =item date
1794:
1795: =back
1796:
1797: Inputs: $workbook
1798:
1799: Returns: $format, a hash reference.
1800:
1801:
1802: =cut
1803:
1804: ###############################################################
1805: ###############################################################
1806: sub define_excel_formats {
1807: my ($workbook) = @_;
1808: my $format;
1809: $format->{'header'} = $workbook->add_format(bold => 1,
1810: bottom => 1,
1811: align => 'center');
1812: $format->{'bold'} = $workbook->add_format(bold=>1);
1813: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
1814: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
1815: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
1816: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
1817: $format->{'i'} = $workbook->add_format(italic=>1);
1818: $format->{'date'} = $workbook->add_format(num_format=>
1819: 'mm/dd/yyyy hh:mm:ss');
1820: return $format;
1821: }
1822:
1823: ###############################################################
1824: ###############################################################
1825:
1826: =pod
1827:
1828: =item * &create_workbook()
1829:
1830: Create an Excel worksheet. If it fails, output message on the
1831: request object and return undefs.
1832:
1833: Inputs: Apache request object
1834:
1835: Returns (undef) on failure,
1836: Excel worksheet object, scalar with filename, and formats
1837: from &Apache::loncommon::define_excel_formats on success
1838:
1839: =cut
1840:
1841: ###############################################################
1842: ###############################################################
1843: sub create_workbook {
1844: my ($r) = @_;
1845: #
1846: # Create the excel spreadsheet
1847: my $filename = '/prtspool/'.
1848: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1849: time.'_'.rand(1000000000).'.xls';
1850: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1851: if (! defined($workbook)) {
1852: $r->log_error("Error creating excel spreadsheet $filename: $!");
1853: $r->print(
1854: '<p class="LC_error">'
1855: .&mt('Problems occurred in creating the new Excel file.')
1856: .' '.&mt('This error has been logged.')
1857: .' '.&mt('Please alert your LON-CAPA administrator.')
1858: .'</p>'
1859: );
1860: return (undef);
1861: }
1862: #
1863: $workbook->set_tempdir(LONCAPA::tempdir());
1864: #
1865: my $format = &Apache::loncommon::define_excel_formats($workbook);
1866: return ($workbook,$filename,$format);
1867: }
1868:
1869: ###############################################################
1870: ###############################################################
1871:
1872: =pod
1873:
1874: =item * &create_text_file()
1875:
1876: Create a file to write to and eventually make available to the user.
1877: If file creation fails, outputs an error message on the request object and
1878: return undefs.
1879:
1880: Inputs: Apache request object, and file suffix
1881:
1882: Returns (undef) on failure,
1883: Filehandle and filename on success.
1884:
1885: =cut
1886:
1887: ###############################################################
1888: ###############################################################
1889: sub create_text_file {
1890: my ($r,$suffix) = @_;
1891: if (! defined($suffix)) { $suffix = 'txt'; };
1892: my $fh;
1893: my $filename = '/prtspool/'.
1894: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1895: time.'_'.rand(1000000000).'.'.$suffix;
1896: $fh = Apache::File->new('>/home/httpd'.$filename);
1897: if (! defined($fh)) {
1898: $r->log_error("Couldn't open $filename for output $!");
1899: $r->print(
1900: '<p class="LC_error">'
1901: .&mt('Problems occurred in creating the output file.')
1902: .' '.&mt('This error has been logged.')
1903: .' '.&mt('Please alert your LON-CAPA administrator.')
1904: .'</p>'
1905: );
1906: }
1907: return ($fh,$filename)
1908: }
1909:
1910:
1911: =pod
1912:
1913: =back
1914:
1915: =cut
1916:
1917: ###############################################################
1918: ## Home server <option> list generating code ##
1919: ###############################################################
1920:
1921: # ------------------------------------------
1922:
1923: sub domain_select {
1924: my ($name,$value,$multiple)=@_;
1925: my %domains=map {
1926: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
1927: } &Apache::lonnet::all_domains();
1928: if ($multiple) {
1929: $domains{''}=&mt('Any domain');
1930: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1931: return &multiple_select_form($name,$value,4,\%domains);
1932: } else {
1933: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1934: return &select_form($name,$value,\%domains);
1935: }
1936: }
1937:
1938: #-------------------------------------------
1939:
1940: =pod
1941:
1942: =head1 Routines for form select boxes
1943:
1944: =over 4
1945:
1946: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1947:
1948: Returns a string containing a <select> element int multiple mode
1949:
1950:
1951: Args:
1952: $name - name of the <select> element
1953: $value - scalar or array ref of values that should already be selected
1954: $size - number of rows long the select element is
1955: $hash - the elements should be 'option' => 'shown text'
1956: (shown text should already have been &mt())
1957: $order - (optional) array ref of the order to show the elements in
1958:
1959: =cut
1960:
1961: #-------------------------------------------
1962: sub multiple_select_form {
1963: my ($name,$value,$size,$hash,$order)=@_;
1964: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
1965: my $output='';
1966: if (! defined($size)) {
1967: $size = 4;
1968: if (scalar(keys(%$hash))<4) {
1969: $size = scalar(keys(%$hash));
1970: }
1971: }
1972: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1973: my @order;
1974: if (ref($order) eq 'ARRAY') {
1975: @order = @{$order};
1976: } else {
1977: @order = sort(keys(%$hash));
1978: }
1979: if (exists($$hash{'select_form_order'})) {
1980: @order = @{$$hash{'select_form_order'}};
1981: }
1982:
1983: foreach my $key (@order) {
1984: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1985: $output.='selected="selected" ' if ($selected{$key});
1986: $output.='>'.$hash->{$key}."</option>\n";
1987: }
1988: $output.="</select>\n";
1989: return $output;
1990: }
1991:
1992: #-------------------------------------------
1993:
1994: =pod
1995:
1996: =item * &select_form($defdom,$name,$hashref,$onchange)
1997:
1998: Returns a string containing a <select name='$name' size='1'> form to
1999: allow a user to select options from a ref to a hash containing:
2000: option_name => displayed text. An optional $onchange can include
2001: a javascript onchange item, e.g., onchange="this.form.submit();"
2002:
2003: See lonrights.pm for an example invocation and use.
2004:
2005: =cut
2006:
2007: #-------------------------------------------
2008: sub select_form {
2009: my ($def,$name,$hashref,$onchange) = @_;
2010: return unless (ref($hashref) eq 'HASH');
2011: if ($onchange) {
2012: $onchange = ' onchange="'.$onchange.'"';
2013: }
2014: my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
2015: my @keys;
2016: if (exists($hashref->{'select_form_order'})) {
2017: @keys=@{$hashref->{'select_form_order'}};
2018: } else {
2019: @keys=sort(keys(%{$hashref}));
2020: }
2021: foreach my $key (@keys) {
2022: $selectform.=
2023: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
2024: ($key eq $def ? 'selected="selected" ' : '').
2025: ">".$hashref->{$key}."</option>\n";
2026: }
2027: $selectform.="</select>";
2028: return $selectform;
2029: }
2030:
2031: # For display filters
2032:
2033: sub display_filter {
2034: my ($context) = @_;
2035: if (!$env{'form.show'}) { $env{'form.show'}=10; }
2036: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
2037: my $phraseinput = 'hidden';
2038: my $includeinput = 'hidden';
2039: my ($checked,$includetypestext);
2040: if ($env{'form.displayfilter'} eq 'containing') {
2041: $phraseinput = 'text';
2042: if ($context eq 'parmslog') {
2043: $includeinput = 'checkbox';
2044: if ($env{'form.includetypes'}) {
2045: $checked = ' checked="checked"';
2046: }
2047: $includetypestext = &mt('Include parameter types');
2048: }
2049: } else {
2050: $includetypestext = ' ';
2051: }
2052: my ($additional,$secondid,$thirdid);
2053: if ($context eq 'parmslog') {
2054: $additional =
2055: '<label><input type="'.$includeinput.'" name="includetypes"'.
2056: $checked.' name="includetypes" value="1" id="includetypes" />'.
2057: ' <span id="includetypestext">'.$includetypestext.'</span>'.
2058: '</label>';
2059: $secondid = 'includetypes';
2060: $thirdid = 'includetypestext';
2061: }
2062: my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
2063: '$secondid','$thirdid')";
2064: return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
2065: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
2066: (&mt('all'),10,20,50,100,1000,10000))).
2067: '</label></span> <span class="LC_nobreak">'.
2068: &mt('Filter: [_1]',
2069: &select_form($env{'form.displayfilter'},
2070: 'displayfilter',
2071: {'currentfolder' => 'Current folder/page',
2072: 'containing' => 'Containing phrase',
2073: 'none' => 'None'},$onchange)).' '.
2074: '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
2075: &HTML::Entities::encode($env{'form.containingphrase'}).
2076: '" />'.$additional;
2077: }
2078:
2079: sub display_filter_js {
2080: my $includetext = &mt('Include parameter types');
2081: return <<"ENDJS";
2082:
2083: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
2084: var firstType = 'hidden';
2085: if (setter.options[setter.selectedIndex].value == 'containing') {
2086: firstType = 'text';
2087: }
2088: firstObject = document.getElementById(firstid);
2089: if (typeof(firstObject) == 'object') {
2090: if (firstObject.type != firstType) {
2091: changeInputType(firstObject,firstType);
2092: }
2093: }
2094: if (context == 'parmslog') {
2095: var secondType = 'hidden';
2096: if (firstType == 'text') {
2097: secondType = 'checkbox';
2098: }
2099: secondObject = document.getElementById(secondid);
2100: if (typeof(secondObject) == 'object') {
2101: if (secondObject.type != secondType) {
2102: changeInputType(secondObject,secondType);
2103: }
2104: }
2105: var textItem = document.getElementById(thirdid);
2106: var currtext = textItem.innerHTML;
2107: var newtext;
2108: if (firstType == 'text') {
2109: newtext = '$includetext';
2110: } else {
2111: newtext = ' ';
2112: }
2113: if (currtext != newtext) {
2114: textItem.innerHTML = newtext;
2115: }
2116: }
2117: return;
2118: }
2119:
2120: function changeInputType(oldObject,newType) {
2121: var newObject = document.createElement('input');
2122: newObject.type = newType;
2123: if (oldObject.size) {
2124: newObject.size = oldObject.size;
2125: }
2126: if (oldObject.value) {
2127: newObject.value = oldObject.value;
2128: }
2129: if (oldObject.name) {
2130: newObject.name = oldObject.name;
2131: }
2132: if (oldObject.id) {
2133: newObject.id = oldObject.id;
2134: }
2135: oldObject.parentNode.replaceChild(newObject,oldObject);
2136: return;
2137: }
2138:
2139: ENDJS
2140: }
2141:
2142: sub gradeleveldescription {
2143: my $gradelevel=shift;
2144: my %gradelevels=(0 => 'Not specified',
2145: 1 => 'Grade 1',
2146: 2 => 'Grade 2',
2147: 3 => 'Grade 3',
2148: 4 => 'Grade 4',
2149: 5 => 'Grade 5',
2150: 6 => 'Grade 6',
2151: 7 => 'Grade 7',
2152: 8 => 'Grade 8',
2153: 9 => 'Grade 9',
2154: 10 => 'Grade 10',
2155: 11 => 'Grade 11',
2156: 12 => 'Grade 12',
2157: 13 => 'Grade 13',
2158: 14 => '100 Level',
2159: 15 => '200 Level',
2160: 16 => '300 Level',
2161: 17 => '400 Level',
2162: 18 => 'Graduate Level');
2163: return &mt($gradelevels{$gradelevel});
2164: }
2165:
2166: sub select_level_form {
2167: my ($deflevel,$name)=@_;
2168: unless ($deflevel) { $deflevel=0; }
2169: my $selectform = "<select name=\"$name\" size=\"1\">\n";
2170: for (my $i=0; $i<=18; $i++) {
2171: $selectform.="<option value=\"$i\" ".
2172: ($i==$deflevel ? 'selected="selected" ' : '').
2173: ">".&gradeleveldescription($i)."</option>\n";
2174: }
2175: $selectform.="</select>";
2176: return $selectform;
2177: }
2178:
2179: #-------------------------------------------
2180:
2181: =pod
2182:
2183: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
2184:
2185: Returns a string containing a <select name='$name' size='1'> form to
2186: allow a user to select the domain to preform an operation in.
2187: See loncreateuser.pm for an example invocation and use.
2188:
2189: If the $includeempty flag is set, it also includes an empty choice ("no domain
2190: selected");
2191:
2192: If the $showdomdesc flag is set, the domain name is followed by the domain description.
2193:
2194: 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.
2195:
2196: The optional $incdoms is a reference to an array of domains which will be the only available options.
2197:
2198: =cut
2199:
2200: #-------------------------------------------
2201: sub select_dom_form {
2202: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
2203: if ($onchange) {
2204: $onchange = ' onchange="'.$onchange.'"';
2205: }
2206: my @domains;
2207: if (ref($incdoms) eq 'ARRAY') {
2208: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
2209: } else {
2210: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
2211: }
2212: if ($includeempty) { @domains=('',@domains); }
2213: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
2214: foreach my $dom (@domains) {
2215: $selectdomain.="<option value=\"$dom\" ".
2216: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
2217: if ($showdomdesc) {
2218: if ($dom ne '') {
2219: my $domdesc = &Apache::lonnet::domain($dom,'description');
2220: if ($domdesc ne '') {
2221: $selectdomain .= ' ('.$domdesc.')';
2222: }
2223: }
2224: }
2225: $selectdomain .= "</option>\n";
2226: }
2227: $selectdomain.="</select>";
2228: return $selectdomain;
2229: }
2230:
2231: #-------------------------------------------
2232:
2233: =pod
2234:
2235: =item * &home_server_form_item($domain,$name,$defaultflag)
2236:
2237: input: 4 arguments (two required, two optional) -
2238: $domain - domain of new user
2239: $name - name of form element
2240: $default - Value of 'default' causes a default item to be first
2241: option, and selected by default.
2242: $hide - Value of 'hide' causes hiding of the name of the server,
2243: if 1 server found, or default, if 0 found.
2244: output: returns 2 items:
2245: (a) form element which contains either:
2246: (i) <select name="$name">
2247: <option value="$hostid1">$hostid $servers{$hostid}</option>
2248: <option value="$hostid2">$hostid $servers{$hostid}</option>
2249: </select>
2250: form item if there are multiple library servers in $domain, or
2251: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2252: if there is only one library server in $domain.
2253:
2254: (b) number of library servers found.
2255:
2256: See loncreateuser.pm for example of use.
2257:
2258: =cut
2259:
2260: #-------------------------------------------
2261: sub home_server_form_item {
2262: my ($domain,$name,$default,$hide) = @_;
2263: my %servers = &Apache::lonnet::get_servers($domain,'library');
2264: my $result;
2265: my $numlib = keys(%servers);
2266: if ($numlib > 1) {
2267: $result .= '<select name="'.$name.'" />'."\n";
2268: if ($default) {
2269: $result .= '<option value="default" selected="selected">'.&mt('default').
2270: '</option>'."\n";
2271: }
2272: foreach my $hostid (sort(keys(%servers))) {
2273: $result.= '<option value="'.$hostid.'">'.
2274: $hostid.' '.$servers{$hostid}."</option>\n";
2275: }
2276: $result .= '</select>'."\n";
2277: } elsif ($numlib == 1) {
2278: my $hostid;
2279: foreach my $item (keys(%servers)) {
2280: $hostid = $item;
2281: }
2282: $result .= '<input type="hidden" name="'.$name.'" value="'.
2283: $hostid.'" />';
2284: if (!$hide) {
2285: $result .= $hostid.' '.$servers{$hostid};
2286: }
2287: $result .= "\n";
2288: } elsif ($default) {
2289: $result .= '<input type="hidden" name="'.$name.
2290: '" value="default" />';
2291: if (!$hide) {
2292: $result .= &mt('default');
2293: }
2294: $result .= "\n";
2295: }
2296: return ($result,$numlib);
2297: }
2298:
2299: =pod
2300:
2301: =back
2302:
2303: =cut
2304:
2305: ###############################################################
2306: ## Decoding User Agent ##
2307: ###############################################################
2308:
2309: =pod
2310:
2311: =head1 Decoding the User Agent
2312:
2313: =over 4
2314:
2315: =item * &decode_user_agent()
2316:
2317: Inputs: $r
2318:
2319: Outputs:
2320:
2321: =over 4
2322:
2323: =item * $httpbrowser
2324:
2325: =item * $clientbrowser
2326:
2327: =item * $clientversion
2328:
2329: =item * $clientmathml
2330:
2331: =item * $clientunicode
2332:
2333: =item * $clientos
2334:
2335: =back
2336:
2337: =back
2338:
2339: =cut
2340:
2341: ###############################################################
2342: ###############################################################
2343: sub decode_user_agent {
2344: my ($r)=@_;
2345: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
2346: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
2347: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
2348: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
2349: my $clientbrowser='unknown';
2350: my $clientversion='0';
2351: my $clientmathml='';
2352: my $clientunicode='0';
2353: for (my $i=0;$i<=$#browsertype;$i++) {
2354: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
2355: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
2356: $clientbrowser=$bname;
2357: $httpbrowser=~/$vreg/i;
2358: $clientversion=$1;
2359: $clientmathml=($clientversion>=$minv);
2360: $clientunicode=($clientversion>=$univ);
2361: }
2362: }
2363: my $clientos='unknown';
2364: if (($httpbrowser=~/linux/i) ||
2365: ($httpbrowser=~/unix/i) ||
2366: ($httpbrowser=~/ux/i) ||
2367: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
2368: if (($httpbrowser=~/vax/i) ||
2369: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
2370: if ($httpbrowser=~/next/i) { $clientos='next'; }
2371: if (($httpbrowser=~/mac/i) ||
2372: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
2373: if ($httpbrowser=~/win/i) { $clientos='win'; }
2374: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
2375: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
2376: $clientunicode,$clientos,);
2377: }
2378:
2379: ###############################################################
2380: ## Authentication changing form generation subroutines ##
2381: ###############################################################
2382: ##
2383: ## All of the authform_xxxxxxx subroutines take their inputs in a
2384: ## hash, and have reasonable default values.
2385: ##
2386: ## formname = the name given in the <form> tag.
2387: #-------------------------------------------
2388:
2389: =pod
2390:
2391: =head1 Authentication Routines
2392:
2393: =over 4
2394:
2395: =item * &authform_xxxxxx()
2396:
2397: The authform_xxxxxx subroutines provide javascript and html forms which
2398: handle some of the conveniences required for authentication forms.
2399: This is not an optimal method, but it works.
2400:
2401: =over 4
2402:
2403: =item * authform_header
2404:
2405: =item * authform_authorwarning
2406:
2407: =item * authform_nochange
2408:
2409: =item * authform_kerberos
2410:
2411: =item * authform_internal
2412:
2413: =item * authform_filesystem
2414:
2415: =back
2416:
2417: See loncreateuser.pm for invocation and use examples.
2418:
2419: =cut
2420:
2421: #-------------------------------------------
2422: sub authform_header{
2423: my %in = (
2424: formname => 'cu',
2425: kerb_def_dom => '',
2426: @_,
2427: );
2428: $in{'formname'} = 'document.' . $in{'formname'};
2429: my $result='';
2430:
2431: #---------------------------------------------- Code for upper case translation
2432: my $Javascript_toUpperCase;
2433: unless ($in{kerb_def_dom}) {
2434: $Javascript_toUpperCase =<<"END";
2435: switch (choice) {
2436: case 'krb': currentform.elements[choicearg].value =
2437: currentform.elements[choicearg].value.toUpperCase();
2438: break;
2439: default:
2440: }
2441: END
2442: } else {
2443: $Javascript_toUpperCase = "";
2444: }
2445:
2446: my $radioval = "'nochange'";
2447: if (defined($in{'curr_authtype'})) {
2448: if ($in{'curr_authtype'} ne '') {
2449: $radioval = "'".$in{'curr_authtype'}."arg'";
2450: }
2451: }
2452: my $argfield = 'null';
2453: if (defined($in{'mode'})) {
2454: if ($in{'mode'} eq 'modifycourse') {
2455: if (defined($in{'curr_autharg'})) {
2456: if ($in{'curr_autharg'} ne '') {
2457: $argfield = "'$in{'curr_autharg'}'";
2458: }
2459: }
2460: }
2461: }
2462:
2463: $result.=<<"END";
2464: var current = new Object();
2465: current.radiovalue = $radioval;
2466: current.argfield = $argfield;
2467:
2468: function changed_radio(choice,currentform) {
2469: var choicearg = choice + 'arg';
2470: // If a radio button in changed, we need to change the argfield
2471: if (current.radiovalue != choice) {
2472: current.radiovalue = choice;
2473: if (current.argfield != null) {
2474: currentform.elements[current.argfield].value = '';
2475: }
2476: if (choice == 'nochange') {
2477: current.argfield = null;
2478: } else {
2479: current.argfield = choicearg;
2480: switch(choice) {
2481: case 'krb':
2482: currentform.elements[current.argfield].value =
2483: "$in{'kerb_def_dom'}";
2484: break;
2485: default:
2486: break;
2487: }
2488: }
2489: }
2490: return;
2491: }
2492:
2493: function changed_text(choice,currentform) {
2494: var choicearg = choice + 'arg';
2495: if (currentform.elements[choicearg].value !='') {
2496: $Javascript_toUpperCase
2497: // clear old field
2498: if ((current.argfield != choicearg) && (current.argfield != null)) {
2499: currentform.elements[current.argfield].value = '';
2500: }
2501: current.argfield = choicearg;
2502: }
2503: set_auth_radio_buttons(choice,currentform);
2504: return;
2505: }
2506:
2507: function set_auth_radio_buttons(newvalue,currentform) {
2508: var numauthchoices = currentform.login.length;
2509: if (typeof numauthchoices == "undefined") {
2510: return;
2511: }
2512: var i=0;
2513: while (i < numauthchoices) {
2514: if (currentform.login[i].value == newvalue) { break; }
2515: i++;
2516: }
2517: if (i == numauthchoices) {
2518: return;
2519: }
2520: current.radiovalue = newvalue;
2521: currentform.login[i].checked = true;
2522: return;
2523: }
2524: END
2525: return $result;
2526: }
2527:
2528: sub authform_authorwarning {
2529: my $result='';
2530: $result='<i>'.
2531: &mt('As a general rule, only authors or co-authors should be '.
2532: 'filesystem authenticated '.
2533: '(which allows access to the server filesystem).')."</i>\n";
2534: return $result;
2535: }
2536:
2537: sub authform_nochange {
2538: my %in = (
2539: formname => 'document.cu',
2540: kerb_def_dom => 'MSU.EDU',
2541: @_,
2542: );
2543: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2544: my $result;
2545: if (!$authnum) {
2546: $result = &mt('Under your current role you are not permitted to change login settings for this user');
2547: } else {
2548: $result = '<label>'.&mt('[_1] Do not change login data',
2549: '<input type="radio" name="login" value="nochange" '.
2550: 'checked="checked" onclick="'.
2551: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
2552: '</label>';
2553: }
2554: return $result;
2555: }
2556:
2557: sub authform_kerberos {
2558: my %in = (
2559: formname => 'document.cu',
2560: kerb_def_dom => 'MSU.EDU',
2561: kerb_def_auth => 'krb4',
2562: @_,
2563: );
2564: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2565: $autharg,$jscall);
2566: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2567: if ($in{'kerb_def_auth'} eq 'krb5') {
2568: $check5 = ' checked="checked"';
2569: } else {
2570: $check4 = ' checked="checked"';
2571: }
2572: $krbarg = $in{'kerb_def_dom'};
2573: if (defined($in{'curr_authtype'})) {
2574: if ($in{'curr_authtype'} eq 'krb') {
2575: $krbcheck = ' checked="checked"';
2576: if (defined($in{'mode'})) {
2577: if ($in{'mode'} eq 'modifyuser') {
2578: $krbcheck = '';
2579: }
2580: }
2581: if (defined($in{'curr_kerb_ver'})) {
2582: if ($in{'curr_krb_ver'} eq '5') {
2583: $check5 = ' checked="checked"';
2584: $check4 = '';
2585: } else {
2586: $check4 = ' checked="checked"';
2587: $check5 = '';
2588: }
2589: }
2590: if (defined($in{'curr_autharg'})) {
2591: $krbarg = $in{'curr_autharg'};
2592: }
2593: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2594: if (defined($in{'curr_autharg'})) {
2595: $result =
2596: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
2597: $in{'curr_autharg'},$krbver);
2598: } else {
2599: $result =
2600: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
2601: }
2602: return $result;
2603: }
2604: }
2605: } else {
2606: if ($authnum == 1) {
2607: $authtype = '<input type="hidden" name="login" value="krb" />';
2608: }
2609: }
2610: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2611: return;
2612: } elsif ($authtype eq '') {
2613: if (defined($in{'mode'})) {
2614: if ($in{'mode'} eq 'modifycourse') {
2615: if ($authnum == 1) {
2616: $authtype = '<input type="radio" name="login" value="krb" />';
2617: }
2618: }
2619: }
2620: }
2621: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
2622: if ($authtype eq '') {
2623: $authtype = '<input type="radio" name="login" value="krb" '.
2624: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
2625: $krbcheck.' />';
2626: }
2627: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
2628: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
2629: $in{'curr_authtype'} eq 'krb5') ||
2630: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
2631: $in{'curr_authtype'} eq 'krb4')) {
2632: $result .= &mt
2633: ('[_1] Kerberos authenticated with domain [_2] '.
2634: '[_3] Version 4 [_4] Version 5 [_5]',
2635: '<label>'.$authtype,
2636: '</label><input type="text" size="10" name="krbarg" '.
2637: 'value="'.$krbarg.'" '.
2638: 'onchange="'.$jscall.'" />',
2639: '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
2640: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
2641: '</label>');
2642: } elsif ($can_assign{'krb4'}) {
2643: $result .= &mt
2644: ('[_1] Kerberos authenticated with domain [_2] '.
2645: '[_3] Version 4 [_4]',
2646: '<label>'.$authtype,
2647: '</label><input type="text" size="10" name="krbarg" '.
2648: 'value="'.$krbarg.'" '.
2649: 'onchange="'.$jscall.'" />',
2650: '<label><input type="hidden" name="krbver" value="4" />',
2651: '</label>');
2652: } elsif ($can_assign{'krb5'}) {
2653: $result .= &mt
2654: ('[_1] Kerberos authenticated with domain [_2] '.
2655: '[_3] Version 5 [_4]',
2656: '<label>'.$authtype,
2657: '</label><input type="text" size="10" name="krbarg" '.
2658: 'value="'.$krbarg.'" '.
2659: 'onchange="'.$jscall.'" />',
2660: '<label><input type="hidden" name="krbver" value="5" />',
2661: '</label>');
2662: }
2663: return $result;
2664: }
2665:
2666: sub authform_internal {
2667: my %in = (
2668: formname => 'document.cu',
2669: kerb_def_dom => 'MSU.EDU',
2670: @_,
2671: );
2672: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
2673: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2674: if (defined($in{'curr_authtype'})) {
2675: if ($in{'curr_authtype'} eq 'int') {
2676: if ($can_assign{'int'}) {
2677: $intcheck = 'checked="checked" ';
2678: if (defined($in{'mode'})) {
2679: if ($in{'mode'} eq 'modifyuser') {
2680: $intcheck = '';
2681: }
2682: }
2683: if (defined($in{'curr_autharg'})) {
2684: $intarg = $in{'curr_autharg'};
2685: }
2686: } else {
2687: $result = &mt('Currently internally authenticated.');
2688: return $result;
2689: }
2690: }
2691: } else {
2692: if ($authnum == 1) {
2693: $authtype = '<input type="hidden" name="login" value="int" />';
2694: }
2695: }
2696: if (!$can_assign{'int'}) {
2697: return;
2698: } elsif ($authtype eq '') {
2699: if (defined($in{'mode'})) {
2700: if ($in{'mode'} eq 'modifycourse') {
2701: if ($authnum == 1) {
2702: $authtype = '<input type="radio" name="login" value="int" />';
2703: }
2704: }
2705: }
2706: }
2707: $jscall = "javascript:changed_radio('int',$in{'formname'});";
2708: if ($authtype eq '') {
2709: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
2710: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
2711: }
2712: $autharg = '<input type="password" size="10" name="intarg" value="'.
2713: $intarg.'" onchange="'.$jscall.'" />';
2714: $result = &mt
2715: ('[_1] Internally authenticated (with initial password [_2])',
2716: '<label>'.$authtype,'</label>'.$autharg);
2717: $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>';
2718: return $result;
2719: }
2720:
2721: sub authform_local {
2722: my %in = (
2723: formname => 'document.cu',
2724: kerb_def_dom => 'MSU.EDU',
2725: @_,
2726: );
2727: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
2728: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2729: if (defined($in{'curr_authtype'})) {
2730: if ($in{'curr_authtype'} eq 'loc') {
2731: if ($can_assign{'loc'}) {
2732: $loccheck = 'checked="checked" ';
2733: if (defined($in{'mode'})) {
2734: if ($in{'mode'} eq 'modifyuser') {
2735: $loccheck = '';
2736: }
2737: }
2738: if (defined($in{'curr_autharg'})) {
2739: $locarg = $in{'curr_autharg'};
2740: }
2741: } else {
2742: $result = &mt('Currently using local (institutional) authentication.');
2743: return $result;
2744: }
2745: }
2746: } else {
2747: if ($authnum == 1) {
2748: $authtype = '<input type="hidden" name="login" value="loc" />';
2749: }
2750: }
2751: if (!$can_assign{'loc'}) {
2752: return;
2753: } elsif ($authtype eq '') {
2754: if (defined($in{'mode'})) {
2755: if ($in{'mode'} eq 'modifycourse') {
2756: if ($authnum == 1) {
2757: $authtype = '<input type="radio" name="login" value="loc" />';
2758: }
2759: }
2760: }
2761: }
2762: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
2763: if ($authtype eq '') {
2764: $authtype = '<input type="radio" name="login" value="loc" '.
2765: $loccheck.' onchange="'.$jscall.'" onclick="'.
2766: $jscall.'" />';
2767: }
2768: $autharg = '<input type="text" size="10" name="locarg" value="'.
2769: $locarg.'" onchange="'.$jscall.'" />';
2770: $result = &mt('[_1] Local Authentication with argument [_2]',
2771: '<label>'.$authtype,'</label>'.$autharg);
2772: return $result;
2773: }
2774:
2775: sub authform_filesystem {
2776: my %in = (
2777: formname => 'document.cu',
2778: kerb_def_dom => 'MSU.EDU',
2779: @_,
2780: );
2781: my ($fsyscheck,$result,$authtype,$autharg,$jscall);
2782: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2783: if (defined($in{'curr_authtype'})) {
2784: if ($in{'curr_authtype'} eq 'fsys') {
2785: if ($can_assign{'fsys'}) {
2786: $fsyscheck = 'checked="checked" ';
2787: if (defined($in{'mode'})) {
2788: if ($in{'mode'} eq 'modifyuser') {
2789: $fsyscheck = '';
2790: }
2791: }
2792: } else {
2793: $result = &mt('Currently Filesystem Authenticated.');
2794: return $result;
2795: }
2796: }
2797: } else {
2798: if ($authnum == 1) {
2799: $authtype = '<input type="hidden" name="login" value="fsys" />';
2800: }
2801: }
2802: if (!$can_assign{'fsys'}) {
2803: return;
2804: } elsif ($authtype eq '') {
2805: if (defined($in{'mode'})) {
2806: if ($in{'mode'} eq 'modifycourse') {
2807: if ($authnum == 1) {
2808: $authtype = '<input type="radio" name="login" value="fsys" />';
2809: }
2810: }
2811: }
2812: }
2813: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
2814: if ($authtype eq '') {
2815: $authtype = '<input type="radio" name="login" value="fsys" '.
2816: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
2817: $jscall.'" />';
2818: }
2819: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
2820: ' onchange="'.$jscall.'" />';
2821: $result = &mt
2822: ('[_1] Filesystem Authenticated (with initial password [_2])',
2823: '<label><input type="radio" name="login" value="fsys" '.
2824: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
2825: '</label><input type="password" size="10" name="fsysarg" value="" '.
2826: 'onchange="'.$jscall.'" />');
2827: return $result;
2828: }
2829:
2830: sub get_assignable_auth {
2831: my ($dom) = @_;
2832: if ($dom eq '') {
2833: $dom = $env{'request.role.domain'};
2834: }
2835: my %can_assign = (
2836: krb4 => 1,
2837: krb5 => 1,
2838: int => 1,
2839: loc => 1,
2840: );
2841: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
2842: if (ref($domconfig{'usercreation'}) eq 'HASH') {
2843: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
2844: my $authhash = $domconfig{'usercreation'}{'authtypes'};
2845: my $context;
2846: if ($env{'request.role'} =~ /^au/) {
2847: $context = 'author';
2848: } elsif ($env{'request.role'} =~ /^dc/) {
2849: $context = 'domain';
2850: } elsif ($env{'request.course.id'}) {
2851: $context = 'course';
2852: }
2853: if ($context) {
2854: if (ref($authhash->{$context}) eq 'HASH') {
2855: %can_assign = %{$authhash->{$context}};
2856: }
2857: }
2858: }
2859: }
2860: my $authnum = 0;
2861: foreach my $key (keys(%can_assign)) {
2862: if ($can_assign{$key}) {
2863: $authnum ++;
2864: }
2865: }
2866: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
2867: $authnum --;
2868: }
2869: return ($authnum,%can_assign);
2870: }
2871:
2872: ###############################################################
2873: ## Get Kerberos Defaults for Domain ##
2874: ###############################################################
2875: ##
2876: ## Returns default kerberos version and an associated argument
2877: ## as listed in file domain.tab. If not listed, provides
2878: ## appropriate default domain and kerberos version.
2879: ##
2880: #-------------------------------------------
2881:
2882: =pod
2883:
2884: =item * &get_kerberos_defaults()
2885:
2886: get_kerberos_defaults($target_domain) returns the default kerberos
2887: version and domain. If not found, it defaults to version 4 and the
2888: domain of the server.
2889:
2890: =over 4
2891:
2892: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
2893:
2894: =back
2895:
2896: =back
2897:
2898: =cut
2899:
2900: #-------------------------------------------
2901: sub get_kerberos_defaults {
2902: my $domain=shift;
2903: my ($krbdef,$krbdefdom);
2904: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
2905: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
2906: $krbdef = $domdefaults{'auth_def'};
2907: $krbdefdom = $domdefaults{'auth_arg_def'};
2908: } else {
2909: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
2910: my $krbdefdom=$1;
2911: $krbdefdom=~tr/a-z/A-Z/;
2912: $krbdef = "krb4";
2913: }
2914: return ($krbdef,$krbdefdom);
2915: }
2916:
2917:
2918: ###############################################################
2919: ## Thesaurus Functions ##
2920: ###############################################################
2921:
2922: =pod
2923:
2924: =head1 Thesaurus Functions
2925:
2926: =over 4
2927:
2928: =item * &initialize_keywords()
2929:
2930: Initializes the package variable %Keywords if it is empty. Uses the
2931: package variable $thesaurus_db_file.
2932:
2933: =cut
2934:
2935: ###################################################
2936:
2937: sub initialize_keywords {
2938: return 1 if (scalar keys(%Keywords));
2939: # If we are here, %Keywords is empty, so fill it up
2940: # Make sure the file we need exists...
2941: if (! -e $thesaurus_db_file) {
2942: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
2943: " failed because it does not exist");
2944: return 0;
2945: }
2946: # Set up the hash as a database
2947: my %thesaurus_db;
2948: if (! tie(%thesaurus_db,'GDBM_File',
2949: $thesaurus_db_file,&GDBM_READER(),0640)){
2950: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
2951: $thesaurus_db_file);
2952: return 0;
2953: }
2954: # Get the average number of appearances of a word.
2955: my $avecount = $thesaurus_db{'average.count'};
2956: # Put keywords (those that appear > average) into %Keywords
2957: while (my ($word,$data)=each (%thesaurus_db)) {
2958: my ($count,undef) = split /:/,$data;
2959: $Keywords{$word}++ if ($count > $avecount);
2960: }
2961: untie %thesaurus_db;
2962: # Remove special values from %Keywords.
2963: foreach my $value ('total.count','average.count') {
2964: delete($Keywords{$value}) if (exists($Keywords{$value}));
2965: }
2966: return 1;
2967: }
2968:
2969: ###################################################
2970:
2971: =pod
2972:
2973: =item * &keyword($word)
2974:
2975: Returns true if $word is a keyword. A keyword is a word that appears more
2976: than the average number of times in the thesaurus database. Calls
2977: &initialize_keywords
2978:
2979: =cut
2980:
2981: ###################################################
2982:
2983: sub keyword {
2984: return if (!&initialize_keywords());
2985: my $word=lc(shift());
2986: $word=~s/\W//g;
2987: return exists($Keywords{$word});
2988: }
2989:
2990: ###############################################################
2991:
2992: =pod
2993:
2994: =item * &get_related_words()
2995:
2996: Look up a word in the thesaurus. Takes a scalar argument and returns
2997: an array of words. If the keyword is not in the thesaurus, an empty array
2998: will be returned. The order of the words returned is determined by the
2999: database which holds them.
3000:
3001: Uses global $thesaurus_db_file.
3002:
3003:
3004: =cut
3005:
3006: ###############################################################
3007: sub get_related_words {
3008: my $keyword = shift;
3009: my %thesaurus_db;
3010: if (! -e $thesaurus_db_file) {
3011: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
3012: "failed because the file does not exist");
3013: return ();
3014: }
3015: if (! tie(%thesaurus_db,'GDBM_File',
3016: $thesaurus_db_file,&GDBM_READER(),0640)){
3017: return ();
3018: }
3019: my @Words=();
3020: my $count=0;
3021: if (exists($thesaurus_db{$keyword})) {
3022: # The first element is the number of times
3023: # the word appears. We do not need it now.
3024: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
3025: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
3026: my $threshold=$mostfrequentcount/10;
3027: foreach my $possibleword (@RelatedWords) {
3028: my ($word,$wordcount)=split(/\,/,$possibleword);
3029: if ($wordcount>$threshold) {
3030: push(@Words,$word);
3031: $count++;
3032: if ($count>10) { last; }
3033: }
3034: }
3035: }
3036: untie %thesaurus_db;
3037: return @Words;
3038: }
3039: ###############################################################
3040: #
3041: # Spell checking
3042: #
3043:
3044: =pod
3045:
3046: =head1 Spell checking
3047:
3048: =over 4
3049:
3050: =item * &check_spelling($wordlist $language)
3051:
3052: Takes a string containing words and feeds it to an external
3053: spellcheck program via a pipeline. Returns a string containing
3054: them mis-spelled words.
3055:
3056: Parameters:
3057:
3058: =over 4
3059:
3060: =item - $wordlist
3061:
3062: String that will be fed into the spellcheck program.
3063:
3064: =item - $language
3065:
3066: Language string that specifies the language for which the spell
3067: check will be performed.
3068:
3069: =back
3070:
3071: =back
3072:
3073: Note: This sub assumes that aspell is installed.
3074:
3075:
3076: =cut
3077:
3078:
3079: =pod
3080:
3081: =back
3082:
3083: =cut
3084:
3085: sub check_spelling {
3086: my ($wordlist, $language) = @_;
3087: my @misspellings;
3088:
3089: # Generate the speller and set the langauge.
3090: # if explicitly selected:
3091:
3092: my $speller = Text::Aspell->new;
3093: if ($language) {
3094: $speller->set_option('lang', $language);
3095: }
3096:
3097: # Turn the word list into an array of words by splittingon whitespace
3098:
3099: my @words = split(/\s+/, $wordlist);
3100:
3101: foreach my $word (@words) {
3102: if(! $speller->check($word)) {
3103: push(@misspellings, $word);
3104: }
3105: }
3106: return join(' ', @misspellings);
3107:
3108: }
3109:
3110: # -------------------------------------------------------------- Plaintext name
3111: =pod
3112:
3113: =head1 User Name Functions
3114:
3115: =over 4
3116:
3117: =item * &plainname($uname,$udom,$first)
3118:
3119: Takes a users logon name and returns it as a string in
3120: "first middle last generation" form
3121: if $first is set to 'lastname' then it returns it as
3122: 'lastname generation, firstname middlename' if their is a lastname
3123:
3124: =cut
3125:
3126:
3127: ###############################################################
3128: sub plainname {
3129: my ($uname,$udom,$first)=@_;
3130: return if (!defined($uname) || !defined($udom));
3131: my %names=&getnames($uname,$udom);
3132: my $name=&Apache::lonnet::format_name($names{'firstname'},
3133: $names{'middlename'},
3134: $names{'lastname'},
3135: $names{'generation'},$first);
3136: $name=~s/^\s+//;
3137: $name=~s/\s+$//;
3138: $name=~s/\s+/ /g;
3139: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
3140: return $name;
3141: }
3142:
3143: # -------------------------------------------------------------------- Nickname
3144: =pod
3145:
3146: =item * &nickname($uname,$udom)
3147:
3148: Gets a users name and returns it as a string as
3149:
3150: ""nickname""
3151:
3152: if the user has a nickname or
3153:
3154: "first middle last generation"
3155:
3156: if the user does not
3157:
3158: =cut
3159:
3160: sub nickname {
3161: my ($uname,$udom)=@_;
3162: return if (!defined($uname) || !defined($udom));
3163: my %names=&getnames($uname,$udom);
3164: my $name=$names{'nickname'};
3165: if ($name) {
3166: $name='"'.$name.'"';
3167: } else {
3168: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
3169: $names{'lastname'}.' '.$names{'generation'};
3170: $name=~s/\s+$//;
3171: $name=~s/\s+/ /g;
3172: }
3173: return $name;
3174: }
3175:
3176: sub getnames {
3177: my ($uname,$udom)=@_;
3178: return if (!defined($uname) || !defined($udom));
3179: if ($udom eq 'public' && $uname eq 'public') {
3180: return ('lastname' => &mt('Public'));
3181: }
3182: my $id=$uname.':'.$udom;
3183: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
3184: if ($cached) {
3185: return %{$names};
3186: } else {
3187: my %loadnames=&Apache::lonnet::get('environment',
3188: ['firstname','middlename','lastname','generation','nickname'],
3189: $udom,$uname);
3190: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
3191: return %loadnames;
3192: }
3193: }
3194:
3195: # -------------------------------------------------------------------- getemails
3196:
3197: =pod
3198:
3199: =item * &getemails($uname,$udom)
3200:
3201: Gets a user's email information and returns it as a hash with keys:
3202: notification, critnotification, permanentemail
3203:
3204: For notification and critnotification, values are comma-separated lists
3205: of e-mail addresses; for permanentemail, value is a single e-mail address.
3206:
3207:
3208: =cut
3209:
3210:
3211: sub getemails {
3212: my ($uname,$udom)=@_;
3213: if ($udom eq 'public' && $uname eq 'public') {
3214: return;
3215: }
3216: if (!$udom) { $udom=$env{'user.domain'}; }
3217: if (!$uname) { $uname=$env{'user.name'}; }
3218: my $id=$uname.':'.$udom;
3219: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
3220: if ($cached) {
3221: return %{$names};
3222: } else {
3223: my %loadnames=&Apache::lonnet::get('environment',
3224: ['notification','critnotification',
3225: 'permanentemail'],
3226: $udom,$uname);
3227: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
3228: return %loadnames;
3229: }
3230: }
3231:
3232: sub flush_email_cache {
3233: my ($uname,$udom)=@_;
3234: if (!$udom) { $udom =$env{'user.domain'}; }
3235: if (!$uname) { $uname=$env{'user.name'}; }
3236: return if ($udom eq 'public' && $uname eq 'public');
3237: my $id=$uname.':'.$udom;
3238: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
3239: }
3240:
3241: # -------------------------------------------------------------------- getlangs
3242:
3243: =pod
3244:
3245: =item * &getlangs($uname,$udom)
3246:
3247: Gets a user's language preference and returns it as a hash with key:
3248: language.
3249:
3250: =cut
3251:
3252:
3253: sub getlangs {
3254: my ($uname,$udom) = @_;
3255: if (!$udom) { $udom =$env{'user.domain'}; }
3256: if (!$uname) { $uname=$env{'user.name'}; }
3257: my $id=$uname.':'.$udom;
3258: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
3259: if ($cached) {
3260: return %{$langs};
3261: } else {
3262: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
3263: $udom,$uname);
3264: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
3265: return %loadlangs;
3266: }
3267: }
3268:
3269: sub flush_langs_cache {
3270: my ($uname,$udom)=@_;
3271: if (!$udom) { $udom =$env{'user.domain'}; }
3272: if (!$uname) { $uname=$env{'user.name'}; }
3273: return if ($udom eq 'public' && $uname eq 'public');
3274: my $id=$uname.':'.$udom;
3275: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
3276: }
3277:
3278: # ------------------------------------------------------------------ Screenname
3279:
3280: =pod
3281:
3282: =item * &screenname($uname,$udom)
3283:
3284: Gets a users screenname and returns it as a string
3285:
3286: =cut
3287:
3288: sub screenname {
3289: my ($uname,$udom)=@_;
3290: if ($uname eq $env{'user.name'} &&
3291: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
3292: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
3293: return $names{'screenname'};
3294: }
3295:
3296:
3297: # ------------------------------------------------------------- Confirm Wrapper
3298: =pod
3299:
3300: =item confirmwrapper
3301:
3302: Wrap messages about completion of operation in box
3303:
3304: =cut
3305:
3306: sub confirmwrapper {
3307: my ($message)=@_;
3308: if ($message) {
3309: return "\n".'<div class="LC_confirm_box">'."\n"
3310: .$message."\n"
3311: .'</div>'."\n";
3312: } else {
3313: return $message;
3314: }
3315: }
3316:
3317: # ------------------------------------------------------------- Message Wrapper
3318:
3319: sub messagewrapper {
3320: my ($link,$username,$domain,$subject,$text)=@_;
3321: return
3322: '<a href="/adm/email?compose=individual&'.
3323: 'recname='.$username.'&recdom='.$domain.
3324: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
3325: 'title="'.&mt('Send message').'">'.$link.'</a>';
3326: }
3327:
3328: # --------------------------------------------------------------- Notes Wrapper
3329:
3330: sub noteswrapper {
3331: my ($link,$un,$do)=@_;
3332: return
3333: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
3334: }
3335:
3336: # ------------------------------------------------------------- Aboutme Wrapper
3337:
3338: sub aboutmewrapper {
3339: my ($link,$username,$domain,$target,$class)=@_;
3340: if (!defined($username) && !defined($domain)) {
3341: return;
3342: }
3343: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
3344: ($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
3345: }
3346:
3347: # ------------------------------------------------------------ Syllabus Wrapper
3348:
3349: sub syllabuswrapper {
3350: my ($linktext,$coursedir,$domain)=@_;
3351: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
3352: }
3353:
3354: # -----------------------------------------------------------------------------
3355:
3356: sub track_student_link {
3357: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
3358: my $link ="/adm/trackstudent?";
3359: my $title = 'View recent activity';
3360: if (defined($sname) && $sname !~ /^\s*$/ &&
3361: defined($sdom) && $sdom !~ /^\s*$/) {
3362: $link .= "selected_student=$sname:$sdom";
3363: $title .= ' of this student';
3364: }
3365: if (defined($target) && $target !~ /^\s*$/) {
3366: $target = qq{target="$target"};
3367: } else {
3368: $target = '';
3369: }
3370: if ($start) { $link.='&start='.$start; }
3371: if ($only_body) { $link .= '&only_body=1'; }
3372: $title = &mt($title);
3373: $linktext = &mt($linktext);
3374: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
3375: &help_open_topic('View_recent_activity');
3376: }
3377:
3378: sub slot_reservations_link {
3379: my ($linktext,$sname,$sdom,$target) = @_;
3380: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
3381: my $title = 'View slot reservation history';
3382: if (defined($sname) && $sname !~ /^\s*$/ &&
3383: defined($sdom) && $sdom !~ /^\s*$/) {
3384: $link .= "&uname=$sname&udom=$sdom";
3385: $title .= ' of this student';
3386: }
3387: if (defined($target) && $target !~ /^\s*$/) {
3388: $target = qq{target="$target"};
3389: } else {
3390: $target = '';
3391: }
3392: $title = &mt($title);
3393: $linktext = &mt($linktext);
3394: return qq{<a href="$link" title="$title" $target>$linktext</a>};
3395: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
3396:
3397: }
3398:
3399: # ===================================================== Display a student photo
3400:
3401:
3402: sub student_image_tag {
3403: my ($domain,$user)=@_;
3404: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
3405: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
3406: return '<img src="'.$imgsrc.'" align="right" />';
3407: } else {
3408: return '';
3409: }
3410: }
3411:
3412: =pod
3413:
3414: =back
3415:
3416: =head1 Access .tab File Data
3417:
3418: =over 4
3419:
3420: =item * &languageids()
3421:
3422: returns list of all language ids
3423:
3424: =cut
3425:
3426: sub languageids {
3427: return sort(keys(%language));
3428: }
3429:
3430: =pod
3431:
3432: =item * &languagedescription()
3433:
3434: returns description of a specified language id
3435:
3436: =cut
3437:
3438: sub languagedescription {
3439: my $code=shift;
3440: return ($supported_language{$code}?'* ':'').
3441: $language{$code}.
3442: ($supported_language{$code}?' ('.&mt('interface available').')':'');
3443: }
3444:
3445: =pod
3446:
3447: =item * &plainlanguagedescription
3448:
3449: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
3450: and the language character encoding (e.g. ISO) separated by a ' - ' string.
3451:
3452: =cut
3453:
3454: sub plainlanguagedescription {
3455: my $code=shift;
3456: return $language{$code};
3457: }
3458:
3459: =pod
3460:
3461: =item * &supportedlanguagecode
3462:
3463: Returns the supported language code (e.g. sptutf maps to pt) given a language
3464: code.
3465:
3466: =cut
3467:
3468: sub supportedlanguagecode {
3469: my $code=shift;
3470: return $supported_language{$code};
3471: }
3472:
3473: =pod
3474:
3475: =item * &latexlanguage()
3476:
3477: Given a language key code returns the correspondnig language to use
3478: to select the correct hyphenation on LaTeX printouts. This is undef if there
3479: is no supported hyphenation for the language code.
3480:
3481: =cut
3482:
3483: sub latexlanguage {
3484: my $code = shift;
3485: return $latex_language{$code};
3486: }
3487:
3488: =pod
3489:
3490: =item * &latexhyphenation()
3491:
3492: Same as above but what's supplied is the language as it might be stored
3493: in the metadata.
3494:
3495: =cut
3496:
3497: sub latexhyphenation {
3498: my $key = shift;
3499: return $latex_language_bykey{$key};
3500: }
3501:
3502: =pod
3503:
3504: =item * ©rightids()
3505:
3506: returns list of all copyrights
3507:
3508: =cut
3509:
3510: sub copyrightids {
3511: return sort(keys(%cprtag));
3512: }
3513:
3514: =pod
3515:
3516: =item * ©rightdescription()
3517:
3518: returns description of a specified copyright id
3519:
3520: =cut
3521:
3522: sub copyrightdescription {
3523: return &mt($cprtag{shift(@_)});
3524: }
3525:
3526: =pod
3527:
3528: =item * &source_copyrightids()
3529:
3530: returns list of all source copyrights
3531:
3532: =cut
3533:
3534: sub source_copyrightids {
3535: return sort(keys(%scprtag));
3536: }
3537:
3538: =pod
3539:
3540: =item * &source_copyrightdescription()
3541:
3542: returns description of a specified source copyright id
3543:
3544: =cut
3545:
3546: sub source_copyrightdescription {
3547: return &mt($scprtag{shift(@_)});
3548: }
3549:
3550: =pod
3551:
3552: =item * &filecategories()
3553:
3554: returns list of all file categories
3555:
3556: =cut
3557:
3558: sub filecategories {
3559: return sort(keys(%category_extensions));
3560: }
3561:
3562: =pod
3563:
3564: =item * &filecategorytypes()
3565:
3566: returns list of file types belonging to a given file
3567: category
3568:
3569: =cut
3570:
3571: sub filecategorytypes {
3572: my ($cat) = @_;
3573: return @{$category_extensions{lc($cat)}};
3574: }
3575:
3576: =pod
3577:
3578: =item * &fileembstyle()
3579:
3580: returns embedding style for a specified file type
3581:
3582: =cut
3583:
3584: sub fileembstyle {
3585: return $fe{lc(shift(@_))};
3586: }
3587:
3588: sub filemimetype {
3589: return $fm{lc(shift(@_))};
3590: }
3591:
3592:
3593: sub filecategoryselect {
3594: my ($name,$value)=@_;
3595: return &select_form($value,$name,
3596: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
3597: }
3598:
3599: =pod
3600:
3601: =item * &filedescription()
3602:
3603: returns description for a specified file type
3604:
3605: =cut
3606:
3607: sub filedescription {
3608: my $file_description = $fd{lc(shift())};
3609: $file_description =~ s:([\[\]]):~$1:g;
3610: return &mt($file_description);
3611: }
3612:
3613: =pod
3614:
3615: =item * &filedescriptionex()
3616:
3617: returns description for a specified file type with
3618: extra formatting
3619:
3620: =cut
3621:
3622: sub filedescriptionex {
3623: my $ex=shift;
3624: my $file_description = $fd{lc($ex)};
3625: $file_description =~ s:([\[\]]):~$1:g;
3626: return '.'.$ex.' '.&mt($file_description);
3627: }
3628:
3629: # End of .tab access
3630: =pod
3631:
3632: =back
3633:
3634: =cut
3635:
3636: # ------------------------------------------------------------------ File Types
3637: sub fileextensions {
3638: return sort(keys(%fe));
3639: }
3640:
3641: # ----------------------------------------------------------- Display Languages
3642: # returns a hash with all desired display languages
3643: #
3644:
3645: sub display_languages {
3646: my %languages=();
3647: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
3648: $languages{$lang}=1;
3649: }
3650: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3651: if ($env{'form.displaylanguage'}) {
3652: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3653: $languages{$lang}=1;
3654: }
3655: }
3656: return %languages;
3657: }
3658:
3659: sub languages {
3660: my ($possible_langs) = @_;
3661: my @preferred_langs = &Apache::lonlocal::preferred_languages();
3662: if (!ref($possible_langs)) {
3663: if( wantarray ) {
3664: return @preferred_langs;
3665: } else {
3666: return $preferred_langs[0];
3667: }
3668: }
3669: my %possibilities = map { $_ => 1 } (@$possible_langs);
3670: my @preferred_possibilities;
3671: foreach my $preferred_lang (@preferred_langs) {
3672: if (exists($possibilities{$preferred_lang})) {
3673: push(@preferred_possibilities, $preferred_lang);
3674: }
3675: }
3676: if( wantarray ) {
3677: return @preferred_possibilities;
3678: }
3679: return $preferred_possibilities[0];
3680: }
3681:
3682: sub user_lang {
3683: my ($touname,$toudom,$fromcid) = @_;
3684: my @userlangs;
3685: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
3686: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
3687: $env{'course.'.$fromcid.'.languages'}));
3688: } else {
3689: my %langhash = &getlangs($touname,$toudom);
3690: if ($langhash{'languages'} ne '') {
3691: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
3692: } else {
3693: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
3694: if ($domdefs{'lang_def'} ne '') {
3695: @userlangs = ($domdefs{'lang_def'});
3696: }
3697: }
3698: }
3699: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
3700: my $user_lh = Apache::localize->get_handle(@languages);
3701: return $user_lh;
3702: }
3703:
3704:
3705: ###############################################################
3706: ## Student Answer Attempts ##
3707: ###############################################################
3708:
3709: =pod
3710:
3711: =head1 Alternate Problem Views
3712:
3713: =over 4
3714:
3715: =item * &get_previous_attempt($symb, $username, $domain, $course,
3716: $getattempt, $regexp, $gradesub)
3717:
3718: Return string with previous attempt on problem. Arguments:
3719:
3720: =over 4
3721:
3722: =item * $symb: Problem, including path
3723:
3724: =item * $username: username of the desired student
3725:
3726: =item * $domain: domain of the desired student
3727:
3728: =item * $course: Course ID
3729:
3730: =item * $getattempt: Leave blank for all attempts, otherwise put
3731: something
3732:
3733: =item * $regexp: if string matches this regexp, the string will be
3734: sent to $gradesub
3735:
3736: =item * $gradesub: routine that processes the string if it matches $regexp
3737:
3738: =back
3739:
3740: The output string is a table containing all desired attempts, if any.
3741:
3742: =cut
3743:
3744: sub get_previous_attempt {
3745: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
3746: my $prevattempts='';
3747: no strict 'refs';
3748: if ($symb) {
3749: my (%returnhash)=
3750: &Apache::lonnet::restore($symb,$course,$domain,$username);
3751: if ($returnhash{'version'}) {
3752: my %lasthash=();
3753: my $version;
3754: for ($version=1;$version<=$returnhash{'version'};$version++) {
3755: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
3756: $lasthash{$key}=$returnhash{$version.':'.$key};
3757: }
3758: }
3759: $prevattempts=&start_data_table().&start_data_table_header_row();
3760: $prevattempts.='<th>'.&mt('History').'</th>';
3761: my (%typeparts,%lasthidden);
3762: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
3763: foreach my $key (sort(keys(%lasthash))) {
3764: my ($ign,@parts) = split(/\./,$key);
3765: if ($#parts > 0) {
3766: my $data=$parts[-1];
3767: next if ($data eq 'foilorder');
3768: pop(@parts);
3769: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
3770: if ($data eq 'type') {
3771: unless ($showsurv) {
3772: my $id = join(',',@parts);
3773: $typeparts{$ign.'.'.$id} = $lasthash{$key};
3774: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
3775: $lasthidden{$ign.'.'.$id} = 1;
3776: }
3777: }
3778: }
3779: } else {
3780: if ($#parts == 0) {
3781: $prevattempts.='<th>'.$parts[0].'</th>';
3782: } else {
3783: $prevattempts.='<th>'.$ign.'</th>';
3784: }
3785: }
3786: }
3787: $prevattempts.=&end_data_table_header_row();
3788: if ($getattempt eq '') {
3789: for ($version=1;$version<=$returnhash{'version'};$version++) {
3790: my @hidden;
3791: if (%typeparts) {
3792: foreach my $id (keys(%typeparts)) {
3793: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
3794: push(@hidden,$id);
3795: }
3796: }
3797: }
3798: $prevattempts.=&start_data_table_row().
3799: '<td>'.&mt('Transaction [_1]',$version).'</td>';
3800: if (@hidden) {
3801: foreach my $key (sort(keys(%lasthash))) {
3802: next if ($key =~ /\.foilorder$/);
3803: my $hide;
3804: foreach my $id (@hidden) {
3805: if ($key =~ /^\Q$id\E/) {
3806: $hide = 1;
3807: last;
3808: }
3809: }
3810: if ($hide) {
3811: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
3812: if (($data eq 'award') || ($data eq 'awarddetail')) {
3813: my $value = &format_previous_attempt_value($key,
3814: $returnhash{$version.':'.$key});
3815: $prevattempts.='<td>'.$value.' </td>';
3816: } else {
3817: $prevattempts.='<td> </td>';
3818: }
3819: } else {
3820: if ($key =~ /\./) {
3821: my $value = &format_previous_attempt_value($key,
3822: $returnhash{$version.':'.$key});
3823: $prevattempts.='<td>'.$value.' </td>';
3824: } else {
3825: $prevattempts.='<td> </td>';
3826: }
3827: }
3828: }
3829: } else {
3830: foreach my $key (sort(keys(%lasthash))) {
3831: next if ($key =~ /\.foilorder$/);
3832: my $value = &format_previous_attempt_value($key,
3833: $returnhash{$version.':'.$key});
3834: $prevattempts.='<td>'.$value.' </td>';
3835: }
3836: }
3837: $prevattempts.=&end_data_table_row();
3838: }
3839: }
3840: my @currhidden = keys(%lasthidden);
3841: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
3842: foreach my $key (sort(keys(%lasthash))) {
3843: next if ($key =~ /\.foilorder$/);
3844: if (%typeparts) {
3845: my $hidden;
3846: foreach my $id (@currhidden) {
3847: if ($key =~ /^\Q$id\E/) {
3848: $hidden = 1;
3849: last;
3850: }
3851: }
3852: if ($hidden) {
3853: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
3854: if (($data eq 'award') || ($data eq 'awarddetail')) {
3855: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3856: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3857: $value = &$gradesub($value);
3858: }
3859: $prevattempts.='<td>'.$value.' </td>';
3860: } else {
3861: $prevattempts.='<td> </td>';
3862: }
3863: } else {
3864: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3865: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3866: $value = &$gradesub($value);
3867: }
3868: $prevattempts.='<td>'.$value.' </td>';
3869: }
3870: } else {
3871: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3872: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3873: $value = &$gradesub($value);
3874: }
3875: $prevattempts.='<td>'.$value.' </td>';
3876: }
3877: }
3878: $prevattempts.= &end_data_table_row().&end_data_table();
3879: } else {
3880: $prevattempts=
3881: &start_data_table().&start_data_table_row().
3882: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
3883: &end_data_table_row().&end_data_table();
3884: }
3885: } else {
3886: $prevattempts=
3887: &start_data_table().&start_data_table_row().
3888: '<td>'.&mt('No data.').'</td>'.
3889: &end_data_table_row().&end_data_table();
3890: }
3891: }
3892:
3893: sub format_previous_attempt_value {
3894: my ($key,$value) = @_;
3895: if (($key =~ /timestamp/) || ($key=~/duedate/)) {
3896: $value = &Apache::lonlocal::locallocaltime($value);
3897: } elsif (ref($value) eq 'ARRAY') {
3898: $value = '('.join(', ', @{ $value }).')';
3899: } elsif ($key =~ /answerstring$/) {
3900: my %answers = &Apache::lonnet::str2hash($value);
3901: my @anskeys = sort(keys(%answers));
3902: if (@anskeys == 1) {
3903: my $answer = $answers{$anskeys[0]};
3904: if ($answer =~ m{\0}) {
3905: $answer =~ s{\0}{,}g;
3906: }
3907: my $tag_internal_answer_name = 'INTERNAL';
3908: if ($anskeys[0] eq $tag_internal_answer_name) {
3909: $value = $answer;
3910: } else {
3911: $value = $anskeys[0].'='.$answer;
3912: }
3913: } else {
3914: foreach my $ans (@anskeys) {
3915: my $answer = $answers{$ans};
3916: if ($answer =~ m{\0}) {
3917: $answer =~ s{\0}{,}g;
3918: }
3919: $value .= $ans.'='.$answer.'<br />';;
3920: }
3921: }
3922: } else {
3923: $value = &unescape($value);
3924: }
3925: return $value;
3926: }
3927:
3928:
3929: sub relative_to_absolute {
3930: my ($url,$output)=@_;
3931: my $parser=HTML::TokeParser->new(\$output);
3932: my $token;
3933: my $thisdir=$url;
3934: my @rlinks=();
3935: while ($token=$parser->get_token) {
3936: if ($token->[0] eq 'S') {
3937: if ($token->[1] eq 'a') {
3938: if ($token->[2]->{'href'}) {
3939: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
3940: }
3941: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
3942: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
3943: } elsif ($token->[1] eq 'base') {
3944: $thisdir=$token->[2]->{'href'};
3945: }
3946: }
3947: }
3948: $thisdir=~s-/[^/]*$--;
3949: foreach my $link (@rlinks) {
3950: unless (($link=~/^https?\:\/\//i) ||
3951: ($link=~/^\//) ||
3952: ($link=~/^javascript:/i) ||
3953: ($link=~/^mailto:/i) ||
3954: ($link=~/^\#/)) {
3955: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
3956: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
3957: }
3958: }
3959: # -------------------------------------------------- Deal with Applet codebases
3960: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
3961: return $output;
3962: }
3963:
3964: =pod
3965:
3966: =item * &get_student_view()
3967:
3968: show a snapshot of what student was looking at
3969:
3970: =cut
3971:
3972: sub get_student_view {
3973: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
3974: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3975: my (%form);
3976: my @elements=('symb','courseid','domain','username');
3977: foreach my $element (@elements) {
3978: $form{'grade_'.$element}=eval '$'.$element #'
3979: }
3980: if (defined($moreenv)) {
3981: %form=(%form,%{$moreenv});
3982: }
3983: if (defined($target)) { $form{'grade_target'} = $target; }
3984: $feedurl=&Apache::lonnet::clutter($feedurl);
3985: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
3986: $userview=~s/\<body[^\>]*\>//gi;
3987: $userview=~s/\<\/body\>//gi;
3988: $userview=~s/\<html\>//gi;
3989: $userview=~s/\<\/html\>//gi;
3990: $userview=~s/\<head\>//gi;
3991: $userview=~s/\<\/head\>//gi;
3992: $userview=~s/action\s*\=/would_be_action\=/gi;
3993: $userview=&relative_to_absolute($feedurl,$userview);
3994: if (wantarray) {
3995: return ($userview,$response);
3996: } else {
3997: return $userview;
3998: }
3999: }
4000:
4001: sub get_student_view_with_retries {
4002: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
4003:
4004: my $ok = 0; # True if we got a good response.
4005: my $content;
4006: my $response;
4007:
4008: # Try to get the student_view done. within the retries count:
4009:
4010: do {
4011: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
4012: $ok = $response->is_success;
4013: if (!$ok) {
4014: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
4015: }
4016: $retries--;
4017: } while (!$ok && ($retries > 0));
4018:
4019: if (!$ok) {
4020: $content = ''; # On error return an empty content.
4021: }
4022: if (wantarray) {
4023: return ($content, $response);
4024: } else {
4025: return $content;
4026: }
4027: }
4028:
4029: =pod
4030:
4031: =item * &get_student_answers()
4032:
4033: show a snapshot of how student was answering problem
4034:
4035: =cut
4036:
4037: sub get_student_answers {
4038: my ($symb,$username,$domain,$courseid,%form) = @_;
4039: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4040: my (%moreenv);
4041: my @elements=('symb','courseid','domain','username');
4042: foreach my $element (@elements) {
4043: $moreenv{'grade_'.$element}=eval '$'.$element #'
4044: }
4045: $moreenv{'grade_target'}='answer';
4046: %moreenv=(%form,%moreenv);
4047: $feedurl = &Apache::lonnet::clutter($feedurl);
4048: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
4049: return $userview;
4050: }
4051:
4052: =pod
4053:
4054: =item * &submlink()
4055:
4056: Inputs: $text $uname $udom $symb $target
4057:
4058: Returns: A link to grades.pm such as to see the SUBM view of a student
4059:
4060: =cut
4061:
4062: ###############################################
4063: sub submlink {
4064: my ($text,$uname,$udom,$symb,$target)=@_;
4065: if (!($uname && $udom)) {
4066: (my $cursymb, my $courseid,$udom,$uname)=
4067: &Apache::lonnet::whichuser($symb);
4068: if (!$symb) { $symb=$cursymb; }
4069: }
4070: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4071: $symb=&escape($symb);
4072: if ($target) { $target=" target=\"$target\""; }
4073: return
4074: '<a href="/adm/grades?command=submission'.
4075: '&symb='.$symb.
4076: '&student='.$uname.
4077: '&userdom='.$udom.'"'.
4078: $target.'>'.$text.'</a>';
4079: }
4080: ##############################################
4081:
4082: =pod
4083:
4084: =item * &pgrdlink()
4085:
4086: Inputs: $text $uname $udom $symb $target
4087:
4088: Returns: A link to grades.pm such as to see the PGRD view of a student
4089:
4090: =cut
4091:
4092: ###############################################
4093: sub pgrdlink {
4094: my $link=&submlink(@_);
4095: $link=~s/(&command=submission)/$1&showgrading=yes/;
4096: return $link;
4097: }
4098: ##############################################
4099:
4100: =pod
4101:
4102: =item * &pprmlink()
4103:
4104: Inputs: $text $uname $udom $symb $target
4105:
4106: Returns: A link to parmset.pm such as to see the PPRM view of a
4107: student and a specific resource
4108:
4109: =cut
4110:
4111: ###############################################
4112: sub pprmlink {
4113: my ($text,$uname,$udom,$symb,$target)=@_;
4114: if (!($uname && $udom)) {
4115: (my $cursymb, my $courseid,$udom,$uname)=
4116: &Apache::lonnet::whichuser($symb);
4117: if (!$symb) { $symb=$cursymb; }
4118: }
4119: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4120: $symb=&escape($symb);
4121: if ($target) { $target="target=\"$target\""; }
4122: return '<a href="/adm/parmset?command=set&'.
4123: 'symb='.$symb.'&uname='.$uname.
4124: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
4125: }
4126: ##############################################
4127:
4128: =pod
4129:
4130: =back
4131:
4132: =cut
4133:
4134: ###############################################
4135:
4136:
4137: sub timehash {
4138: my ($thistime) = @_;
4139: my $timezone = &Apache::lonlocal::gettimezone();
4140: my $dt = DateTime->from_epoch(epoch => $thistime)
4141: ->set_time_zone($timezone);
4142: my $wday = $dt->day_of_week();
4143: if ($wday == 7) { $wday = 0; }
4144: return ( 'second' => $dt->second(),
4145: 'minute' => $dt->minute(),
4146: 'hour' => $dt->hour(),
4147: 'day' => $dt->day_of_month(),
4148: 'month' => $dt->month(),
4149: 'year' => $dt->year(),
4150: 'weekday' => $wday,
4151: 'dayyear' => $dt->day_of_year(),
4152: 'dlsav' => $dt->is_dst() );
4153: }
4154:
4155: sub utc_string {
4156: my ($date)=@_;
4157: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
4158: }
4159:
4160: sub maketime {
4161: my %th=@_;
4162: my ($epoch_time,$timezone,$dt);
4163: $timezone = &Apache::lonlocal::gettimezone();
4164: eval {
4165: $dt = DateTime->new( year => $th{'year'},
4166: month => $th{'month'},
4167: day => $th{'day'},
4168: hour => $th{'hour'},
4169: minute => $th{'minute'},
4170: second => $th{'second'},
4171: time_zone => $timezone,
4172: );
4173: };
4174: if (!$@) {
4175: $epoch_time = $dt->epoch;
4176: if ($epoch_time) {
4177: return $epoch_time;
4178: }
4179: }
4180: return POSIX::mktime(
4181: ($th{'seconds'},$th{'minutes'},$th{'hours'},
4182: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
4183: }
4184:
4185: #########################################
4186:
4187: sub findallcourses {
4188: my ($roles,$uname,$udom) = @_;
4189: my %roles;
4190: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
4191: my %courses;
4192: my $now=time;
4193: if (!defined($uname)) {
4194: $uname = $env{'user.name'};
4195: }
4196: if (!defined($udom)) {
4197: $udom = $env{'user.domain'};
4198: }
4199: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
4200: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
4201: if (!%roles) {
4202: %roles = (
4203: cc => 1,
4204: co => 1,
4205: in => 1,
4206: ep => 1,
4207: ta => 1,
4208: cr => 1,
4209: st => 1,
4210: );
4211: }
4212: foreach my $entry (keys(%roleshash)) {
4213: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
4214: if ($trole =~ /^cr/) {
4215: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
4216: } else {
4217: next if (!exists($roles{$trole}));
4218: }
4219: if ($tend) {
4220: next if ($tend < $now);
4221: }
4222: if ($tstart) {
4223: next if ($tstart > $now);
4224: }
4225: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
4226: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
4227: my $value = $trole.'/'.$cdom.'/';
4228: if ($secpart eq '') {
4229: ($cnum,$role) = split(/_/,$cnumpart);
4230: $sec = 'none';
4231: $value .= $cnum.'/';
4232: } else {
4233: $cnum = $cnumpart;
4234: ($sec,$role) = split(/_/,$secpart);
4235: $value .= $cnum.'/'.$sec;
4236: }
4237: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4238: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4239: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4240: }
4241: } else {
4242: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4243: }
4244: }
4245: } else {
4246: foreach my $key (keys(%env)) {
4247: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
4248: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
4249: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
4250: next if ($role eq 'ca' || $role eq 'aa');
4251: next if (%roles && !exists($roles{$role}));
4252: my ($starttime,$endtime)=split(/\./,$env{$key});
4253: my $active=1;
4254: if ($starttime) {
4255: if ($now<$starttime) { $active=0; }
4256: }
4257: if ($endtime) {
4258: if ($now>$endtime) { $active=0; }
4259: }
4260: if ($active) {
4261: my $value = $role.'/'.$cdom.'/'.$cnum.'/';
4262: if ($sec eq '') {
4263: $sec = 'none';
4264: } else {
4265: $value .= $sec;
4266: }
4267: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4268: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4269: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4270: }
4271: } else {
4272: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4273: }
4274: }
4275: }
4276: }
4277: }
4278: return %courses;
4279: }
4280:
4281: ###############################################
4282:
4283: sub blockcheck {
4284: my ($setters,$activity,$uname,$udom,$url) = @_;
4285:
4286: if (!defined($udom)) {
4287: $udom = $env{'user.domain'};
4288: }
4289: if (!defined($uname)) {
4290: $uname = $env{'user.name'};
4291: }
4292:
4293: # If uname and udom are for a course, check for blocks in the course.
4294:
4295: if (&Apache::lonnet::is_course($udom,$uname)) {
4296: my ($startblock,$endblock,$triggerblock) =
4297: &get_blocks($setters,$activity,$udom,$uname,$url);
4298: return ($startblock,$endblock,$triggerblock);
4299: }
4300:
4301: my $startblock = 0;
4302: my $endblock = 0;
4303: my $triggerblock = '';
4304: my %live_courses = &findallcourses(undef,$uname,$udom);
4305:
4306: # If uname is for a user, and activity is course-specific, i.e.,
4307: # boards, chat or groups, check for blocking in current course only.
4308:
4309: if (($activity eq 'boards' || $activity eq 'chat' ||
4310: $activity eq 'groups') && ($env{'request.course.id'})) {
4311: foreach my $key (keys(%live_courses)) {
4312: if ($key ne $env{'request.course.id'}) {
4313: delete($live_courses{$key});
4314: }
4315: }
4316: }
4317:
4318: my $otheruser = 0;
4319: my %own_courses;
4320: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
4321: # Resource belongs to user other than current user.
4322: $otheruser = 1;
4323: # Gather courses for current user
4324: %own_courses =
4325: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
4326: }
4327:
4328: # Gather active course roles - course coordinator, instructor,
4329: # exam proctor, ta, student, or custom role.
4330:
4331: foreach my $course (keys(%live_courses)) {
4332: my ($cdom,$cnum);
4333: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
4334: $cdom = $env{'course.'.$course.'.domain'};
4335: $cnum = $env{'course.'.$course.'.num'};
4336: } else {
4337: ($cdom,$cnum) = split(/_/,$course);
4338: }
4339: my $no_ownblock = 0;
4340: my $no_userblock = 0;
4341: if ($otheruser && $activity ne 'com') {
4342: # Check if current user has 'evb' priv for this
4343: if (defined($own_courses{$course})) {
4344: foreach my $sec (keys(%{$own_courses{$course}})) {
4345: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4346: if ($sec ne 'none') {
4347: $checkrole .= '/'.$sec;
4348: }
4349: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4350: $no_ownblock = 1;
4351: last;
4352: }
4353: }
4354: }
4355: # if they have 'evb' priv and are currently not playing student
4356: next if (($no_ownblock) &&
4357: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
4358: }
4359: foreach my $sec (keys(%{$live_courses{$course}})) {
4360: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4361: if ($sec ne 'none') {
4362: $checkrole .= '/'.$sec;
4363: }
4364: if ($otheruser) {
4365: # Resource belongs to user other than current user.
4366: # Assemble privs for that user, and check for 'evb' priv.
4367: my (%allroles,%userroles);
4368: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
4369: foreach my $entry (@{$live_courses{$course}{$sec}}) {
4370: my ($trole,$tdom,$tnum,$tsec);
4371: if ($entry =~ /^cr/) {
4372: ($trole,$tdom,$tnum,$tsec) =
4373: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
4374: } else {
4375: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
4376: }
4377: my ($spec,$area,$trest);
4378: $area = '/'.$tdom.'/'.$tnum;
4379: $trest = $tnum;
4380: if ($tsec ne '') {
4381: $area .= '/'.$tsec;
4382: $trest .= '/'.$tsec;
4383: }
4384: $spec = $trole.'.'.$area;
4385: if ($trole =~ /^cr/) {
4386: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
4387: $tdom,$spec,$trest,$area);
4388: } else {
4389: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
4390: $tdom,$spec,$trest,$area);
4391: }
4392: }
4393: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
4394: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
4395: if ($1) {
4396: $no_userblock = 1;
4397: last;
4398: }
4399: }
4400: }
4401: } else {
4402: # Resource belongs to current user
4403: # Check for 'evb' priv via lonnet::allowed().
4404: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4405: $no_ownblock = 1;
4406: last;
4407: }
4408: }
4409: }
4410: # if they have the evb priv and are currently not playing student
4411: next if (($no_ownblock) &&
4412: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
4413: next if ($no_userblock);
4414:
4415: # Retrieve blocking times and identity of locker for course
4416: # of specified user, unless user has 'evb' privilege.
4417:
4418: my ($start,$end,$trigger) =
4419: &get_blocks($setters,$activity,$cdom,$cnum,$url);
4420: if (($start != 0) &&
4421: (($startblock == 0) || ($startblock > $start))) {
4422: $startblock = $start;
4423: if ($trigger ne '') {
4424: $triggerblock = $trigger;
4425: }
4426: }
4427: if (($end != 0) &&
4428: (($endblock == 0) || ($endblock < $end))) {
4429: $endblock = $end;
4430: if ($trigger ne '') {
4431: $triggerblock = $trigger;
4432: }
4433: }
4434: }
4435: return ($startblock,$endblock,$triggerblock);
4436: }
4437:
4438: sub get_blocks {
4439: my ($setters,$activity,$cdom,$cnum,$url) = @_;
4440: my $startblock = 0;
4441: my $endblock = 0;
4442: my $triggerblock = '';
4443: my $course = $cdom.'_'.$cnum;
4444: $setters->{$course} = {};
4445: $setters->{$course}{'staff'} = [];
4446: $setters->{$course}{'times'} = [];
4447: $setters->{$course}{'triggers'} = [];
4448: my (@blockers,%triggered);
4449: my $now = time;
4450: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
4451: if ($activity eq 'docs') {
4452: @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
4453: foreach my $block (@blockers) {
4454: if ($block =~ /^firstaccess____(.+)$/) {
4455: my $item = $1;
4456: my $type = 'map';
4457: my $timersymb = $item;
4458: if ($item eq 'course') {
4459: $type = 'course';
4460: } elsif ($item =~ /___\d+___/) {
4461: $type = 'resource';
4462: } else {
4463: $timersymb = &Apache::lonnet::symbread($item);
4464: }
4465: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4466: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4467: $triggered{$block} = {
4468: start => $start,
4469: end => $end,
4470: type => $type,
4471: };
4472: }
4473: }
4474: } else {
4475: foreach my $block (keys(%commblocks)) {
4476: if ($block =~ m/^(\d+)____(\d+)$/) {
4477: my ($start,$end) = ($1,$2);
4478: if ($start <= time && $end >= time) {
4479: if (ref($commblocks{$block}) eq 'HASH') {
4480: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
4481: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
4482: unless(grep(/^\Q$block\E$/,@blockers)) {
4483: push(@blockers,$block);
4484: }
4485: }
4486: }
4487: }
4488: }
4489: } elsif ($block =~ /^firstaccess____(.+)$/) {
4490: my $item = $1;
4491: my $timersymb = $item;
4492: my $type = 'map';
4493: if ($item eq 'course') {
4494: $type = 'course';
4495: } elsif ($item =~ /___\d+___/) {
4496: $type = 'resource';
4497: } else {
4498: $timersymb = &Apache::lonnet::symbread($item);
4499: }
4500: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4501: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4502: if ($start && $end) {
4503: if (($start <= time) && ($end >= time)) {
4504: unless (grep(/^\Q$block\E$/,@blockers)) {
4505: push(@blockers,$block);
4506: $triggered{$block} = {
4507: start => $start,
4508: end => $end,
4509: type => $type,
4510: };
4511: }
4512: }
4513: }
4514: }
4515: }
4516: }
4517: foreach my $blocker (@blockers) {
4518: my ($staff_name,$staff_dom,$title,$blocks) =
4519: &parse_block_record($commblocks{$blocker});
4520: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
4521: my ($start,$end,$triggertype);
4522: if ($blocker =~ m/^(\d+)____(\d+)$/) {
4523: ($start,$end) = ($1,$2);
4524: } elsif (ref($triggered{$blocker}) eq 'HASH') {
4525: $start = $triggered{$blocker}{'start'};
4526: $end = $triggered{$blocker}{'end'};
4527: $triggertype = $triggered{$blocker}{'type'};
4528: }
4529: if ($start) {
4530: push(@{$$setters{$course}{'times'}}, [$start,$end]);
4531: if ($triggertype) {
4532: push(@{$$setters{$course}{'triggers'}},$triggertype);
4533: } else {
4534: push(@{$$setters{$course}{'triggers'}},0);
4535: }
4536: if ( ($startblock == 0) || ($startblock > $start) ) {
4537: $startblock = $start;
4538: if ($triggertype) {
4539: $triggerblock = $blocker;
4540: }
4541: }
4542: if ( ($endblock == 0) || ($endblock < $end) ) {
4543: $endblock = $end;
4544: if ($triggertype) {
4545: $triggerblock = $blocker;
4546: }
4547: }
4548: }
4549: }
4550: return ($startblock,$endblock,$triggerblock);
4551: }
4552:
4553: sub parse_block_record {
4554: my ($record) = @_;
4555: my ($setuname,$setudom,$title,$blocks);
4556: if (ref($record) eq 'HASH') {
4557: ($setuname,$setudom) = split(/:/,$record->{'setter'});
4558: $title = &unescape($record->{'event'});
4559: $blocks = $record->{'blocks'};
4560: } else {
4561: my @data = split(/:/,$record,3);
4562: if (scalar(@data) eq 2) {
4563: $title = $data[1];
4564: ($setuname,$setudom) = split(/@/,$data[0]);
4565: } else {
4566: ($setuname,$setudom,$title) = @data;
4567: }
4568: $blocks = { 'com' => 'on' };
4569: }
4570: return ($setuname,$setudom,$title,$blocks);
4571: }
4572:
4573: sub blocking_status {
4574: my ($activity,$uname,$udom,$url) = @_;
4575: my %setters;
4576:
4577: # check for active blocking
4578: my ($startblock,$endblock,$triggerblock) =
4579: &blockcheck(\%setters,$activity,$uname,$udom,$url);
4580: my $blocked = 0;
4581: if ($startblock && $endblock) {
4582: $blocked = 1;
4583: }
4584:
4585: # caller just wants to know whether a block is active
4586: if (!wantarray) { return $blocked; }
4587:
4588: # build a link to a popup window containing the details
4589: my $querystring = "?activity=$activity";
4590: # $uname and $udom decide whose portfolio the user is trying to look at
4591: if ($activity eq 'port') {
4592: $querystring .= "&udom=$udom" if $udom;
4593: $querystring .= "&uname=$uname" if $uname;
4594: } elsif ($activity eq 'docs') {
4595: $querystring .= '&url='.&HTML::Entities::encode($url,'&"');
4596: }
4597:
4598: my $output .= <<'END_MYBLOCK';
4599: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
4600: var options = "width=" + w + ",height=" + h + ",";
4601: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
4602: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
4603: var newWin = window.open(url, wdwName, options);
4604: newWin.focus();
4605: }
4606: END_MYBLOCK
4607:
4608: $output = Apache::lonhtmlcommon::scripttag($output);
4609:
4610: my $popupUrl = "/adm/blockingstatus/$querystring";
4611: my $text = &mt('Communication Blocked');
4612: if ($activity eq 'docs') {
4613: $text = &mt('Content Access Blocked');
4614: } elsif ($activity eq 'printout') {
4615: $text = &mt('Printing Blocked');
4616: }
4617: $output .= <<"END_BLOCK";
4618: <div class='LC_comblock'>
4619: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4620: title='$text'>
4621: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
4622: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4623: title='$text'>$text</a>
4624: </div>
4625:
4626: END_BLOCK
4627:
4628: return ($blocked, $output);
4629: }
4630:
4631: ###############################################
4632:
4633: sub check_ip_acc {
4634: my ($acc)=@_;
4635: &Apache::lonxml::debug("acc is $acc");
4636: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
4637: return 1;
4638: }
4639: my $allowed=0;
4640: my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
4641:
4642: my $name;
4643: foreach my $pattern (split(',',$acc)) {
4644: $pattern =~ s/^\s*//;
4645: $pattern =~ s/\s*$//;
4646: if ($pattern =~ /\*$/) {
4647: #35.8.*
4648: $pattern=~s/\*//;
4649: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4650: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
4651: #35.8.3.[34-56]
4652: my $low=$2;
4653: my $high=$3;
4654: $pattern=$1;
4655: if ($ip =~ /^\Q$pattern\E/) {
4656: my $last=(split(/\./,$ip))[3];
4657: if ($last <=$high && $last >=$low) { $allowed=1; }
4658: }
4659: } elsif ($pattern =~ /^\*/) {
4660: #*.msu.edu
4661: $pattern=~s/\*//;
4662: if (!defined($name)) {
4663: use Socket;
4664: my $netaddr=inet_aton($ip);
4665: ($name)=gethostbyaddr($netaddr,AF_INET);
4666: }
4667: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4668: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
4669: #127.0.0.1
4670: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4671: } else {
4672: #some.name.com
4673: if (!defined($name)) {
4674: use Socket;
4675: my $netaddr=inet_aton($ip);
4676: ($name)=gethostbyaddr($netaddr,AF_INET);
4677: }
4678: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4679: }
4680: if ($allowed) { last; }
4681: }
4682: return $allowed;
4683: }
4684:
4685: ###############################################
4686:
4687: =pod
4688:
4689: =head1 Domain Template Functions
4690:
4691: =over 4
4692:
4693: =item * &determinedomain()
4694:
4695: Inputs: $domain (usually will be undef)
4696:
4697: Returns: Determines which domain should be used for designs
4698:
4699: =cut
4700:
4701: ###############################################
4702: sub determinedomain {
4703: my $domain=shift;
4704: if (! $domain) {
4705: # Determine domain if we have not been given one
4706: $domain = &Apache::lonnet::default_login_domain();
4707: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
4708: if ($env{'request.role.domain'}) {
4709: $domain=$env{'request.role.domain'};
4710: }
4711: }
4712: return $domain;
4713: }
4714: ###############################################
4715:
4716: sub devalidate_domconfig_cache {
4717: my ($udom)=@_;
4718: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
4719: }
4720:
4721: # ---------------------- Get domain configuration for a domain
4722: sub get_domainconf {
4723: my ($udom) = @_;
4724: my $cachetime=1800;
4725: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
4726: if (defined($cached)) { return %{$result}; }
4727:
4728: my %domconfig = &Apache::lonnet::get_dom('configuration',
4729: ['login','rolecolors','autoenroll'],$udom);
4730: my (%designhash,%legacy);
4731: if (keys(%domconfig) > 0) {
4732: if (ref($domconfig{'login'}) eq 'HASH') {
4733: if (keys(%{$domconfig{'login'}})) {
4734: foreach my $key (keys(%{$domconfig{'login'}})) {
4735: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
4736: if ($key eq 'loginvia') {
4737: if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
4738: foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
4739: if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
4740: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
4741: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
4742: $designhash{$udom.'.login.loginvia'} = $server;
4743: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
4744:
4745: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
4746: } else {
4747: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
4748: }
4749: if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
4750: $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
4751: }
4752: }
4753: }
4754: }
4755: }
4756: } else {
4757: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
4758: $designhash{$udom.'.login.'.$key.'_'.$img} =
4759: $domconfig{'login'}{$key}{$img};
4760: }
4761: }
4762: } else {
4763: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
4764: }
4765: }
4766: } else {
4767: $legacy{'login'} = 1;
4768: }
4769: } else {
4770: $legacy{'login'} = 1;
4771: }
4772: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
4773: if (keys(%{$domconfig{'rolecolors'}})) {
4774: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
4775: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
4776: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
4777: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
4778: }
4779: }
4780: }
4781: } else {
4782: $legacy{'rolecolors'} = 1;
4783: }
4784: } else {
4785: $legacy{'rolecolors'} = 1;
4786: }
4787: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
4788: if ($domconfig{'autoenroll'}{'co-owners'}) {
4789: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
4790: }
4791: }
4792: if (keys(%legacy) > 0) {
4793: my %legacyhash = &get_legacy_domconf($udom);
4794: foreach my $item (keys(%legacyhash)) {
4795: if ($item =~ /^\Q$udom\E\.login/) {
4796: if ($legacy{'login'}) {
4797: $designhash{$item} = $legacyhash{$item};
4798: }
4799: } else {
4800: if ($legacy{'rolecolors'}) {
4801: $designhash{$item} = $legacyhash{$item};
4802: }
4803: }
4804: }
4805: }
4806: } else {
4807: %designhash = &get_legacy_domconf($udom);
4808: }
4809: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
4810: $cachetime);
4811: return %designhash;
4812: }
4813:
4814: sub get_legacy_domconf {
4815: my ($udom) = @_;
4816: my %legacyhash;
4817: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
4818: my $designfile = $designdir.'/'.$udom.'.tab';
4819: if (-e $designfile) {
4820: if ( open (my $fh,"<$designfile") ) {
4821: while (my $line = <$fh>) {
4822: next if ($line =~ /^\#/);
4823: chomp($line);
4824: my ($key,$val)=(split(/\=/,$line));
4825: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
4826: }
4827: close($fh);
4828: }
4829: }
4830: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
4831: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
4832: }
4833: return %legacyhash;
4834: }
4835:
4836: =pod
4837:
4838: =item * &domainlogo()
4839:
4840: Inputs: $domain (usually will be undef)
4841:
4842: Returns: A link to a domain logo, if the domain logo exists.
4843: If the domain logo does not exist, a description of the domain.
4844:
4845: =cut
4846:
4847: ###############################################
4848: sub domainlogo {
4849: my $domain = &determinedomain(shift);
4850: my %designhash = &get_domainconf($domain);
4851: # See if there is a logo
4852: if ($designhash{$domain.'.login.domlogo'} ne '') {
4853: my $imgsrc = $designhash{$domain.'.login.domlogo'};
4854: if ($imgsrc =~ m{^/(adm|res)/}) {
4855: if ($imgsrc =~ m{^/res/}) {
4856: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
4857: &Apache::lonnet::repcopy($local_name);
4858: }
4859: $imgsrc = &lonhttpdurl($imgsrc);
4860: }
4861: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
4862: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
4863: return &Apache::lonnet::domain($domain,'description');
4864: } else {
4865: return '';
4866: }
4867: }
4868: ##############################################
4869:
4870: =pod
4871:
4872: =item * &designparm()
4873:
4874: Inputs: $which parameter; $domain (usually will be undef)
4875:
4876: Returns: value of designparamter $which
4877:
4878: =cut
4879:
4880:
4881: ##############################################
4882: sub designparm {
4883: my ($which,$domain)=@_;
4884: if (exists($env{'environment.color.'.$which})) {
4885: return $env{'environment.color.'.$which};
4886: }
4887: $domain=&determinedomain($domain);
4888: my %domdesign;
4889: unless ($domain eq 'public') {
4890: %domdesign = &get_domainconf($domain);
4891: }
4892: my $output;
4893: if ($domdesign{$domain.'.'.$which} ne '') {
4894: $output = $domdesign{$domain.'.'.$which};
4895: } else {
4896: $output = $defaultdesign{$which};
4897: }
4898: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
4899: ($which =~ /login\.(img|logo|domlogo|login)/)) {
4900: if ($output =~ m{^/(adm|res)/}) {
4901: if ($output =~ m{^/res/}) {
4902: my $local_name = &Apache::lonnet::filelocation('',$output);
4903: &Apache::lonnet::repcopy($local_name);
4904: }
4905: $output = &lonhttpdurl($output);
4906: }
4907: }
4908: return $output;
4909: }
4910:
4911: ##############################################
4912: =pod
4913:
4914: =item * &authorspace()
4915:
4916: Inputs: $url (usually will be undef).
4917:
4918: Returns: Path to Construction Space containing the resource or
4919: directory being viewed (or for which action is being taken).
4920: If $url is provided, and begins /priv/<domain>/<uname>
4921: the path will be that portion of the $context argument.
4922: Otherwise the path will be for the author space of the current
4923: user when the current role is author, or for that of the
4924: co-author/assistant co-author space when the current role
4925: is co-author or assistant co-author.
4926:
4927: =cut
4928:
4929: sub authorspace {
4930: my ($url) = @_;
4931: if ($url ne '') {
4932: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
4933: return $1;
4934: }
4935: }
4936: my $caname = '';
4937: my $cadom = '';
4938: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
4939: ($cadom,$caname) =
4940: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
4941: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
4942: $caname = $env{'user.name'};
4943: $cadom = $env{'user.domain'};
4944: }
4945: if (($caname ne '') && ($cadom ne '')) {
4946: return "/priv/$cadom/$caname/";
4947: }
4948: return;
4949: }
4950:
4951: ##############################################
4952: =pod
4953:
4954: =item * &head_subbox()
4955:
4956: Inputs: $content (contains HTML code with page functions, etc.)
4957:
4958: Returns: HTML div with $content
4959: To be included in page header
4960:
4961: =cut
4962:
4963: sub head_subbox {
4964: my ($content)=@_;
4965: my $output =
4966: '<div class="LC_head_subbox">'
4967: .$content
4968: .'</div>'
4969: }
4970:
4971: ##############################################
4972: =pod
4973:
4974: =item * &CSTR_pageheader()
4975:
4976: Input: (optional) filename from which breadcrumb trail is built.
4977: In most cases no input as needed, as $env{'request.filename'}
4978: is appropriate for use in building the breadcrumb trail.
4979:
4980: Returns: HTML div with CSTR path and recent box
4981: To be included on Construction Space pages
4982:
4983: =cut
4984:
4985: sub CSTR_pageheader {
4986: my ($trailfile) = @_;
4987: if ($trailfile eq '') {
4988: $trailfile = $env{'request.filename'};
4989: }
4990:
4991: # this is for resources; directories have customtitle, and crumbs
4992: # and select recent are created in lonpubdir.pm
4993:
4994: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
4995: my ($udom,$uname,$thisdisfn)=
4996: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
4997: my $formaction = "/priv/$udom/$uname/$thisdisfn";
4998: $formaction =~ s{/+}{/}g;
4999:
5000: my $parentpath = '';
5001: my $lastitem = '';
5002: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
5003: $parentpath = $1;
5004: $lastitem = $2;
5005: } else {
5006: $lastitem = $thisdisfn;
5007: }
5008:
5009: my $output =
5010: '<div>'
5011: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
5012: .'<b>'.&mt('Construction Space:').'</b> '
5013: .'<form name="dirs" method="post" action="'.$formaction
5014: .'" target="_top">' #FIXME lonpubdir: target="_parent"
5015: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
5016:
5017: if ($lastitem) {
5018: $output .=
5019: '<span class="LC_filename">'
5020: .$lastitem
5021: .'</span>';
5022: }
5023: $output .=
5024: '<br />'
5025: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
5026: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
5027: .'</form>'
5028: .&Apache::lonmenu::constspaceform()
5029: .'</div>';
5030:
5031: return $output;
5032: }
5033:
5034: ###############################################
5035: ###############################################
5036:
5037: =pod
5038:
5039: =back
5040:
5041: =head1 HTML Helpers
5042:
5043: =over 4
5044:
5045: =item * &bodytag()
5046:
5047: Returns a uniform header for LON-CAPA web pages.
5048:
5049: Inputs:
5050:
5051: =over 4
5052:
5053: =item * $title, A title to be displayed on the page.
5054:
5055: =item * $function, the current role (can be undef).
5056:
5057: =item * $addentries, extra parameters for the <body> tag.
5058:
5059: =item * $bodyonly, if defined, only return the <body> tag.
5060:
5061: =item * $domain, if defined, force a given domain.
5062:
5063: =item * $forcereg, if page should register as content page (relevant for
5064: text interface only)
5065:
5066: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
5067: navigational links
5068:
5069: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
5070:
5071: =item * $args, optional argument valid values are
5072: no_auto_mt_title -> prevents &mt()ing the title arg
5073: inherit_jsmath -> when creating popup window in a page,
5074: should it have jsmath forced on by the
5075: current page
5076:
5077: =item * $advtoolsref, optional argument, ref to an array containing
5078: inlineremote items to be added in "Functions" menu below
5079: breadcrumbs.
5080:
5081: =back
5082:
5083: Returns: A uniform header for LON-CAPA web pages.
5084: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
5085: If $bodyonly is undef or zero, an html string containing a <body> tag and
5086: other decorations will be returned.
5087:
5088: =cut
5089:
5090: sub bodytag {
5091: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
5092: $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
5093:
5094: my $public;
5095: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
5096: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
5097: $public = 1;
5098: }
5099: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
5100:
5101: $function = &get_users_function() if (!$function);
5102: my $img = &designparm($function.'.img',$domain);
5103: my $font = &designparm($function.'.font',$domain);
5104: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
5105:
5106: my %design = ( 'style' => 'margin-top: 0',
5107: 'bgcolor' => $pgbg,
5108: 'text' => $font,
5109: 'alink' => &designparm($function.'.alink',$domain),
5110: 'vlink' => &designparm($function.'.vlink',$domain),
5111: 'link' => &designparm($function.'.link',$domain),);
5112: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
5113:
5114: # role and realm
5115: my ($role,$realm) = split(/\./,$env{'request.role'},2);
5116: if ($role eq 'ca') {
5117: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
5118: $realm = &plainname($rname,$rdom);
5119: }
5120: # realm
5121: if ($env{'request.course.id'}) {
5122: if ($env{'request.role'} !~ /^cr/) {
5123: $role = &Apache::lonnet::plaintext($role,&course_type());
5124: }
5125: if ($env{'request.course.sec'}) {
5126: $role .= (' 'x2).'- '.&mt('section:').' '.$env{'request.course.sec'};
5127: }
5128: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
5129: } else {
5130: $role = &Apache::lonnet::plaintext($role);
5131: }
5132:
5133: if (!$realm) { $realm=' '; }
5134:
5135: my $extra_body_attr = &make_attr_string($forcereg,\%design);
5136:
5137: # construct main body tag
5138: my $bodytag = "<body $extra_body_attr>".
5139: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
5140:
5141: if ($bodyonly) {
5142: return $bodytag;
5143: }
5144:
5145: my $name = &plainname($env{'user.name'},$env{'user.domain'});
5146: if ($public) {
5147: undef($role);
5148: } else {
5149: $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
5150: undef,'LC_menubuttons_link');
5151: }
5152:
5153: my $titleinfo = '<h1>'.$title.'</h1>';
5154: #
5155: # Extra info if you are the DC
5156: my $dc_info = '';
5157: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
5158: $env{'course.'.$env{'request.course.id'}.
5159: '.domain'}.'/'})) {
5160: my $cid = $env{'request.course.id'};
5161: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
5162: $dc_info =~ s/\s+$//;
5163: }
5164:
5165: $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
5166: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
5167:
5168: if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') {
5169: return $bodytag;
5170: }
5171:
5172: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
5173:
5174: # if ($env{'request.state'} eq 'construct') {
5175: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
5176: # }
5177:
5178:
5179:
5180: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
5181: if ($dc_info) {
5182: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
5183: }
5184: $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
5185: <em>$realm</em> $dc_info</div>|;
5186: return $bodytag;
5187: }
5188:
5189: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
5190: $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
5191: }
5192:
5193: $bodytag .= Apache::lonhtmlcommon::scripttag(
5194: Apache::lonmenu::utilityfunctions(), 'start');
5195:
5196: $bodytag .= Apache::lonmenu::primary_menu();
5197:
5198: if ($dc_info) {
5199: $dc_info = &dc_courseid_toggle($dc_info);
5200: }
5201: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
5202:
5203: #don't show menus for public users
5204: if (!$public){
5205: $bodytag .= Apache::lonmenu::secondary_menu();
5206: $bodytag .= Apache::lonmenu::serverform();
5207: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5208: if ($env{'request.state'} eq 'construct') {
5209: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
5210: $args->{'bread_crumbs'});
5211: } elsif ($forcereg) {
5212: $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
5213: $args->{'group'});
5214: } else {
5215: $bodytag .=
5216: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
5217: $forcereg,$args->{'group'},
5218: $args->{'bread_crumbs'},
5219: $advtoolsref);
5220: }
5221: }else{
5222: # this is to seperate menu from content when there's no secondary
5223: # menu. Especially needed for public accessible ressources.
5224: $bodytag .= '<hr style="clear:both" />';
5225: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5226: }
5227:
5228: return $bodytag;
5229: }
5230:
5231: sub dc_courseid_toggle {
5232: my ($dc_info) = @_;
5233: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
5234: '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
5235: &mt('(More ...)').'</a></span>'.
5236: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
5237: }
5238:
5239: sub make_attr_string {
5240: my ($register,$attr_ref) = @_;
5241:
5242: if ($attr_ref && !ref($attr_ref)) {
5243: die("addentries Must be a hash ref ".
5244: join(':',caller(1))." ".
5245: join(':',caller(0))." ");
5246: }
5247:
5248: if ($register) {
5249: my ($on_load,$on_unload);
5250: foreach my $key (keys(%{$attr_ref})) {
5251: if (lc($key) eq 'onload') {
5252: $on_load.=$attr_ref->{$key}.';';
5253: delete($attr_ref->{$key});
5254:
5255: } elsif (lc($key) eq 'onunload') {
5256: $on_unload.=$attr_ref->{$key}.';';
5257: delete($attr_ref->{$key});
5258: }
5259: }
5260: $attr_ref->{'onload'} = $on_load;
5261: $attr_ref->{'onunload'}= $on_unload;
5262: }
5263:
5264: my $attr_string;
5265: foreach my $attr (keys(%$attr_ref)) {
5266: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
5267: }
5268: return $attr_string;
5269: }
5270:
5271:
5272: ###############################################
5273: ###############################################
5274:
5275: =pod
5276:
5277: =item * &endbodytag()
5278:
5279: Returns a uniform footer for LON-CAPA web pages.
5280:
5281: Inputs: 1 - optional reference to an args hash
5282: If in the hash, key for noredirectlink has a value which evaluates to true,
5283: a 'Continue' link is not displayed if the page contains an
5284: internal redirect in the <head></head> section,
5285: i.e., $env{'internal.head.redirect'} exists
5286:
5287: =cut
5288:
5289: sub endbodytag {
5290: my ($args) = @_;
5291: my $endbodytag;
5292: unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
5293: $endbodytag='</body>';
5294: }
5295: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
5296: if ( exists( $env{'internal.head.redirect'} ) ) {
5297: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
5298: $endbodytag=
5299: "<br /><a href=\"$env{'internal.head.redirect'}\">".
5300: &mt('Continue').'</a>'.
5301: $endbodytag;
5302: }
5303: }
5304: return $endbodytag;
5305: }
5306:
5307: =pod
5308:
5309: =item * &standard_css()
5310:
5311: Returns a style sheet
5312:
5313: Inputs: (all optional)
5314: domain -> force to color decorate a page for a specific
5315: domain
5316: function -> force usage of a specific rolish color scheme
5317: bgcolor -> override the default page bgcolor
5318:
5319: =cut
5320:
5321: sub standard_css {
5322: my ($function,$domain,$bgcolor) = @_;
5323: $function = &get_users_function() if (!$function);
5324: my $img = &designparm($function.'.img', $domain);
5325: my $tabbg = &designparm($function.'.tabbg', $domain);
5326: my $font = &designparm($function.'.font', $domain);
5327: my $fontmenu = &designparm($function.'.fontmenu', $domain);
5328: #second colour for later usage
5329: my $sidebg = &designparm($function.'.sidebg',$domain);
5330: my $pgbg_or_bgcolor =
5331: $bgcolor ||
5332: &designparm($function.'.pgbg', $domain);
5333: my $pgbg = &designparm($function.'.pgbg', $domain);
5334: my $alink = &designparm($function.'.alink', $domain);
5335: my $vlink = &designparm($function.'.vlink', $domain);
5336: my $link = &designparm($function.'.link', $domain);
5337:
5338: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
5339: my $mono = 'monospace';
5340: my $data_table_head = $sidebg;
5341: my $data_table_light = '#FAFAFA';
5342: my $data_table_dark = '#E0E0E0';
5343: my $data_table_darker = '#CCCCCC';
5344: my $data_table_highlight = '#FFFF00';
5345: my $mail_new = '#FFBB77';
5346: my $mail_new_hover = '#DD9955';
5347: my $mail_read = '#BBBB77';
5348: my $mail_read_hover = '#999944';
5349: my $mail_replied = '#AAAA88';
5350: my $mail_replied_hover = '#888855';
5351: my $mail_other = '#99BBBB';
5352: my $mail_other_hover = '#669999';
5353: my $table_header = '#DDDDDD';
5354: my $feedback_link_bg = '#BBBBBB';
5355: my $lg_border_color = '#C8C8C8';
5356: my $button_hover = '#BF2317';
5357:
5358: my $border = ($env{'browser.type'} eq 'explorer' ||
5359: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
5360: : '0 3px 0 4px';
5361:
5362:
5363: return <<END;
5364:
5365: /* needed for iframe to allow 100% height in FF */
5366: body, html {
5367: margin: 0;
5368: padding: 0 0.5%;
5369: height: 99%; /* to avoid scrollbars */
5370: }
5371:
5372: body {
5373: font-family: $sans;
5374: line-height:130%;
5375: font-size:0.83em;
5376: color:$font;
5377: }
5378:
5379: a:focus,
5380: a:focus img {
5381: color: red;
5382: }
5383:
5384: form, .inline {
5385: display: inline;
5386: }
5387:
5388: .LC_right {
5389: text-align:right;
5390: }
5391:
5392: .LC_middle {
5393: vertical-align:middle;
5394: }
5395:
5396: .LC_400Box {
5397: width:400px;
5398: }
5399:
5400: .LC_iframecontainer {
5401: width: 98%;
5402: margin: 0;
5403: position: fixed;
5404: top: 8.5em;
5405: bottom: 0;
5406: }
5407:
5408: .LC_iframecontainer iframe{
5409: border: none;
5410: width: 100%;
5411: height: 100%;
5412: }
5413:
5414: .LC_filename {
5415: font-family: $mono;
5416: white-space:pre;
5417: font-size: 120%;
5418: }
5419:
5420: .LC_fileicon {
5421: border: none;
5422: height: 1.3em;
5423: vertical-align: text-bottom;
5424: margin-right: 0.3em;
5425: text-decoration:none;
5426: }
5427:
5428: .LC_setting {
5429: text-decoration:underline;
5430: }
5431:
5432: .LC_error {
5433: color: red;
5434: }
5435:
5436: .LC_warning {
5437: color: darkorange;
5438: }
5439:
5440: .LC_diff_removed {
5441: color: red;
5442: }
5443:
5444: .LC_info,
5445: .LC_success,
5446: .LC_diff_added {
5447: color: green;
5448: }
5449:
5450: div.LC_confirm_box {
5451: background-color: #FAFAFA;
5452: border: 1px solid $lg_border_color;
5453: margin-right: 0;
5454: padding: 5px;
5455: }
5456:
5457: div.LC_confirm_box .LC_error img,
5458: div.LC_confirm_box .LC_success img {
5459: vertical-align: middle;
5460: }
5461:
5462: .LC_icon {
5463: border: none;
5464: vertical-align: middle;
5465: }
5466:
5467: .LC_docs_spacer {
5468: width: 25px;
5469: height: 1px;
5470: border: none;
5471: }
5472:
5473: .LC_internal_info {
5474: color: #999999;
5475: }
5476:
5477: .LC_discussion {
5478: background: $data_table_dark;
5479: border: 1px solid black;
5480: margin: 2px;
5481: }
5482:
5483: .LC_disc_action_left {
5484: background: $sidebg;
5485: text-align: left;
5486: padding: 4px;
5487: margin: 2px;
5488: }
5489:
5490: .LC_disc_action_right {
5491: background: $sidebg;
5492: text-align: right;
5493: padding: 4px;
5494: margin: 2px;
5495: }
5496:
5497: .LC_disc_new_item {
5498: background: white;
5499: border: 2px solid red;
5500: margin: 4px;
5501: padding: 4px;
5502: }
5503:
5504: .LC_disc_old_item {
5505: background: white;
5506: margin: 4px;
5507: padding: 4px;
5508: }
5509:
5510: table.LC_pastsubmission {
5511: border: 1px solid black;
5512: margin: 2px;
5513: }
5514:
5515: table#LC_menubuttons {
5516: width: 100%;
5517: background: $pgbg;
5518: border: 2px;
5519: border-collapse: separate;
5520: padding: 0;
5521: }
5522:
5523: table#LC_title_bar a {
5524: color: $fontmenu;
5525: }
5526:
5527: table#LC_title_bar {
5528: clear: both;
5529: display: none;
5530: }
5531:
5532: table#LC_title_bar,
5533: table.LC_breadcrumbs, /* obsolete? */
5534: table#LC_title_bar.LC_with_remote {
5535: width: 100%;
5536: border-color: $pgbg;
5537: border-style: solid;
5538: border-width: $border;
5539: background: $pgbg;
5540: color: $fontmenu;
5541: border-collapse: collapse;
5542: padding: 0;
5543: margin: 0;
5544: }
5545:
5546: ul.LC_breadcrumb_tools_outerlist {
5547: margin: 0;
5548: padding: 0;
5549: position: relative;
5550: list-style: none;
5551: }
5552: ul.LC_breadcrumb_tools_outerlist li {
5553: display: inline;
5554: }
5555:
5556: .LC_breadcrumb_tools_navigation {
5557: padding: 0;
5558: margin: 0;
5559: float: left;
5560: }
5561: .LC_breadcrumb_tools_tools {
5562: padding: 0;
5563: margin: 0;
5564: float: right;
5565: }
5566:
5567: table#LC_title_bar td {
5568: background: $tabbg;
5569: }
5570:
5571: table#LC_menubuttons img {
5572: border: none;
5573: }
5574:
5575: .LC_breadcrumbs_component {
5576: float: right;
5577: margin: 0 1em;
5578: }
5579: .LC_breadcrumbs_component img {
5580: vertical-align: middle;
5581: }
5582:
5583: td.LC_table_cell_checkbox {
5584: text-align: center;
5585: }
5586:
5587: .LC_fontsize_small {
5588: font-size: 70%;
5589: }
5590:
5591: #LC_breadcrumbs {
5592: clear:both;
5593: background: $sidebg;
5594: border-bottom: 1px solid $lg_border_color;
5595: line-height: 2.5em;
5596: overflow: hidden;
5597: margin: 0;
5598: padding: 0;
5599: text-align: left;
5600: }
5601:
5602: .LC_head_subbox, .LC_actionbox {
5603: clear:both;
5604: background: #F8F8F8; /* $sidebg; */
5605: border: 1px solid $sidebg;
5606: margin: 0 0 10px 0;
5607: padding: 3px;
5608: text-align: left;
5609: }
5610:
5611: .LC_fontsize_medium {
5612: font-size: 85%;
5613: }
5614:
5615: .LC_fontsize_large {
5616: font-size: 120%;
5617: }
5618:
5619: .LC_menubuttons_inline_text {
5620: color: $font;
5621: font-size: 90%;
5622: padding-left:3px;
5623: }
5624:
5625: .LC_menubuttons_inline_text img{
5626: vertical-align: middle;
5627: }
5628:
5629: li.LC_menubuttons_inline_text img {
5630: cursor:pointer;
5631: text-decoration: none;
5632: }
5633:
5634: .LC_menubuttons_link {
5635: text-decoration: none;
5636: }
5637:
5638: .LC_menubuttons_category {
5639: color: $font;
5640: background: $pgbg;
5641: font-size: larger;
5642: font-weight: bold;
5643: }
5644:
5645: td.LC_menubuttons_text {
5646: color: $font;
5647: }
5648:
5649: .LC_current_location {
5650: background: $tabbg;
5651: }
5652:
5653: table.LC_data_table {
5654: border: 1px solid #000000;
5655: border-collapse: separate;
5656: border-spacing: 1px;
5657: background: $pgbg;
5658: }
5659:
5660: .LC_data_table_dense {
5661: font-size: small;
5662: }
5663:
5664: table.LC_nested_outer {
5665: border: 1px solid #000000;
5666: border-collapse: collapse;
5667: border-spacing: 0;
5668: width: 100%;
5669: }
5670:
5671: table.LC_innerpickbox,
5672: table.LC_nested {
5673: border: none;
5674: border-collapse: collapse;
5675: border-spacing: 0;
5676: width: 100%;
5677: }
5678:
5679: table.LC_data_table tr th,
5680: table.LC_calendar tr th,
5681: table.LC_prior_tries tr th,
5682: table.LC_innerpickbox tr th {
5683: font-weight: bold;
5684: background-color: $data_table_head;
5685: color:$fontmenu;
5686: font-size:90%;
5687: }
5688:
5689: table.LC_innerpickbox tr th,
5690: table.LC_innerpickbox tr td {
5691: vertical-align: top;
5692: }
5693:
5694: table.LC_data_table tr.LC_info_row > td {
5695: background-color: #CCCCCC;
5696: font-weight: bold;
5697: text-align: left;
5698: }
5699:
5700: table.LC_data_table tr.LC_odd_row > td {
5701: background-color: $data_table_light;
5702: padding: 2px;
5703: vertical-align: top;
5704: }
5705:
5706: table.LC_pick_box tr > td.LC_odd_row {
5707: background-color: $data_table_light;
5708: vertical-align: top;
5709: }
5710:
5711: table.LC_data_table tr.LC_even_row > td {
5712: background-color: $data_table_dark;
5713: padding: 2px;
5714: vertical-align: top;
5715: }
5716:
5717: table.LC_pick_box tr > td.LC_even_row {
5718: background-color: $data_table_dark;
5719: vertical-align: top;
5720: }
5721:
5722: table.LC_data_table tr.LC_data_table_highlight td {
5723: background-color: $data_table_darker;
5724: }
5725:
5726: table.LC_data_table tr td.LC_leftcol_header {
5727: background-color: $data_table_head;
5728: font-weight: bold;
5729: }
5730:
5731: table.LC_data_table tr.LC_empty_row td,
5732: table.LC_nested tr.LC_empty_row td {
5733: font-weight: bold;
5734: font-style: italic;
5735: text-align: center;
5736: padding: 8px;
5737: }
5738:
5739: table.LC_data_table tr.LC_empty_row td,
5740: table.LC_data_table tr.LC_footer_row td {
5741: background-color: $sidebg;
5742: }
5743:
5744: table.LC_nested tr.LC_empty_row td {
5745: background-color: #FFFFFF;
5746: }
5747:
5748: table.LC_caption {
5749: }
5750:
5751: table.LC_nested tr.LC_empty_row td {
5752: padding: 4ex
5753: }
5754:
5755: table.LC_nested_outer tr th {
5756: font-weight: bold;
5757: color:$fontmenu;
5758: background-color: $data_table_head;
5759: font-size: small;
5760: border-bottom: 1px solid #000000;
5761: }
5762:
5763: table.LC_nested_outer tr td.LC_subheader {
5764: background-color: $data_table_head;
5765: font-weight: bold;
5766: font-size: small;
5767: border-bottom: 1px solid #000000;
5768: text-align: right;
5769: }
5770:
5771: table.LC_nested tr.LC_info_row td {
5772: background-color: #CCCCCC;
5773: font-weight: bold;
5774: font-size: small;
5775: text-align: center;
5776: }
5777:
5778: table.LC_nested tr.LC_info_row td.LC_left_item,
5779: table.LC_nested_outer tr th.LC_left_item {
5780: text-align: left;
5781: }
5782:
5783: table.LC_nested td {
5784: background-color: #FFFFFF;
5785: font-size: small;
5786: }
5787:
5788: table.LC_nested_outer tr th.LC_right_item,
5789: table.LC_nested tr.LC_info_row td.LC_right_item,
5790: table.LC_nested tr.LC_odd_row td.LC_right_item,
5791: table.LC_nested tr td.LC_right_item {
5792: text-align: right;
5793: }
5794:
5795: table.LC_nested tr.LC_odd_row td {
5796: background-color: #EEEEEE;
5797: }
5798:
5799: table.LC_createuser {
5800: }
5801:
5802: table.LC_createuser tr.LC_section_row td {
5803: font-size: small;
5804: }
5805:
5806: table.LC_createuser tr.LC_info_row td {
5807: background-color: #CCCCCC;
5808: font-weight: bold;
5809: text-align: center;
5810: }
5811:
5812: table.LC_calendar {
5813: border: 1px solid #000000;
5814: border-collapse: collapse;
5815: width: 98%;
5816: }
5817:
5818: table.LC_calendar_pickdate {
5819: font-size: xx-small;
5820: }
5821:
5822: table.LC_calendar tr td {
5823: border: 1px solid #000000;
5824: vertical-align: top;
5825: width: 14%;
5826: }
5827:
5828: table.LC_calendar tr td.LC_calendar_day_empty {
5829: background-color: $data_table_dark;
5830: }
5831:
5832: table.LC_calendar tr td.LC_calendar_day_current {
5833: background-color: $data_table_highlight;
5834: }
5835:
5836: table.LC_data_table tr td.LC_mail_new {
5837: background-color: $mail_new;
5838: }
5839:
5840: table.LC_data_table tr.LC_mail_new:hover {
5841: background-color: $mail_new_hover;
5842: }
5843:
5844: table.LC_data_table tr td.LC_mail_read {
5845: background-color: $mail_read;
5846: }
5847:
5848: /*
5849: table.LC_data_table tr.LC_mail_read:hover {
5850: background-color: $mail_read_hover;
5851: }
5852: */
5853:
5854: table.LC_data_table tr td.LC_mail_replied {
5855: background-color: $mail_replied;
5856: }
5857:
5858: /*
5859: table.LC_data_table tr.LC_mail_replied:hover {
5860: background-color: $mail_replied_hover;
5861: }
5862: */
5863:
5864: table.LC_data_table tr td.LC_mail_other {
5865: background-color: $mail_other;
5866: }
5867:
5868: /*
5869: table.LC_data_table tr.LC_mail_other:hover {
5870: background-color: $mail_other_hover;
5871: }
5872: */
5873:
5874: table.LC_data_table tr > td.LC_browser_file,
5875: table.LC_data_table tr > td.LC_browser_file_published {
5876: background: #AAEE77;
5877: }
5878:
5879: table.LC_data_table tr > td.LC_browser_file_locked,
5880: table.LC_data_table tr > td.LC_browser_file_unpublished {
5881: background: #FFAA99;
5882: }
5883:
5884: table.LC_data_table tr > td.LC_browser_file_obsolete {
5885: background: #888888;
5886: }
5887:
5888: table.LC_data_table tr > td.LC_browser_file_modified,
5889: table.LC_data_table tr > td.LC_browser_file_metamodified {
5890: background: #F8F866;
5891: }
5892:
5893: table.LC_data_table tr.LC_browser_folder > td {
5894: background: #E0E8FF;
5895: }
5896:
5897: table.LC_data_table tr > td.LC_roles_is {
5898: /* background: #77FF77; */
5899: }
5900:
5901: table.LC_data_table tr > td.LC_roles_future {
5902: border-right: 8px solid #FFFF77;
5903: }
5904:
5905: table.LC_data_table tr > td.LC_roles_will {
5906: border-right: 8px solid #FFAA77;
5907: }
5908:
5909: table.LC_data_table tr > td.LC_roles_expired {
5910: border-right: 8px solid #FF7777;
5911: }
5912:
5913: table.LC_data_table tr > td.LC_roles_will_not {
5914: border-right: 8px solid #AAFF77;
5915: }
5916:
5917: table.LC_data_table tr > td.LC_roles_selected {
5918: border-right: 8px solid #11CC55;
5919: }
5920:
5921: span.LC_current_location {
5922: font-size:larger;
5923: background: $pgbg;
5924: }
5925:
5926: span.LC_current_nav_location {
5927: font-weight:bold;
5928: background: $sidebg;
5929: }
5930:
5931: span.LC_parm_menu_item {
5932: font-size: larger;
5933: }
5934:
5935: span.LC_parm_scope_all {
5936: color: red;
5937: }
5938:
5939: span.LC_parm_scope_folder {
5940: color: green;
5941: }
5942:
5943: span.LC_parm_scope_resource {
5944: color: orange;
5945: }
5946:
5947: span.LC_parm_part {
5948: color: blue;
5949: }
5950:
5951: span.LC_parm_folder,
5952: span.LC_parm_symb {
5953: font-size: x-small;
5954: font-family: $mono;
5955: color: #AAAAAA;
5956: }
5957:
5958: ul.LC_parm_parmlist li {
5959: display: inline-block;
5960: padding: 0.3em 0.8em;
5961: vertical-align: top;
5962: width: 150px;
5963: border-top:1px solid $lg_border_color;
5964: }
5965:
5966: td.LC_parm_overview_level_menu,
5967: td.LC_parm_overview_map_menu,
5968: td.LC_parm_overview_parm_selectors,
5969: td.LC_parm_overview_restrictions {
5970: border: 1px solid black;
5971: border-collapse: collapse;
5972: }
5973:
5974: table.LC_parm_overview_restrictions td {
5975: border-width: 1px 4px 1px 4px;
5976: border-style: solid;
5977: border-color: $pgbg;
5978: text-align: center;
5979: }
5980:
5981: table.LC_parm_overview_restrictions th {
5982: background: $tabbg;
5983: border-width: 1px 4px 1px 4px;
5984: border-style: solid;
5985: border-color: $pgbg;
5986: }
5987:
5988: table#LC_helpmenu {
5989: border: none;
5990: height: 55px;
5991: border-spacing: 0;
5992: }
5993:
5994: table#LC_helpmenu fieldset legend {
5995: font-size: larger;
5996: }
5997:
5998: table#LC_helpmenu_links {
5999: width: 100%;
6000: border: 1px solid black;
6001: background: $pgbg;
6002: padding: 0;
6003: border-spacing: 1px;
6004: }
6005:
6006: table#LC_helpmenu_links tr td {
6007: padding: 1px;
6008: background: $tabbg;
6009: text-align: center;
6010: font-weight: bold;
6011: }
6012:
6013: table#LC_helpmenu_links a:link,
6014: table#LC_helpmenu_links a:visited,
6015: table#LC_helpmenu_links a:active {
6016: text-decoration: none;
6017: color: $font;
6018: }
6019:
6020: table#LC_helpmenu_links a:hover {
6021: text-decoration: underline;
6022: color: $vlink;
6023: }
6024:
6025: .LC_chrt_popup_exists {
6026: border: 1px solid #339933;
6027: margin: -1px;
6028: }
6029:
6030: .LC_chrt_popup_up {
6031: border: 1px solid yellow;
6032: margin: -1px;
6033: }
6034:
6035: .LC_chrt_popup {
6036: border: 1px solid #8888FF;
6037: background: #CCCCFF;
6038: }
6039:
6040: table.LC_pick_box {
6041: border-collapse: separate;
6042: background: white;
6043: border: 1px solid black;
6044: border-spacing: 1px;
6045: }
6046:
6047: table.LC_pick_box td.LC_pick_box_title {
6048: background: $sidebg;
6049: font-weight: bold;
6050: text-align: left;
6051: vertical-align: top;
6052: width: 184px;
6053: padding: 8px;
6054: }
6055:
6056: table.LC_pick_box td.LC_pick_box_value {
6057: text-align: left;
6058: padding: 8px;
6059: }
6060:
6061: table.LC_pick_box td.LC_pick_box_select {
6062: text-align: left;
6063: padding: 8px;
6064: }
6065:
6066: table.LC_pick_box td.LC_pick_box_separator {
6067: padding: 0;
6068: height: 1px;
6069: background: black;
6070: }
6071:
6072: table.LC_pick_box td.LC_pick_box_submit {
6073: text-align: right;
6074: }
6075:
6076: table.LC_pick_box td.LC_evenrow_value {
6077: text-align: left;
6078: padding: 8px;
6079: background-color: $data_table_light;
6080: }
6081:
6082: table.LC_pick_box td.LC_oddrow_value {
6083: text-align: left;
6084: padding: 8px;
6085: background-color: $data_table_light;
6086: }
6087:
6088: span.LC_helpform_receipt_cat {
6089: font-weight: bold;
6090: }
6091:
6092: table.LC_group_priv_box {
6093: background: white;
6094: border: 1px solid black;
6095: border-spacing: 1px;
6096: }
6097:
6098: table.LC_group_priv_box td.LC_pick_box_title {
6099: background: $tabbg;
6100: font-weight: bold;
6101: text-align: right;
6102: width: 184px;
6103: }
6104:
6105: table.LC_group_priv_box td.LC_groups_fixed {
6106: background: $data_table_light;
6107: text-align: center;
6108: }
6109:
6110: table.LC_group_priv_box td.LC_groups_optional {
6111: background: $data_table_dark;
6112: text-align: center;
6113: }
6114:
6115: table.LC_group_priv_box td.LC_groups_functionality {
6116: background: $data_table_darker;
6117: text-align: center;
6118: font-weight: bold;
6119: }
6120:
6121: table.LC_group_priv td {
6122: text-align: left;
6123: padding: 0;
6124: }
6125:
6126: .LC_navbuttons {
6127: margin: 2ex 0ex 2ex 0ex;
6128: }
6129:
6130: .LC_topic_bar {
6131: font-weight: bold;
6132: background: $tabbg;
6133: margin: 1em 0em 1em 2em;
6134: padding: 3px;
6135: font-size: 1.2em;
6136: }
6137:
6138: .LC_topic_bar span {
6139: left: 0.5em;
6140: position: absolute;
6141: vertical-align: middle;
6142: font-size: 1.2em;
6143: }
6144:
6145: table.LC_course_group_status {
6146: margin: 20px;
6147: }
6148:
6149: table.LC_status_selector td {
6150: vertical-align: top;
6151: text-align: center;
6152: padding: 4px;
6153: }
6154:
6155: div.LC_feedback_link {
6156: clear: both;
6157: background: $sidebg;
6158: width: 100%;
6159: padding-bottom: 10px;
6160: border: 1px $tabbg solid;
6161: height: 22px;
6162: line-height: 22px;
6163: padding-top: 5px;
6164: }
6165:
6166: div.LC_feedback_link img {
6167: height: 22px;
6168: vertical-align:middle;
6169: }
6170:
6171: div.LC_feedback_link a {
6172: text-decoration: none;
6173: }
6174:
6175: div.LC_comblock {
6176: display:inline;
6177: color:$font;
6178: font-size:90%;
6179: }
6180:
6181: div.LC_feedback_link div.LC_comblock {
6182: padding-left:5px;
6183: }
6184:
6185: div.LC_feedback_link div.LC_comblock a {
6186: color:$font;
6187: }
6188:
6189: span.LC_feedback_link {
6190: /* background: $feedback_link_bg; */
6191: font-size: larger;
6192: }
6193:
6194: span.LC_message_link {
6195: /* background: $feedback_link_bg; */
6196: font-size: larger;
6197: position: absolute;
6198: right: 1em;
6199: }
6200:
6201: table.LC_prior_tries {
6202: border: 1px solid #000000;
6203: border-collapse: separate;
6204: border-spacing: 1px;
6205: }
6206:
6207: table.LC_prior_tries td {
6208: padding: 2px;
6209: }
6210:
6211: .LC_answer_correct {
6212: background: lightgreen;
6213: color: darkgreen;
6214: padding: 6px;
6215: }
6216:
6217: .LC_answer_charged_try {
6218: background: #FFAAAA;
6219: color: darkred;
6220: padding: 6px;
6221: }
6222:
6223: .LC_answer_not_charged_try,
6224: .LC_answer_no_grade,
6225: .LC_answer_late {
6226: background: lightyellow;
6227: color: black;
6228: padding: 6px;
6229: }
6230:
6231: .LC_answer_previous {
6232: background: lightblue;
6233: color: darkblue;
6234: padding: 6px;
6235: }
6236:
6237: .LC_answer_no_message {
6238: background: #FFFFFF;
6239: color: black;
6240: padding: 6px;
6241: }
6242:
6243: .LC_answer_unknown {
6244: background: orange;
6245: color: black;
6246: padding: 6px;
6247: }
6248:
6249: span.LC_prior_numerical,
6250: span.LC_prior_string,
6251: span.LC_prior_custom,
6252: span.LC_prior_reaction,
6253: span.LC_prior_math {
6254: font-family: $mono;
6255: white-space: pre;
6256: }
6257:
6258: span.LC_prior_string {
6259: font-family: $mono;
6260: white-space: pre;
6261: }
6262:
6263: table.LC_prior_option {
6264: width: 100%;
6265: border-collapse: collapse;
6266: }
6267:
6268: table.LC_prior_rank,
6269: table.LC_prior_match {
6270: border-collapse: collapse;
6271: }
6272:
6273: table.LC_prior_option tr td,
6274: table.LC_prior_rank tr td,
6275: table.LC_prior_match tr td {
6276: border: 1px solid #000000;
6277: }
6278:
6279: .LC_nobreak {
6280: white-space: nowrap;
6281: }
6282:
6283: span.LC_cusr_emph {
6284: font-style: italic;
6285: }
6286:
6287: span.LC_cusr_subheading {
6288: font-weight: normal;
6289: font-size: 85%;
6290: }
6291:
6292: div.LC_docs_entry_move {
6293: border: 1px solid #BBBBBB;
6294: background: #DDDDDD;
6295: width: 22px;
6296: padding: 1px;
6297: margin: 0;
6298: }
6299:
6300: table.LC_data_table tr > td.LC_docs_entry_commands,
6301: table.LC_data_table tr > td.LC_docs_entry_parameter {
6302: font-size: x-small;
6303: }
6304:
6305: .LC_docs_entry_parameter {
6306: white-space: nowrap;
6307: }
6308:
6309: .LC_docs_copy {
6310: color: #000099;
6311: }
6312:
6313: .LC_docs_cut {
6314: color: #550044;
6315: }
6316:
6317: .LC_docs_rename {
6318: color: #009900;
6319: }
6320:
6321: .LC_docs_remove {
6322: color: #990000;
6323: }
6324:
6325: .LC_docs_reinit_warn,
6326: .LC_docs_ext_edit {
6327: font-size: x-small;
6328: }
6329:
6330: table.LC_docs_adddocs td,
6331: table.LC_docs_adddocs th {
6332: border: 1px solid #BBBBBB;
6333: padding: 4px;
6334: background: #DDDDDD;
6335: }
6336:
6337: table.LC_sty_begin {
6338: background: #BBFFBB;
6339: }
6340:
6341: table.LC_sty_end {
6342: background: #FFBBBB;
6343: }
6344:
6345: table.LC_double_column {
6346: border-width: 0;
6347: border-collapse: collapse;
6348: width: 100%;
6349: padding: 2px;
6350: }
6351:
6352: table.LC_double_column tr td.LC_left_col {
6353: top: 2px;
6354: left: 2px;
6355: width: 47%;
6356: vertical-align: top;
6357: }
6358:
6359: table.LC_double_column tr td.LC_right_col {
6360: top: 2px;
6361: right: 2px;
6362: width: 47%;
6363: vertical-align: top;
6364: }
6365:
6366: div.LC_left_float {
6367: float: left;
6368: padding-right: 5%;
6369: padding-bottom: 4px;
6370: }
6371:
6372: div.LC_clear_float_header {
6373: padding-bottom: 2px;
6374: }
6375:
6376: div.LC_clear_float_footer {
6377: padding-top: 10px;
6378: clear: both;
6379: }
6380:
6381: div.LC_grade_show_user {
6382: /* border-left: 5px solid $sidebg; */
6383: border-top: 5px solid #000000;
6384: margin: 50px 0 0 0;
6385: padding: 15px 0 5px 10px;
6386: }
6387:
6388: div.LC_grade_show_user_odd_row {
6389: /* border-left: 5px solid #000000; */
6390: }
6391:
6392: div.LC_grade_show_user div.LC_Box {
6393: margin-right: 50px;
6394: }
6395:
6396: div.LC_grade_submissions,
6397: div.LC_grade_message_center,
6398: div.LC_grade_info_links {
6399: margin: 5px;
6400: width: 99%;
6401: background: #FFFFFF;
6402: }
6403:
6404: div.LC_grade_submissions_header,
6405: div.LC_grade_message_center_header {
6406: font-weight: bold;
6407: font-size: large;
6408: }
6409:
6410: div.LC_grade_submissions_body,
6411: div.LC_grade_message_center_body {
6412: border: 1px solid black;
6413: width: 99%;
6414: background: #FFFFFF;
6415: }
6416:
6417: table.LC_scantron_action {
6418: width: 100%;
6419: }
6420:
6421: table.LC_scantron_action tr th {
6422: font-weight:bold;
6423: font-style:normal;
6424: }
6425:
6426: .LC_edit_problem_header,
6427: div.LC_edit_problem_footer {
6428: font-weight: normal;
6429: font-size: medium;
6430: margin: 2px;
6431: background-color: $sidebg;
6432: }
6433:
6434: div.LC_edit_problem_header,
6435: div.LC_edit_problem_header div,
6436: div.LC_edit_problem_footer,
6437: div.LC_edit_problem_footer div,
6438: div.LC_edit_problem_editxml_header,
6439: div.LC_edit_problem_editxml_header div {
6440: margin-top: 5px;
6441: }
6442:
6443: div.LC_edit_problem_header_title {
6444: font-weight: bold;
6445: font-size: larger;
6446: background: $tabbg;
6447: padding: 3px;
6448: margin: 0 0 5px 0;
6449: }
6450:
6451: table.LC_edit_problem_header_title {
6452: width: 100%;
6453: background: $tabbg;
6454: }
6455:
6456: div.LC_edit_problem_discards {
6457: float: left;
6458: padding-bottom: 5px;
6459: }
6460:
6461: div.LC_edit_problem_saves {
6462: float: right;
6463: padding-bottom: 5px;
6464: }
6465:
6466: img.stift {
6467: border-width: 0;
6468: vertical-align: middle;
6469: }
6470:
6471: table td.LC_mainmenu_col_fieldset {
6472: vertical-align: top;
6473: }
6474:
6475: div.LC_createcourse {
6476: margin: 10px 10px 10px 10px;
6477: }
6478:
6479: .LC_dccid {
6480: margin: 0.2em 0 0 0;
6481: padding: 0;
6482: font-size: 90%;
6483: display:none;
6484: }
6485:
6486: ol.LC_primary_menu a:hover,
6487: ol#LC_MenuBreadcrumbs a:hover,
6488: ol#LC_PathBreadcrumbs a:hover,
6489: ul#LC_secondary_menu a:hover,
6490: .LC_FormSectionClearButton input:hover
6491: ul.LC_TabContent li:hover a {
6492: color:$button_hover;
6493: text-decoration:none;
6494: }
6495:
6496: h1 {
6497: padding: 0;
6498: line-height:130%;
6499: }
6500:
6501: h2,
6502: h3,
6503: h4,
6504: h5,
6505: h6 {
6506: margin: 5px 0 5px 0;
6507: padding: 0;
6508: line-height:130%;
6509: }
6510:
6511: .LC_hcell {
6512: padding:3px 15px 3px 15px;
6513: margin: 0;
6514: background-color:$tabbg;
6515: color:$fontmenu;
6516: border-bottom:solid 1px $lg_border_color;
6517: }
6518:
6519: .LC_Box > .LC_hcell {
6520: margin: 0 -10px 10px -10px;
6521: }
6522:
6523: .LC_noBorder {
6524: border: 0;
6525: }
6526:
6527: .LC_FormSectionClearButton input {
6528: background-color:transparent;
6529: border: none;
6530: cursor:pointer;
6531: text-decoration:underline;
6532: }
6533:
6534: .LC_help_open_topic {
6535: color: #FFFFFF;
6536: background-color: #EEEEFF;
6537: margin: 1px;
6538: padding: 4px;
6539: border: 1px solid #000033;
6540: white-space: nowrap;
6541: /* vertical-align: middle; */
6542: }
6543:
6544: dl,
6545: ul,
6546: div,
6547: fieldset {
6548: margin: 10px 10px 10px 0;
6549: /* overflow: hidden; */
6550: }
6551:
6552: fieldset > legend {
6553: font-weight: bold;
6554: padding: 0 5px 0 5px;
6555: }
6556:
6557: #LC_nav_bar {
6558: float: left;
6559: background-color: $pgbg_or_bgcolor;
6560: margin: 0 0 2px 0;
6561: }
6562:
6563: #LC_realm {
6564: margin: 0.2em 0 0 0;
6565: padding: 0;
6566: font-weight: bold;
6567: text-align: center;
6568: background-color: $pgbg_or_bgcolor;
6569: }
6570:
6571: #LC_nav_bar em {
6572: font-weight: bold;
6573: font-style: normal;
6574: }
6575:
6576: ol.LC_primary_menu {
6577: float: right;
6578: margin: 0;
6579: padding: 0;
6580: background-color: $pgbg_or_bgcolor;
6581: }
6582:
6583: ol#LC_PathBreadcrumbs {
6584: margin: 0;
6585: }
6586:
6587: ol.LC_primary_menu li {
6588: color: RGB(80, 80, 80);
6589: vertical-align: middle;
6590: text-align: left;
6591: list-style: none;
6592: float: left;
6593: }
6594:
6595: ol.LC_primary_menu li a {
6596: display: block;
6597: margin: 0;
6598: padding: 0 5px 0 10px;
6599: text-decoration: none;
6600: }
6601:
6602: ol.LC_primary_menu li ul {
6603: display: none;
6604: width: 10em;
6605: background-color: $data_table_light;
6606: }
6607:
6608: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
6609: display: block;
6610: position: absolute;
6611: margin: 0;
6612: padding: 0;
6613: z-index: 2;
6614: }
6615:
6616: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
6617: font-size: 90%;
6618: vertical-align: top;
6619: float: none;
6620: border-left: 1px solid black;
6621: border-right: 1px solid black;
6622: }
6623:
6624: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
6625: background-color:$data_table_light;
6626: }
6627:
6628: ol.LC_primary_menu li li a:hover {
6629: color:$button_hover;
6630: background-color:$data_table_dark;
6631: }
6632:
6633: ol.LC_primary_menu li img {
6634: vertical-align: bottom;
6635: height: 1.1em;
6636: margin: 0.2em 0 0 0;
6637: }
6638:
6639: ol.LC_primary_menu a {
6640: color: RGB(80, 80, 80);
6641: text-decoration: none;
6642: }
6643:
6644: ol.LC_primary_menu a.LC_new_message {
6645: font-weight:bold;
6646: color: darkred;
6647: }
6648:
6649: ol.LC_docs_parameters {
6650: margin-left: 0;
6651: padding: 0;
6652: list-style: none;
6653: }
6654:
6655: ol.LC_docs_parameters li {
6656: margin: 0;
6657: padding-right: 20px;
6658: display: inline;
6659: }
6660:
6661: ol.LC_docs_parameters li:before {
6662: content: "\\002022 \\0020";
6663: }
6664:
6665: li.LC_docs_parameters_title {
6666: font-weight: bold;
6667: }
6668:
6669: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
6670: content: "";
6671: }
6672:
6673: ul#LC_secondary_menu {
6674: clear: right;
6675: color: $fontmenu;
6676: background: $tabbg;
6677: list-style: none;
6678: padding: 0;
6679: margin: 0;
6680: width: 100%;
6681: text-align: left;
6682: float: left;
6683: }
6684:
6685: ul#LC_secondary_menu li {
6686: font-weight: bold;
6687: line-height: 1.8em;
6688: border-right: 1px solid black;
6689: float: left;
6690: }
6691:
6692: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
6693: background-color: $data_table_light;
6694: }
6695:
6696: ul#LC_secondary_menu li a {
6697: padding: 0 0.8em;
6698: }
6699:
6700: ul#LC_secondary_menu li ul {
6701: display: none;
6702: }
6703:
6704: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
6705: display: block;
6706: position: absolute;
6707: margin: 0;
6708: padding: 0;
6709: list-style:none;
6710: float: none;
6711: background-color: $data_table_light;
6712: z-index: 2;
6713: margin-left: -1px;
6714: }
6715:
6716: ul#LC_secondary_menu li ul li {
6717: font-size: 90%;
6718: vertical-align: top;
6719: border-left: 1px solid black;
6720: border-right: 1px solid black;
6721: background-color: $data_table_light
6722: list-style:none;
6723: float: none;
6724: }
6725:
6726: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
6727: background-color: $data_table_dark;
6728: }
6729:
6730: ul.LC_TabContent {
6731: display:block;
6732: background: $sidebg;
6733: border-bottom: solid 1px $lg_border_color;
6734: list-style:none;
6735: margin: -1px -10px 0 -10px;
6736: padding: 0;
6737: }
6738:
6739: ul.LC_TabContent li,
6740: ul.LC_TabContentBigger li {
6741: float:left;
6742: }
6743:
6744: ul#LC_secondary_menu li a {
6745: color: $fontmenu;
6746: text-decoration: none;
6747: }
6748:
6749: ul.LC_TabContent {
6750: min-height:20px;
6751: }
6752:
6753: ul.LC_TabContent li {
6754: vertical-align:middle;
6755: padding: 0 16px 0 10px;
6756: background-color:$tabbg;
6757: border-bottom:solid 1px $lg_border_color;
6758: border-left: solid 1px $font;
6759: }
6760:
6761: ul.LC_TabContent .right {
6762: float:right;
6763: }
6764:
6765: ul.LC_TabContent li a,
6766: ul.LC_TabContent li {
6767: color:rgb(47,47,47);
6768: text-decoration:none;
6769: font-size:95%;
6770: font-weight:bold;
6771: min-height:20px;
6772: }
6773:
6774: ul.LC_TabContent li a:hover,
6775: ul.LC_TabContent li a:focus {
6776: color: $button_hover;
6777: background:none;
6778: outline:none;
6779: }
6780:
6781: ul.LC_TabContent li:hover {
6782: color: $button_hover;
6783: cursor:pointer;
6784: }
6785:
6786: ul.LC_TabContent li.active {
6787: color: $font;
6788: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
6789: border-bottom:solid 1px #FFFFFF;
6790: cursor: default;
6791: }
6792:
6793: ul.LC_TabContent li.active a {
6794: color:$font;
6795: background:#FFFFFF;
6796: outline: none;
6797: }
6798:
6799: ul.LC_TabContent li.goback {
6800: float: left;
6801: border-left: none;
6802: }
6803:
6804: #maincoursedoc {
6805: clear:both;
6806: }
6807:
6808: ul.LC_TabContentBigger {
6809: display:block;
6810: list-style:none;
6811: padding: 0;
6812: }
6813:
6814: ul.LC_TabContentBigger li {
6815: vertical-align:bottom;
6816: height: 30px;
6817: font-size:110%;
6818: font-weight:bold;
6819: color: #737373;
6820: }
6821:
6822: ul.LC_TabContentBigger li.active {
6823: position: relative;
6824: top: 1px;
6825: }
6826:
6827: ul.LC_TabContentBigger li a {
6828: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
6829: height: 30px;
6830: line-height: 30px;
6831: text-align: center;
6832: display: block;
6833: text-decoration: none;
6834: outline: none;
6835: }
6836:
6837: ul.LC_TabContentBigger li.active a {
6838: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
6839: color:$font;
6840: }
6841:
6842: ul.LC_TabContentBigger li b {
6843: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
6844: display: block;
6845: float: left;
6846: padding: 0 30px;
6847: border-bottom: 1px solid $lg_border_color;
6848: }
6849:
6850: ul.LC_TabContentBigger li:hover b {
6851: color:$button_hover;
6852: }
6853:
6854: ul.LC_TabContentBigger li.active b {
6855: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
6856: color:$font;
6857: border: 0;
6858: }
6859:
6860:
6861: ul.LC_CourseBreadcrumbs {
6862: background: $sidebg;
6863: height: 2em;
6864: padding-left: 10px;
6865: margin: 0;
6866: list-style-position: inside;
6867: }
6868:
6869: ol#LC_MenuBreadcrumbs,
6870: ol#LC_PathBreadcrumbs {
6871: padding-left: 10px;
6872: margin: 0;
6873: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
6874: }
6875:
6876: ol#LC_MenuBreadcrumbs li,
6877: ol#LC_PathBreadcrumbs li,
6878: ul.LC_CourseBreadcrumbs li {
6879: display: inline;
6880: white-space: normal;
6881: }
6882:
6883: ol#LC_MenuBreadcrumbs li a,
6884: ul.LC_CourseBreadcrumbs li a {
6885: text-decoration: none;
6886: font-size:90%;
6887: }
6888:
6889: ol#LC_MenuBreadcrumbs h1 {
6890: display: inline;
6891: font-size: 90%;
6892: line-height: 2.5em;
6893: margin: 0;
6894: padding: 0;
6895: }
6896:
6897: ol#LC_PathBreadcrumbs li a {
6898: text-decoration:none;
6899: font-size:100%;
6900: font-weight:bold;
6901: }
6902:
6903: .LC_Box {
6904: border: solid 1px $lg_border_color;
6905: padding: 0 10px 10px 10px;
6906: }
6907:
6908: .LC_DocsBox {
6909: border: solid 1px $lg_border_color;
6910: padding: 0 0 10px 10px;
6911: }
6912:
6913: .LC_AboutMe_Image {
6914: float:left;
6915: margin-right:10px;
6916: }
6917:
6918: .LC_Clear_AboutMe_Image {
6919: clear:left;
6920: }
6921:
6922: dl.LC_ListStyleClean dt {
6923: padding-right: 5px;
6924: display: table-header-group;
6925: }
6926:
6927: dl.LC_ListStyleClean dd {
6928: display: table-row;
6929: }
6930:
6931: .LC_ListStyleClean,
6932: .LC_ListStyleSimple,
6933: .LC_ListStyleNormal,
6934: .LC_ListStyleSpecial {
6935: /* display:block; */
6936: list-style-position: inside;
6937: list-style-type: none;
6938: overflow: hidden;
6939: padding: 0;
6940: }
6941:
6942: .LC_ListStyleSimple li,
6943: .LC_ListStyleSimple dd,
6944: .LC_ListStyleNormal li,
6945: .LC_ListStyleNormal dd,
6946: .LC_ListStyleSpecial li,
6947: .LC_ListStyleSpecial dd {
6948: margin: 0;
6949: padding: 5px 5px 5px 10px;
6950: clear: both;
6951: }
6952:
6953: .LC_ListStyleClean li,
6954: .LC_ListStyleClean dd {
6955: padding-top: 0;
6956: padding-bottom: 0;
6957: }
6958:
6959: .LC_ListStyleSimple dd,
6960: .LC_ListStyleSimple li {
6961: border-bottom: solid 1px $lg_border_color;
6962: }
6963:
6964: .LC_ListStyleSpecial li,
6965: .LC_ListStyleSpecial dd {
6966: list-style-type: none;
6967: background-color: RGB(220, 220, 220);
6968: margin-bottom: 4px;
6969: }
6970:
6971: table.LC_SimpleTable {
6972: margin:5px;
6973: border:solid 1px $lg_border_color;
6974: }
6975:
6976: table.LC_SimpleTable tr {
6977: padding: 0;
6978: border:solid 1px $lg_border_color;
6979: }
6980:
6981: table.LC_SimpleTable thead {
6982: background:rgb(220,220,220);
6983: }
6984:
6985: div.LC_columnSection {
6986: display: block;
6987: clear: both;
6988: overflow: hidden;
6989: margin: 0;
6990: }
6991:
6992: div.LC_columnSection>* {
6993: float: left;
6994: margin: 10px 20px 10px 0;
6995: overflow:hidden;
6996: }
6997:
6998: table em {
6999: font-weight: bold;
7000: font-style: normal;
7001: }
7002:
7003: table.LC_tableBrowseRes,
7004: table.LC_tableOfContent {
7005: border:none;
7006: border-spacing: 1px;
7007: padding: 3px;
7008: background-color: #FFFFFF;
7009: font-size: 90%;
7010: }
7011:
7012: table.LC_tableOfContent {
7013: border-collapse: collapse;
7014: }
7015:
7016: table.LC_tableBrowseRes a,
7017: table.LC_tableOfContent a {
7018: background-color: transparent;
7019: text-decoration: none;
7020: }
7021:
7022: table.LC_tableOfContent img {
7023: border: none;
7024: height: 1.3em;
7025: vertical-align: text-bottom;
7026: margin-right: 0.3em;
7027: }
7028:
7029: a#LC_content_toolbar_firsthomework {
7030: background-image:url(/res/adm/pages/open-first-problem.gif);
7031: }
7032:
7033: a#LC_content_toolbar_everything {
7034: background-image:url(/res/adm/pages/show-all.gif);
7035: }
7036:
7037: a#LC_content_toolbar_uncompleted {
7038: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
7039: }
7040:
7041: #LC_content_toolbar_clearbubbles {
7042: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
7043: }
7044:
7045: a#LC_content_toolbar_changefolder {
7046: background : url(/res/adm/pages/close-all-folders.gif) top center ;
7047: }
7048:
7049: a#LC_content_toolbar_changefolder_toggled {
7050: background-image:url(/res/adm/pages/open-all-folders.gif);
7051: }
7052:
7053: a#LC_content_toolbar_edittoplevel {
7054: background-image:url(/res/adm/pages/edittoplevel.gif);
7055: }
7056:
7057: ul#LC_toolbar li a:hover {
7058: background-position: bottom center;
7059: }
7060:
7061: ul#LC_toolbar {
7062: padding: 0;
7063: margin: 2px;
7064: list-style:none;
7065: position:relative;
7066: background-color:white;
7067: overflow: auto;
7068: }
7069:
7070: ul#LC_toolbar li {
7071: border:1px solid white;
7072: padding: 0;
7073: margin: 0;
7074: float: left;
7075: display:inline;
7076: vertical-align:middle;
7077: white-space: nowrap;
7078: }
7079:
7080:
7081: a.LC_toolbarItem {
7082: display:block;
7083: padding: 0;
7084: margin: 0;
7085: height: 32px;
7086: width: 32px;
7087: color:white;
7088: border: none;
7089: background-repeat:no-repeat;
7090: background-color:transparent;
7091: }
7092:
7093: ul.LC_funclist {
7094: margin: 0;
7095: padding: 0.5em 1em 0.5em 0;
7096: }
7097:
7098: ul.LC_funclist > li:first-child {
7099: font-weight:bold;
7100: margin-left:0.8em;
7101: }
7102:
7103: ul.LC_funclist + ul.LC_funclist {
7104: /*
7105: left border as a seperator if we have more than
7106: one list
7107: */
7108: border-left: 1px solid $sidebg;
7109: /*
7110: this hides the left border behind the border of the
7111: outer box if element is wrapped to the next 'line'
7112: */
7113: margin-left: -1px;
7114: }
7115:
7116: ul.LC_funclist li {
7117: display: inline;
7118: white-space: nowrap;
7119: margin: 0 0 0 25px;
7120: line-height: 150%;
7121: }
7122:
7123: .LC_hidden {
7124: display: none;
7125: }
7126:
7127: .LCmodal-overlay {
7128: position:fixed;
7129: top:0;
7130: right:0;
7131: bottom:0;
7132: left:0;
7133: height:100%;
7134: width:100%;
7135: margin:0;
7136: padding:0;
7137: background:#999;
7138: opacity:.75;
7139: filter: alpha(opacity=75);
7140: -moz-opacity: 0.75;
7141: z-index:101;
7142: }
7143:
7144: * html .LCmodal-overlay {
7145: position: absolute;
7146: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
7147: }
7148:
7149: .LCmodal-window {
7150: position:fixed;
7151: top:50%;
7152: left:50%;
7153: margin:0;
7154: padding:0;
7155: z-index:102;
7156: }
7157:
7158: * html .LCmodal-window {
7159: position:absolute;
7160: }
7161:
7162: .LCclose-window {
7163: position:absolute;
7164: width:32px;
7165: height:32px;
7166: right:8px;
7167: top:8px;
7168: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
7169: text-indent:-99999px;
7170: overflow:hidden;
7171: cursor:pointer;
7172: }
7173:
7174: /*
7175: styles used by TTH when "Default set of options to pass to tth/m
7176: when converting TeX" in course settings has been set
7177:
7178: option passed: -t
7179:
7180: */
7181:
7182: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
7183: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
7184: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
7185: td div.norm {line-height:normal;}
7186:
7187: /*
7188: option passed -y3
7189: */
7190:
7191: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
7192: span.overacc2 {position: relative; left: .8em; top: -1.2ex;}
7193: span.overacc1 {position: relative; left: .6em; top: -1.2ex;}
7194:
7195: END
7196: }
7197:
7198: =pod
7199:
7200: =item * &headtag()
7201:
7202: Returns a uniform footer for LON-CAPA web pages.
7203:
7204: Inputs: $title - optional title for the head
7205: $head_extra - optional extra HTML to put inside the <head>
7206: $args - optional arguments
7207: force_register - if is true call registerurl so the remote is
7208: informed
7209: redirect -> array ref of
7210: 1- seconds before redirect occurs
7211: 2- url to redirect to
7212: 3- whether the side effect should occur
7213: (side effect of setting
7214: $env{'internal.head.redirect'} to the url
7215: redirected too)
7216: domain -> force to color decorate a page for a specific
7217: domain
7218: function -> force usage of a specific rolish color scheme
7219: bgcolor -> override the default page bgcolor
7220: no_auto_mt_title
7221: -> prevent &mt()ing the title arg
7222:
7223: =cut
7224:
7225: sub headtag {
7226: my ($title,$head_extra,$args) = @_;
7227:
7228: my $function = $args->{'function'} || &get_users_function();
7229: my $domain = $args->{'domain'} || &determinedomain();
7230: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
7231: my $url = join(':',$env{'user.name'},$env{'user.domain'},
7232: $Apache::lonnet::perlvar{'lonVersion'},
7233: #time(),
7234: $env{'environment.color.timestamp'},
7235: $function,$domain,$bgcolor);
7236:
7237: $url = '/adm/css/'.&escape($url).'.css';
7238:
7239: my $result =
7240: '<head>'.
7241: &font_settings();
7242:
7243: my $inhibitprint = &print_suppression();
7244:
7245: if (!$args->{'frameset'}) {
7246: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
7247: }
7248: if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
7249: $result .= Apache::lonxml::display_title();
7250: }
7251: if (!$args->{'no_nav_bar'}
7252: && !$args->{'only_body'}
7253: && !$args->{'frameset'}) {
7254: $result .= &help_menu_js();
7255: $result.=&modal_window();
7256: $result.=&togglebox_script();
7257: $result.=&wishlist_window();
7258: $result.=&LCprogressbarUpdate_script();
7259: } else {
7260: if ($args->{'add_modal'}) {
7261: $result.=&modal_window();
7262: }
7263: if ($args->{'add_wishlist'}) {
7264: $result.=&wishlist_window();
7265: }
7266: if ($args->{'add_togglebox'}) {
7267: $result.=&togglebox_script();
7268: }
7269: if ($args->{'add_progressbar'}) {
7270: $result.=&LCprogressbarUpdate_script();
7271: }
7272: }
7273: if (ref($args->{'redirect'})) {
7274: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
7275: $url = &Apache::lonenc::check_encrypt($url);
7276: if (!$inhibit_continue) {
7277: $env{'internal.head.redirect'} = $url;
7278: }
7279: $result.=<<ADDMETA
7280: <meta http-equiv="pragma" content="no-cache" />
7281: <meta http-equiv="Refresh" content="$time; url=$url" />
7282: ADDMETA
7283: }
7284: if (!defined($title)) {
7285: $title = 'The LearningOnline Network with CAPA';
7286: }
7287: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
7288: $result .= '<title> LON-CAPA '.$title.'</title>'
7289: .'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
7290: .$inhibitprint
7291: .$head_extra;
7292: return $result.'</head>';
7293: }
7294:
7295: =pod
7296:
7297: =item * &font_settings()
7298:
7299: Returns neccessary <meta> to set the proper encoding
7300:
7301: Inputs: none
7302:
7303: =cut
7304:
7305: sub font_settings {
7306: my $headerstring='';
7307: if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
7308: $headerstring.=
7309: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
7310: }
7311: return $headerstring;
7312: }
7313:
7314: =pod
7315:
7316: =item * &print_suppression()
7317:
7318: In course context returns css which causes the body to be blank when media="print",
7319: if printout generation is unavailable for the current resource.
7320:
7321: This could be because:
7322:
7323: (a) printstartdate is in the future
7324:
7325: (b) printenddate is in the past
7326:
7327: (c) there is an active exam block with "printout"
7328: functionality blocked
7329:
7330: Users with pav, pfo or evb privileges are exempt.
7331:
7332: Inputs: none
7333:
7334: =cut
7335:
7336:
7337: sub print_suppression {
7338: my $noprint;
7339: if ($env{'request.course.id'}) {
7340: my $scope = $env{'request.course.id'};
7341: if ((&Apache::lonnet::allowed('pav',$scope)) ||
7342: (&Apache::lonnet::allowed('pfo',$scope))) {
7343: return;
7344: }
7345: if ($env{'request.course.sec'} ne '') {
7346: $scope .= "/$env{'request.course.sec'}";
7347: if ((&Apache::lonnet::allowed('pav',$scope)) ||
7348: (&Apache::lonnet::allowed('pfo',$scope))) {
7349: return;
7350: }
7351: }
7352: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7353: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7354: my $blocked = &blocking_status('printout',$cnum,$cdom);
7355: if ($blocked) {
7356: my $checkrole = "cm./$cdom/$cnum";
7357: if ($env{'request.course.sec'} ne '') {
7358: $checkrole .= "/$env{'request.course.sec'}";
7359: }
7360: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
7361: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
7362: $noprint = 1;
7363: }
7364: }
7365: unless ($noprint) {
7366: my $symb = &Apache::lonnet::symbread();
7367: if ($symb ne '') {
7368: my $navmap = Apache::lonnavmaps::navmap->new();
7369: if (ref($navmap)) {
7370: my $res = $navmap->getBySymb($symb);
7371: if (ref($res)) {
7372: if (!$res->resprintable()) {
7373: $noprint = 1;
7374: }
7375: }
7376: }
7377: }
7378: }
7379: if ($noprint) {
7380: return <<"ENDSTYLE";
7381: <style type="text/css" media="print">
7382: body { display:none }
7383: </style>
7384: ENDSTYLE
7385: }
7386: }
7387: return;
7388: }
7389:
7390: =pod
7391:
7392: =item * &xml_begin()
7393:
7394: Returns the needed doctype and <html>
7395:
7396: Inputs: none
7397:
7398: =cut
7399:
7400: sub xml_begin {
7401: my $output='';
7402:
7403: if ($env{'browser.mathml'}) {
7404: $output='<?xml version="1.0"?>'
7405: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
7406: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
7407:
7408: # .'<!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">] >'
7409: .'<!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">'
7410: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
7411: .'xmlns="http://www.w3.org/1999/xhtml">';
7412: } else {
7413: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
7414: .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
7415: }
7416: return $output;
7417: }
7418:
7419: =pod
7420:
7421: =item * &start_page()
7422:
7423: Returns a complete <html> .. <body> section for LON-CAPA web pages.
7424:
7425: Inputs:
7426:
7427: =over 4
7428:
7429: $title - optional title for the page
7430:
7431: $head_extra - optional extra HTML to incude inside the <head>
7432:
7433: $args - additional optional args supported are:
7434:
7435: =over 8
7436:
7437: only_body -> is true will set &bodytag() onlybodytag
7438: arg on
7439: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
7440: add_entries -> additional attributes to add to the <body>
7441: domain -> force to color decorate a page for a
7442: specific domain
7443: function -> force usage of a specific rolish color
7444: scheme
7445: redirect -> see &headtag()
7446: bgcolor -> override the default page bg color
7447: js_ready -> return a string ready for being used in
7448: a javascript writeln
7449: html_encode -> return a string ready for being used in
7450: a html attribute
7451: force_register -> if is true will turn on the &bodytag()
7452: $forcereg arg
7453: frameset -> if true will start with a <frameset>
7454: rather than <body>
7455: skip_phases -> hash ref of
7456: head -> skip the <html><head> generation
7457: body -> skip all <body> generation
7458: no_auto_mt_title -> prevent &mt()ing the title arg
7459: inherit_jsmath -> when creating popup window in a page,
7460: should it have jsmath forced on by the
7461: current page
7462: bread_crumbs -> Array containing breadcrumbs
7463: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
7464: group -> includes the current group, if page is for a
7465: specific group
7466:
7467: =back
7468:
7469: =back
7470:
7471: =cut
7472:
7473: sub start_page {
7474: my ($title,$head_extra,$args) = @_;
7475: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
7476:
7477: $env{'internal.start_page'}++;
7478: my ($result,@advtools);
7479:
7480: if (! exists($args->{'skip_phases'}{'head'}) ) {
7481: $result .= &xml_begin() . &headtag($title, $head_extra, $args);
7482: }
7483:
7484: if (! exists($args->{'skip_phases'}{'body'}) ) {
7485: if ($args->{'frameset'}) {
7486: my $attr_string = &make_attr_string($args->{'force_register'},
7487: $args->{'add_entries'});
7488: $result .= "\n<frameset $attr_string>\n";
7489: } else {
7490: $result .=
7491: &bodytag($title,
7492: $args->{'function'}, $args->{'add_entries'},
7493: $args->{'only_body'}, $args->{'domain'},
7494: $args->{'force_register'}, $args->{'no_nav_bar'},
7495: $args->{'bgcolor'}, $args,
7496: \@advtools);
7497: }
7498: }
7499:
7500: if ($args->{'js_ready'}) {
7501: $result = &js_ready($result);
7502: }
7503: if ($args->{'html_encode'}) {
7504: $result = &html_encode($result);
7505: }
7506:
7507: # Preparation for new and consistent functionlist at top of screen
7508: # if ($args->{'functionlist'}) {
7509: # $result .= &build_functionlist();
7510: #}
7511:
7512: # Don't add anything more if only_body wanted or in const space
7513: return $result if $args->{'only_body'}
7514: || $env{'request.state'} eq 'construct';
7515:
7516: #Breadcrumbs
7517: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
7518: &Apache::lonhtmlcommon::clear_breadcrumbs();
7519: #if any br links exists, add them to the breadcrumbs
7520: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
7521: foreach my $crumb (@{$args->{'bread_crumbs'}}){
7522: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
7523: }
7524: }
7525: # if @advtools array contains items add then to the breadcrumbs
7526: if (@advtools > 0) {
7527: &Apache::lonmenu::advtools_crumbs(@advtools);
7528: }
7529:
7530: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
7531: if(exists($args->{'bread_crumbs_component'})){
7532: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
7533: }else{
7534: $result .= &Apache::lonhtmlcommon::breadcrumbs();
7535: }
7536: }
7537: return $result;
7538: }
7539:
7540: sub end_page {
7541: my ($args) = @_;
7542: $env{'internal.end_page'}++;
7543: my $result;
7544: if ($args->{'discussion'}) {
7545: my ($target,$parser);
7546: if (ref($args->{'discussion'})) {
7547: ($target,$parser) =($args->{'discussion'}{'target'},
7548: $args->{'discussion'}{'parser'});
7549: }
7550: $result .= &Apache::lonxml::xmlend($target,$parser);
7551: }
7552: if ($args->{'frameset'}) {
7553: $result .= '</frameset>';
7554: } else {
7555: $result .= &endbodytag($args);
7556: }
7557: unless ($args->{'notbody'}) {
7558: $result .= "\n</html>";
7559: }
7560:
7561: if ($args->{'js_ready'}) {
7562: $result = &js_ready($result);
7563: }
7564:
7565: if ($args->{'html_encode'}) {
7566: $result = &html_encode($result);
7567: }
7568:
7569: return $result;
7570: }
7571:
7572: sub wishlist_window {
7573: return(<<'ENDWISHLIST');
7574: <script type="text/javascript">
7575: // <![CDATA[
7576: // <!-- BEGIN LON-CAPA Internal
7577: function set_wishlistlink(title, path) {
7578: if (!title) {
7579: title = document.title;
7580: title = title.replace(/^LON-CAPA /,'');
7581: }
7582: if (!path) {
7583: path = location.pathname;
7584: }
7585: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
7586: 'wishlistNewLink','width=560,height=350,scrollbars=0');
7587: }
7588: // END LON-CAPA Internal -->
7589: // ]]>
7590: </script>
7591: ENDWISHLIST
7592: }
7593:
7594: sub modal_window {
7595: return(<<'ENDMODAL');
7596: <script type="text/javascript">
7597: // <![CDATA[
7598: // <!-- BEGIN LON-CAPA Internal
7599: var modalWindow = {
7600: parent:"body",
7601: windowId:null,
7602: content:null,
7603: width:null,
7604: height:null,
7605: close:function()
7606: {
7607: $(".LCmodal-window").remove();
7608: $(".LCmodal-overlay").remove();
7609: },
7610: open:function()
7611: {
7612: var modal = "";
7613: modal += "<div class=\"LCmodal-overlay\"></div>";
7614: 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;\">";
7615: modal += this.content;
7616: modal += "</div>";
7617:
7618: $(this.parent).append(modal);
7619:
7620: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
7621: $(".LCclose-window").click(function(){modalWindow.close();});
7622: $(".LCmodal-overlay").click(function(){modalWindow.close();});
7623: }
7624: };
7625: var openMyModal = function(source,width,height,scrolling)
7626: {
7627: modalWindow.windowId = "myModal";
7628: modalWindow.width = width;
7629: modalWindow.height = height;
7630: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'></iframe>";
7631: modalWindow.open();
7632: };
7633: // END LON-CAPA Internal -->
7634: // ]]>
7635: </script>
7636: ENDMODAL
7637: }
7638:
7639: sub modal_link {
7640: my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_;
7641: unless ($width) { $width=480; }
7642: unless ($height) { $height=400; }
7643: unless ($scrolling) { $scrolling='yes'; }
7644: my $target_attr;
7645: if (defined($target)) {
7646: $target_attr = 'target="'.$target.'"';
7647: }
7648: return <<"ENDLINK";
7649: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling'); return false;">
7650: $linktext</a>
7651: ENDLINK
7652: }
7653:
7654: sub modal_adhoc_script {
7655: my ($funcname,$width,$height,$content)=@_;
7656: return (<<ENDADHOC);
7657: <script type="text/javascript">
7658: // <![CDATA[
7659: var $funcname = function()
7660: {
7661: modalWindow.windowId = "myModal";
7662: modalWindow.width = $width;
7663: modalWindow.height = $height;
7664: modalWindow.content = '$content';
7665: modalWindow.open();
7666: };
7667: // ]]>
7668: </script>
7669: ENDADHOC
7670: }
7671:
7672: sub modal_adhoc_inner {
7673: my ($funcname,$width,$height,$content)=@_;
7674: my $innerwidth=$width-20;
7675: $content=&js_ready(
7676: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
7677: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px').
7678: $content.
7679: &end_scrollbox().
7680: &end_page()
7681: );
7682: return &modal_adhoc_script($funcname,$width,$height,$content);
7683: }
7684:
7685: sub modal_adhoc_window {
7686: my ($funcname,$width,$height,$content,$linktext)=@_;
7687: return &modal_adhoc_inner($funcname,$width,$height,$content).
7688: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
7689: }
7690:
7691: sub modal_adhoc_launch {
7692: my ($funcname,$width,$height,$content)=@_;
7693: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
7694: <script type="text/javascript">
7695: // <![CDATA[
7696: $funcname();
7697: // ]]>
7698: </script>
7699: ENDLAUNCH
7700: }
7701:
7702: sub modal_adhoc_close {
7703: return (<<ENDCLOSE);
7704: <script type="text/javascript">
7705: // <![CDATA[
7706: modalWindow.close();
7707: // ]]>
7708: </script>
7709: ENDCLOSE
7710: }
7711:
7712: sub togglebox_script {
7713: return(<<ENDTOGGLE);
7714: <script type="text/javascript">
7715: // <![CDATA[
7716: function LCtoggleDisplay(id,hidetext,showtext) {
7717: link = document.getElementById(id + "link").childNodes[0];
7718: with (document.getElementById(id).style) {
7719: if (display == "none" ) {
7720: display = "inline";
7721: link.nodeValue = hidetext;
7722: } else {
7723: display = "none";
7724: link.nodeValue = showtext;
7725: }
7726: }
7727: }
7728: // ]]>
7729: </script>
7730: ENDTOGGLE
7731: }
7732:
7733: sub start_togglebox {
7734: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
7735: unless ($heading) { $heading=''; } else { $heading.=' '; }
7736: unless ($showtext) { $showtext=&mt('show'); }
7737: unless ($hidetext) { $hidetext=&mt('hide'); }
7738: unless ($headerbg) { $headerbg='#FFFFFF'; }
7739: return &start_data_table().
7740: &start_data_table_header_row().
7741: '<td bgcolor="'.$headerbg.'">'.$heading.
7742: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
7743: $showtext.'\')">'.$showtext.'</a>]</td>'.
7744: &end_data_table_header_row().
7745: '<tr id="'.$id.'" style="display:none""><td>';
7746: }
7747:
7748: sub end_togglebox {
7749: return '</td></tr>'.&end_data_table();
7750: }
7751:
7752: sub LCprogressbar_script {
7753: my ($id)=@_;
7754: return(<<ENDPROGRESS);
7755: <script type="text/javascript">
7756: // <![CDATA[
7757: \$('#progressbar$id').progressbar({
7758: value: 0,
7759: change: function(event, ui) {
7760: var newVal = \$(this).progressbar('option', 'value');
7761: \$('.pblabel', this).text(LCprogressTxt);
7762: }
7763: });
7764: // ]]>
7765: </script>
7766: ENDPROGRESS
7767: }
7768:
7769: sub LCprogressbarUpdate_script {
7770: return(<<ENDPROGRESSUPDATE);
7771: <style type="text/css">
7772: .ui-progressbar { position:relative; }
7773: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
7774: </style>
7775: <script type="text/javascript">
7776: // <![CDATA[
7777: var LCprogressTxt='---';
7778:
7779: function LCupdateProgress(percent,progresstext,id) {
7780: LCprogressTxt=progresstext;
7781: \$('#progressbar'+id).progressbar('value',percent);
7782: }
7783: // ]]>
7784: </script>
7785: ENDPROGRESSUPDATE
7786: }
7787:
7788: my $LClastpercent;
7789: my $LCidcnt;
7790: my $LCcurrentid;
7791:
7792: sub LCprogressbar {
7793: my ($r)=(@_);
7794: $LClastpercent=0;
7795: $LCidcnt++;
7796: $LCcurrentid=$$.'_'.$LCidcnt;
7797: my $starting=&mt('Starting');
7798: my $content=(<<ENDPROGBAR);
7799: <p>
7800: <div id="progressbar$LCcurrentid">
7801: <span class="pblabel">$starting</span>
7802: </div>
7803: </p>
7804: ENDPROGBAR
7805: &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
7806: }
7807:
7808: sub LCprogressbarUpdate {
7809: my ($r,$val,$text)=@_;
7810: unless ($val) {
7811: if ($LClastpercent) {
7812: $val=$LClastpercent;
7813: } else {
7814: $val=0;
7815: }
7816: }
7817: if ($val<0) { $val=0; }
7818: if ($val>100) { $val=0; }
7819: $LClastpercent=$val;
7820: unless ($text) { $text=$val.'%'; }
7821: $text=&js_ready($text);
7822: &r_print($r,<<ENDUPDATE);
7823: <script type="text/javascript">
7824: // <![CDATA[
7825: LCupdateProgress($val,'$text','$LCcurrentid');
7826: // ]]>
7827: </script>
7828: ENDUPDATE
7829: }
7830:
7831: sub LCprogressbarClose {
7832: my ($r)=@_;
7833: $LClastpercent=0;
7834: &r_print($r,<<ENDCLOSE);
7835: <script type="text/javascript">
7836: // <![CDATA[
7837: \$("#progressbar$LCcurrentid").hide('slow');
7838: // ]]>
7839: </script>
7840: ENDCLOSE
7841: }
7842:
7843: sub r_print {
7844: my ($r,$to_print)=@_;
7845: if ($r) {
7846: $r->print($to_print);
7847: $r->rflush();
7848: } else {
7849: print($to_print);
7850: }
7851: }
7852:
7853: sub html_encode {
7854: my ($result) = @_;
7855:
7856: $result = &HTML::Entities::encode($result,'<>&"');
7857:
7858: return $result;
7859: }
7860:
7861: sub js_ready {
7862: my ($result) = @_;
7863:
7864: $result =~ s/[\n\r]/ /xmsg;
7865: $result =~ s/\\/\\\\/xmsg;
7866: $result =~ s/'/\\'/xmsg;
7867: $result =~ s{</}{<\\/}xmsg;
7868:
7869: return $result;
7870: }
7871:
7872: sub validate_page {
7873: if ( exists($env{'internal.start_page'})
7874: && $env{'internal.start_page'} > 1) {
7875: &Apache::lonnet::logthis('start_page called multiple times '.
7876: $env{'internal.start_page'}.' '.
7877: $ENV{'request.filename'});
7878: }
7879: if ( exists($env{'internal.end_page'})
7880: && $env{'internal.end_page'} > 1) {
7881: &Apache::lonnet::logthis('end_page called multiple times '.
7882: $env{'internal.end_page'}.' '.
7883: $env{'request.filename'});
7884: }
7885: if ( exists($env{'internal.start_page'})
7886: && ! exists($env{'internal.end_page'})) {
7887: &Apache::lonnet::logthis('start_page called without end_page '.
7888: $env{'request.filename'});
7889: }
7890: if ( ! exists($env{'internal.start_page'})
7891: && exists($env{'internal.end_page'})) {
7892: &Apache::lonnet::logthis('end_page called without start_page'.
7893: $env{'request.filename'});
7894: }
7895: }
7896:
7897:
7898: sub start_scrollbox {
7899: my ($outerwidth,$width,$height,$id,$bgcolor)=@_;
7900: unless ($outerwidth) { $outerwidth='520px'; }
7901: unless ($width) { $width='500px'; }
7902: unless ($height) { $height='200px'; }
7903: my ($table_id,$div_id,$tdcol);
7904: if ($id ne '') {
7905: $table_id = " id='table_$id'";
7906: $div_id = " id='div_$id'";
7907: }
7908: if ($bgcolor ne '') {
7909: $tdcol = "background-color: $bgcolor;";
7910: }
7911: return <<"END";
7912: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol"><div style="overflow:auto; width:$width; height: $height;"$div_id>
7913: END
7914: }
7915:
7916: sub end_scrollbox {
7917: return '</div></td></tr></table>';
7918: }
7919:
7920: sub simple_error_page {
7921: my ($r,$title,$msg) = @_;
7922: my $page =
7923: &Apache::loncommon::start_page($title).
7924: '<p class="LC_error">'.&mt($msg).'</p>'.
7925: &Apache::loncommon::end_page();
7926: if (ref($r)) {
7927: $r->print($page);
7928: return;
7929: }
7930: return $page;
7931: }
7932:
7933: {
7934: my @row_count;
7935:
7936: sub start_data_table_count {
7937: unshift(@row_count, 0);
7938: return;
7939: }
7940:
7941: sub end_data_table_count {
7942: shift(@row_count);
7943: return;
7944: }
7945:
7946: sub start_data_table {
7947: my ($add_class,$id) = @_;
7948: my $css_class = (join(' ','LC_data_table',$add_class));
7949: my $table_id;
7950: if (defined($id)) {
7951: $table_id = ' id="'.$id.'"';
7952: }
7953: &start_data_table_count();
7954: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
7955: }
7956:
7957: sub end_data_table {
7958: &end_data_table_count();
7959: return '</table>'."\n";;
7960: }
7961:
7962: sub start_data_table_row {
7963: my ($add_class, $id) = @_;
7964: $row_count[0]++;
7965: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
7966: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
7967: $id = (' id="'.$id.'"') unless ($id eq '');
7968: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
7969: }
7970:
7971: sub continue_data_table_row {
7972: my ($add_class, $id) = @_;
7973: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
7974: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
7975: $id = (' id="'.$id.'"') unless ($id eq '');
7976: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
7977: }
7978:
7979: sub end_data_table_row {
7980: return '</tr>'."\n";;
7981: }
7982:
7983: sub start_data_table_empty_row {
7984: # $row_count[0]++;
7985: return '<tr class="LC_empty_row" >'."\n";;
7986: }
7987:
7988: sub end_data_table_empty_row {
7989: return '</tr>'."\n";;
7990: }
7991:
7992: sub start_data_table_header_row {
7993: return '<tr class="LC_header_row">'."\n";;
7994: }
7995:
7996: sub end_data_table_header_row {
7997: return '</tr>'."\n";;
7998: }
7999:
8000: sub data_table_caption {
8001: my $caption = shift;
8002: return "<caption class=\"LC_caption\">$caption</caption>";
8003: }
8004: }
8005:
8006: =pod
8007:
8008: =item * &inhibit_menu_check($arg)
8009:
8010: Checks for a inhibitmenu state and generates output to preserve it
8011:
8012: Inputs: $arg - can be any of
8013: - undef - in which case the return value is a string
8014: to add into arguments list of a uri
8015: - 'input' - in which case the return value is a HTML
8016: <form> <input> field of type hidden to
8017: preserve the value
8018: - a url - in which case the return value is the url with
8019: the neccesary cgi args added to preserve the
8020: inhibitmenu state
8021: - a ref to a url - no return value, but the string is
8022: updated to include the neccessary cgi
8023: args to preserve the inhibitmenu state
8024:
8025: =cut
8026:
8027: sub inhibit_menu_check {
8028: my ($arg) = @_;
8029: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
8030: if ($arg eq 'input') {
8031: if ($env{'form.inhibitmenu'}) {
8032: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
8033: } else {
8034: return
8035: }
8036: }
8037: if ($env{'form.inhibitmenu'}) {
8038: if (ref($arg)) {
8039: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
8040: } elsif ($arg eq '') {
8041: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
8042: } else {
8043: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
8044: }
8045: }
8046: if (!ref($arg)) {
8047: return $arg;
8048: }
8049: }
8050:
8051: ###############################################
8052:
8053: =pod
8054:
8055: =back
8056:
8057: =head1 User Information Routines
8058:
8059: =over 4
8060:
8061: =item * &get_users_function()
8062:
8063: Used by &bodytag to determine the current users primary role.
8064: Returns either 'student','coordinator','admin', or 'author'.
8065:
8066: =cut
8067:
8068: ###############################################
8069: sub get_users_function {
8070: my $function = 'norole';
8071: if ($env{'request.role'}=~/^(st)/) {
8072: $function='student';
8073: }
8074: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
8075: $function='coordinator';
8076: }
8077: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
8078: $function='admin';
8079: }
8080: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
8081: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
8082: $function='author';
8083: }
8084: return $function;
8085: }
8086:
8087: ###############################################
8088:
8089: =pod
8090:
8091: =item * &show_course()
8092:
8093: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
8094: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
8095:
8096: Inputs:
8097: None
8098:
8099: Outputs:
8100: Scalar: 1 if 'Course' to be used, 0 otherwise.
8101:
8102: =cut
8103:
8104: ###############################################
8105: sub show_course {
8106: my $course = !$env{'user.adv'};
8107: if (!$env{'user.adv'}) {
8108: foreach my $env (keys(%env)) {
8109: next if ($env !~ m/^user\.priv\./);
8110: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
8111: $course = 0;
8112: last;
8113: }
8114: }
8115: }
8116: return $course;
8117: }
8118:
8119: ###############################################
8120:
8121: =pod
8122:
8123: =item * &check_user_status()
8124:
8125: Determines current status of supplied role for a
8126: specific user. Roles can be active, previous or future.
8127:
8128: Inputs:
8129: user's domain, user's username, course's domain,
8130: course's number, optional section ID.
8131:
8132: Outputs:
8133: role status: active, previous or future.
8134:
8135: =cut
8136:
8137: sub check_user_status {
8138: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
8139: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
8140: my @uroles = keys %userinfo;
8141: my $srchstr;
8142: my $active_chk = 'none';
8143: my $now = time;
8144: if (@uroles > 0) {
8145: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
8146: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
8147: } else {
8148: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
8149: }
8150: if (grep/^\Q$srchstr\E$/,@uroles) {
8151: my $role_end = 0;
8152: my $role_start = 0;
8153: $active_chk = 'active';
8154: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
8155: $role_end = $1;
8156: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
8157: $role_start = $1;
8158: }
8159: }
8160: if ($role_start > 0) {
8161: if ($now < $role_start) {
8162: $active_chk = 'future';
8163: }
8164: }
8165: if ($role_end > 0) {
8166: if ($now > $role_end) {
8167: $active_chk = 'previous';
8168: }
8169: }
8170: }
8171: }
8172: return $active_chk;
8173: }
8174:
8175: ###############################################
8176:
8177: =pod
8178:
8179: =item * &get_sections()
8180:
8181: Determines all the sections for a course including
8182: sections with students and sections containing other roles.
8183: Incoming parameters:
8184:
8185: 1. domain
8186: 2. course number
8187: 3. reference to array containing roles for which sections should
8188: be gathered (optional).
8189: 4. reference to array containing status types for which sections
8190: should be gathered (optional).
8191:
8192: If the third argument is undefined, sections are gathered for any role.
8193: If the fourth argument is undefined, sections are gathered for any status.
8194: Permissible values are 'active' or 'future' or 'previous'.
8195:
8196: Returns section hash (keys are section IDs, values are
8197: number of users in each section), subject to the
8198: optional roles filter, optional status filter
8199:
8200: =cut
8201:
8202: ###############################################
8203: sub get_sections {
8204: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
8205: if (!defined($cdom) || !defined($cnum)) {
8206: my $cid = $env{'request.course.id'};
8207:
8208: return if (!defined($cid));
8209:
8210: $cdom = $env{'course.'.$cid.'.domain'};
8211: $cnum = $env{'course.'.$cid.'.num'};
8212: }
8213:
8214: my %sectioncount;
8215: my $now = time;
8216:
8217: if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
8218: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
8219: my $sec_index = &Apache::loncoursedata::CL_SECTION();
8220: my $status_index = &Apache::loncoursedata::CL_STATUS();
8221: my $start_index = &Apache::loncoursedata::CL_START();
8222: my $end_index = &Apache::loncoursedata::CL_END();
8223: my $status;
8224: while (my ($student,$data) = each(%$classlist)) {
8225: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
8226: $data->[$status_index],
8227: $data->[$start_index],
8228: $data->[$end_index]);
8229: if ($stu_status eq 'Active') {
8230: $status = 'active';
8231: } elsif ($end < $now) {
8232: $status = 'previous';
8233: } elsif ($start > $now) {
8234: $status = 'future';
8235: }
8236: if ($section ne '-1' && $section !~ /^\s*$/) {
8237: if ((!defined($possible_status)) || (($status ne '') &&
8238: (grep/^\Q$status\E$/,@{$possible_status}))) {
8239: $sectioncount{$section}++;
8240: }
8241: }
8242: }
8243: }
8244: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
8245: foreach my $user (sort(keys(%courseroles))) {
8246: if ($user !~ /^(\w{2})/) { next; }
8247: my ($role) = ($user =~ /^(\w{2})/);
8248: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
8249: my ($section,$status);
8250: if ($role eq 'cr' &&
8251: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
8252: $section=$1;
8253: }
8254: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
8255: if (!defined($section) || $section eq '-1') { next; }
8256: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
8257: if ($end == -1 && $start == -1) {
8258: next; #deleted role
8259: }
8260: if (!defined($possible_status)) {
8261: $sectioncount{$section}++;
8262: } else {
8263: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
8264: $status = 'active';
8265: } elsif ($end < $now) {
8266: $status = 'future';
8267: } elsif ($start > $now) {
8268: $status = 'previous';
8269: }
8270: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
8271: $sectioncount{$section}++;
8272: }
8273: }
8274: }
8275: return %sectioncount;
8276: }
8277:
8278: ###############################################
8279:
8280: =pod
8281:
8282: =item * &get_course_users()
8283:
8284: Retrieves usernames:domains for users in the specified course
8285: with specific role(s), and access status.
8286:
8287: Incoming parameters:
8288: 1. course domain
8289: 2. course number
8290: 3. access status: users must have - either active,
8291: previous, future, or all.
8292: 4. reference to array of permissible roles
8293: 5. reference to array of section restrictions (optional)
8294: 6. reference to results object (hash of hashes).
8295: 7. reference to optional userdata hash
8296: 8. reference to optional statushash
8297: 9. flag if privileged users (except those set to unhide in
8298: course settings) should be excluded
8299: Keys of top level results hash are roles.
8300: Keys of inner hashes are username:domain, with
8301: values set to access type.
8302: Optional userdata hash returns an array with arguments in the
8303: same order as loncoursedata::get_classlist() for student data.
8304:
8305: Optional statushash returns
8306:
8307: Entries for end, start, section and status are blank because
8308: of the possibility of multiple values for non-student roles.
8309:
8310: =cut
8311:
8312: ###############################################
8313:
8314: sub get_course_users {
8315: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
8316: my %idx = ();
8317: my %seclists;
8318:
8319: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
8320: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
8321: $idx{end} = &Apache::loncoursedata::CL_END();
8322: $idx{start} = &Apache::loncoursedata::CL_START();
8323: $idx{id} = &Apache::loncoursedata::CL_ID();
8324: $idx{section} = &Apache::loncoursedata::CL_SECTION();
8325: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
8326: $idx{status} = &Apache::loncoursedata::CL_STATUS();
8327:
8328: if (grep(/^st$/,@{$roles})) {
8329: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
8330: my $now = time;
8331: foreach my $student (keys(%{$classlist})) {
8332: my $match = 0;
8333: my $secmatch = 0;
8334: my $section = $$classlist{$student}[$idx{section}];
8335: my $status = $$classlist{$student}[$idx{status}];
8336: if ($section eq '') {
8337: $section = 'none';
8338: }
8339: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
8340: if (grep(/^all$/,@{$sections})) {
8341: $secmatch = 1;
8342: } elsif ($$classlist{$student}[$idx{section}] eq '') {
8343: if (grep(/^none$/,@{$sections})) {
8344: $secmatch = 1;
8345: }
8346: } else {
8347: if (grep(/^\Q$section\E$/,@{$sections})) {
8348: $secmatch = 1;
8349: }
8350: }
8351: if (!$secmatch) {
8352: next;
8353: }
8354: }
8355: if (defined($$types{'active'})) {
8356: if ($$classlist{$student}[$idx{status}] eq 'Active') {
8357: push(@{$$users{st}{$student}},'active');
8358: $match = 1;
8359: }
8360: }
8361: if (defined($$types{'previous'})) {
8362: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
8363: push(@{$$users{st}{$student}},'previous');
8364: $match = 1;
8365: }
8366: }
8367: if (defined($$types{'future'})) {
8368: if ($$classlist{$student}[$idx{status}] eq 'Future') {
8369: push(@{$$users{st}{$student}},'future');
8370: $match = 1;
8371: }
8372: }
8373: if ($match) {
8374: push(@{$seclists{$student}},$section);
8375: if (ref($userdata) eq 'HASH') {
8376: $$userdata{$student} = $$classlist{$student};
8377: }
8378: if (ref($statushash) eq 'HASH') {
8379: $statushash->{$student}{'st'}{$section} = $status;
8380: }
8381: }
8382: }
8383: }
8384: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
8385: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
8386: my $now = time;
8387: my %displaystatus = ( previous => 'Expired',
8388: active => 'Active',
8389: future => 'Future',
8390: );
8391: my %nothide;
8392: if ($hidepriv) {
8393: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
8394: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
8395: if ($user !~ /:/) {
8396: $nothide{join(':',split(/[\@]/,$user))}=1;
8397: } else {
8398: $nothide{$user} = 1;
8399: }
8400: }
8401: }
8402: foreach my $person (sort(keys(%coursepersonnel))) {
8403: my $match = 0;
8404: my $secmatch = 0;
8405: my $status;
8406: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
8407: $user =~ s/:$//;
8408: my ($end,$start) = split(/:/,$coursepersonnel{$person});
8409: if ($end == -1 || $start == -1) {
8410: next;
8411: }
8412: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
8413: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
8414: my ($uname,$udom) = split(/:/,$user);
8415: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
8416: if (grep(/^all$/,@{$sections})) {
8417: $secmatch = 1;
8418: } elsif ($usec eq '') {
8419: if (grep(/^none$/,@{$sections})) {
8420: $secmatch = 1;
8421: }
8422: } else {
8423: if (grep(/^\Q$usec\E$/,@{$sections})) {
8424: $secmatch = 1;
8425: }
8426: }
8427: if (!$secmatch) {
8428: next;
8429: }
8430: }
8431: if ($usec eq '') {
8432: $usec = 'none';
8433: }
8434: if ($uname ne '' && $udom ne '') {
8435: if ($hidepriv) {
8436: if ((&Apache::lonnet::privileged($uname,$udom)) &&
8437: (!$nothide{$uname.':'.$udom})) {
8438: next;
8439: }
8440: }
8441: if ($end > 0 && $end < $now) {
8442: $status = 'previous';
8443: } elsif ($start > $now) {
8444: $status = 'future';
8445: } else {
8446: $status = 'active';
8447: }
8448: foreach my $type (keys(%{$types})) {
8449: if ($status eq $type) {
8450: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
8451: push(@{$$users{$role}{$user}},$type);
8452: }
8453: $match = 1;
8454: }
8455: }
8456: if (($match) && (ref($userdata) eq 'HASH')) {
8457: if (!exists($$userdata{$uname.':'.$udom})) {
8458: &get_user_info($udom,$uname,\%idx,$userdata);
8459: }
8460: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
8461: push(@{$seclists{$uname.':'.$udom}},$usec);
8462: }
8463: if (ref($statushash) eq 'HASH') {
8464: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
8465: }
8466: }
8467: }
8468: }
8469: }
8470: if (grep(/^ow$/,@{$roles})) {
8471: if ((defined($cdom)) && (defined($cnum))) {
8472: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
8473: if ( defined($csettings{'internal.courseowner'}) ) {
8474: my $owner = $csettings{'internal.courseowner'};
8475: next if ($owner eq '');
8476: my ($ownername,$ownerdom);
8477: if ($owner =~ /^([^:]+):([^:]+)$/) {
8478: $ownername = $1;
8479: $ownerdom = $2;
8480: } else {
8481: $ownername = $owner;
8482: $ownerdom = $cdom;
8483: $owner = $ownername.':'.$ownerdom;
8484: }
8485: @{$$users{'ow'}{$owner}} = 'any';
8486: if (defined($userdata) &&
8487: !exists($$userdata{$owner})) {
8488: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
8489: if (!grep(/^none$/,@{$seclists{$owner}})) {
8490: push(@{$seclists{$owner}},'none');
8491: }
8492: if (ref($statushash) eq 'HASH') {
8493: $statushash->{$owner}{'ow'}{'none'} = 'Any';
8494: }
8495: }
8496: }
8497: }
8498: }
8499: foreach my $user (keys(%seclists)) {
8500: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
8501: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
8502: }
8503: }
8504: return;
8505: }
8506:
8507: sub get_user_info {
8508: my ($udom,$uname,$idx,$userdata) = @_;
8509: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
8510: &plainname($uname,$udom,'lastname');
8511: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
8512: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
8513: my %idhash = &Apache::lonnet::idrget($udom,($uname));
8514: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
8515: return;
8516: }
8517:
8518: ###############################################
8519:
8520: =pod
8521:
8522: =item * &get_user_quota()
8523:
8524: Retrieves quota assigned for storage of portfolio files for a user
8525:
8526: Incoming parameters:
8527: 1. user's username
8528: 2. user's domain
8529:
8530: Returns:
8531: 1. Disk quota (in Mb) assigned to student.
8532: 2. (Optional) Type of setting: custom or default
8533: (individually assigned or default for user's
8534: institutional status).
8535: 3. (Optional) - User's institutional status (e.g., faculty, staff
8536: or student - types as defined in localenroll::inst_usertypes
8537: for user's domain, which determines default quota for user.
8538: 4. (Optional) - Default quota which would apply to the user.
8539:
8540: If a value has been stored in the user's environment,
8541: it will return that, otherwise it returns the maximal default
8542: defined for the user's instituional status(es) in the domain.
8543:
8544: =cut
8545:
8546: ###############################################
8547:
8548:
8549: sub get_user_quota {
8550: my ($uname,$udom) = @_;
8551: my ($quota,$quotatype,$settingstatus,$defquota);
8552: if (!defined($udom)) {
8553: $udom = $env{'user.domain'};
8554: }
8555: if (!defined($uname)) {
8556: $uname = $env{'user.name'};
8557: }
8558: if (($udom eq '' || $uname eq '') ||
8559: ($udom eq 'public') && ($uname eq 'public')) {
8560: $quota = 0;
8561: $quotatype = 'default';
8562: $defquota = 0;
8563: } else {
8564: my $inststatus;
8565: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
8566: $quota = $env{'environment.portfolioquota'};
8567: $inststatus = $env{'environment.inststatus'};
8568: } else {
8569: my %userenv =
8570: &Apache::lonnet::get('environment',['portfolioquota',
8571: 'inststatus'],$udom,$uname);
8572: my ($tmp) = keys(%userenv);
8573: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8574: $quota = $userenv{'portfolioquota'};
8575: $inststatus = $userenv{'inststatus'};
8576: } else {
8577: undef(%userenv);
8578: }
8579: }
8580: ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
8581: if ($quota eq '') {
8582: $quota = $defquota;
8583: $quotatype = 'default';
8584: } else {
8585: $quotatype = 'custom';
8586: }
8587: }
8588: if (wantarray) {
8589: return ($quota,$quotatype,$settingstatus,$defquota);
8590: } else {
8591: return $quota;
8592: }
8593: }
8594:
8595: ###############################################
8596:
8597: =pod
8598:
8599: =item * &default_quota()
8600:
8601: Retrieves default quota assigned for storage of user portfolio files,
8602: given an (optional) user's institutional status.
8603:
8604: Incoming parameters:
8605: 1. domain
8606: 2. (Optional) institutional status(es). This is a : separated list of
8607: status types (e.g., faculty, staff, student etc.)
8608: which apply to the user for whom the default is being retrieved.
8609: If the institutional status string in undefined, the domain
8610: default quota will be returned.
8611:
8612: Returns:
8613: 1. Default disk quota (in Mb) for user portfolios in the domain.
8614: 2. (Optional) institutional type which determined the value of the
8615: default quota.
8616:
8617: If a value has been stored in the domain's configuration db,
8618: it will return that, otherwise it returns 20 (for backwards
8619: compatibility with domains which have not set up a configuration
8620: db file; the original statically defined portfolio quota was 20 Mb).
8621:
8622: If the user's status includes multiple types (e.g., staff and student),
8623: the largest default quota which applies to the user determines the
8624: default quota returned.
8625:
8626: =back
8627:
8628: =cut
8629:
8630: ###############################################
8631:
8632:
8633: sub default_quota {
8634: my ($udom,$inststatus) = @_;
8635: my ($defquota,$settingstatus);
8636: my %quotahash = &Apache::lonnet::get_dom('configuration',
8637: ['quotas'],$udom);
8638: if (ref($quotahash{'quotas'}) eq 'HASH') {
8639: if ($inststatus ne '') {
8640: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
8641: foreach my $item (@statuses) {
8642: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
8643: if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
8644: if ($defquota eq '') {
8645: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
8646: $settingstatus = $item;
8647: } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
8648: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
8649: $settingstatus = $item;
8650: }
8651: }
8652: } else {
8653: if ($quotahash{'quotas'}{$item} ne '') {
8654: if ($defquota eq '') {
8655: $defquota = $quotahash{'quotas'}{$item};
8656: $settingstatus = $item;
8657: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
8658: $defquota = $quotahash{'quotas'}{$item};
8659: $settingstatus = $item;
8660: }
8661: }
8662: }
8663: }
8664: }
8665: if ($defquota eq '') {
8666: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
8667: $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
8668: } else {
8669: $defquota = $quotahash{'quotas'}{'default'};
8670: }
8671: $settingstatus = 'default';
8672: }
8673: } else {
8674: $settingstatus = 'default';
8675: $defquota = 20;
8676: }
8677: if (wantarray) {
8678: return ($defquota,$settingstatus);
8679: } else {
8680: return $defquota;
8681: }
8682: }
8683:
8684: sub get_secgrprole_info {
8685: my ($cdom,$cnum,$needroles,$type) = @_;
8686: my %sections_count = &get_sections($cdom,$cnum);
8687: my @sections = (sort {$a <=> $b} keys(%sections_count));
8688: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
8689: my @groups = sort(keys(%curr_groups));
8690: my $allroles = [];
8691: my $rolehash;
8692: my $accesshash = {
8693: active => 'Currently has access',
8694: future => 'Will have future access',
8695: previous => 'Previously had access',
8696: };
8697: if ($needroles) {
8698: $rolehash = {'all' => 'all'};
8699: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
8700: if (&Apache::lonnet::error(%user_roles)) {
8701: undef(%user_roles);
8702: }
8703: foreach my $item (keys(%user_roles)) {
8704: my ($role)=split(/\:/,$item,2);
8705: if ($role eq 'cr') { next; }
8706: if ($role =~ /^cr/) {
8707: $$rolehash{$role} = (split('/',$role))[3];
8708: } else {
8709: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
8710: }
8711: }
8712: foreach my $key (sort(keys(%{$rolehash}))) {
8713: push(@{$allroles},$key);
8714: }
8715: push (@{$allroles},'st');
8716: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
8717: }
8718: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
8719: }
8720:
8721: sub user_picker {
8722: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
8723: my $currdom = $dom;
8724: my %curr_selected = (
8725: srchin => 'dom',
8726: srchby => 'lastname',
8727: );
8728: my $srchterm;
8729: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
8730: if ($srch->{'srchby'} ne '') {
8731: $curr_selected{'srchby'} = $srch->{'srchby'};
8732: }
8733: if ($srch->{'srchin'} ne '') {
8734: $curr_selected{'srchin'} = $srch->{'srchin'};
8735: }
8736: if ($srch->{'srchtype'} ne '') {
8737: $curr_selected{'srchtype'} = $srch->{'srchtype'};
8738: }
8739: if ($srch->{'srchdomain'} ne '') {
8740: $currdom = $srch->{'srchdomain'};
8741: }
8742: $srchterm = $srch->{'srchterm'};
8743: }
8744: my %lt=&Apache::lonlocal::texthash(
8745: 'usr' => 'Search criteria',
8746: 'doma' => 'Domain/institution to search',
8747: 'uname' => 'username',
8748: 'lastname' => 'last name',
8749: 'lastfirst' => 'last name, first name',
8750: 'crs' => 'in this course',
8751: 'dom' => 'in selected LON-CAPA domain',
8752: 'alc' => 'all LON-CAPA',
8753: 'instd' => 'in institutional directory for selected domain',
8754: 'exact' => 'is',
8755: 'contains' => 'contains',
8756: 'begins' => 'begins with',
8757: 'youm' => "You must include some text to search for.",
8758: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
8759: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
8760: 'yomc' => "You must choose a domain when using an institutional directory search.",
8761: 'ymcd' => "You must choose a domain when using a domain search.",
8762: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
8763: 'whse' => "When searching by last,first you must include at least one character in the first name.",
8764: 'thfo' => "The following need to be corrected before the search can be run:",
8765: );
8766: my $domform = &select_dom_form($currdom,'srchdomain',1,1);
8767: my $srchinsel = ' <select name="srchin">';
8768:
8769: my @srchins = ('crs','dom','alc','instd');
8770:
8771: foreach my $option (@srchins) {
8772: # FIXME 'alc' option unavailable until
8773: # loncreateuser::print_user_query_page()
8774: # has been completed.
8775: next if ($option eq 'alc');
8776: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
8777: next if ($option eq 'crs' && !$env{'request.course.id'});
8778: if ($curr_selected{'srchin'} eq $option) {
8779: $srchinsel .= '
8780: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
8781: } else {
8782: $srchinsel .= '
8783: <option value="'.$option.'">'.$lt{$option}.'</option>';
8784: }
8785: }
8786: $srchinsel .= "\n </select>\n";
8787:
8788: my $srchbysel = ' <select name="srchby">';
8789: foreach my $option ('lastname','lastfirst','uname') {
8790: if ($curr_selected{'srchby'} eq $option) {
8791: $srchbysel .= '
8792: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
8793: } else {
8794: $srchbysel .= '
8795: <option value="'.$option.'">'.$lt{$option}.'</option>';
8796: }
8797: }
8798: $srchbysel .= "\n </select>\n";
8799:
8800: my $srchtypesel = ' <select name="srchtype">';
8801: foreach my $option ('begins','contains','exact') {
8802: if ($curr_selected{'srchtype'} eq $option) {
8803: $srchtypesel .= '
8804: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
8805: } else {
8806: $srchtypesel .= '
8807: <option value="'.$option.'">'.$lt{$option}.'</option>';
8808: }
8809: }
8810: $srchtypesel .= "\n </select>\n";
8811:
8812: my ($newuserscript,$new_user_create);
8813: my $context_dom = $env{'request.role.domain'};
8814: if ($context eq 'requestcrs') {
8815: if ($env{'form.coursedom'} ne '') {
8816: $context_dom = $env{'form.coursedom'};
8817: }
8818: }
8819: if ($forcenewuser) {
8820: if (ref($srch) eq 'HASH') {
8821: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
8822: if ($cancreate) {
8823: $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>';
8824: } else {
8825: my $helplink = 'javascript:helpMenu('."'display'".')';
8826: my %usertypetext = (
8827: official => 'institutional',
8828: unofficial => 'non-institutional',
8829: );
8830: $new_user_create = '<p class="LC_warning">'
8831: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
8832: .' '
8833: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
8834: ,'<a href="'.$helplink.'">','</a>')
8835: .'</p><br />';
8836: }
8837: }
8838: }
8839:
8840: $newuserscript = <<"ENDSCRIPT";
8841:
8842: function setSearch(createnew,callingForm) {
8843: if (createnew == 1) {
8844: for (var i=0; i<callingForm.srchby.length; i++) {
8845: if (callingForm.srchby.options[i].value == 'uname') {
8846: callingForm.srchby.selectedIndex = i;
8847: }
8848: }
8849: for (var i=0; i<callingForm.srchin.length; i++) {
8850: if ( callingForm.srchin.options[i].value == 'dom') {
8851: callingForm.srchin.selectedIndex = i;
8852: }
8853: }
8854: for (var i=0; i<callingForm.srchtype.length; i++) {
8855: if (callingForm.srchtype.options[i].value == 'exact') {
8856: callingForm.srchtype.selectedIndex = i;
8857: }
8858: }
8859: for (var i=0; i<callingForm.srchdomain.length; i++) {
8860: if (callingForm.srchdomain.options[i].value == '$context_dom') {
8861: callingForm.srchdomain.selectedIndex = i;
8862: }
8863: }
8864: }
8865: }
8866: ENDSCRIPT
8867:
8868: }
8869:
8870: my $output = <<"END_BLOCK";
8871: <script type="text/javascript">
8872: // <![CDATA[
8873: function validateEntry(callingForm) {
8874:
8875: var checkok = 1;
8876: var srchin;
8877: for (var i=0; i<callingForm.srchin.length; i++) {
8878: if ( callingForm.srchin[i].checked ) {
8879: srchin = callingForm.srchin[i].value;
8880: }
8881: }
8882:
8883: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
8884: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
8885: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
8886: var srchterm = callingForm.srchterm.value;
8887: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
8888: var msg = "";
8889:
8890: if (srchterm == "") {
8891: checkok = 0;
8892: msg += "$lt{'youm'}\\n";
8893: }
8894:
8895: if (srchtype== 'begins') {
8896: if (srchterm.length < 2) {
8897: checkok = 0;
8898: msg += "$lt{'thte'}\\n";
8899: }
8900: }
8901:
8902: if (srchtype== 'contains') {
8903: if (srchterm.length < 3) {
8904: checkok = 0;
8905: msg += "$lt{'thet'}\\n";
8906: }
8907: }
8908: if (srchin == 'instd') {
8909: if (srchdomain == '') {
8910: checkok = 0;
8911: msg += "$lt{'yomc'}\\n";
8912: }
8913: }
8914: if (srchin == 'dom') {
8915: if (srchdomain == '') {
8916: checkok = 0;
8917: msg += "$lt{'ymcd'}\\n";
8918: }
8919: }
8920: if (srchby == 'lastfirst') {
8921: if (srchterm.indexOf(",") == -1) {
8922: checkok = 0;
8923: msg += "$lt{'whus'}\\n";
8924: }
8925: if (srchterm.indexOf(",") == srchterm.length -1) {
8926: checkok = 0;
8927: msg += "$lt{'whse'}\\n";
8928: }
8929: }
8930: if (checkok == 0) {
8931: alert("$lt{'thfo'}\\n"+msg);
8932: return;
8933: }
8934: if (checkok == 1) {
8935: callingForm.submit();
8936: }
8937: }
8938:
8939: $newuserscript
8940:
8941: // ]]>
8942: </script>
8943:
8944: $new_user_create
8945:
8946: END_BLOCK
8947:
8948: $output .= &Apache::lonhtmlcommon::start_pick_box().
8949: &Apache::lonhtmlcommon::row_title($lt{'doma'}).
8950: $domform.
8951: &Apache::lonhtmlcommon::row_closure().
8952: &Apache::lonhtmlcommon::row_title($lt{'usr'}).
8953: $srchbysel.
8954: $srchtypesel.
8955: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
8956: $srchinsel.
8957: &Apache::lonhtmlcommon::row_closure(1).
8958: &Apache::lonhtmlcommon::end_pick_box().
8959: '<br />';
8960: return $output;
8961: }
8962:
8963: sub user_rule_check {
8964: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
8965: my $response;
8966: if (ref($usershash) eq 'HASH') {
8967: foreach my $user (keys(%{$usershash})) {
8968: my ($uname,$udom) = split(/:/,$user);
8969: next if ($udom eq '' || $uname eq '');
8970: my ($id,$newuser);
8971: if (ref($usershash->{$user}) eq 'HASH') {
8972: $newuser = $usershash->{$user}->{'newuser'};
8973: $id = $usershash->{$user}->{'id'};
8974: }
8975: my $inst_response;
8976: if (ref($checks) eq 'HASH') {
8977: if (defined($checks->{'username'})) {
8978: ($inst_response,%{$inst_results->{$user}}) =
8979: &Apache::lonnet::get_instuser($udom,$uname);
8980: } elsif (defined($checks->{'id'})) {
8981: ($inst_response,%{$inst_results->{$user}}) =
8982: &Apache::lonnet::get_instuser($udom,undef,$id);
8983: }
8984: } else {
8985: ($inst_response,%{$inst_results->{$user}}) =
8986: &Apache::lonnet::get_instuser($udom,$uname);
8987: return;
8988: }
8989: if (!$got_rules->{$udom}) {
8990: my %domconfig = &Apache::lonnet::get_dom('configuration',
8991: ['usercreation'],$udom);
8992: if (ref($domconfig{'usercreation'}) eq 'HASH') {
8993: foreach my $item ('username','id') {
8994: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
8995: $$curr_rules{$udom}{$item} =
8996: $domconfig{'usercreation'}{$item.'_rule'};
8997: }
8998: }
8999: }
9000: $got_rules->{$udom} = 1;
9001: }
9002: foreach my $item (keys(%{$checks})) {
9003: if (ref($$curr_rules{$udom}) eq 'HASH') {
9004: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
9005: if (@{$$curr_rules{$udom}{$item}} > 0) {
9006: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
9007: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
9008: if ($rule_check{$rule}) {
9009: $$rulematch{$user}{$item} = $rule;
9010: if ($inst_response eq 'ok') {
9011: if (ref($inst_results) eq 'HASH') {
9012: if (ref($inst_results->{$user}) eq 'HASH') {
9013: if (keys(%{$inst_results->{$user}}) == 0) {
9014: $$alerts{$item}{$udom}{$uname} = 1;
9015: }
9016: }
9017: }
9018: }
9019: last;
9020: }
9021: }
9022: }
9023: }
9024: }
9025: }
9026: }
9027: }
9028: return;
9029: }
9030:
9031: sub user_rule_formats {
9032: my ($domain,$domdesc,$curr_rules,$check) = @_;
9033: my %text = (
9034: 'username' => 'Usernames',
9035: 'id' => 'IDs',
9036: );
9037: my $output;
9038: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
9039: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
9040: if (@{$ruleorder} > 0) {
9041: $output = '<br />'.
9042: &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
9043: '<span class="LC_cusr_emph">','</span>',$domdesc).
9044: ' <ul>';
9045: foreach my $rule (@{$ruleorder}) {
9046: if (ref($curr_rules) eq 'ARRAY') {
9047: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
9048: if (ref($rules->{$rule}) eq 'HASH') {
9049: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
9050: $rules->{$rule}{'desc'}.'</li>';
9051: }
9052: }
9053: }
9054: }
9055: $output .= '</ul>';
9056: }
9057: }
9058: return $output;
9059: }
9060:
9061: sub instrule_disallow_msg {
9062: my ($checkitem,$domdesc,$count,$mode) = @_;
9063: my $response;
9064: my %text = (
9065: item => 'username',
9066: items => 'usernames',
9067: match => 'matches',
9068: do => 'does',
9069: action => 'a username',
9070: one => 'one',
9071: );
9072: if ($count > 1) {
9073: $text{'item'} = 'usernames';
9074: $text{'match'} ='match';
9075: $text{'do'} = 'do';
9076: $text{'action'} = 'usernames',
9077: $text{'one'} = 'ones';
9078: }
9079: if ($checkitem eq 'id') {
9080: $text{'items'} = 'IDs';
9081: $text{'item'} = 'ID';
9082: $text{'action'} = 'an ID';
9083: if ($count > 1) {
9084: $text{'item'} = 'IDs';
9085: $text{'action'} = 'IDs';
9086: }
9087: }
9088: $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 />';
9089: if ($mode eq 'upload') {
9090: if ($checkitem eq 'username') {
9091: $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'}.");
9092: } elsif ($checkitem eq 'id') {
9093: $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.");
9094: }
9095: } elsif ($mode eq 'selfcreate') {
9096: if ($checkitem eq 'id') {
9097: $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.");
9098: }
9099: } else {
9100: if ($checkitem eq 'username') {
9101: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
9102: } elsif ($checkitem eq 'id') {
9103: $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.");
9104: }
9105: }
9106: return $response;
9107: }
9108:
9109: sub personal_data_fieldtitles {
9110: my %fieldtitles = &Apache::lonlocal::texthash (
9111: id => 'Student/Employee ID',
9112: permanentemail => 'E-mail address',
9113: lastname => 'Last Name',
9114: firstname => 'First Name',
9115: middlename => 'Middle Name',
9116: generation => 'Generation',
9117: gen => 'Generation',
9118: inststatus => 'Affiliation',
9119: );
9120: return %fieldtitles;
9121: }
9122:
9123: sub sorted_inst_types {
9124: my ($dom) = @_;
9125: my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
9126: my $othertitle = &mt('All users');
9127: if ($env{'request.course.id'}) {
9128: $othertitle = &mt('Any users');
9129: }
9130: my @types;
9131: if (ref($order) eq 'ARRAY') {
9132: @types = @{$order};
9133: }
9134: if (@types == 0) {
9135: if (ref($usertypes) eq 'HASH') {
9136: @types = sort(keys(%{$usertypes}));
9137: }
9138: }
9139: if (keys(%{$usertypes}) > 0) {
9140: $othertitle = &mt('Other users');
9141: }
9142: return ($othertitle,$usertypes,\@types);
9143: }
9144:
9145: sub get_institutional_codes {
9146: my ($settings,$allcourses,$LC_code) = @_;
9147: # Get complete list of course sections to update
9148: my @currsections = ();
9149: my @currxlists = ();
9150: my $coursecode = $$settings{'internal.coursecode'};
9151:
9152: if ($$settings{'internal.sectionnums'} ne '') {
9153: @currsections = split(/,/,$$settings{'internal.sectionnums'});
9154: }
9155:
9156: if ($$settings{'internal.crosslistings'} ne '') {
9157: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
9158: }
9159:
9160: if (@currxlists > 0) {
9161: foreach (@currxlists) {
9162: if (m/^([^:]+):(\w*)$/) {
9163: unless (grep/^$1$/,@{$allcourses}) {
9164: push @{$allcourses},$1;
9165: $$LC_code{$1} = $2;
9166: }
9167: }
9168: }
9169: }
9170:
9171: if (@currsections > 0) {
9172: foreach (@currsections) {
9173: if (m/^(\w+):(\w*)$/) {
9174: my $sec = $coursecode.$1;
9175: my $lc_sec = $2;
9176: unless (grep/^$sec$/,@{$allcourses}) {
9177: push @{$allcourses},$sec;
9178: $$LC_code{$sec} = $lc_sec;
9179: }
9180: }
9181: }
9182: }
9183: return;
9184: }
9185:
9186: sub get_standard_codeitems {
9187: return ('Year','Semester','Department','Number','Section');
9188: }
9189:
9190: =pod
9191:
9192: =head1 Slot Helpers
9193:
9194: =over 4
9195:
9196: =item * sorted_slots()
9197:
9198: Sorts an array of slot names in order of an optional sort key,
9199: default sort is by slot start time (earliest first).
9200:
9201: Inputs:
9202:
9203: =over 4
9204:
9205: slotsarr - Reference to array of unsorted slot names.
9206:
9207: slots - Reference to hash of hash, where outer hash keys are slot names.
9208:
9209: sortkey - Name of key in inner hash to be sorted on (e.g., starttime).
9210:
9211: =back
9212:
9213: Returns:
9214:
9215: =over 4
9216:
9217: sorted - An array of slot names sorted by a specified sort key
9218: (default sort key is start time of the slot).
9219:
9220: =back
9221:
9222: =cut
9223:
9224:
9225: sub sorted_slots {
9226: my ($slotsarr,$slots,$sortkey) = @_;
9227: if ($sortkey eq '') {
9228: $sortkey = 'starttime';
9229: }
9230: my @sorted;
9231: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
9232: @sorted =
9233: sort {
9234: if (ref($slots->{$a}) && ref($slots->{$b})) {
9235: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
9236: }
9237: if (ref($slots->{$a})) { return -1;}
9238: if (ref($slots->{$b})) { return 1;}
9239: return 0;
9240: } @{$slotsarr};
9241: }
9242: return @sorted;
9243: }
9244:
9245: =pod
9246:
9247: =item * get_future_slots()
9248:
9249: Inputs:
9250:
9251: =over 4
9252:
9253: cnum - course number
9254:
9255: cdom - course domain
9256:
9257: now - current UNIX time
9258:
9259: symb - optional symb
9260:
9261: =back
9262:
9263: Returns:
9264:
9265: =over 4
9266:
9267: sorted_reservable - ref to array of student_schedulable slots currently
9268: reservable, ordered by end date of reservation period.
9269:
9270: reservable_now - ref to hash of student_schedulable slots currently
9271: reservable.
9272:
9273: Keys in inner hash are:
9274: (a) symb: either blank or symb to which slot use is restricted.
9275: (b) endreserve: end date of reservation period.
9276:
9277: sorted_future - ref to array of student_schedulable slots reservable in
9278: the future, ordered by start date of reservation period.
9279:
9280: future_reservable - ref to hash of student_schedulable slots reservable
9281: in the future.
9282:
9283: Keys in inner hash are:
9284: (a) symb: either blank or symb to which slot use is restricted.
9285: (b) startreserve: start date of reservation period.
9286:
9287: =back
9288:
9289: =cut
9290:
9291: sub get_future_slots {
9292: my ($cnum,$cdom,$now,$symb) = @_;
9293: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
9294: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
9295: foreach my $slot (keys(%slots)) {
9296: next unless($slots{$slot}->{'type'} eq 'schedulable_student');
9297: if ($symb) {
9298: next if (($slots{$slot}->{'symb'} ne '') &&
9299: ($slots{$slot}->{'symb'} ne $symb));
9300: }
9301: if (($slots{$slot}->{'starttime'} > $now) &&
9302: ($slots{$slot}->{'endtime'} > $now)) {
9303: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
9304: my $userallowed = 0;
9305: if ($slots{$slot}->{'allowedsections'}) {
9306: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
9307: if (!defined($env{'request.role.sec'})
9308: && grep(/^No section assigned$/,@allowed_sec)) {
9309: $userallowed=1;
9310: } else {
9311: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
9312: $userallowed=1;
9313: }
9314: }
9315: unless ($userallowed) {
9316: if (defined($env{'request.course.groups'})) {
9317: my @groups = split(/:/,$env{'request.course.groups'});
9318: foreach my $group (@groups) {
9319: if (grep(/^\Q$group\E$/,@allowed_sec)) {
9320: $userallowed=1;
9321: last;
9322: }
9323: }
9324: }
9325: }
9326: }
9327: if ($slots{$slot}->{'allowedusers'}) {
9328: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
9329: my $user = $env{'user.name'}.':'.$env{'user.domain'};
9330: if (grep(/^\Q$user\E$/,@allowed_users)) {
9331: $userallowed = 1;
9332: }
9333: }
9334: next unless($userallowed);
9335: }
9336: my $startreserve = $slots{$slot}->{'startreserve'};
9337: my $endreserve = $slots{$slot}->{'endreserve'};
9338: my $symb = $slots{$slot}->{'symb'};
9339: if (($startreserve < $now) &&
9340: (!$endreserve || $endreserve > $now)) {
9341: my $lastres = $endreserve;
9342: if (!$lastres) {
9343: $lastres = $slots{$slot}->{'starttime'};
9344: }
9345: $reservable_now{$slot} = {
9346: symb => $symb,
9347: endreserve => $lastres
9348: };
9349: } elsif (($startreserve > $now) &&
9350: (!$endreserve || $endreserve > $startreserve)) {
9351: $future_reservable{$slot} = {
9352: symb => $symb,
9353: startreserve => $startreserve
9354: };
9355: }
9356: }
9357: }
9358: my @unsorted_reservable = keys(%reservable_now);
9359: if (@unsorted_reservable > 0) {
9360: @sorted_reservable =
9361: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
9362: }
9363: my @unsorted_future = keys(%future_reservable);
9364: if (@unsorted_future > 0) {
9365: @sorted_future =
9366: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
9367: }
9368: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
9369: }
9370:
9371: =pod
9372:
9373: =back
9374:
9375: =head1 HTTP Helpers
9376:
9377: =over 4
9378:
9379: =item * &get_unprocessed_cgi($query,$possible_names)
9380:
9381: Modify the %env hash to contain unprocessed CGI form parameters held in
9382: $query. The parameters listed in $possible_names (an array reference),
9383: will be set in $env{'form.name'} if they do not already exist.
9384:
9385: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
9386: $possible_names is an ref to an array of form element names. As an example:
9387: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
9388: will result in $env{'form.uname'} and $env{'form.udom'} being set.
9389:
9390: =cut
9391:
9392: sub get_unprocessed_cgi {
9393: my ($query,$possible_names)= @_;
9394: # $Apache::lonxml::debug=1;
9395: foreach my $pair (split(/&/,$query)) {
9396: my ($name, $value) = split(/=/,$pair);
9397: $name = &unescape($name);
9398: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
9399: $value =~ tr/+/ /;
9400: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
9401: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
9402: }
9403: }
9404: }
9405:
9406: =pod
9407:
9408: =item * &cacheheader()
9409:
9410: returns cache-controlling header code
9411:
9412: =cut
9413:
9414: sub cacheheader {
9415: unless ($env{'request.method'} eq 'GET') { return ''; }
9416: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
9417: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
9418: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
9419: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
9420: return $output;
9421: }
9422:
9423: =pod
9424:
9425: =item * &no_cache($r)
9426:
9427: specifies header code to not have cache
9428:
9429: =cut
9430:
9431: sub no_cache {
9432: my ($r) = @_;
9433: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
9434: $env{'request.method'} ne 'GET') { return ''; }
9435: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
9436: $r->no_cache(1);
9437: $r->header_out("Expires" => $date);
9438: $r->header_out("Pragma" => "no-cache");
9439: }
9440:
9441: sub content_type {
9442: my ($r,$type,$charset) = @_;
9443: if ($r) {
9444: # Note that printout.pl calls this with undef for $r.
9445: &no_cache($r);
9446: }
9447: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
9448: unless ($charset) {
9449: $charset=&Apache::lonlocal::current_encoding;
9450: }
9451: if ($charset) { $type.='; charset='.$charset; }
9452: if ($r) {
9453: $r->content_type($type);
9454: } else {
9455: print("Content-type: $type\n\n");
9456: }
9457: }
9458:
9459: =pod
9460:
9461: =item * &add_to_env($name,$value)
9462:
9463: adds $name to the %env hash with value
9464: $value, if $name already exists, the entry is converted to an array
9465: reference and $value is added to the array.
9466:
9467: =cut
9468:
9469: sub add_to_env {
9470: my ($name,$value)=@_;
9471: if (defined($env{$name})) {
9472: if (ref($env{$name})) {
9473: #already have multiple values
9474: push(@{ $env{$name} },$value);
9475: } else {
9476: #first time seeing multiple values, convert hash entry to an arrayref
9477: my $first=$env{$name};
9478: undef($env{$name});
9479: push(@{ $env{$name} },$first,$value);
9480: }
9481: } else {
9482: $env{$name}=$value;
9483: }
9484: }
9485:
9486: =pod
9487:
9488: =item * &get_env_multiple($name)
9489:
9490: gets $name from the %env hash, it seemlessly handles the cases where multiple
9491: values may be defined and end up as an array ref.
9492:
9493: returns an array of values
9494:
9495: =cut
9496:
9497: sub get_env_multiple {
9498: my ($name) = @_;
9499: my @values;
9500: if (defined($env{$name})) {
9501: # exists is it an array
9502: if (ref($env{$name})) {
9503: @values=@{ $env{$name} };
9504: } else {
9505: $values[0]=$env{$name};
9506: }
9507: }
9508: return(@values);
9509: }
9510:
9511: sub ask_for_embedded_content {
9512: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
9513: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
9514: %currsubfile,%unused,$rem);
9515: my $counter = 0;
9516: my $numnew = 0;
9517: my $numremref = 0;
9518: my $numinvalid = 0;
9519: my $numpathchg = 0;
9520: my $numexisting = 0;
9521: my $numunused = 0;
9522: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
9523: $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path);
9524: my $heading = &mt('Upload embedded files');
9525: my $buttontext = &mt('Upload');
9526:
9527: my $navmap;
9528: if ($env{'request.course.id'}) {
9529: $navmap = Apache::lonnavmaps::navmap->new();
9530: }
9531: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
9532: my $current_path='/';
9533: if ($env{'form.currentpath'}) {
9534: $current_path = $env{'form.currentpath'};
9535: }
9536: if ($actionurl eq '/adm/coursegrp_portfolio') {
9537: $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9538: $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
9539: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
9540: } else {
9541: $udom = $env{'user.domain'};
9542: $uname = $env{'user.name'};
9543: $url = '/userfiles/portfolio';
9544: }
9545: $toplevel = $url.'/';
9546: $url .= $current_path;
9547: $getpropath = 1;
9548: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
9549: ($actionurl eq '/adm/imsimport')) {
9550: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
9551: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
9552: $toplevel = $url;
9553: if ($rest ne '') {
9554: $url .= $rest;
9555: }
9556: } elsif ($actionurl eq '/adm/coursedocs') {
9557: if (ref($args) eq 'HASH') {
9558: $url = $args->{'docs_url'};
9559: $toplevel = $url;
9560: if ($args->{'context'} eq 'paste') {
9561: ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
9562: ($path) =
9563: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
9564: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
9565: $fileloc =~ s{^/}{};
9566: }
9567: }
9568: } elsif ($actionurl eq '/adm/dependencies') {
9569: if ($env{'request.course.id'} ne '') {
9570: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9571: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9572: if (ref($args) eq 'HASH') {
9573: $url = $args->{'docs_url'};
9574: $title = $args->{'docs_title'};
9575: $toplevel = "/$url";
9576: ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
9577: ($path) =
9578: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
9579: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
9580: $fileloc =~ s{^/}{};
9581: ($filename) = ($fileloc =~ m{.+/([^/]+)$});
9582: $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
9583: }
9584: }
9585: }
9586: my $now = time();
9587: foreach my $embed_file (keys(%{$allfiles})) {
9588: my $absolutepath;
9589: if ($embed_file =~ m{^\w+://}) {
9590: $newfiles{$embed_file} = 1;
9591: $mapping{$embed_file} = $embed_file;
9592: } else {
9593: if ($embed_file =~ m{^/}) {
9594: $absolutepath = $embed_file;
9595: $embed_file =~ s{^(/+)}{};
9596: }
9597: if ($embed_file =~ m{/}) {
9598: my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
9599: $path = &check_for_traversal($path,$url,$toplevel);
9600: my $item = $fname;
9601: if ($path ne '') {
9602: $item = $path.'/'.$fname;
9603: $subdependencies{$path}{$fname} = 1;
9604: } else {
9605: $dependencies{$item} = 1;
9606: }
9607: if ($absolutepath) {
9608: $mapping{$item} = $absolutepath;
9609: } else {
9610: $mapping{$item} = $embed_file;
9611: }
9612: } else {
9613: $dependencies{$embed_file} = 1;
9614: if ($absolutepath) {
9615: $mapping{$embed_file} = $absolutepath;
9616: } else {
9617: $mapping{$embed_file} = $embed_file;
9618: }
9619: }
9620: }
9621: }
9622: my $dirptr = 16384;
9623: foreach my $path (keys(%subdependencies)) {
9624: $currsubfile{$path} = {};
9625: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
9626: my ($sublistref,$listerror) =
9627: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
9628: if (ref($sublistref) eq 'ARRAY') {
9629: foreach my $line (@{$sublistref}) {
9630: my ($file_name,$rest) = split(/\&/,$line,2);
9631: $currsubfile{$path}{$file_name} = 1;
9632: }
9633: }
9634: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
9635: if (opendir(my $dir,$url.'/'.$path)) {
9636: my @subdir_list = grep(!/^\./,readdir($dir));
9637: map {$currsubfile{$path}{$_} = 1;} @subdir_list;
9638: }
9639: } elsif (($actionurl eq '/adm/dependencies') ||
9640: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
9641: ($args->{'context'} eq 'paste'))) {
9642: if ($env{'request.course.id'} ne '') {
9643: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
9644: if ($dir ne '') {
9645: my ($sublistref,$listerror) =
9646: &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
9647: if (ref($sublistref) eq 'ARRAY') {
9648: foreach my $line (@{$sublistref}) {
9649: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
9650: undef,$mtime)=split(/\&/,$line,12);
9651: unless (($testdir&$dirptr) ||
9652: ($file_name =~ /^\.\.?$/)) {
9653: $currsubfile{$path}{$file_name} = [$size,$mtime];
9654: }
9655: }
9656: }
9657: }
9658: }
9659: }
9660: foreach my $file (keys(%{$subdependencies{$path}})) {
9661: if (exists($currsubfile{$path}{$file})) {
9662: my $item = $path.'/'.$file;
9663: unless ($mapping{$item} eq $item) {
9664: $pathchanges{$item} = 1;
9665: }
9666: $existing{$item} = 1;
9667: $numexisting ++;
9668: } else {
9669: $newfiles{$path.'/'.$file} = 1;
9670: }
9671: }
9672: if ($actionurl eq '/adm/dependencies') {
9673: foreach my $path (keys(%currsubfile)) {
9674: if (ref($currsubfile{$path}) eq 'HASH') {
9675: foreach my $file (keys(%{$currsubfile{$path}})) {
9676: unless ($subdependencies{$path}{$file}) {
9677: next if (($rem ne '') &&
9678: (($env{"httpref.$rem"."$path/$file"} ne '') ||
9679: (ref($navmap) &&
9680: (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
9681: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
9682: ($navmap->getResourceByUrl($rem."$path/$1")))))));
9683: $unused{$path.'/'.$file} = 1;
9684: }
9685: }
9686: }
9687: }
9688: }
9689: }
9690: my %currfile;
9691: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
9692: my ($dirlistref,$listerror) =
9693: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
9694: if (ref($dirlistref) eq 'ARRAY') {
9695: foreach my $line (@{$dirlistref}) {
9696: my ($file_name,$rest) = split(/\&/,$line,2);
9697: $currfile{$file_name} = 1;
9698: }
9699: }
9700: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
9701: if (opendir(my $dir,$url)) {
9702: my @dir_list = grep(!/^\./,readdir($dir));
9703: map {$currfile{$_} = 1;} @dir_list;
9704: }
9705: } elsif (($actionurl eq '/adm/dependencies') ||
9706: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
9707: ($args->{'context'} eq 'paste'))) {
9708: if ($env{'request.course.id'} ne '') {
9709: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
9710: if ($dir ne '') {
9711: my ($dirlistref,$listerror) =
9712: &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
9713: if (ref($dirlistref) eq 'ARRAY') {
9714: foreach my $line (@{$dirlistref}) {
9715: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
9716: $size,undef,$mtime)=split(/\&/,$line,12);
9717: unless (($testdir&$dirptr) ||
9718: ($file_name =~ /^\.\.?$/)) {
9719: $currfile{$file_name} = [$size,$mtime];
9720: }
9721: }
9722: }
9723: }
9724: }
9725: }
9726: foreach my $file (keys(%dependencies)) {
9727: if (exists($currfile{$file})) {
9728: unless ($mapping{$file} eq $file) {
9729: $pathchanges{$file} = 1;
9730: }
9731: $existing{$file} = 1;
9732: $numexisting ++;
9733: } else {
9734: $newfiles{$file} = 1;
9735: }
9736: }
9737: foreach my $file (keys(%currfile)) {
9738: unless (($file eq $filename) ||
9739: ($file eq $filename.'.bak') ||
9740: ($dependencies{$file})) {
9741: if ($actionurl eq '/adm/dependencies') {
9742: next if (($rem ne '') &&
9743: (($env{"httpref.$rem".$file} ne '') ||
9744: (ref($navmap) &&
9745: (($navmap->getResourceByUrl($rem.$file) ne '') ||
9746: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
9747: ($navmap->getResourceByUrl($rem.$1)))))));
9748: }
9749: $unused{$file} = 1;
9750: }
9751: }
9752: if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
9753: ($args->{'context'} eq 'paste')) {
9754: $counter = scalar(keys(%existing));
9755: $numpathchg = scalar(keys(%pathchanges));
9756: return ($output,$counter,$numpathchg,\%existing);
9757: }
9758: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
9759: if ($actionurl eq '/adm/dependencies') {
9760: next if ($embed_file =~ m{^\w+://});
9761: }
9762: $upload_output .= &start_data_table_row().
9763: '<td><img src="'.&icon($embed_file).'" /> '.
9764: '<span class="LC_filename">'.$embed_file.'</span>';
9765: unless ($mapping{$embed_file} eq $embed_file) {
9766: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
9767: }
9768: $upload_output .= '</td><td>';
9769: if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) {
9770: $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
9771: $numremref++;
9772: } elsif ($args->{'error_on_invalid_names'}
9773: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
9774: $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
9775: $numinvalid++;
9776: } else {
9777: $upload_output .= &embedded_file_element('upload_embedded',$counter,
9778: $embed_file,\%mapping,
9779: $allfiles,$codebase,'upload');
9780: $counter ++;
9781: $numnew ++;
9782: }
9783: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
9784: }
9785: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
9786: if ($actionurl eq '/adm/dependencies') {
9787: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
9788: $modify_output .= &start_data_table_row().
9789: '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
9790: '<img src="'.&icon($embed_file).'" border="0" />'.
9791: ' <span class="LC_filename">'.$embed_file.'</span></a></td>'.
9792: '<td>'.$size.'</td>'.
9793: '<td>'.$mtime.'</td>'.
9794: '<td><label><input type="checkbox" name="mod_upload_dep" '.
9795: 'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
9796: $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
9797: '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
9798: &embedded_file_element('upload_embedded',$counter,
9799: $embed_file,\%mapping,
9800: $allfiles,$codebase,'modify').
9801: '</div></td>'.
9802: &end_data_table_row()."\n";
9803: $counter ++;
9804: } else {
9805: $upload_output .= &start_data_table_row().
9806: '<td><span class="LC_filename">'.$embed_file.'</span></td>';
9807: '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
9808: &Apache::loncommon::end_data_table_row()."\n";
9809: }
9810: }
9811: my $delidx = $counter;
9812: foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
9813: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
9814: $delete_output .= &start_data_table_row().
9815: '<td><img src="'.&icon($oldfile).'" />'.
9816: ' <span class="LC_filename">'.$oldfile.'</span></td>'.
9817: '<td>'.$size.'</td>'.
9818: '<td>'.$mtime.'</td>'.
9819: '<td><label><input type="checkbox" name="del_upload_dep" '.
9820: ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
9821: &embedded_file_element('upload_embedded',$delidx,
9822: $oldfile,\%mapping,$allfiles,
9823: $codebase,'delete').'</td>'.
9824: &end_data_table_row()."\n";
9825: $numunused ++;
9826: $delidx ++;
9827: }
9828: if ($upload_output) {
9829: $upload_output = &start_data_table().
9830: $upload_output.
9831: &end_data_table()."\n";
9832: }
9833: if ($modify_output) {
9834: $modify_output = &start_data_table().
9835: &start_data_table_header_row().
9836: '<th>'.&mt('File').'</th>'.
9837: '<th>'.&mt('Size (KB)').'</th>'.
9838: '<th>'.&mt('Modified').'</th>'.
9839: '<th>'.&mt('Upload replacement?').'</th>'.
9840: &end_data_table_header_row().
9841: $modify_output.
9842: &end_data_table()."\n";
9843: }
9844: if ($delete_output) {
9845: $delete_output = &start_data_table().
9846: &start_data_table_header_row().
9847: '<th>'.&mt('File').'</th>'.
9848: '<th>'.&mt('Size (KB)').'</th>'.
9849: '<th>'.&mt('Modified').'</th>'.
9850: '<th>'.&mt('Delete?').'</th>'.
9851: &end_data_table_header_row().
9852: $delete_output.
9853: &end_data_table()."\n";
9854: }
9855: my $applies = 0;
9856: if ($numremref) {
9857: $applies ++;
9858: }
9859: if ($numinvalid) {
9860: $applies ++;
9861: }
9862: if ($numexisting) {
9863: $applies ++;
9864: }
9865: if ($counter || $numunused) {
9866: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
9867: ' method="post" enctype="multipart/form-data">'."\n".
9868: $state.'<h3>'.$heading.'</h3>';
9869: if ($actionurl eq '/adm/dependencies') {
9870: if ($numnew) {
9871: $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
9872: '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
9873: $upload_output.'<br />'."\n";
9874: }
9875: if ($numexisting) {
9876: $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
9877: '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
9878: $modify_output.'<br />'."\n";
9879: $buttontext = &mt('Save changes');
9880: }
9881: if ($numunused) {
9882: $output .= '<h4>'.&mt('Unused files').'</h4>'.
9883: '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
9884: $delete_output.'<br />'."\n";
9885: $buttontext = &mt('Save changes');
9886: }
9887: } else {
9888: $output .= $upload_output.'<br />'."\n";
9889: }
9890: $output .= '<input type ="hidden" name="number_embedded_items" value="'.
9891: $counter.'" />'."\n";
9892: if ($actionurl eq '/adm/dependencies') {
9893: $output .= '<input type ="hidden" name="number_newemb_items" value="'.
9894: $numnew.'" />'."\n";
9895: } elsif ($actionurl eq '') {
9896: $output .= '<input type="hidden" name="phase" value="three" />';
9897: }
9898: } elsif ($applies) {
9899: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
9900: if ($applies > 1) {
9901: $output .=
9902: &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
9903: if ($numremref) {
9904: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
9905: }
9906: if ($numinvalid) {
9907: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
9908: }
9909: if ($numexisting) {
9910: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
9911: }
9912: $output .= '</ul><br />';
9913: } elsif ($numremref) {
9914: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
9915: } elsif ($numinvalid) {
9916: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
9917: } elsif ($numexisting) {
9918: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
9919: }
9920: $output .= $upload_output.'<br />';
9921: }
9922: my ($pathchange_output,$chgcount);
9923: $chgcount = $counter;
9924: if (keys(%pathchanges) > 0) {
9925: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
9926: if ($counter) {
9927: $output .= &embedded_file_element('pathchange',$chgcount,
9928: $embed_file,\%mapping,
9929: $allfiles,$codebase,'change');
9930: } else {
9931: $pathchange_output .=
9932: &start_data_table_row().
9933: '<td><input type ="checkbox" name="namechange" value="'.
9934: $chgcount.'" checked="checked" /></td>'.
9935: '<td>'.$mapping{$embed_file}.'</td>'.
9936: '<td>'.$embed_file.
9937: &embedded_file_element('pathchange',$numpathchg,$embed_file,
9938: \%mapping,$allfiles,$codebase,'change').
9939: '</td>'.&end_data_table_row();
9940: }
9941: $numpathchg ++;
9942: $chgcount ++;
9943: }
9944: }
9945: if ($counter) {
9946: if ($numpathchg) {
9947: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
9948: $numpathchg.'" />'."\n";
9949: }
9950: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
9951: ($actionurl eq '/adm/imsimport')) {
9952: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
9953: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
9954: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
9955: } elsif ($actionurl eq '/adm/dependencies') {
9956: $output .= '<input type="hidden" name="action" value="process_changes" />';
9957: }
9958: $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
9959: } elsif ($numpathchg) {
9960: my %pathchange = ();
9961: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
9962: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
9963: $output .= '<p>'.&mt('or').'</p>';
9964: }
9965: }
9966: return ($output,$counter,$numpathchg);
9967: }
9968:
9969: sub embedded_file_element {
9970: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
9971: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
9972: (ref($codebase) eq 'HASH'));
9973: my $output;
9974: if (($context eq 'upload_embedded') && ($type ne 'delete')) {
9975: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
9976: }
9977: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
9978: &escape($embed_file).'" />';
9979: unless (($context eq 'upload_embedded') &&
9980: ($mapping->{$embed_file} eq $embed_file)) {
9981: $output .='
9982: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
9983: }
9984: my $attrib;
9985: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
9986: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
9987: }
9988: $output .=
9989: "\n\t\t".
9990: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
9991: $attrib.'" />';
9992: if (exists($codebase->{$mapping->{$embed_file}})) {
9993: $output .=
9994: "\n\t\t".
9995: '<input name="codebase_'.$num.'" type="hidden" value="'.
9996: &escape($codebase->{$mapping->{$embed_file}}).'" />';
9997: }
9998: return $output;
9999: }
10000:
10001: sub get_dependency_details {
10002: my ($currfile,$currsubfile,$embed_file) = @_;
10003: my ($size,$mtime,$showsize,$showmtime);
10004: if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
10005: if ($embed_file =~ m{/}) {
10006: my ($path,$fname) = split(/\//,$embed_file);
10007: if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
10008: ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
10009: }
10010: } else {
10011: if (ref($currfile->{$embed_file}) eq 'ARRAY') {
10012: ($size,$mtime) = @{$currfile->{$embed_file}};
10013: }
10014: }
10015: $showsize = $size/1024.0;
10016: $showsize = sprintf("%.1f",$showsize);
10017: if ($mtime > 0) {
10018: $showmtime = &Apache::lonlocal::locallocaltime($mtime);
10019: }
10020: }
10021: return ($showsize,$showmtime);
10022: }
10023:
10024: sub ask_embedded_js {
10025: return <<"END";
10026: <script type="text/javascript"">
10027: // <![CDATA[
10028: function toggleBrowse(counter) {
10029: var chkboxid = document.getElementById('mod_upload_dep_'+counter);
10030: var fileid = document.getElementById('embedded_item_'+counter);
10031: var uploaddivid = document.getElementById('moduploaddep_'+counter);
10032: if (chkboxid.checked == true) {
10033: uploaddivid.style.display='block';
10034: } else {
10035: uploaddivid.style.display='none';
10036: fileid.value = '';
10037: }
10038: }
10039: // ]]>
10040: </script>
10041:
10042: END
10043: }
10044:
10045: sub upload_embedded {
10046: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
10047: $current_disk_usage,$hiddenstate,$actionurl) = @_;
10048: my (%pathchange,$output,$modifyform,$footer,$returnflag);
10049: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
10050: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
10051: my $orig_uploaded_filename =
10052: $env{'form.embedded_item_'.$i.'.filename'};
10053: foreach my $type ('orig','ref','attrib','codebase') {
10054: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
10055: $env{'form.embedded_'.$type.'_'.$i} =
10056: &unescape($env{'form.embedded_'.$type.'_'.$i});
10057: }
10058: }
10059: my ($path,$fname) =
10060: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
10061: # no path, whole string is fname
10062: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
10063: $fname = &Apache::lonnet::clean_filename($fname);
10064: # See if there is anything left
10065: next if ($fname eq '');
10066:
10067: # Check if file already exists as a file or directory.
10068: my ($state,$msg);
10069: if ($context eq 'portfolio') {
10070: my $port_path = $dirpath;
10071: if ($group ne '') {
10072: $port_path = "groups/$group/$port_path";
10073: }
10074: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
10075: $fname,$group,'embedded_item_'.$i,
10076: $dir_root,$port_path,$disk_quota,
10077: $current_disk_usage,$uname,$udom);
10078: if ($state eq 'will_exceed_quota'
10079: || $state eq 'file_locked') {
10080: $output .= $msg;
10081: next;
10082: }
10083: } elsif (($context eq 'author') || ($context eq 'testbank')) {
10084: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
10085: if ($state eq 'exists') {
10086: $output .= $msg;
10087: next;
10088: }
10089: }
10090: # Check if extension is valid
10091: if (($fname =~ /\.(\w+)$/) &&
10092: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10093: $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
10094: next;
10095: } elsif (($fname =~ /\.(\w+)$/) &&
10096: (!defined(&Apache::loncommon::fileembstyle($1)))) {
10097: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10098: next;
10099: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10100: $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10101: next;
10102: }
10103: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10104: if ($context eq 'portfolio') {
10105: my $result;
10106: if ($state eq 'existingfile') {
10107: $result=
10108: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10109: $dirpath.$env{'form.currentpath'}.$path);
10110: } else {
10111: $result=
10112: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10113: $dirpath.
10114: $env{'form.currentpath'}.$path);
10115: if ($result !~ m|^/uploaded/|) {
10116: $output .= '<span class="LC_error">'
10117: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10118: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10119: .'</span><br />';
10120: next;
10121: } else {
10122: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10123: $path.$fname.'</span>').'<br />';
10124: }
10125: }
10126: } elsif ($context eq 'coursedoc') {
10127: my $result =
10128: &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
10129: $dirpath.'/'.$path);
10130: if ($result !~ m|^/uploaded/|) {
10131: $output .= '<span class="LC_error">'
10132: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10133: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10134: .'</span><br />';
10135: next;
10136: } else {
10137: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10138: $path.$fname.'</span>').'<br />';
10139: }
10140: } else {
10141: # Save the file
10142: my $target = $env{'form.embedded_item_'.$i};
10143: my $fullpath = $dir_root.$dirpath.'/'.$path;
10144: my $dest = $fullpath.$fname;
10145: my $url = $url_root.$dirpath.'/'.$path.$fname;
10146: my @parts=split(/\//,"$dirpath/$path");
10147: my $count;
10148: my $filepath = $dir_root;
10149: foreach my $subdir (@parts) {
10150: $filepath .= "/$subdir";
10151: if (!-e $filepath) {
10152: mkdir($filepath,0770);
10153: }
10154: }
10155: my $fh;
10156: if (!open($fh,'>'.$dest)) {
10157: &Apache::lonnet::logthis('Failed to create '.$dest);
10158: $output .= '<span class="LC_error">'.
10159: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10160: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10161: '</span><br />';
10162: } else {
10163: if (!print $fh $env{'form.embedded_item_'.$i}) {
10164: &Apache::lonnet::logthis('Failed to write to '.$dest);
10165: $output .= '<span class="LC_error">'.
10166: &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10167: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10168: '</span><br />';
10169: } else {
10170: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10171: $url.'</span>').'<br />';
10172: unless ($context eq 'testbank') {
10173: $footer .= &mt('View embedded file: [_1]',
10174: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10175: }
10176: }
10177: close($fh);
10178: }
10179: }
10180: if ($env{'form.embedded_ref_'.$i}) {
10181: $pathchange{$i} = 1;
10182: }
10183: }
10184: if ($output) {
10185: $output = '<p>'.$output.'</p>';
10186: }
10187: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10188: $returnflag = 'ok';
10189: my $numpathchgs = scalar(keys(%pathchange));
10190: if ($numpathchgs > 0) {
10191: if ($context eq 'portfolio') {
10192: $output .= '<p>'.&mt('or').'</p>';
10193: } elsif ($context eq 'testbank') {
10194: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10195: '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10196: $returnflag = 'modify_orightml';
10197: }
10198: }
10199: return ($output.$footer,$returnflag,$numpathchgs);
10200: }
10201:
10202: sub modify_html_form {
10203: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10204: my $end = 0;
10205: my $modifyform;
10206: if ($context eq 'upload_embedded') {
10207: return unless (ref($pathchange) eq 'HASH');
10208: if ($env{'form.number_embedded_items'}) {
10209: $end += $env{'form.number_embedded_items'};
10210: }
10211: if ($env{'form.number_pathchange_items'}) {
10212: $end += $env{'form.number_pathchange_items'};
10213: }
10214: if ($end) {
10215: for (my $i=0; $i<$end; $i++) {
10216: if ($i < $env{'form.number_embedded_items'}) {
10217: next unless($pathchange->{$i});
10218: }
10219: $modifyform .=
10220: &start_data_table_row().
10221: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10222: 'checked="checked" /></td>'.
10223: '<td>'.$env{'form.embedded_ref_'.$i}.
10224: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10225: &escape($env{'form.embedded_ref_'.$i}).'" />'.
10226: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10227: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10228: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10229: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10230: '<td>'.$env{'form.embedded_orig_'.$i}.
10231: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10232: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10233: &end_data_table_row();
10234: }
10235: }
10236: } else {
10237: $modifyform = $pathchgtable;
10238: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10239: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10240: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10241: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10242: }
10243: }
10244: if ($modifyform) {
10245: if ($actionurl eq '/adm/dependencies') {
10246: $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10247: }
10248: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10249: '<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".
10250: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10251: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10252: '</ol></p>'."\n".'<p>'.
10253: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10254: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10255: &start_data_table()."\n".
10256: &start_data_table_header_row().
10257: '<th>'.&mt('Change?').'</th>'.
10258: '<th>'.&mt('Current reference').'</th>'.
10259: '<th>'.&mt('Required reference').'</th>'.
10260: &end_data_table_header_row()."\n".
10261: $modifyform.
10262: &end_data_table().'<br />'."\n".$hiddenstate.
10263: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10264: '</form>'."\n";
10265: }
10266: return;
10267: }
10268:
10269: sub modify_html_refs {
10270: my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
10271: my $container;
10272: if ($context eq 'portfolio') {
10273: $container = $env{'form.container'};
10274: } elsif ($context eq 'coursedoc') {
10275: $container = $env{'form.primaryurl'};
10276: } elsif ($context eq 'manage_dependencies') {
10277: (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10278: $container = "/$container";
10279: } else {
10280: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10281: }
10282: my (%allfiles,%codebase,$output,$content);
10283: my @changes = &get_env_multiple('form.namechange');
10284: unless (@changes > 0) {
10285: if (wantarray) {
10286: return ('',0,0);
10287: } else {
10288: return;
10289: }
10290: }
10291: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
10292: ($context eq 'manage_dependencies')) {
10293: unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10294: if (wantarray) {
10295: return ('',0,0);
10296: } else {
10297: return;
10298: }
10299: }
10300: $content = &Apache::lonnet::getfile($container);
10301: if ($content eq '-1') {
10302: if (wantarray) {
10303: return ('',0,0);
10304: } else {
10305: return;
10306: }
10307: }
10308: } else {
10309: unless ($container =~ /^\Q$dir_root\E/) {
10310: if (wantarray) {
10311: return ('',0,0);
10312: } else {
10313: return;
10314: }
10315: }
10316: if (open(my $fh,"<$container")) {
10317: $content = join('', <$fh>);
10318: close($fh);
10319: } else {
10320: if (wantarray) {
10321: return ('',0,0);
10322: } else {
10323: return;
10324: }
10325: }
10326: }
10327: my ($count,$codebasecount) = (0,0);
10328: my $mm = new File::MMagic;
10329: my $mime_type = $mm->checktype_contents($content);
10330: if ($mime_type eq 'text/html') {
10331: my $parse_result =
10332: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
10333: \%codebase,\$content);
10334: if ($parse_result eq 'ok') {
10335: foreach my $i (@changes) {
10336: my $orig = &unescape($env{'form.embedded_orig_'.$i});
10337: my $ref = &unescape($env{'form.embedded_ref_'.$i});
10338: if ($allfiles{$ref}) {
10339: my $newname = $orig;
10340: my ($attrib_regexp,$codebase);
10341: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
10342: if ($attrib_regexp =~ /:/) {
10343: $attrib_regexp =~ s/\:/|/g;
10344: }
10345: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10346: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10347: $count += $numchg;
10348: }
10349: if ($env{'form.embedded_codebase_'.$i} ne '') {
10350: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
10351: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
10352: $codebasecount ++;
10353: }
10354: }
10355: }
10356: if ($count || $codebasecount) {
10357: my $saveresult;
10358: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
10359: ($context eq 'manage_dependencies')) {
10360: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10361: if ($url eq $container) {
10362: my ($fname) = ($container =~ m{/([^/]+)$});
10363: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10364: $count,'<span class="LC_filename">'.
10365: $fname.'</span>').'</p>';
10366: } else {
10367: $output = '<p class="LC_error">'.
10368: &mt('Error: update failed for: [_1].',
10369: '<span class="LC_filename">'.
10370: $container.'</span>').'</p>';
10371: }
10372: } else {
10373: if (open(my $fh,">$container")) {
10374: print $fh $content;
10375: close($fh);
10376: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10377: $count,'<span class="LC_filename">'.
10378: $container.'</span>').'</p>';
10379: } else {
10380: $output = '<p class="LC_error">'.
10381: &mt('Error: could not update [_1].',
10382: '<span class="LC_filename">'.
10383: $container.'</span>').'</p>';
10384: }
10385: }
10386: }
10387: } else {
10388: &logthis('Failed to parse '.$container.
10389: ' to modify references: '.$parse_result);
10390: }
10391: }
10392: if (wantarray) {
10393: return ($output,$count,$codebasecount);
10394: } else {
10395: return $output;
10396: }
10397: }
10398:
10399: sub check_for_existing {
10400: my ($path,$fname,$element) = @_;
10401: my ($state,$msg);
10402: if (-d $path.'/'.$fname) {
10403: $state = 'exists';
10404: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10405: } elsif (-e $path.'/'.$fname) {
10406: $state = 'exists';
10407: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10408: }
10409: if ($state eq 'exists') {
10410: $msg = '<span class="LC_error">'.$msg.'</span><br />';
10411: }
10412: return ($state,$msg);
10413: }
10414:
10415: sub check_for_upload {
10416: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
10417: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
10418: my $filesize = length($env{'form.'.$element});
10419: if (!$filesize) {
10420: my $msg = '<span class="LC_error">'.
10421: &mt('Unable to upload [_1]. (size = [_2] bytes)',
10422: '<span class="LC_filename">'.$fname.'</span>',
10423: $filesize).'<br />'.
10424: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
10425: '</span>';
10426: return ('zero_bytes',$msg);
10427: }
10428: $filesize = $filesize/1000; #express in k (1024?)
10429: my $getpropath = 1;
10430: my ($dirlistref,$listerror) =
10431: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
10432: my $found_file = 0;
10433: my $locked_file = 0;
10434: my @lockers;
10435: my $navmap;
10436: if ($env{'request.course.id'}) {
10437: $navmap = Apache::lonnavmaps::navmap->new();
10438: }
10439: if (ref($dirlistref) eq 'ARRAY') {
10440: foreach my $line (@{$dirlistref}) {
10441: my ($file_name,$rest)=split(/\&/,$line,2);
10442: if ($file_name eq $fname){
10443: $file_name = $path.$file_name;
10444: if ($group ne '') {
10445: $file_name = $group.$file_name;
10446: }
10447: $found_file = 1;
10448: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
10449: foreach my $lock (@lockers) {
10450: if (ref($lock) eq 'ARRAY') {
10451: my ($symb,$crsid) = @{$lock};
10452: if ($crsid eq $env{'request.course.id'}) {
10453: if (ref($navmap)) {
10454: my $res = $navmap->getBySymb($symb);
10455: foreach my $part (@{$res->parts()}) {
10456: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
10457: unless (($slot_status == $res->RESERVED) ||
10458: ($slot_status == $res->RESERVED_LOCATION)) {
10459: $locked_file = 1;
10460: }
10461: }
10462: } else {
10463: $locked_file = 1;
10464: }
10465: } else {
10466: $locked_file = 1;
10467: }
10468: }
10469: }
10470: } else {
10471: my @info = split(/\&/,$rest);
10472: my $currsize = $info[6]/1000;
10473: if ($currsize < $filesize) {
10474: my $extra = $filesize - $currsize;
10475: if (($current_disk_usage + $extra) > $disk_quota) {
10476: my $msg = '<span class="LC_error">'.
10477: &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.',
10478: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
10479: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10480: $disk_quota,$current_disk_usage);
10481: return ('will_exceed_quota',$msg);
10482: }
10483: }
10484: }
10485: }
10486: }
10487: }
10488: if (($current_disk_usage + $filesize) > $disk_quota){
10489: my $msg = '<span class="LC_error">'.
10490: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
10491: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
10492: return ('will_exceed_quota',$msg);
10493: } elsif ($found_file) {
10494: if ($locked_file) {
10495: my $msg = '<span class="LC_error">';
10496: $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>');
10497: $msg .= '</span><br />';
10498: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
10499: return ('file_locked',$msg);
10500: } else {
10501: my $msg = '<span class="LC_error">';
10502: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
10503: $msg .= '</span>';
10504: return ('existingfile',$msg);
10505: }
10506: }
10507: }
10508:
10509: sub check_for_traversal {
10510: my ($path,$url,$toplevel) = @_;
10511: my @parts=split(/\//,$path);
10512: my $cleanpath;
10513: my $fullpath = $url;
10514: for (my $i=0;$i<@parts;$i++) {
10515: next if ($parts[$i] eq '.');
10516: if ($parts[$i] eq '..') {
10517: $fullpath =~ s{([^/]+/)$}{};
10518: } else {
10519: $fullpath .= $parts[$i].'/';
10520: }
10521: }
10522: if ($fullpath =~ /^\Q$url\E(.*)$/) {
10523: $cleanpath = $1;
10524: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
10525: my $curr_toprel = $1;
10526: my @parts = split(/\//,$curr_toprel);
10527: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
10528: my @urlparts = split(/\//,$url_toprel);
10529: my $doubledots;
10530: my $startdiff = -1;
10531: for (my $i=0; $i<@urlparts; $i++) {
10532: if ($startdiff == -1) {
10533: unless ($urlparts[$i] eq $parts[$i]) {
10534: $startdiff = $i;
10535: $doubledots .= '../';
10536: }
10537: } else {
10538: $doubledots .= '../';
10539: }
10540: }
10541: if ($startdiff > -1) {
10542: $cleanpath = $doubledots;
10543: for (my $i=$startdiff; $i<@parts; $i++) {
10544: $cleanpath .= $parts[$i].'/';
10545: }
10546: }
10547: }
10548: $cleanpath =~ s{(/)$}{};
10549: return $cleanpath;
10550: }
10551:
10552: sub is_archive_file {
10553: my ($mimetype) = @_;
10554: if (($mimetype eq 'application/octet-stream') ||
10555: ($mimetype eq 'application/x-stuffit') ||
10556: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
10557: return 1;
10558: }
10559: return;
10560: }
10561:
10562: sub decompress_form {
10563: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
10564: my %lt = &Apache::lonlocal::texthash (
10565: this => 'This file is an archive file.',
10566: camt => 'This file is a Camtasia archive file.',
10567: itsc => 'Its contents are as follows:',
10568: youm => 'You may wish to extract its contents.',
10569: extr => 'Extract contents',
10570: auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
10571: proa => 'Process automatically?',
10572: yes => 'Yes',
10573: no => 'No',
10574: fold => 'Title for folder containing movie',
10575: movi => 'Title for page containing embedded movie',
10576: );
10577: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
10578: my ($is_camtasia,$topdir,%toplevel,@paths);
10579: my $info = &list_archive_contents($fileloc,\@paths);
10580: if (@paths) {
10581: foreach my $path (@paths) {
10582: $path =~ s{^/}{};
10583: if ($path =~ m{^([^/]+)/$}) {
10584: $topdir = $1;
10585: }
10586: if ($path =~ m{^([^/]+)/}) {
10587: $toplevel{$1} = $path;
10588: } else {
10589: $toplevel{$path} = $path;
10590: }
10591: }
10592: }
10593: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
10594: my @camtasia = ("$topdir/","$topdir/index.html",
10595: "$topdir/media/",
10596: "$topdir/media/$topdir.mp4",
10597: "$topdir/media/FirstFrame.png",
10598: "$topdir/media/player.swf",
10599: "$topdir/media/swfobject.js",
10600: "$topdir/media/expressInstall.swf");
10601: my @diffs = &compare_arrays(\@paths,\@camtasia);
10602: if (@diffs == 0) {
10603: $is_camtasia = 1;
10604: }
10605: }
10606: my $output;
10607: if ($is_camtasia) {
10608: $output = <<"ENDCAM";
10609: <script type="text/javascript" language="Javascript">
10610: // <![CDATA[
10611:
10612: function camtasiaToggle() {
10613: for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
10614: if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
10615: if (document.uploaded_decompress.autoextract_camtasia[i].value == 1) {
10616:
10617: document.getElementById('camtasia_titles').style.display='block';
10618: } else {
10619: document.getElementById('camtasia_titles').style.display='none';
10620: }
10621: }
10622: }
10623: return;
10624: }
10625:
10626: // ]]>
10627: </script>
10628: <p>$lt{'camt'}</p>
10629: ENDCAM
10630: } else {
10631: $output = '<p>'.$lt{'this'};
10632: if ($info eq '') {
10633: $output .= ' '.$lt{'youm'}.'</p>'."\n";
10634: } else {
10635: $output .= ' '.$lt{'itsc'}.'</p>'."\n".
10636: '<div><pre>'.$info.'</pre></div>';
10637: }
10638: }
10639: $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
10640: my $duplicates;
10641: my $num = 0;
10642: if (ref($dirlist) eq 'ARRAY') {
10643: foreach my $item (@{$dirlist}) {
10644: if (ref($item) eq 'ARRAY') {
10645: if (exists($toplevel{$item->[0]})) {
10646: $duplicates .=
10647: &start_data_table_row().
10648: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
10649: 'value="0" checked="checked" />'.&mt('No').'</label>'.
10650: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '.
10651: 'value="1" />'.&mt('Yes').'</label>'.
10652: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
10653: '<td>'.$item->[0].'</td>';
10654: if ($item->[2]) {
10655: $duplicates .= '<td>'.&mt('Directory').'</td>';
10656: } else {
10657: $duplicates .= '<td>'.&mt('File').'</td>';
10658: }
10659: $duplicates .= '<td>'.$item->[3].'</td>'.
10660: '<td>'.
10661: &Apache::lonlocal::locallocaltime($item->[4]).
10662: '</td>'.
10663: &end_data_table_row();
10664: $num ++;
10665: }
10666: }
10667: }
10668: }
10669: my $itemcount;
10670: if (@paths > 0) {
10671: $itemcount = scalar(@paths);
10672: } else {
10673: $itemcount = 1;
10674: }
10675: if ($is_camtasia) {
10676: $output .= $lt{'auto'}.'<br />'.
10677: '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
10678: '<input type="radio" name="autoextract_camtasia" value="1" onclick="javascript:camtasiaToggle();" checked="checked" />'.
10679: $lt{'yes'}.'</label> <label>'.
10680: '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
10681: $lt{'no'}.'</label></span><br />'.
10682: '<div id="camtasia_titles" style="display:block">'.
10683: &Apache::lonhtmlcommon::start_pick_box().
10684: &Apache::lonhtmlcommon::row_title($lt{'fold'}).
10685: '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
10686: &Apache::lonhtmlcommon::row_closure().
10687: &Apache::lonhtmlcommon::row_title($lt{'movi'}).
10688: '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
10689: &Apache::lonhtmlcommon::row_closure(1).
10690: &Apache::lonhtmlcommon::end_pick_box().
10691: '</div>';
10692: }
10693: $output .=
10694: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
10695: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
10696: "\n";
10697: if ($duplicates ne '') {
10698: $output .= '<p><span class="LC_warning">'.
10699: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.
10700: &start_data_table().
10701: &start_data_table_header_row().
10702: '<th>'.&mt('Overwrite?').'</th>'.
10703: '<th>'.&mt('Name').'</th>'.
10704: '<th>'.&mt('Type').'</th>'.
10705: '<th>'.&mt('Size').'</th>'.
10706: '<th>'.&mt('Last modified').'</th>'.
10707: &end_data_table_header_row().
10708: $duplicates.
10709: &end_data_table().
10710: '</p>';
10711: }
10712: $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
10713: if (ref($hiddenelements) eq 'HASH') {
10714: foreach my $hidden (sort(keys(%{$hiddenelements}))) {
10715: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
10716: }
10717: }
10718: $output .= <<"END";
10719: <br />
10720: <input type="submit" name="decompress" value="$lt{'extr'}" />
10721: </form>
10722: $noextract
10723: END
10724: return $output;
10725: }
10726:
10727: sub decompression_utility {
10728: my ($program) = @_;
10729: my @utilities = ('tar','gunzip','bunzip2','unzip');
10730: my $location;
10731: if (grep(/^\Q$program\E$/,@utilities)) {
10732: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
10733: '/usr/sbin/') {
10734: if (-x $dir.$program) {
10735: $location = $dir.$program;
10736: last;
10737: }
10738: }
10739: }
10740: return $location;
10741: }
10742:
10743: sub list_archive_contents {
10744: my ($file,$pathsref) = @_;
10745: my (@cmd,$output);
10746: my $needsregexp;
10747: if ($file =~ /\.zip$/) {
10748: @cmd = (&decompression_utility('unzip'),"-l");
10749: $needsregexp = 1;
10750: } elsif (($file =~ m/\.tar\.gz$/) ||
10751: ($file =~ /\.tgz$/)) {
10752: @cmd = (&decompression_utility('tar'),"-ztf");
10753: } elsif ($file =~ /\.tar\.bz2$/) {
10754: @cmd = (&decompression_utility('tar'),"-jtf");
10755: } elsif ($file =~ m|\.tar$|) {
10756: @cmd = (&decompression_utility('tar'),"-tf");
10757: }
10758: if (@cmd) {
10759: undef($!);
10760: undef($@);
10761: if (open(my $fh,"-|", @cmd, $file)) {
10762: while (my $line = <$fh>) {
10763: $output .= $line;
10764: chomp($line);
10765: my $item;
10766: if ($needsregexp) {
10767: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/);
10768: } else {
10769: $item = $line;
10770: }
10771: if ($item ne '') {
10772: unless (grep(/^\Q$item\E$/,@{$pathsref})) {
10773: push(@{$pathsref},$item);
10774: }
10775: }
10776: }
10777: close($fh);
10778: }
10779: }
10780: return $output;
10781: }
10782:
10783: sub decompress_uploaded_file {
10784: my ($file,$dir) = @_;
10785: &Apache::lonnet::appenv({'cgi.file' => $file});
10786: &Apache::lonnet::appenv({'cgi.dir' => $dir});
10787: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
10788: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
10789: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
10790: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
10791: my $decompressed = $env{'cgi.decompressed'};
10792: &Apache::lonnet::delenv('cgi.file');
10793: &Apache::lonnet::delenv('cgi.dir');
10794: &Apache::lonnet::delenv('cgi.decompressed');
10795: return ($decompressed,$result);
10796: }
10797:
10798: sub process_decompression {
10799: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
10800: my ($dir,$error,$warning,$output);
10801: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
10802: $error = &mt('File name not a supported archive file type.').
10803: '<br />'.&mt('File name should end with one of: [_1].',
10804: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
10805: } else {
10806: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
10807: if ($docuhome eq 'no_host') {
10808: $error = &mt('Could not determine home server for course.');
10809: } else {
10810: my @ids=&Apache::lonnet::current_machine_ids();
10811: my $currdir = "$dir_root/$destination";
10812: if (grep(/^\Q$docuhome\E$/,@ids)) {
10813: $dir = &LONCAPA::propath($docudom,$docuname).
10814: "$dir_root/$destination";
10815: } else {
10816: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
10817: "$dir_root/$docudom/$docuname/$destination";
10818: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
10819: $error = &mt('Archive file not found.');
10820: }
10821: }
10822: my (@to_overwrite,@to_skip);
10823: if ($env{'form.archive_overwrite_total'} > 0) {
10824: my $total = $env{'form.archive_overwrite_total'};
10825: for (my $i=0; $i<$total; $i++) {
10826: if ($env{'form.archive_overwrite_'.$i} == 1) {
10827: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
10828: } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
10829: push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
10830: }
10831: }
10832: }
10833: my $numskip = scalar(@to_skip);
10834: if (($numskip > 0) &&
10835: ($numskip == $env{'form.archive_itemcount'})) {
10836: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');
10837: } elsif ($dir eq '') {
10838: $error = &mt('Directory containing archive file unavailable.');
10839: } elsif (!$error) {
10840: my ($decompressed,$display);
10841: if ($numskip > 0) {
10842: my $tempdir = time.'_'.$$.int(rand(10000));
10843: mkdir("$dir/$tempdir",0755);
10844: system("mv $dir/$file $dir/$tempdir/$file");
10845: ($decompressed,$display) =
10846: &decompress_uploaded_file($file,"$dir/$tempdir");
10847: foreach my $item (@to_skip) {
10848: if (($item ne '') && ($item !~ /\.\./)) {
10849: if (-f "$dir/$tempdir/$item") {
10850: unlink("$dir/$tempdir/$item");
10851: } elsif (-d "$dir/$tempdir/$item") {
10852: system("rm -rf $dir/$tempdir/$item");
10853: }
10854: }
10855: }
10856: system("mv $dir/$tempdir/* $dir");
10857: rmdir("$dir/$tempdir");
10858: } else {
10859: ($decompressed,$display) =
10860: &decompress_uploaded_file($file,$dir);
10861: }
10862: if ($decompressed eq 'ok') {
10863: $output = '<p class="LC_info">'.
10864: &mt('Files extracted successfully from archive.').
10865: '</p>'."\n";
10866: my ($warning,$result,@contents);
10867: my ($newdirlistref,$newlisterror) =
10868: &Apache::lonnet::dirlist($currdir,$docudom,
10869: $docuname,1);
10870: my (%is_dir,%changes,@newitems);
10871: my $dirptr = 16384;
10872: if (ref($newdirlistref) eq 'ARRAY') {
10873: foreach my $dir_line (@{$newdirlistref}) {
10874: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
10875: unless (($item =~ /^\.+$/) || ($item eq $file) ||
10876: ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
10877: push(@newitems,$item);
10878: if ($dirptr&$testdir) {
10879: $is_dir{$item} = 1;
10880: }
10881: $changes{$item} = 1;
10882: }
10883: }
10884: }
10885: if (keys(%changes) > 0) {
10886: foreach my $item (sort(@newitems)) {
10887: if ($changes{$item}) {
10888: push(@contents,$item);
10889: }
10890: }
10891: }
10892: if (@contents > 0) {
10893: my $wantform;
10894: unless ($env{'form.autoextract_camtasia'}) {
10895: $wantform = 1;
10896: }
10897: my (%children,%parent,%dirorder,%titles);
10898: my ($count,$datatable) = &get_extracted($docudom,$docuname,
10899: $currdir,\%is_dir,
10900: \%children,\%parent,
10901: \@contents,\%dirorder,
10902: \%titles,$wantform);
10903: if ($datatable ne '') {
10904: $output .= &archive_options_form('decompressed',$datatable,
10905: $count,$hiddenelem);
10906: my $startcount = 6;
10907: $output .= &archive_javascript($startcount,$count,
10908: \%titles,\%children);
10909: }
10910: if ($env{'form.autoextract_camtasia'}) {
10911: my %displayed;
10912: my $total = 1;
10913: $env{'form.archive_directory'} = [];
10914: foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
10915: my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
10916: $path =~ s{/$}{};
10917: my $item;
10918: if ($path ne '') {
10919: $item = "$path/$titles{$i}";
10920: } else {
10921: $item = $titles{$i};
10922: }
10923: $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
10924: if ($item eq $contents[0]) {
10925: push(@{$env{'form.archive_directory'}},$i);
10926: $env{'form.archive_'.$i} = 'display';
10927: $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
10928: $displayed{'folder'} = $i;
10929: } elsif ($item eq "$contents[0]/index.html") {
10930: $env{'form.archive_'.$i} = 'display';
10931: $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
10932: $displayed{'web'} = $i;
10933: } else {
10934: if ($item eq "$contents[0]/media") {
10935: push(@{$env{'form.archive_directory'}},$i);
10936: }
10937: $env{'form.archive_'.$i} = 'dependency';
10938: }
10939: $total ++;
10940: }
10941: for (my $i=1; $i<$total; $i++) {
10942: next if ($i == $displayed{'web'});
10943: next if ($i == $displayed{'folder'});
10944: $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
10945: }
10946: $env{'form.phase'} = 'decompress_cleanup';
10947: $env{'form.archivedelete'} = 1;
10948: $env{'form.archive_count'} = $total-1;
10949: $output .=
10950: &process_extracted_files('coursedocs',$docudom,
10951: $docuname,$destination,
10952: $dir_root,$hiddenelem);
10953: }
10954: } else {
10955: $warning = &mt('No new items extracted from archive file.');
10956: }
10957: } else {
10958: $output = $display;
10959: $error = &mt('An error occurred during extraction from the archive file.');
10960: }
10961: }
10962: }
10963: }
10964: if ($error) {
10965: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
10966: $error.'</p>'."\n";
10967: }
10968: if ($warning) {
10969: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
10970: }
10971: return $output;
10972: }
10973:
10974: sub get_extracted {
10975: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
10976: $titles,$wantform) = @_;
10977: my $count = 0;
10978: my $depth = 0;
10979: my $datatable;
10980: my @hierarchy;
10981: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
10982: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
10983: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
10984: foreach my $item (@{$contents}) {
10985: $count ++;
10986: @{$dirorder->{$count}} = @hierarchy;
10987: $titles->{$count} = $item;
10988: &archive_hierarchy($depth,$count,$parent,$children);
10989: if ($wantform) {
10990: $datatable .= &archive_row($is_dir->{$item},$item,
10991: $currdir,$depth,$count);
10992: }
10993: if ($is_dir->{$item}) {
10994: $depth ++;
10995: push(@hierarchy,$count);
10996: $parent->{$depth} = $count;
10997: $datatable .=
10998: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
10999: \$depth,\$count,\@hierarchy,$dirorder,
11000: $children,$parent,$titles,$wantform);
11001: $depth --;
11002: pop(@hierarchy);
11003: }
11004: }
11005: return ($count,$datatable);
11006: }
11007:
11008: sub recurse_extracted_archive {
11009: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
11010: $children,$parent,$titles,$wantform) = @_;
11011: my $result='';
11012: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
11013: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
11014: (ref($dirorder) eq 'HASH')) {
11015: return $result;
11016: }
11017: my $dirptr = 16384;
11018: my ($newdirlistref,$newlisterror) =
11019: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
11020: if (ref($newdirlistref) eq 'ARRAY') {
11021: foreach my $dir_line (@{$newdirlistref}) {
11022: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11023: unless ($item =~ /^\.+$/) {
11024: $$count ++;
11025: @{$dirorder->{$$count}} = @{$hierarchy};
11026: $titles->{$$count} = $item;
11027: &archive_hierarchy($$depth,$$count,$parent,$children);
11028:
11029: my $is_dir;
11030: if ($dirptr&$testdir) {
11031: $is_dir = 1;
11032: }
11033: if ($wantform) {
11034: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
11035: }
11036: if ($is_dir) {
11037: $$depth ++;
11038: push(@{$hierarchy},$$count);
11039: $parent->{$$depth} = $$count;
11040: $result .=
11041: &recurse_extracted_archive("$currdir/$item",$docudom,
11042: $docuname,$depth,$count,
11043: $hierarchy,$dirorder,$children,
11044: $parent,$titles,$wantform);
11045: $$depth --;
11046: pop(@{$hierarchy});
11047: }
11048: }
11049: }
11050: }
11051: return $result;
11052: }
11053:
11054: sub archive_hierarchy {
11055: my ($depth,$count,$parent,$children) =@_;
11056: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
11057: if (exists($parent->{$depth})) {
11058: $children->{$parent->{$depth}} .= $count.':';
11059: }
11060: }
11061: return;
11062: }
11063:
11064: sub archive_row {
11065: my ($is_dir,$item,$currdir,$depth,$count) = @_;
11066: my ($name) = ($item =~ m{([^/]+)$});
11067: my %choices = &Apache::lonlocal::texthash (
11068: 'display' => 'Add as file',
11069: 'dependency' => 'Include as dependency',
11070: 'discard' => 'Discard',
11071: );
11072: if ($is_dir) {
11073: $choices{'display'} = &mt('Add as folder');
11074: }
11075: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
11076: my $offset = 0;
11077: foreach my $action ('display','dependency','discard') {
11078: $offset ++;
11079: if ($action ne 'display') {
11080: $offset ++;
11081: }
11082: $output .= '<td><span class="LC_nobreak">'.
11083: '<label><input type="radio" name="archive_'.$count.
11084: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
11085: my $text = $choices{$action};
11086: if ($is_dir) {
11087: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
11088: if ($action eq 'display') {
11089: $text = &mt('Add as folder');
11090: }
11091: } else {
11092: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
11093:
11094: }
11095: $output .= ' /> '.$choices{$action}.'</label></span>';
11096: if ($action eq 'dependency') {
11097: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
11098: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '.
11099: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
11100: '<option value=""></option>'."\n".
11101: '</select>'."\n".
11102: '</div>';
11103: } elsif ($action eq 'display') {
11104: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11105: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11106: '</div>';
11107: }
11108: $output .= '</td>';
11109: }
11110: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11111: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2);
11112: for (my $i=0; $i<$depth; $i++) {
11113: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11114: }
11115: if ($is_dir) {
11116: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n".
11117: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11118: } else {
11119: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11120: }
11121: $output .= ' '.$name.'</td>'."\n".
11122: &end_data_table_row();
11123: return $output;
11124: }
11125:
11126: sub archive_options_form {
11127: my ($form,$display,$count,$hiddenelem) = @_;
11128: my %lt = &Apache::lonlocal::texthash(
11129: perm => 'Permanently remove archive file?',
11130: hows => 'How should each extracted item be incorporated in the course?',
11131: cont => 'Content actions for all',
11132: addf => 'Add as folder/file',
11133: incd => 'Include as dependency for a displayed file',
11134: disc => 'Discard',
11135: no => 'No',
11136: yes => 'Yes',
11137: save => 'Save',
11138: );
11139: my $output = <<"END";
11140: <form name="$form" method="post" action="">
11141: <p><span class="LC_nobreak">$lt{'perm'}
11142: <label>
11143: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11144: </label>
11145:
11146: <label>
11147: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11148: </span>
11149: </p>
11150: <input type="hidden" name="phase" value="decompress_cleanup" />
11151: <br />$lt{'hows'}
11152: <div class="LC_columnSection">
11153: <fieldset>
11154: <legend>$lt{'cont'}</legend>
11155: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" />
11156: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11157: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11158: </fieldset>
11159: </div>
11160: END
11161: return $output.
11162: &start_data_table()."\n".
11163: $display."\n".
11164: &end_data_table()."\n".
11165: '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11166: $hiddenelem.
11167: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11168: '</form>';
11169: }
11170:
11171: sub archive_javascript {
11172: my ($startcount,$numitems,$titles,$children) = @_;
11173: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11174: my $maintitle = $env{'form.comment'};
11175: my $scripttag = <<START;
11176: <script type="text/javascript">
11177: // <![CDATA[
11178:
11179: function checkAll(form,prefix) {
11180: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$");
11181: for (var i=0; i < form.elements.length; i++) {
11182: var id = form.elements[i].id;
11183: if ((id != '') && (id != undefined)) {
11184: if (idstr.test(id)) {
11185: if (form.elements[i].type == 'radio') {
11186: form.elements[i].checked = true;
11187: var nostart = i-$startcount;
11188: var offset = nostart%7;
11189: var count = (nostart-offset)/7;
11190: dependencyCheck(form,count,offset);
11191: }
11192: }
11193: }
11194: }
11195: }
11196:
11197: function propagateCheck(form,count) {
11198: if (count > 0) {
11199: var startelement = $startcount + ((count-1) * 7);
11200: for (var j=1; j<6; j++) {
11201: if ((j != 2) && (j != 4)) {
11202: var item = startelement + j;
11203: if (form.elements[item].type == 'radio') {
11204: if (form.elements[item].checked) {
11205: containerCheck(form,count,j);
11206: break;
11207: }
11208: }
11209: }
11210: }
11211: }
11212: }
11213:
11214: numitems = $numitems
11215: var titles = new Array(numitems);
11216: var parents = new Array(numitems);
11217: for (var i=0; i<numitems; i++) {
11218: parents[i] = new Array;
11219: }
11220: var maintitle = '$maintitle';
11221:
11222: START
11223:
11224: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
11225: my @contents = split(/:/,$children->{$container});
11226: for (my $i=0; $i<@contents; $i ++) {
11227: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
11228: }
11229: }
11230:
11231: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
11232: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
11233: }
11234:
11235: $scripttag .= <<END;
11236:
11237: function containerCheck(form,count,offset) {
11238: if (count > 0) {
11239: dependencyCheck(form,count,offset);
11240: var item = (offset+$startcount)+7*(count-1);
11241: form.elements[item].checked = true;
11242: if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
11243: if (parents[count].length > 0) {
11244: for (var j=0; j<parents[count].length; j++) {
11245: containerCheck(form,parents[count][j],offset);
11246: }
11247: }
11248: }
11249: }
11250: }
11251:
11252: function dependencyCheck(form,count,offset) {
11253: if (count > 0) {
11254: var chosen = (offset+$startcount)+7*(count-1);
11255: var depitem = $startcount + ((count-1) * 7) + 4;
11256: var currtype = form.elements[depitem].type;
11257: if (form.elements[chosen].value == 'dependency') {
11258: document.getElementById('arc_depon_'+count).style.display='block';
11259: form.elements[depitem].options.length = 0;
11260: form.elements[depitem].options[0] = new Option('Select','',true,true);
11261: for (var i=1; i<=numitems; i++) {
11262: if (i == count) {
11263: continue;
11264: }
11265: var startelement = $startcount + (i-1) * 7;
11266: for (var j=1; j<6; j++) {
11267: if ((j != 2) && (j!= 4)) {
11268: var item = startelement + j;
11269: if (form.elements[item].type == 'radio') {
11270: if (form.elements[item].checked) {
11271: if (form.elements[item].value == 'display') {
11272: var n = form.elements[depitem].options.length;
11273: form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
11274: }
11275: }
11276: }
11277: }
11278: }
11279: }
11280: } else {
11281: document.getElementById('arc_depon_'+count).style.display='none';
11282: form.elements[depitem].options.length = 0;
11283: form.elements[depitem].options[0] = new Option('Select','',true,true);
11284: }
11285: titleCheck(form,count,offset);
11286: }
11287: }
11288:
11289: function propagateSelect(form,count,offset) {
11290: if (count > 0) {
11291: var item = (1+offset+$startcount)+7*(count-1);
11292: var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
11293: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11294: if (parents[count].length > 0) {
11295: for (var j=0; j<parents[count].length; j++) {
11296: containerSelect(form,parents[count][j],offset,picked);
11297: }
11298: }
11299: }
11300: }
11301: }
11302:
11303: function containerSelect(form,count,offset,picked) {
11304: if (count > 0) {
11305: var item = (offset+$startcount)+7*(count-1);
11306: if (form.elements[item].type == 'radio') {
11307: if (form.elements[item].value == 'dependency') {
11308: if (form.elements[item+1].type == 'select-one') {
11309: for (var i=0; i<form.elements[item+1].options.length; i++) {
11310: if (form.elements[item+1].options[i].value == picked) {
11311: form.elements[item+1].selectedIndex = i;
11312: break;
11313: }
11314: }
11315: }
11316: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11317: if (parents[count].length > 0) {
11318: for (var j=0; j<parents[count].length; j++) {
11319: containerSelect(form,parents[count][j],offset,picked);
11320: }
11321: }
11322: }
11323: }
11324: }
11325: }
11326: }
11327:
11328: function titleCheck(form,count,offset) {
11329: if (count > 0) {
11330: var chosen = (offset+$startcount)+7*(count-1);
11331: var depitem = $startcount + ((count-1) * 7) + 2;
11332: var currtype = form.elements[depitem].type;
11333: if (form.elements[chosen].value == 'display') {
11334: document.getElementById('arc_title_'+count).style.display='block';
11335: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
11336: document.getElementById('archive_title_'+count).value=maintitle;
11337: }
11338: } else {
11339: document.getElementById('arc_title_'+count).style.display='none';
11340: if (currtype == 'text') {
11341: document.getElementById('archive_title_'+count).value='';
11342: }
11343: }
11344: }
11345: return;
11346: }
11347:
11348: // ]]>
11349: </script>
11350: END
11351: return $scripttag;
11352: }
11353:
11354: sub process_extracted_files {
11355: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
11356: my $numitems = $env{'form.archive_count'};
11357: return unless ($numitems);
11358: my @ids=&Apache::lonnet::current_machine_ids();
11359: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
11360: %folders,%containers,%mapinner,%prompttofetch);
11361: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11362: if (grep(/^\Q$docuhome\E$/,@ids)) {
11363: $prefix = &LONCAPA::propath($docudom,$docuname);
11364: $pathtocheck = "$dir_root/$destination";
11365: $dir = $dir_root;
11366: $ishome = 1;
11367: } else {
11368: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
11369: $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
11370: $dir = "$dir_root/$docudom/$docuname";
11371: }
11372: my $currdir = "$dir_root/$destination";
11373: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
11374: if ($env{'form.folderpath'}) {
11375: my @items = split('&',$env{'form.folderpath'});
11376: $folders{'0'} = $items[-2];
11377: if ($env{'form.folderpath'} =~ /\:1$/) {
11378: $containers{'0'}='page';
11379: } else {
11380: $containers{'0'}='sequence';
11381: }
11382: }
11383: my @archdirs = &get_env_multiple('form.archive_directory');
11384: if ($numitems) {
11385: for (my $i=1; $i<=$numitems; $i++) {
11386: my $path = $env{'form.archive_content_'.$i};
11387: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
11388: my $item = $1;
11389: $toplevelitems{$item} = $i;
11390: if (grep(/^\Q$i\E$/,@archdirs)) {
11391: $is_dir{$item} = 1;
11392: }
11393: }
11394: }
11395: }
11396: my ($output,%children,%parent,%titles,%dirorder,$result);
11397: if (keys(%toplevelitems) > 0) {
11398: my @contents = sort(keys(%toplevelitems));
11399: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
11400: \%parent,\@contents,\%dirorder,\%titles);
11401: }
11402: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
11403: if ($numitems) {
11404: for (my $i=1; $i<=$numitems; $i++) {
11405: next if ($env{'form.archive_'.$i} eq 'dependency');
11406: my $path = $env{'form.archive_content_'.$i};
11407: if ($path =~ /^\Q$pathtocheck\E/) {
11408: if ($env{'form.archive_'.$i} eq 'discard') {
11409: if ($prefix ne '' && $path ne '') {
11410: if (-e $prefix.$path) {
11411: if ((@archdirs > 0) &&
11412: (grep(/^\Q$i\E$/,@archdirs))) {
11413: $todeletedir{$prefix.$path} = 1;
11414: } else {
11415: $todelete{$prefix.$path} = 1;
11416: }
11417: }
11418: }
11419: } elsif ($env{'form.archive_'.$i} eq 'display') {
11420: my ($docstitle,$title,$url,$outer);
11421: ($title) = ($path =~ m{/([^/]+)$});
11422: $docstitle = $env{'form.archive_title_'.$i};
11423: if ($docstitle eq '') {
11424: $docstitle = $title;
11425: }
11426: $outer = 0;
11427: if (ref($dirorder{$i}) eq 'ARRAY') {
11428: if (@{$dirorder{$i}} > 0) {
11429: foreach my $item (reverse(@{$dirorder{$i}})) {
11430: if ($env{'form.archive_'.$item} eq 'display') {
11431: $outer = $item;
11432: last;
11433: }
11434: }
11435: }
11436: }
11437: my ($errtext,$fatal) =
11438: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
11439: '/'.$folders{$outer}.'.'.
11440: $containers{$outer});
11441: next if ($fatal);
11442: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
11443: if ($context eq 'coursedocs') {
11444: $mapinner{$i} = time;
11445: $folders{$i} = 'default_'.$mapinner{$i};
11446: $containers{$i} = 'sequence';
11447: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11448: $folders{$i}.'.'.$containers{$i};
11449: my $newidx = &LONCAPA::map::getresidx();
11450: $LONCAPA::map::resources[$newidx]=
11451: $docstitle.':'.$url.':false:normal:res';
11452: push(@LONCAPA::map::order,$newidx);
11453: my ($outtext,$errtext) =
11454: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11455: $docuname.'/'.$folders{$outer}.
11456: '.'.$containers{$outer},1,1);
11457: $newseqid{$i} = $newidx;
11458: unless ($errtext) {
11459: $result .= '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
11460: }
11461: }
11462: } else {
11463: if ($context eq 'coursedocs') {
11464: my $newidx=&LONCAPA::map::getresidx();
11465: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11466: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
11467: $title;
11468: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
11469: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
11470: }
11471: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11472: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
11473: }
11474: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11475: system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
11476: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
11477: unless ($ishome) {
11478: my $fetch = "$newdest{$i}/$title";
11479: $fetch =~ s/^\Q$prefix$dir\E//;
11480: $prompttofetch{$fetch} = 1;
11481: }
11482: }
11483: $LONCAPA::map::resources[$newidx]=
11484: $docstitle.':'.$url.':false:normal:res';
11485: push(@LONCAPA::map::order, $newidx);
11486: my ($outtext,$errtext)=
11487: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11488: $docuname.'/'.$folders{$outer}.
11489: '.'.$containers{$outer},1,1);
11490: unless ($errtext) {
11491: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
11492: $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
11493: }
11494: }
11495: }
11496: }
11497: }
11498: } else {
11499: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
11500: }
11501: }
11502: for (my $i=1; $i<=$numitems; $i++) {
11503: next unless ($env{'form.archive_'.$i} eq 'dependency');
11504: my $path = $env{'form.archive_content_'.$i};
11505: if ($path =~ /^\Q$pathtocheck\E/) {
11506: my ($title) = ($path =~ m{/([^/]+)$});
11507: $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
11508: if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
11509: if (ref($dirorder{$i}) eq 'ARRAY') {
11510: my ($itemidx,$fullpath,$relpath);
11511: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
11512: my $container = $dirorder{$referrer{$i}}->[-1];
11513: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
11514: if ($dirorder{$i}->[$j] eq $container) {
11515: $itemidx = $j;
11516: }
11517: }
11518: }
11519: if ($itemidx eq '') {
11520: $itemidx = 0;
11521: }
11522: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
11523: if ($mapinner{$referrer{$i}}) {
11524: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
11525: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11526: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11527: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11528: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11529: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11530: if (!-e $fullpath) {
11531: mkdir($fullpath,0755);
11532: }
11533: }
11534: } else {
11535: last;
11536: }
11537: }
11538: }
11539: } elsif ($newdest{$referrer{$i}}) {
11540: $fullpath = $newdest{$referrer{$i}};
11541: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11542: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
11543: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
11544: last;
11545: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11546: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11547: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11548: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11549: if (!-e $fullpath) {
11550: mkdir($fullpath,0755);
11551: }
11552: }
11553: } else {
11554: last;
11555: }
11556: }
11557: }
11558: if ($fullpath ne '') {
11559: if (-e "$prefix$path") {
11560: system("mv $prefix$path $fullpath/$title");
11561: }
11562: if (-e "$fullpath/$title") {
11563: my $showpath;
11564: if ($relpath ne '') {
11565: $showpath = "$relpath/$title";
11566: } else {
11567: $showpath = "/$title";
11568: }
11569: $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
11570: }
11571: unless ($ishome) {
11572: my $fetch = "$fullpath/$title";
11573: $fetch =~ s/^\Q$prefix$dir\E//;
11574: $prompttofetch{$fetch} = 1;
11575: }
11576: }
11577: }
11578: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
11579: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
11580: $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
11581: }
11582: } else {
11583: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
11584: }
11585: }
11586: if (keys(%todelete)) {
11587: foreach my $key (keys(%todelete)) {
11588: unlink($key);
11589: }
11590: }
11591: if (keys(%todeletedir)) {
11592: foreach my $key (keys(%todeletedir)) {
11593: rmdir($key);
11594: }
11595: }
11596: foreach my $dir (sort(keys(%is_dir))) {
11597: if (($pathtocheck ne '') && ($dir ne '')) {
11598: &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
11599: }
11600: }
11601: if ($result ne '') {
11602: $output .= '<ul>'."\n".
11603: $result."\n".
11604: '</ul>';
11605: }
11606: unless ($ishome) {
11607: my $replicationfail;
11608: foreach my $item (keys(%prompttofetch)) {
11609: my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
11610: unless ($fetchresult eq 'ok') {
11611: $replicationfail .= '<li>'.$item.'</li>'."\n";
11612: }
11613: }
11614: if ($replicationfail) {
11615: $output .= '<p class="LC_error">'.
11616: &mt('Course home server failed to retrieve:').'<ul>'.
11617: $replicationfail.
11618: '</ul></p>';
11619: }
11620: }
11621: } else {
11622: $warning = &mt('No items found in archive.');
11623: }
11624: if ($error) {
11625: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11626: $error.'</p>'."\n";
11627: }
11628: if ($warning) {
11629: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11630: }
11631: return $output;
11632: }
11633:
11634: sub cleanup_empty_dirs {
11635: my ($path) = @_;
11636: if (($path ne '') && (-d $path)) {
11637: if (opendir(my $dirh,$path)) {
11638: my @dircontents = grep(!/^\./,readdir($dirh));
11639: my $numitems = 0;
11640: foreach my $item (@dircontents) {
11641: if (-d "$path/$item") {
11642: &cleanup_empty_dirs("$path/$item");
11643: if (-e "$path/$item") {
11644: $numitems ++;
11645: }
11646: } else {
11647: $numitems ++;
11648: }
11649: }
11650: if ($numitems == 0) {
11651: rmdir($path);
11652: }
11653: closedir($dirh);
11654: }
11655: }
11656: return;
11657: }
11658:
11659: =pod
11660:
11661: =item &get_folder_hierarchy()
11662:
11663: Provides hierarchy of names of folders/sub-folders containing the current
11664: item,
11665:
11666: Inputs: 3
11667: - $navmap - navmaps object
11668:
11669: - $map - url for map (either the trigger itself, or map containing
11670: the resource, which is the trigger).
11671:
11672: - $showitem - 1 => show title for map itself; 0 => do not show.
11673:
11674: Outputs: 1 @pathitems - array of folder/subfolder names.
11675:
11676: =cut
11677:
11678: sub get_folder_hierarchy {
11679: my ($navmap,$map,$showitem) = @_;
11680: my @pathitems;
11681: if (ref($navmap)) {
11682: my $mapres = $navmap->getResourceByUrl($map);
11683: if (ref($mapres)) {
11684: my $pcslist = $mapres->map_hierarchy();
11685: if ($pcslist ne '') {
11686: my @pcs = split(/,/,$pcslist);
11687: foreach my $pc (@pcs) {
11688: if ($pc == 1) {
11689: push(@pathitems,&mt('Main Course Documents'));
11690: } else {
11691: my $res = $navmap->getByMapPc($pc);
11692: if (ref($res)) {
11693: my $title = $res->compTitle();
11694: $title =~ s/\W+/_/g;
11695: if ($title ne '') {
11696: push(@pathitems,$title);
11697: }
11698: }
11699: }
11700: }
11701: }
11702: if ($showitem) {
11703: if ($mapres->{ID} eq '0.0') {
11704: push(@pathitems,&mt('Main Course Documents'));
11705: } else {
11706: my $maptitle = $mapres->compTitle();
11707: $maptitle =~ s/\W+/_/g;
11708: if ($maptitle ne '') {
11709: push(@pathitems,$maptitle);
11710: }
11711: }
11712: }
11713: }
11714: }
11715: return @pathitems;
11716: }
11717:
11718: =pod
11719:
11720: =item * &get_turnedin_filepath()
11721:
11722: Determines path in a user's portfolio file for storage of files uploaded
11723: to a specific essayresponse or dropbox item.
11724:
11725: Inputs: 3 required + 1 optional.
11726: $symb is symb for resource, $uname and $udom are for current user (required).
11727: $caller is optional (can be "submission", if routine is called when storing
11728: an upoaded file when "Submit Answer" button was pressed).
11729:
11730: Returns array containing $path and $multiresp.
11731: $path is path in portfolio. $multiresp is 1 if this resource contains more
11732: than one file upload item. Callers of routine should append partid as a
11733: subdirectory to $path in cases where $multiresp is 1.
11734:
11735: Called by: homework/essayresponse.pm and homework/structuretags.pm
11736:
11737: =cut
11738:
11739: sub get_turnedin_filepath {
11740: my ($symb,$uname,$udom,$caller) = @_;
11741: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
11742: my $turnindir;
11743: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
11744: $turnindir = $userhash{'turnindir'};
11745: my ($path,$multiresp);
11746: if ($turnindir eq '') {
11747: if ($caller eq 'submission') {
11748: $turnindir = &mt('turned in');
11749: $turnindir =~ s/\W+/_/g;
11750: my %newhash = (
11751: 'turnindir' => $turnindir,
11752: );
11753: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
11754: }
11755: }
11756: if ($turnindir ne '') {
11757: $path = '/'.$turnindir.'/';
11758: my ($multipart,$turnin,@pathitems);
11759: my $navmap = Apache::lonnavmaps::navmap->new();
11760: if (defined($navmap)) {
11761: my $mapres = $navmap->getResourceByUrl($map);
11762: if (ref($mapres)) {
11763: my $pcslist = $mapres->map_hierarchy();
11764: if ($pcslist ne '') {
11765: foreach my $pc (split(/,/,$pcslist)) {
11766: my $res = $navmap->getByMapPc($pc);
11767: if (ref($res)) {
11768: my $title = $res->compTitle();
11769: $title =~ s/\W+/_/g;
11770: if ($title ne '') {
11771: push(@pathitems,$title);
11772: }
11773: }
11774: }
11775: }
11776: my $maptitle = $mapres->compTitle();
11777: $maptitle =~ s/\W+/_/g;
11778: if ($maptitle ne '') {
11779: push(@pathitems,$maptitle);
11780: }
11781: unless ($env{'request.state'} eq 'construct') {
11782: my $res = $navmap->getBySymb($symb);
11783: if (ref($res)) {
11784: my $partlist = $res->parts();
11785: my $totaluploads = 0;
11786: if (ref($partlist) eq 'ARRAY') {
11787: foreach my $part (@{$partlist}) {
11788: my @types = $res->responseType($part);
11789: my @ids = $res->responseIds($part);
11790: for (my $i=0; $i < scalar(@ids); $i++) {
11791: if ($types[$i] eq 'essay') {
11792: my $partid = $part.'_'.$ids[$i];
11793: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
11794: $totaluploads ++;
11795: }
11796: }
11797: }
11798: }
11799: if ($totaluploads > 1) {
11800: $multiresp = 1;
11801: }
11802: }
11803: }
11804: }
11805: } else {
11806: return;
11807: }
11808: } else {
11809: return;
11810: }
11811: my $restitle=&Apache::lonnet::gettitle($symb);
11812: $restitle =~ s/\W+/_/g;
11813: if ($restitle eq '') {
11814: $restitle = ($resurl =~ m{/[^/]+$});
11815: if ($restitle eq '') {
11816: $restitle = time;
11817: }
11818: }
11819: push(@pathitems,$restitle);
11820: $path .= join('/',@pathitems);
11821: }
11822: return ($path,$multiresp);
11823: }
11824:
11825: =pod
11826:
11827: =back
11828:
11829: =head1 CSV Upload/Handling functions
11830:
11831: =over 4
11832:
11833: =item * &upfile_store($r)
11834:
11835: Store uploaded file, $r should be the HTTP Request object,
11836: needs $env{'form.upfile'}
11837: returns $datatoken to be put into hidden field
11838:
11839: =cut
11840:
11841: sub upfile_store {
11842: my $r=shift;
11843: $env{'form.upfile'}=~s/\r/\n/gs;
11844: $env{'form.upfile'}=~s/\f/\n/gs;
11845: $env{'form.upfile'}=~s/\n+/\n/gs;
11846: $env{'form.upfile'}=~s/\n+$//gs;
11847:
11848: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
11849: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
11850: {
11851: my $datafile = $r->dir_config('lonDaemons').
11852: '/tmp/'.$datatoken.'.tmp';
11853: if ( open(my $fh,">$datafile") ) {
11854: print $fh $env{'form.upfile'};
11855: close($fh);
11856: }
11857: }
11858: return $datatoken;
11859: }
11860:
11861: =pod
11862:
11863: =item * &load_tmp_file($r)
11864:
11865: Load uploaded file from tmp, $r should be the HTTP Request object,
11866: needs $env{'form.datatoken'},
11867: sets $env{'form.upfile'} to the contents of the file
11868:
11869: =cut
11870:
11871: sub load_tmp_file {
11872: my $r=shift;
11873: my @studentdata=();
11874: {
11875: my $studentfile = $r->dir_config('lonDaemons').
11876: '/tmp/'.$env{'form.datatoken'}.'.tmp';
11877: if ( open(my $fh,"<$studentfile") ) {
11878: @studentdata=<$fh>;
11879: close($fh);
11880: }
11881: }
11882: $env{'form.upfile'}=join('',@studentdata);
11883: }
11884:
11885: =pod
11886:
11887: =item * &upfile_record_sep()
11888:
11889: Separate uploaded file into records
11890: returns array of records,
11891: needs $env{'form.upfile'} and $env{'form.upfiletype'}
11892:
11893: =cut
11894:
11895: sub upfile_record_sep {
11896: if ($env{'form.upfiletype'} eq 'xml') {
11897: } else {
11898: my @records;
11899: foreach my $line (split(/\n/,$env{'form.upfile'})) {
11900: if ($line=~/^\s*$/) { next; }
11901: push(@records,$line);
11902: }
11903: return @records;
11904: }
11905: }
11906:
11907: =pod
11908:
11909: =item * &record_sep($record)
11910:
11911: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
11912:
11913: =cut
11914:
11915: sub takeleft {
11916: my $index=shift;
11917: return substr('0000'.$index,-4,4);
11918: }
11919:
11920: sub record_sep {
11921: my $record=shift;
11922: my %components=();
11923: if ($env{'form.upfiletype'} eq 'xml') {
11924: } elsif ($env{'form.upfiletype'} eq 'space') {
11925: my $i=0;
11926: foreach my $field (split(/\s+/,$record)) {
11927: $field=~s/^(\"|\')//;
11928: $field=~s/(\"|\')$//;
11929: $components{&takeleft($i)}=$field;
11930: $i++;
11931: }
11932: } elsif ($env{'form.upfiletype'} eq 'tab') {
11933: my $i=0;
11934: foreach my $field (split(/\t/,$record)) {
11935: $field=~s/^(\"|\')//;
11936: $field=~s/(\"|\')$//;
11937: $components{&takeleft($i)}=$field;
11938: $i++;
11939: }
11940: } else {
11941: my $separator=',';
11942: if ($env{'form.upfiletype'} eq 'semisv') {
11943: $separator=';';
11944: }
11945: my $i=0;
11946: # the character we are looking for to indicate the end of a quote or a record
11947: my $looking_for=$separator;
11948: # do not add the characters to the fields
11949: my $ignore=0;
11950: # we just encountered a separator (or the beginning of the record)
11951: my $just_found_separator=1;
11952: # store the field we are working on here
11953: my $field='';
11954: # work our way through all characters in record
11955: foreach my $character ($record=~/(.)/g) {
11956: if ($character eq $looking_for) {
11957: if ($character ne $separator) {
11958: # Found the end of a quote, again looking for separator
11959: $looking_for=$separator;
11960: $ignore=1;
11961: } else {
11962: # Found a separator, store away what we got
11963: $components{&takeleft($i)}=$field;
11964: $i++;
11965: $just_found_separator=1;
11966: $ignore=0;
11967: $field='';
11968: }
11969: next;
11970: }
11971: # single or double quotation marks after a separator indicate beginning of a quote
11972: # we are now looking for the end of the quote and need to ignore separators
11973: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
11974: $looking_for=$character;
11975: next;
11976: }
11977: # ignore would be true after we reached the end of a quote
11978: if ($ignore) { next; }
11979: if (($just_found_separator) && ($character=~/\s/)) { next; }
11980: $field.=$character;
11981: $just_found_separator=0;
11982: }
11983: # catch the very last entry, since we never encountered the separator
11984: $components{&takeleft($i)}=$field;
11985: }
11986: return %components;
11987: }
11988:
11989: ######################################################
11990: ######################################################
11991:
11992: =pod
11993:
11994: =item * &upfile_select_html()
11995:
11996: Return HTML code to select a file from the users machine and specify
11997: the file type.
11998:
11999: =cut
12000:
12001: ######################################################
12002: ######################################################
12003: sub upfile_select_html {
12004: my %Types = (
12005: csv => &mt('CSV (comma separated values, spreadsheet)'),
12006: semisv => &mt('Semicolon separated values'),
12007: space => &mt('Space separated'),
12008: tab => &mt('Tabulator separated'),
12009: # xml => &mt('HTML/XML'),
12010: );
12011: my $Str = '<input type="file" name="upfile" size="50" />'.
12012: '<br />'.&mt('Type').': <select name="upfiletype">';
12013: foreach my $type (sort(keys(%Types))) {
12014: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
12015: }
12016: $Str .= "</select>\n";
12017: return $Str;
12018: }
12019:
12020: sub get_samples {
12021: my ($records,$toget) = @_;
12022: my @samples=({});
12023: my $got=0;
12024: foreach my $rec (@$records) {
12025: my %temp = &record_sep($rec);
12026: if (! grep(/\S/, values(%temp))) { next; }
12027: if (%temp) {
12028: $samples[$got]=\%temp;
12029: $got++;
12030: if ($got == $toget) { last; }
12031: }
12032: }
12033: return \@samples;
12034: }
12035:
12036: ######################################################
12037: ######################################################
12038:
12039: =pod
12040:
12041: =item * &csv_print_samples($r,$records)
12042:
12043: Prints a table of sample values from each column uploaded $r is an
12044: Apache Request ref, $records is an arrayref from
12045: &Apache::loncommon::upfile_record_sep
12046:
12047: =cut
12048:
12049: ######################################################
12050: ######################################################
12051: sub csv_print_samples {
12052: my ($r,$records) = @_;
12053: my $samples = &get_samples($records,5);
12054:
12055: $r->print(&mt('Samples').'<br />'.&start_data_table().
12056: &start_data_table_header_row());
12057: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12058: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
12059: $r->print(&end_data_table_header_row());
12060: foreach my $hash (@$samples) {
12061: $r->print(&start_data_table_row());
12062: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12063: $r->print('<td>');
12064: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
12065: $r->print('</td>');
12066: }
12067: $r->print(&end_data_table_row());
12068: }
12069: $r->print(&end_data_table().'<br />'."\n");
12070: }
12071:
12072: ######################################################
12073: ######################################################
12074:
12075: =pod
12076:
12077: =item * &csv_print_select_table($r,$records,$d)
12078:
12079: Prints a table to create associations between values and table columns.
12080:
12081: $r is an Apache Request ref,
12082: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12083: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
12084:
12085: =cut
12086:
12087: ######################################################
12088: ######################################################
12089: sub csv_print_select_table {
12090: my ($r,$records,$d) = @_;
12091: my $i=0;
12092: my $samples = &get_samples($records,1);
12093: $r->print(&mt('Associate columns with student attributes.')."\n".
12094: &start_data_table().&start_data_table_header_row().
12095: '<th>'.&mt('Attribute').'</th>'.
12096: '<th>'.&mt('Column').'</th>'.
12097: &end_data_table_header_row()."\n");
12098: foreach my $array_ref (@$d) {
12099: my ($value,$display,$defaultcol)=@{ $array_ref };
12100: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
12101:
12102: $r->print('<td><select name="f'.$i.'"'.
12103: ' onchange="javascript:flip(this.form,'.$i.');">');
12104: $r->print('<option value="none"></option>');
12105: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12106: $r->print('<option value="'.$sample.'"'.
12107: ($sample eq $defaultcol ? ' selected="selected" ' : '').
12108: '>'.&mt('Column [_1]',($sample+1)).'</option>');
12109: }
12110: $r->print('</select></td>'.&end_data_table_row()."\n");
12111: $i++;
12112: }
12113: $r->print(&end_data_table());
12114: $i--;
12115: return $i;
12116: }
12117:
12118: ######################################################
12119: ######################################################
12120:
12121: =pod
12122:
12123: =item * &csv_samples_select_table($r,$records,$d)
12124:
12125: Prints a table of sample values from the upload and can make associate samples to internal names.
12126:
12127: $r is an Apache Request ref,
12128: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12129: $d is an array of 2 element arrays (internal name, displayed name)
12130:
12131: =cut
12132:
12133: ######################################################
12134: ######################################################
12135: sub csv_samples_select_table {
12136: my ($r,$records,$d) = @_;
12137: my $i=0;
12138: #
12139: my $max_samples = 5;
12140: my $samples = &get_samples($records,$max_samples);
12141: $r->print(&start_data_table().
12142: &start_data_table_header_row().'<th>'.
12143: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12144: &end_data_table_header_row());
12145:
12146: foreach my $key (sort(keys(%{ $samples->[0] }))) {
12147: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12148: ' onchange="javascript:flip(this.form,'.$i.');">');
12149: foreach my $option (@$d) {
12150: my ($value,$display,$defaultcol)=@{ $option };
12151: $r->print('<option value="'.$value.'"'.
12152: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12153: $display.'</option>');
12154: }
12155: $r->print('</select></td><td>');
12156: foreach my $line (0..($max_samples-1)) {
12157: if (defined($samples->[$line]{$key})) {
12158: $r->print($samples->[$line]{$key}."<br />\n");
12159: }
12160: }
12161: $r->print('</td>'.&end_data_table_row());
12162: $i++;
12163: }
12164: $r->print(&end_data_table());
12165: $i--;
12166: return($i);
12167: }
12168:
12169: ######################################################
12170: ######################################################
12171:
12172: =pod
12173:
12174: =item * &clean_excel_name($name)
12175:
12176: Returns a replacement for $name which does not contain any illegal characters.
12177:
12178: =cut
12179:
12180: ######################################################
12181: ######################################################
12182: sub clean_excel_name {
12183: my ($name) = @_;
12184: $name =~ s/[:\*\?\/\\]//g;
12185: if (length($name) > 31) {
12186: $name = substr($name,0,31);
12187: }
12188: return $name;
12189: }
12190:
12191: =pod
12192:
12193: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
12194:
12195: Returns either 1 or undef
12196:
12197: 1 if the part is to be hidden, undef if it is to be shown
12198:
12199: Arguments are:
12200:
12201: $id the id of the part to be checked
12202: $symb, optional the symb of the resource to check
12203: $udom, optional the domain of the user to check for
12204: $uname, optional the username of the user to check for
12205:
12206: =cut
12207:
12208: sub check_if_partid_hidden {
12209: my ($id,$symb,$udom,$uname) = @_;
12210: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
12211: $symb,$udom,$uname);
12212: my $truth=1;
12213: #if the string starts with !, then the list is the list to show not hide
12214: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
12215: my @hiddenlist=split(/,/,$hiddenparts);
12216: foreach my $checkid (@hiddenlist) {
12217: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
12218: }
12219: return !$truth;
12220: }
12221:
12222:
12223: ############################################################
12224: ############################################################
12225:
12226: =pod
12227:
12228: =back
12229:
12230: =head1 cgi-bin script and graphing routines
12231:
12232: =over 4
12233:
12234: =item * &get_cgi_id()
12235:
12236: Inputs: none
12237:
12238: Returns an id which can be used to pass environment variables
12239: to various cgi-bin scripts. These environment variables will
12240: be removed from the users environment after a given time by
12241: the routine &Apache::lonnet::transfer_profile_to_env.
12242:
12243: =cut
12244:
12245: ############################################################
12246: ############################################################
12247: my $uniq=0;
12248: sub get_cgi_id {
12249: $uniq=($uniq+1)%100000;
12250: return (time.'_'.$$.'_'.$uniq);
12251: }
12252:
12253: ############################################################
12254: ############################################################
12255:
12256: =pod
12257:
12258: =item * &DrawBarGraph()
12259:
12260: Facilitates the plotting of data in a (stacked) bar graph.
12261: Puts plot definition data into the users environment in order for
12262: graph.png to plot it. Returns an <img> tag for the plot.
12263: The bars on the plot are labeled '1','2',...,'n'.
12264:
12265: Inputs:
12266:
12267: =over 4
12268:
12269: =item $Title: string, the title of the plot
12270:
12271: =item $xlabel: string, text describing the X-axis of the plot
12272:
12273: =item $ylabel: string, text describing the Y-axis of the plot
12274:
12275: =item $Max: scalar, the maximum Y value to use in the plot
12276: If $Max is < any data point, the graph will not be rendered.
12277:
12278: =item $colors: array ref holding the colors to be used for the data sets when
12279: they are plotted. If undefined, default values will be used.
12280:
12281: =item $labels: array ref holding the labels to use on the x-axis for the bars.
12282:
12283: =item @Values: An array of array references. Each array reference holds data
12284: to be plotted in a stacked bar chart.
12285:
12286: =item If the final element of @Values is a hash reference the key/value
12287: pairs will be added to the graph definition.
12288:
12289: =back
12290:
12291: Returns:
12292:
12293: An <img> tag which references graph.png and the appropriate identifying
12294: information for the plot.
12295:
12296: =cut
12297:
12298: ############################################################
12299: ############################################################
12300: sub DrawBarGraph {
12301: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
12302: #
12303: if (! defined($colors)) {
12304: $colors = ['#33ff00',
12305: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
12306: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
12307: ];
12308: }
12309: my $extra_settings = {};
12310: if (ref($Values[-1]) eq 'HASH') {
12311: $extra_settings = pop(@Values);
12312: }
12313: #
12314: my $identifier = &get_cgi_id();
12315: my $id = 'cgi.'.$identifier;
12316: if (! @Values || ref($Values[0]) ne 'ARRAY') {
12317: return '';
12318: }
12319: #
12320: my @Labels;
12321: if (defined($labels)) {
12322: @Labels = @$labels;
12323: } else {
12324: for (my $i=0;$i<@{$Values[0]};$i++) {
12325: push (@Labels,$i+1);
12326: }
12327: }
12328: #
12329: my $NumBars = scalar(@{$Values[0]});
12330: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
12331: my %ValuesHash;
12332: my $NumSets=1;
12333: foreach my $array (@Values) {
12334: next if (! ref($array));
12335: $ValuesHash{$id.'.data.'.$NumSets++} =
12336: join(',',@$array);
12337: }
12338: #
12339: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
12340: if ($NumBars < 3) {
12341: $width = 120+$NumBars*32;
12342: $xskip = 1;
12343: $bar_width = 30;
12344: } elsif ($NumBars < 5) {
12345: $width = 120+$NumBars*20;
12346: $xskip = 1;
12347: $bar_width = 20;
12348: } elsif ($NumBars < 10) {
12349: $width = 120+$NumBars*15;
12350: $xskip = 1;
12351: $bar_width = 15;
12352: } elsif ($NumBars <= 25) {
12353: $width = 120+$NumBars*11;
12354: $xskip = 5;
12355: $bar_width = 8;
12356: } elsif ($NumBars <= 50) {
12357: $width = 120+$NumBars*8;
12358: $xskip = 5;
12359: $bar_width = 4;
12360: } else {
12361: $width = 120+$NumBars*8;
12362: $xskip = 5;
12363: $bar_width = 4;
12364: }
12365: #
12366: $Max = 1 if ($Max < 1);
12367: if ( int($Max) < $Max ) {
12368: $Max++;
12369: $Max = int($Max);
12370: }
12371: $Title = '' if (! defined($Title));
12372: $xlabel = '' if (! defined($xlabel));
12373: $ylabel = '' if (! defined($ylabel));
12374: $ValuesHash{$id.'.title'} = &escape($Title);
12375: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
12376: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
12377: $ValuesHash{$id.'.y_max_value'} = $Max;
12378: $ValuesHash{$id.'.NumBars'} = $NumBars;
12379: $ValuesHash{$id.'.NumSets'} = $NumSets;
12380: $ValuesHash{$id.'.PlotType'} = 'bar';
12381: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
12382: $ValuesHash{$id.'.height'} = $height;
12383: $ValuesHash{$id.'.width'} = $width;
12384: $ValuesHash{$id.'.xskip'} = $xskip;
12385: $ValuesHash{$id.'.bar_width'} = $bar_width;
12386: $ValuesHash{$id.'.labels'} = join(',',@Labels);
12387: #
12388: # Deal with other parameters
12389: while (my ($key,$value) = each(%$extra_settings)) {
12390: $ValuesHash{$id.'.'.$key} = $value;
12391: }
12392: #
12393: &Apache::lonnet::appenv(\%ValuesHash);
12394: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12395: }
12396:
12397: ############################################################
12398: ############################################################
12399:
12400: =pod
12401:
12402: =item * &DrawXYGraph()
12403:
12404: Facilitates the plotting of data in an XY graph.
12405: Puts plot definition data into the users environment in order for
12406: graph.png to plot it. Returns an <img> tag for the plot.
12407:
12408: Inputs:
12409:
12410: =over 4
12411:
12412: =item $Title: string, the title of the plot
12413:
12414: =item $xlabel: string, text describing the X-axis of the plot
12415:
12416: =item $ylabel: string, text describing the Y-axis of the plot
12417:
12418: =item $Max: scalar, the maximum Y value to use in the plot
12419: If $Max is < any data point, the graph will not be rendered.
12420:
12421: =item $colors: Array ref containing the hex color codes for the data to be
12422: plotted in. If undefined, default values will be used.
12423:
12424: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12425:
12426: =item $Ydata: Array ref containing Array refs.
12427: Each of the contained arrays will be plotted as a separate curve.
12428:
12429: =item %Values: hash indicating or overriding any default values which are
12430: passed to graph.png.
12431: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12432:
12433: =back
12434:
12435: Returns:
12436:
12437: An <img> tag which references graph.png and the appropriate identifying
12438: information for the plot.
12439:
12440: =cut
12441:
12442: ############################################################
12443: ############################################################
12444: sub DrawXYGraph {
12445: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
12446: #
12447: # Create the identifier for the graph
12448: my $identifier = &get_cgi_id();
12449: my $id = 'cgi.'.$identifier;
12450: #
12451: $Title = '' if (! defined($Title));
12452: $xlabel = '' if (! defined($xlabel));
12453: $ylabel = '' if (! defined($ylabel));
12454: my %ValuesHash =
12455: (
12456: $id.'.title' => &escape($Title),
12457: $id.'.xlabel' => &escape($xlabel),
12458: $id.'.ylabel' => &escape($ylabel),
12459: $id.'.y_max_value'=> $Max,
12460: $id.'.labels' => join(',',@$Xlabels),
12461: $id.'.PlotType' => 'XY',
12462: );
12463: #
12464: if (defined($colors) && ref($colors) eq 'ARRAY') {
12465: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
12466: }
12467: #
12468: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
12469: return '';
12470: }
12471: my $NumSets=1;
12472: foreach my $array (@{$Ydata}){
12473: next if (! ref($array));
12474: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12475: }
12476: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
12477: #
12478: # Deal with other parameters
12479: while (my ($key,$value) = each(%Values)) {
12480: $ValuesHash{$id.'.'.$key} = $value;
12481: }
12482: #
12483: &Apache::lonnet::appenv(\%ValuesHash);
12484: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12485: }
12486:
12487: ############################################################
12488: ############################################################
12489:
12490: =pod
12491:
12492: =item * &DrawXYYGraph()
12493:
12494: Facilitates the plotting of data in an XY graph with two Y axes.
12495: Puts plot definition data into the users environment in order for
12496: graph.png to plot it. Returns an <img> tag for the plot.
12497:
12498: Inputs:
12499:
12500: =over 4
12501:
12502: =item $Title: string, the title of the plot
12503:
12504: =item $xlabel: string, text describing the X-axis of the plot
12505:
12506: =item $ylabel: string, text describing the Y-axis of the plot
12507:
12508: =item $colors: Array ref containing the hex color codes for the data to be
12509: plotted in. If undefined, default values will be used.
12510:
12511: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12512:
12513: =item $Ydata1: The first data set
12514:
12515: =item $Min1: The minimum value of the left Y-axis
12516:
12517: =item $Max1: The maximum value of the left Y-axis
12518:
12519: =item $Ydata2: The second data set
12520:
12521: =item $Min2: The minimum value of the right Y-axis
12522:
12523: =item $Max2: The maximum value of the left Y-axis
12524:
12525: =item %Values: hash indicating or overriding any default values which are
12526: passed to graph.png.
12527: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12528:
12529: =back
12530:
12531: Returns:
12532:
12533: An <img> tag which references graph.png and the appropriate identifying
12534: information for the plot.
12535:
12536: =cut
12537:
12538: ############################################################
12539: ############################################################
12540: sub DrawXYYGraph {
12541: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
12542: $Ydata2,$Min2,$Max2,%Values)=@_;
12543: #
12544: # Create the identifier for the graph
12545: my $identifier = &get_cgi_id();
12546: my $id = 'cgi.'.$identifier;
12547: #
12548: $Title = '' if (! defined($Title));
12549: $xlabel = '' if (! defined($xlabel));
12550: $ylabel = '' if (! defined($ylabel));
12551: my %ValuesHash =
12552: (
12553: $id.'.title' => &escape($Title),
12554: $id.'.xlabel' => &escape($xlabel),
12555: $id.'.ylabel' => &escape($ylabel),
12556: $id.'.labels' => join(',',@$Xlabels),
12557: $id.'.PlotType' => 'XY',
12558: $id.'.NumSets' => 2,
12559: $id.'.two_axes' => 1,
12560: $id.'.y1_max_value' => $Max1,
12561: $id.'.y1_min_value' => $Min1,
12562: $id.'.y2_max_value' => $Max2,
12563: $id.'.y2_min_value' => $Min2,
12564: );
12565: #
12566: if (defined($colors) && ref($colors) eq 'ARRAY') {
12567: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
12568: }
12569: #
12570: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
12571: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
12572: return '';
12573: }
12574: my $NumSets=1;
12575: foreach my $array ($Ydata1,$Ydata2){
12576: next if (! ref($array));
12577: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12578: }
12579: #
12580: # Deal with other parameters
12581: while (my ($key,$value) = each(%Values)) {
12582: $ValuesHash{$id.'.'.$key} = $value;
12583: }
12584: #
12585: &Apache::lonnet::appenv(\%ValuesHash);
12586: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12587: }
12588:
12589: ############################################################
12590: ############################################################
12591:
12592: =pod
12593:
12594: =back
12595:
12596: =head1 Statistics helper routines?
12597:
12598: Bad place for them but what the hell.
12599:
12600: =over 4
12601:
12602: =item * &chartlink()
12603:
12604: Returns a link to the chart for a specific student.
12605:
12606: Inputs:
12607:
12608: =over 4
12609:
12610: =item $linktext: The text of the link
12611:
12612: =item $sname: The students username
12613:
12614: =item $sdomain: The students domain
12615:
12616: =back
12617:
12618: =back
12619:
12620: =cut
12621:
12622: ############################################################
12623: ############################################################
12624: sub chartlink {
12625: my ($linktext, $sname, $sdomain) = @_;
12626: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
12627: '&SelectedStudent='.&escape($sname.':'.$sdomain).
12628: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
12629: '">'.$linktext.'</a>';
12630: }
12631:
12632: #######################################################
12633: #######################################################
12634:
12635: =pod
12636:
12637: =head1 Course Environment Routines
12638:
12639: =over 4
12640:
12641: =item * &restore_course_settings()
12642:
12643: =item * &store_course_settings()
12644:
12645: Restores/Store indicated form parameters from the course environment.
12646: Will not overwrite existing values of the form parameters.
12647:
12648: Inputs:
12649: a scalar describing the data (e.g. 'chart', 'problem_analysis')
12650:
12651: a hash ref describing the data to be stored. For example:
12652:
12653: %Save_Parameters = ('Status' => 'scalar',
12654: 'chartoutputmode' => 'scalar',
12655: 'chartoutputdata' => 'scalar',
12656: 'Section' => 'array',
12657: 'Group' => 'array',
12658: 'StudentData' => 'array',
12659: 'Maps' => 'array');
12660:
12661: Returns: both routines return nothing
12662:
12663: =back
12664:
12665: =cut
12666:
12667: #######################################################
12668: #######################################################
12669: sub store_course_settings {
12670: return &store_settings($env{'request.course.id'},@_);
12671: }
12672:
12673: sub store_settings {
12674: # save to the environment
12675: # appenv the same items, just to be safe
12676: my $udom = $env{'user.domain'};
12677: my $uname = $env{'user.name'};
12678: my ($context,$prefix,$Settings) = @_;
12679: my %SaveHash;
12680: my %AppHash;
12681: while (my ($setting,$type) = each(%$Settings)) {
12682: my $basename = join('.','internal',$context,$prefix,$setting);
12683: my $envname = 'environment.'.$basename;
12684: if (exists($env{'form.'.$setting})) {
12685: # Save this value away
12686: if ($type eq 'scalar' &&
12687: (! exists($env{$envname}) ||
12688: $env{$envname} ne $env{'form.'.$setting})) {
12689: $SaveHash{$basename} = $env{'form.'.$setting};
12690: $AppHash{$envname} = $env{'form.'.$setting};
12691: } elsif ($type eq 'array') {
12692: my $stored_form;
12693: if (ref($env{'form.'.$setting})) {
12694: $stored_form = join(',',
12695: map {
12696: &escape($_);
12697: } sort(@{$env{'form.'.$setting}}));
12698: } else {
12699: $stored_form =
12700: &escape($env{'form.'.$setting});
12701: }
12702: # Determine if the array contents are the same.
12703: if ($stored_form ne $env{$envname}) {
12704: $SaveHash{$basename} = $stored_form;
12705: $AppHash{$envname} = $stored_form;
12706: }
12707: }
12708: }
12709: }
12710: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
12711: $udom,$uname);
12712: if ($put_result !~ /^(ok|delayed)/) {
12713: &Apache::lonnet::logthis('unable to save form parameters, '.
12714: 'got error:'.$put_result);
12715: }
12716: # Make sure these settings stick around in this session, too
12717: &Apache::lonnet::appenv(\%AppHash);
12718: return;
12719: }
12720:
12721: sub restore_course_settings {
12722: return &restore_settings($env{'request.course.id'},@_);
12723: }
12724:
12725: sub restore_settings {
12726: my ($context,$prefix,$Settings) = @_;
12727: while (my ($setting,$type) = each(%$Settings)) {
12728: next if (exists($env{'form.'.$setting}));
12729: my $envname = 'environment.internal.'.$context.'.'.$prefix.
12730: '.'.$setting;
12731: if (exists($env{$envname})) {
12732: if ($type eq 'scalar') {
12733: $env{'form.'.$setting} = $env{$envname};
12734: } elsif ($type eq 'array') {
12735: $env{'form.'.$setting} = [
12736: map {
12737: &unescape($_);
12738: } split(',',$env{$envname})
12739: ];
12740: }
12741: }
12742: }
12743: }
12744:
12745: #######################################################
12746: #######################################################
12747:
12748: =pod
12749:
12750: =head1 Domain E-mail Routines
12751:
12752: =over 4
12753:
12754: =item * &build_recipient_list()
12755:
12756: Build recipient lists for five types of e-mail:
12757: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
12758: (d) Help requests, (e) Course requests needing approval, generated by
12759: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
12760: loncoursequeueadmin.pm respectively.
12761:
12762: Inputs:
12763: defmail (scalar - email address of default recipient),
12764: mailing type (scalar - errormail, packagesmail, or helpdeskmail),
12765: defdom (domain for which to retrieve configuration settings),
12766: origmail (scalar - email address of recipient from loncapa.conf,
12767: i.e., predates configuration by DC via domainprefs.pm
12768:
12769: Returns: comma separated list of addresses to which to send e-mail.
12770:
12771: =back
12772:
12773: =cut
12774:
12775: ############################################################
12776: ############################################################
12777: sub build_recipient_list {
12778: my ($defmail,$mailing,$defdom,$origmail) = @_;
12779: my @recipients;
12780: my $otheremails;
12781: my %domconfig =
12782: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
12783: if (ref($domconfig{'contacts'}) eq 'HASH') {
12784: if (exists($domconfig{'contacts'}{$mailing})) {
12785: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
12786: my @contacts = ('adminemail','supportemail');
12787: foreach my $item (@contacts) {
12788: if ($domconfig{'contacts'}{$mailing}{$item}) {
12789: my $addr = $domconfig{'contacts'}{$item};
12790: if (!grep(/^\Q$addr\E$/,@recipients)) {
12791: push(@recipients,$addr);
12792: }
12793: }
12794: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
12795: }
12796: }
12797: } elsif ($origmail ne '') {
12798: push(@recipients,$origmail);
12799: }
12800: } elsif ($origmail ne '') {
12801: push(@recipients,$origmail);
12802: }
12803: if (defined($defmail)) {
12804: if ($defmail ne '') {
12805: push(@recipients,$defmail);
12806: }
12807: }
12808: if ($otheremails) {
12809: my @others;
12810: if ($otheremails =~ /,/) {
12811: @others = split(/,/,$otheremails);
12812: } else {
12813: push(@others,$otheremails);
12814: }
12815: foreach my $addr (@others) {
12816: if (!grep(/^\Q$addr\E$/,@recipients)) {
12817: push(@recipients,$addr);
12818: }
12819: }
12820: }
12821: my $recipientlist = join(',',@recipients);
12822: return $recipientlist;
12823: }
12824:
12825: ############################################################
12826: ############################################################
12827:
12828: =pod
12829:
12830: =head1 Course Catalog Routines
12831:
12832: =over 4
12833:
12834: =item * &gather_categories()
12835:
12836: Converts category definitions - keys of categories hash stored in
12837: coursecategories in configuration.db on the primary library server in a
12838: domain - to an array. Also generates javascript and idx hash used to
12839: generate Domain Coordinator interface for editing Course Categories.
12840:
12841: Inputs:
12842:
12843: categories (reference to hash of category definitions).
12844:
12845: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12846: categories and subcategories).
12847:
12848: idx (reference to hash of counters used in Domain Coordinator interface for
12849: editing Course Categories).
12850:
12851: jsarray (reference to array of categories used to create Javascript arrays for
12852: Domain Coordinator interface for editing Course Categories).
12853:
12854: Returns: nothing
12855:
12856: Side effects: populates cats, idx and jsarray.
12857:
12858: =cut
12859:
12860: sub gather_categories {
12861: my ($categories,$cats,$idx,$jsarray) = @_;
12862: my %counters;
12863: my $num = 0;
12864: foreach my $item (keys(%{$categories})) {
12865: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
12866: if ($container eq '' && $depth == 0) {
12867: $cats->[$depth][$categories->{$item}] = $cat;
12868: } else {
12869: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
12870: }
12871: my ($escitem,$tail) = split(/:/,$item,2);
12872: if ($counters{$tail} eq '') {
12873: $counters{$tail} = $num;
12874: $num ++;
12875: }
12876: if (ref($idx) eq 'HASH') {
12877: $idx->{$item} = $counters{$tail};
12878: }
12879: if (ref($jsarray) eq 'ARRAY') {
12880: push(@{$jsarray->[$counters{$tail}]},$item);
12881: }
12882: }
12883: return;
12884: }
12885:
12886: =pod
12887:
12888: =item * &extract_categories()
12889:
12890: Used to generate breadcrumb trails for course categories.
12891:
12892: Inputs:
12893:
12894: categories (reference to hash of category definitions).
12895:
12896: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12897: categories and subcategories).
12898:
12899: trails (reference to array of breacrumb trails for each category).
12900:
12901: allitems (reference to hash - key is category key
12902: (format: escaped(name):escaped(parent category):depth in hierarchy).
12903:
12904: idx (reference to hash of counters used in Domain Coordinator interface for
12905: editing Course Categories).
12906:
12907: jsarray (reference to array of categories used to create Javascript arrays for
12908: Domain Coordinator interface for editing Course Categories).
12909:
12910: subcats (reference to hash of arrays containing all subcategories within each
12911: category, -recursive)
12912:
12913: Returns: nothing
12914:
12915: Side effects: populates trails and allitems hash references.
12916:
12917: =cut
12918:
12919: sub extract_categories {
12920: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
12921: if (ref($categories) eq 'HASH') {
12922: &gather_categories($categories,$cats,$idx,$jsarray);
12923: if (ref($cats->[0]) eq 'ARRAY') {
12924: for (my $i=0; $i<@{$cats->[0]}; $i++) {
12925: my $name = $cats->[0][$i];
12926: my $item = &escape($name).'::0';
12927: my $trailstr;
12928: if ($name eq 'instcode') {
12929: $trailstr = &mt('Official courses (with institutional codes)');
12930: } elsif ($name eq 'communities') {
12931: $trailstr = &mt('Communities');
12932: } else {
12933: $trailstr = $name;
12934: }
12935: if ($allitems->{$item} eq '') {
12936: push(@{$trails},$trailstr);
12937: $allitems->{$item} = scalar(@{$trails})-1;
12938: }
12939: my @parents = ($name);
12940: if (ref($cats->[1]{$name}) eq 'ARRAY') {
12941: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
12942: my $category = $cats->[1]{$name}[$j];
12943: if (ref($subcats) eq 'HASH') {
12944: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
12945: }
12946: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
12947: }
12948: } else {
12949: if (ref($subcats) eq 'HASH') {
12950: $subcats->{$item} = [];
12951: }
12952: }
12953: }
12954: }
12955: }
12956: return;
12957: }
12958:
12959: =pod
12960:
12961: =item *&recurse_categories()
12962:
12963: Recursively used to generate breadcrumb trails for course categories.
12964:
12965: Inputs:
12966:
12967: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12968: categories and subcategories).
12969:
12970: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
12971:
12972: category (current course category, for which breadcrumb trail is being generated).
12973:
12974: trails (reference to array of breadcrumb trails for each category).
12975:
12976: allitems (reference to hash - key is category key
12977: (format: escaped(name):escaped(parent category):depth in hierarchy).
12978:
12979: parents (array containing containers directories for current category,
12980: back to top level).
12981:
12982: Returns: nothing
12983:
12984: Side effects: populates trails and allitems hash references
12985:
12986: =cut
12987:
12988: sub recurse_categories {
12989: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
12990: my $shallower = $depth - 1;
12991: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
12992: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
12993: my $name = $cats->[$depth]{$category}[$k];
12994: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
12995: my $trailstr = join(' -> ',(@{$parents},$category));
12996: if ($allitems->{$item} eq '') {
12997: push(@{$trails},$trailstr);
12998: $allitems->{$item} = scalar(@{$trails})-1;
12999: }
13000: my $deeper = $depth+1;
13001: push(@{$parents},$category);
13002: if (ref($subcats) eq 'HASH') {
13003: my $subcat = &escape($name).':'.$category.':'.$depth;
13004: for (my $j=@{$parents}; $j>=0; $j--) {
13005: my $higher;
13006: if ($j > 0) {
13007: $higher = &escape($parents->[$j]).':'.
13008: &escape($parents->[$j-1]).':'.$j;
13009: } else {
13010: $higher = &escape($parents->[$j]).'::'.$j;
13011: }
13012: push(@{$subcats->{$higher}},$subcat);
13013: }
13014: }
13015: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
13016: $subcats);
13017: pop(@{$parents});
13018: }
13019: } else {
13020: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13021: my $trailstr = join(' -> ',(@{$parents},$category));
13022: if ($allitems->{$item} eq '') {
13023: push(@{$trails},$trailstr);
13024: $allitems->{$item} = scalar(@{$trails})-1;
13025: }
13026: }
13027: return;
13028: }
13029:
13030: =pod
13031:
13032: =item *&assign_categories_table()
13033:
13034: Create a datatable for display of hierarchical categories in a domain,
13035: with checkboxes to allow a course to be categorized.
13036:
13037: Inputs:
13038:
13039: cathash - reference to hash of categories defined for the domain (from
13040: configuration.db)
13041:
13042: currcat - scalar with an & separated list of categories assigned to a course.
13043:
13044: type - scalar contains course type (Course or Community).
13045:
13046: Returns: $output (markup to be displayed)
13047:
13048: =cut
13049:
13050: sub assign_categories_table {
13051: my ($cathash,$currcat,$type) = @_;
13052: my $output;
13053: if (ref($cathash) eq 'HASH') {
13054: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
13055: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
13056: $maxdepth = scalar(@cats);
13057: if (@cats > 0) {
13058: my $itemcount = 0;
13059: if (ref($cats[0]) eq 'ARRAY') {
13060: my @currcategories;
13061: if ($currcat ne '') {
13062: @currcategories = split('&',$currcat);
13063: }
13064: my $table;
13065: for (my $i=0; $i<@{$cats[0]}; $i++) {
13066: my $parent = $cats[0][$i];
13067: next if ($parent eq 'instcode');
13068: if ($type eq 'Community') {
13069: next unless ($parent eq 'communities');
13070: } else {
13071: next if ($parent eq 'communities');
13072: }
13073: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13074: my $item = &escape($parent).'::0';
13075: my $checked = '';
13076: if (@currcategories > 0) {
13077: if (grep(/^\Q$item\E$/,@currcategories)) {
13078: $checked = ' checked="checked"';
13079: }
13080: }
13081: my $parent_title = $parent;
13082: if ($parent eq 'communities') {
13083: $parent_title = &mt('Communities');
13084: }
13085: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
13086: '<input type="checkbox" name="usecategory" value="'.
13087: $item.'"'.$checked.' />'.$parent_title.'</span>'.
13088: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
13089: my $depth = 1;
13090: push(@path,$parent);
13091: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
13092: pop(@path);
13093: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
13094: $itemcount ++;
13095: }
13096: if ($itemcount) {
13097: $output = &Apache::loncommon::start_data_table().
13098: $table.
13099: &Apache::loncommon::end_data_table();
13100: }
13101: }
13102: }
13103: }
13104: return $output;
13105: }
13106:
13107: =pod
13108:
13109: =item *&assign_category_rows()
13110:
13111: Create a datatable row for display of nested categories in a domain,
13112: with checkboxes to allow a course to be categorized,called recursively.
13113:
13114: Inputs:
13115:
13116: itemcount - track row number for alternating colors
13117:
13118: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13119: categories and subcategories.
13120:
13121: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13122:
13123: parent - parent of current category item
13124:
13125: path - Array containing all categories back up through the hierarchy from the
13126: current category to the top level.
13127:
13128: currcategories - reference to array of current categories assigned to the course
13129:
13130: Returns: $output (markup to be displayed).
13131:
13132: =cut
13133:
13134: sub assign_category_rows {
13135: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13136: my ($text,$name,$item,$chgstr);
13137: if (ref($cats) eq 'ARRAY') {
13138: my $maxdepth = scalar(@{$cats});
13139: if (ref($cats->[$depth]) eq 'HASH') {
13140: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13141: my $numchildren = @{$cats->[$depth]{$parent}};
13142: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13143: $text .= '<td><table class="LC_datatable">';
13144: for (my $j=0; $j<$numchildren; $j++) {
13145: $name = $cats->[$depth]{$parent}[$j];
13146: $item = &escape($name).':'.&escape($parent).':'.$depth;
13147: my $deeper = $depth+1;
13148: my $checked = '';
13149: if (ref($currcategories) eq 'ARRAY') {
13150: if (@{$currcategories} > 0) {
13151: if (grep(/^\Q$item\E$/,@{$currcategories})) {
13152: $checked = ' checked="checked"';
13153: }
13154: }
13155: }
13156: $text .= '<tr><td><span class="LC_nobreak"><label>'.
13157: '<input type="checkbox" name="usecategory" value="'.
13158: $item.'"'.$checked.' />'.$name.'</label></span>'.
13159: '<input type="hidden" name="catname" value="'.$name.'" />'.
13160: '</td><td>';
13161: if (ref($path) eq 'ARRAY') {
13162: push(@{$path},$name);
13163: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13164: pop(@{$path});
13165: }
13166: $text .= '</td></tr>';
13167: }
13168: $text .= '</table></td>';
13169: }
13170: }
13171: }
13172: return $text;
13173: }
13174:
13175: ############################################################
13176: ############################################################
13177:
13178:
13179: sub commit_customrole {
13180: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
13181: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
13182: ($start?', '.&mt('starting').' '.localtime($start):'').
13183: ($end?', ending '.localtime($end):'').': <b>'.
13184: &Apache::lonnet::assigncustomrole(
13185: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
13186: '</b><br />';
13187: return $output;
13188: }
13189:
13190: sub commit_standardrole {
13191: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
13192: my ($output,$logmsg,$linefeed);
13193: if ($context eq 'auto') {
13194: $linefeed = "\n";
13195: } else {
13196: $linefeed = "<br />\n";
13197: }
13198: if ($three eq 'st') {
13199: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
13200: $one,$two,$sec,$context);
13201: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
13202: ($result eq 'unknown_course') || ($result eq 'refused')) {
13203: $output = $logmsg.' '.&mt('Error: ').$result."\n";
13204: } else {
13205: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
13206: ($start?', '.&mt('starting').' '.localtime($start):'').
13207: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13208: if ($context eq 'auto') {
13209: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
13210: } else {
13211: $output .= '<b>'.$result.'</b>'.$linefeed.
13212: &mt('Add to classlist').': <b>ok</b>';
13213: }
13214: $output .= $linefeed;
13215: }
13216: } else {
13217: $output = &mt('Assigning').' '.$three.' in '.$url.
13218: ($start?', '.&mt('starting').' '.localtime($start):'').
13219: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13220: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
13221: if ($context eq 'auto') {
13222: $output .= $result.$linefeed;
13223: } else {
13224: $output .= '<b>'.$result.'</b>'.$linefeed;
13225: }
13226: }
13227: return $output;
13228: }
13229:
13230: sub commit_studentrole {
13231: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
13232: my ($result,$linefeed,$oldsecurl,$newsecurl);
13233: if ($context eq 'auto') {
13234: $linefeed = "\n";
13235: } else {
13236: $linefeed = '<br />'."\n";
13237: }
13238: if (defined($one) && defined($two)) {
13239: my $cid=$one.'_'.$two;
13240: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
13241: my $secchange = 0;
13242: my $expire_role_result;
13243: my $modify_section_result;
13244: if ($oldsec ne '-1') {
13245: if ($oldsec ne $sec) {
13246: $secchange = 1;
13247: my $now = time;
13248: my $uurl='/'.$cid;
13249: $uurl=~s/\_/\//g;
13250: if ($oldsec) {
13251: $uurl.='/'.$oldsec;
13252: }
13253: $oldsecurl = $uurl;
13254: $expire_role_result =
13255: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
13256: if ($env{'request.course.sec'} ne '') {
13257: if ($expire_role_result eq 'refused') {
13258: my @roles = ('st');
13259: my @statuses = ('previous');
13260: my @roledoms = ($one);
13261: my $withsec = 1;
13262: my %roleshash =
13263: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
13264: \@statuses,\@roles,\@roledoms,$withsec);
13265: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
13266: my ($oldstart,$oldend) =
13267: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
13268: if ($oldend > 0 && $oldend <= $now) {
13269: $expire_role_result = 'ok';
13270: }
13271: }
13272: }
13273: }
13274: $result = $expire_role_result;
13275: }
13276: }
13277: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
13278: $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
13279: if ($modify_section_result =~ /^ok/) {
13280: if ($secchange == 1) {
13281: if ($sec eq '') {
13282: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
13283: } else {
13284: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
13285: }
13286: } elsif ($oldsec eq '-1') {
13287: if ($sec eq '') {
13288: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
13289: } else {
13290: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13291: }
13292: } else {
13293: if ($sec eq '') {
13294: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
13295: } else {
13296: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13297: }
13298: }
13299: } else {
13300: if ($secchange) {
13301: $$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;
13302: } else {
13303: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
13304: }
13305: }
13306: $result = $modify_section_result;
13307: } elsif ($secchange == 1) {
13308: if ($oldsec eq '') {
13309: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
13310: } else {
13311: $$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;
13312: }
13313: if ($expire_role_result eq 'refused') {
13314: my $newsecurl = '/'.$cid;
13315: $newsecurl =~ s/\_/\//g;
13316: if ($sec ne '') {
13317: $newsecurl.='/'.$sec;
13318: }
13319: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
13320: if ($sec eq '') {
13321: $$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;
13322: } else {
13323: $$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;
13324: }
13325: }
13326: }
13327: }
13328: } else {
13329: $$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;
13330: $result = "error: incomplete course id\n";
13331: }
13332: return $result;
13333: }
13334:
13335: sub show_role_extent {
13336: my ($scope,$context,$role) = @_;
13337: $scope =~ s{^/}{};
13338: my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
13339: push(@courseroles,'co');
13340: my @authorroles = &Apache::lonuserutils::roles_by_context('author');
13341: if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
13342: $scope =~ s{/}{_};
13343: return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
13344: } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
13345: my ($audom,$auname) = split(/\//,$scope);
13346: return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
13347: &Apache::loncommon::plainname($auname,$audom).'</span>');
13348: } else {
13349: $scope =~ s{/$}{};
13350: return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
13351: &Apache::lonnet::domain($scope,'description').'</span>');
13352: }
13353: }
13354:
13355: ############################################################
13356: ############################################################
13357:
13358: sub check_clone {
13359: my ($args,$linefeed) = @_;
13360: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
13361: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
13362: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
13363: my $clonemsg;
13364: my $can_clone = 0;
13365: my $lctype = lc($args->{'crstype'});
13366: if ($lctype ne 'community') {
13367: $lctype = 'course';
13368: }
13369: if ($clonehome eq 'no_host') {
13370: if ($args->{'crstype'} eq 'Community') {
13371: $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'});
13372: } else {
13373: $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'});
13374: }
13375: } else {
13376: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
13377: if ($args->{'crstype'} eq 'Community') {
13378: if ($clonedesc{'type'} ne 'Community') {
13379: $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'});
13380: return ($can_clone, $clonemsg, $cloneid, $clonehome);
13381: }
13382: }
13383: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
13384: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
13385: $can_clone = 1;
13386: } else {
13387: my %clonehash = &Apache::lonnet::get('environment',['cloners'],
13388: $args->{'clonedomain'},$args->{'clonecourse'});
13389: my @cloners = split(/,/,$clonehash{'cloners'});
13390: if (grep(/^\*$/,@cloners)) {
13391: $can_clone = 1;
13392: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
13393: $can_clone = 1;
13394: } else {
13395: my $ccrole = 'cc';
13396: if ($args->{'crstype'} eq 'Community') {
13397: $ccrole = 'co';
13398: }
13399: my %roleshash =
13400: &Apache::lonnet::get_my_roles($args->{'ccuname'},
13401: $args->{'ccdomain'},
13402: 'userroles',['active'],[$ccrole],
13403: [$args->{'clonedomain'}]);
13404: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
13405: $can_clone = 1;
13406: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
13407: $can_clone = 1;
13408: } else {
13409: if ($args->{'crstype'} eq 'Community') {
13410: $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'});
13411: } else {
13412: $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'});
13413: }
13414: }
13415: }
13416: }
13417: }
13418: return ($can_clone, $clonemsg, $cloneid, $clonehome);
13419: }
13420:
13421: sub construct_course {
13422: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
13423: my $outcome;
13424: my $linefeed = '<br />'."\n";
13425: if ($context eq 'auto') {
13426: $linefeed = "\n";
13427: }
13428:
13429: #
13430: # Are we cloning?
13431: #
13432: my ($can_clone, $clonemsg, $cloneid, $clonehome);
13433: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
13434: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
13435: if ($context ne 'auto') {
13436: if ($clonemsg ne '') {
13437: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
13438: }
13439: }
13440: $outcome .= $clonemsg.$linefeed;
13441:
13442: if (!$can_clone) {
13443: return (0,$outcome);
13444: }
13445: }
13446:
13447: #
13448: # Open course
13449: #
13450: my $crstype = lc($args->{'crstype'});
13451: my %cenv=();
13452: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
13453: $args->{'cdescr'},
13454: $args->{'curl'},
13455: $args->{'course_home'},
13456: $args->{'nonstandard'},
13457: $args->{'crscode'},
13458: $args->{'ccuname'}.':'.
13459: $args->{'ccdomain'},
13460: $args->{'crstype'},
13461: $cnum,$context,$category);
13462:
13463: # Note: The testing routines depend on this being output; see
13464: # Utils::Course. This needs to at least be output as a comment
13465: # if anyone ever decides to not show this, and Utils::Course::new
13466: # will need to be suitably modified.
13467: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
13468: if ($$courseid =~ /^error:/) {
13469: return (0,$outcome);
13470: }
13471:
13472: #
13473: # Check if created correctly
13474: #
13475: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
13476: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
13477: if ($crsuhome eq 'no_host') {
13478: $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
13479: return (0,$outcome);
13480: }
13481: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
13482:
13483: #
13484: # Do the cloning
13485: #
13486: if ($can_clone && $cloneid) {
13487: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
13488: if ($context ne 'auto') {
13489: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
13490: }
13491: $outcome .= $clonemsg.$linefeed;
13492: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
13493: # Copy all files
13494: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
13495: # Restore URL
13496: $cenv{'url'}=$oldcenv{'url'};
13497: # Restore title
13498: $cenv{'description'}=$oldcenv{'description'};
13499: # Restore creation date, creator and creation context.
13500: $cenv{'internal.created'}=$oldcenv{'internal.created'};
13501: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
13502: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
13503: # Mark as cloned
13504: $cenv{'clonedfrom'}=$cloneid;
13505: # Need to clone grading mode
13506: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
13507: $cenv{'grading'}=$newenv{'grading'};
13508: # Do not clone these environment entries
13509: &Apache::lonnet::del('environment',
13510: ['default_enrollment_start_date',
13511: 'default_enrollment_end_date',
13512: 'question.email',
13513: 'policy.email',
13514: 'comment.email',
13515: 'pch.users.denied',
13516: 'plc.users.denied',
13517: 'hidefromcat',
13518: 'categories'],
13519: $$crsudom,$$crsunum);
13520: }
13521:
13522: #
13523: # Set environment (will override cloned, if existing)
13524: #
13525: my @sections = ();
13526: my @xlists = ();
13527: if ($args->{'crstype'}) {
13528: $cenv{'type'}=$args->{'crstype'};
13529: }
13530: if ($args->{'crsid'}) {
13531: $cenv{'courseid'}=$args->{'crsid'};
13532: }
13533: if ($args->{'crscode'}) {
13534: $cenv{'internal.coursecode'}=$args->{'crscode'};
13535: }
13536: if ($args->{'crsquota'} ne '') {
13537: $cenv{'internal.coursequota'}=$args->{'crsquota'};
13538: } else {
13539: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
13540: }
13541: if ($args->{'ccuname'}) {
13542: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
13543: ':'.$args->{'ccdomain'};
13544: } else {
13545: $cenv{'internal.courseowner'} = $args->{'curruser'};
13546: }
13547: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
13548: if ($args->{'crssections'}) {
13549: $cenv{'internal.sectionnums'} = '';
13550: if ($args->{'crssections'} =~ m/,/) {
13551: @sections = split/,/,$args->{'crssections'};
13552: } else {
13553: $sections[0] = $args->{'crssections'};
13554: }
13555: if (@sections > 0) {
13556: foreach my $item (@sections) {
13557: my ($sec,$gp) = split/:/,$item;
13558: my $class = $args->{'crscode'}.$sec;
13559: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
13560: $cenv{'internal.sectionnums'} .= $item.',';
13561: unless ($addcheck eq 'ok') {
13562: push @badclasses, $class;
13563: }
13564: }
13565: $cenv{'internal.sectionnums'} =~ s/,$//;
13566: }
13567: }
13568: # do not hide course coordinator from staff listing,
13569: # even if privileged
13570: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13571: # add crosslistings
13572: if ($args->{'crsxlist'}) {
13573: $cenv{'internal.crosslistings'}='';
13574: if ($args->{'crsxlist'} =~ m/,/) {
13575: @xlists = split/,/,$args->{'crsxlist'};
13576: } else {
13577: $xlists[0] = $args->{'crsxlist'};
13578: }
13579: if (@xlists > 0) {
13580: foreach my $item (@xlists) {
13581: my ($xl,$gp) = split/:/,$item;
13582: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
13583: $cenv{'internal.crosslistings'} .= $item.',';
13584: unless ($addcheck eq 'ok') {
13585: push @badclasses, $xl;
13586: }
13587: }
13588: $cenv{'internal.crosslistings'} =~ s/,$//;
13589: }
13590: }
13591: if ($args->{'autoadds'}) {
13592: $cenv{'internal.autoadds'}=$args->{'autoadds'};
13593: }
13594: if ($args->{'autodrops'}) {
13595: $cenv{'internal.autodrops'}=$args->{'autodrops'};
13596: }
13597: # check for notification of enrollment changes
13598: my @notified = ();
13599: if ($args->{'notify_owner'}) {
13600: if ($args->{'ccuname'} ne '') {
13601: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
13602: }
13603: }
13604: if ($args->{'notify_dc'}) {
13605: if ($uname ne '') {
13606: push(@notified,$uname.':'.$udom);
13607: }
13608: }
13609: if (@notified > 0) {
13610: my $notifylist;
13611: if (@notified > 1) {
13612: $notifylist = join(',',@notified);
13613: } else {
13614: $notifylist = $notified[0];
13615: }
13616: $cenv{'internal.notifylist'} = $notifylist;
13617: }
13618: if (@badclasses > 0) {
13619: my %lt=&Apache::lonlocal::texthash(
13620: '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',
13621: 'dnhr' => 'does not have rights to access enrollment in these classes',
13622: 'adby' => 'as determined by the policies of your institution on access to official classlists'
13623: );
13624: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
13625: ' ('.$lt{'adby'}.')';
13626: if ($context eq 'auto') {
13627: $outcome .= $badclass_msg.$linefeed;
13628: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
13629: foreach my $item (@badclasses) {
13630: if ($context eq 'auto') {
13631: $outcome .= " - $item\n";
13632: } else {
13633: $outcome .= "<li>$item</li>\n";
13634: }
13635: }
13636: if ($context eq 'auto') {
13637: $outcome .= $linefeed;
13638: } else {
13639: $outcome .= "</ul><br /><br /></div>\n";
13640: }
13641: }
13642: }
13643: if ($args->{'no_end_date'}) {
13644: $args->{'endaccess'} = 0;
13645: }
13646: $cenv{'internal.autostart'}=$args->{'enrollstart'};
13647: $cenv{'internal.autoend'}=$args->{'enrollend'};
13648: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
13649: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
13650: if ($args->{'showphotos'}) {
13651: $cenv{'internal.showphotos'}=$args->{'showphotos'};
13652: }
13653: $cenv{'internal.authtype'} = $args->{'authtype'};
13654: $cenv{'internal.autharg'} = $args->{'autharg'};
13655: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
13656: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
13657: 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');
13658: if ($context eq 'auto') {
13659: $outcome .= $krb_msg;
13660: } else {
13661: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
13662: }
13663: $outcome .= $linefeed;
13664: }
13665: }
13666: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
13667: if ($args->{'setpolicy'}) {
13668: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13669: }
13670: if ($args->{'setcontent'}) {
13671: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13672: }
13673: }
13674: if ($args->{'reshome'}) {
13675: $cenv{'reshome'}=$args->{'reshome'}.'/';
13676: $cenv{'reshome'}=~s/\/+$/\//;
13677: }
13678: #
13679: # course has keyed access
13680: #
13681: if ($args->{'setkeys'}) {
13682: $cenv{'keyaccess'}='yes';
13683: }
13684: # if specified, key authority is not course, but user
13685: # only active if keyaccess is yes
13686: if ($args->{'keyauth'}) {
13687: my ($user,$domain) = split(':',$args->{'keyauth'});
13688: $user = &LONCAPA::clean_username($user);
13689: $domain = &LONCAPA::clean_username($domain);
13690: if ($user ne '' && $domain ne '') {
13691: $cenv{'keyauth'}=$user.':'.$domain;
13692: }
13693: }
13694:
13695: if ($args->{'disresdis'}) {
13696: $cenv{'pch.roles.denied'}='st';
13697: }
13698: if ($args->{'disablechat'}) {
13699: $cenv{'plc.roles.denied'}='st';
13700: }
13701:
13702: # Record we've not yet viewed the Course Initialization Helper for this
13703: # course
13704: $cenv{'course.helper.not.run'} = 1;
13705: #
13706: # Use new Randomseed
13707: #
13708: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
13709: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
13710: #
13711: # The encryption code and receipt prefix for this course
13712: #
13713: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
13714: $cenv{'internal.encpref'}=100+int(9*rand(99));
13715: #
13716: # By default, use standard grading
13717: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
13718:
13719: $outcome .= $linefeed.&mt('Setting environment').': '.
13720: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
13721: #
13722: # Open all assignments
13723: #
13724: if ($args->{'openall'}) {
13725: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
13726: my %storecontent = ($storeunder => time,
13727: $storeunder.'.type' => 'date_start');
13728:
13729: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
13730: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
13731: }
13732: #
13733: # Set first page
13734: #
13735: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
13736: || ($cloneid)) {
13737: use LONCAPA::map;
13738: $outcome .= &mt('Setting first resource').': ';
13739:
13740: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
13741: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
13742:
13743: $outcome .= ($fatal?$errtext:'read ok').' - ';
13744: my $title; my $url;
13745: if ($args->{'firstres'} eq 'syl') {
13746: $title=&mt('Syllabus');
13747: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
13748: } else {
13749: $title=&mt('Table of Contents');
13750: $url='/adm/navmaps';
13751: }
13752:
13753: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
13754: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
13755:
13756: if ($errtext) { $fatal=2; }
13757: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
13758: }
13759:
13760: return (1,$outcome);
13761: }
13762:
13763: ############################################################
13764: ############################################################
13765:
13766: #SD
13767: # only Community and Course, or anything else?
13768: sub course_type {
13769: my ($cid) = @_;
13770: if (!defined($cid)) {
13771: $cid = $env{'request.course.id'};
13772: }
13773: if (defined($env{'course.'.$cid.'.type'})) {
13774: return $env{'course.'.$cid.'.type'};
13775: } else {
13776: return 'Course';
13777: }
13778: }
13779:
13780: sub group_term {
13781: my $crstype = &course_type();
13782: my %names = (
13783: 'Course' => 'group',
13784: 'Community' => 'group',
13785: );
13786: return $names{$crstype};
13787: }
13788:
13789: sub course_types {
13790: my @types = ('official','unofficial','community');
13791: my %typename = (
13792: official => 'Official course',
13793: unofficial => 'Unofficial course',
13794: community => 'Community',
13795: );
13796: return (\@types,\%typename);
13797: }
13798:
13799: sub icon {
13800: my ($file)=@_;
13801: my $curfext = lc((split(/\./,$file))[-1]);
13802: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
13803: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
13804: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
13805: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
13806: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
13807: $curfext.".gif") {
13808: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
13809: $curfext.".gif";
13810: }
13811: }
13812: return &lonhttpdurl($iconname);
13813: }
13814:
13815: sub lonhttpdurl {
13816: #
13817: # Had been used for "small fry" static images on separate port 8080.
13818: # Modify here if lightweight http functionality desired again.
13819: # Currently eliminated due to increasing firewall issues.
13820: #
13821: my ($url)=@_;
13822: return $url;
13823: }
13824:
13825: sub connection_aborted {
13826: my ($r)=@_;
13827: $r->print(" ");$r->rflush();
13828: my $c = $r->connection;
13829: return $c->aborted();
13830: }
13831:
13832: # Escapes strings that may have embedded 's that will be put into
13833: # strings as 'strings'.
13834: sub escape_single {
13835: my ($input) = @_;
13836: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
13837: $input =~ s/\'/\\\'/g; # Esacpe the 's....
13838: return $input;
13839: }
13840:
13841: # Same as escape_single, but escape's "'s This
13842: # can be used for "strings"
13843: sub escape_double {
13844: my ($input) = @_;
13845: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
13846: $input =~ s/\"/\\\"/g; # Esacpe the "s....
13847: return $input;
13848: }
13849:
13850: # Escapes the last element of a full URL.
13851: sub escape_url {
13852: my ($url) = @_;
13853: my @urlslices = split(/\//, $url,-1);
13854: my $lastitem = &escape(pop(@urlslices));
13855: return join('/',@urlslices).'/'.$lastitem;
13856: }
13857:
13858: sub compare_arrays {
13859: my ($arrayref1,$arrayref2) = @_;
13860: my (@difference,%count);
13861: @difference = ();
13862: %count = ();
13863: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
13864: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
13865: foreach my $element (keys(%count)) {
13866: if ($count{$element} == 1) {
13867: push(@difference,$element);
13868: }
13869: }
13870: }
13871: return @difference;
13872: }
13873:
13874: # -------------------------------------------------------- Initialize user login
13875: sub init_user_environment {
13876: my ($r, $username, $domain, $authhost, $form, $args) = @_;
13877: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
13878:
13879: my $public=($username eq 'public' && $domain eq 'public');
13880:
13881: # See if old ID present, if so, remove
13882:
13883: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
13884: my $now=time;
13885:
13886: if ($public) {
13887: my $max_public=100;
13888: my $oldest;
13889: my $oldest_time=0;
13890: for(my $next=1;$next<=$max_public;$next++) {
13891: if (-e $lonids."/publicuser_$next.id") {
13892: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
13893: if ($mtime<$oldest_time || !$oldest_time) {
13894: $oldest_time=$mtime;
13895: $oldest=$next;
13896: }
13897: } else {
13898: $cookie="publicuser_$next";
13899: last;
13900: }
13901: }
13902: if (!$cookie) { $cookie="publicuser_$oldest"; }
13903: } else {
13904: # if this isn't a robot, kill any existing non-robot sessions
13905: if (!$args->{'robot'}) {
13906: opendir(DIR,$lonids);
13907: while ($filename=readdir(DIR)) {
13908: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
13909: unlink($lonids.'/'.$filename);
13910: }
13911: }
13912: closedir(DIR);
13913: }
13914: # Give them a new cookie
13915: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
13916: : $now.$$.int(rand(10000)));
13917: $cookie="$username\_$id\_$domain\_$authhost";
13918:
13919: # Initialize roles
13920:
13921: ($userroles,$firstaccenv,$timerintenv) =
13922: &Apache::lonnet::rolesinit($domain,$username,$authhost);
13923: }
13924: # ------------------------------------ Check browser type and MathML capability
13925:
13926: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
13927: $clientunicode,$clientos) = &decode_user_agent($r);
13928:
13929: # ------------------------------------------------------------- Get environment
13930:
13931: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
13932: my ($tmp) = keys(%userenv);
13933: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13934: } else {
13935: undef(%userenv);
13936: }
13937: if (($userenv{'interface'}) && (!$form->{'interface'})) {
13938: $form->{'interface'}=$userenv{'interface'};
13939: }
13940: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
13941:
13942: # --------------- Do not trust query string to be put directly into environment
13943: foreach my $option ('interface','localpath','localres') {
13944: $form->{$option}=~s/[\n\r\=]//gs;
13945: }
13946: # --------------------------------------------------------- Write first profile
13947:
13948: {
13949: my %initial_env =
13950: ("user.name" => $username,
13951: "user.domain" => $domain,
13952: "user.home" => $authhost,
13953: "browser.type" => $clientbrowser,
13954: "browser.version" => $clientversion,
13955: "browser.mathml" => $clientmathml,
13956: "browser.unicode" => $clientunicode,
13957: "browser.os" => $clientos,
13958: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
13959: "request.course.fn" => '',
13960: "request.course.uri" => '',
13961: "request.course.sec" => '',
13962: "request.role" => 'cm',
13963: "request.role.adv" => $env{'user.adv'},
13964: "request.host" => $ENV{'REMOTE_ADDR'},);
13965:
13966: if ($form->{'localpath'}) {
13967: $initial_env{"browser.localpath"} = $form->{'localpath'};
13968: $initial_env{"browser.localres"} = $form->{'localres'};
13969: }
13970:
13971: if ($form->{'interface'}) {
13972: $form->{'interface'}=~s/\W//gs;
13973: $initial_env{"browser.interface"} = $form->{'interface'};
13974: $env{'browser.interface'}=$form->{'interface'};
13975: }
13976:
13977: my %is_adv = ( is_adv => $env{'user.adv'} );
13978: my %domdef;
13979: unless ($domain eq 'public') {
13980: %domdef = &Apache::lonnet::get_domain_defaults($domain);
13981: }
13982:
13983: foreach my $tool ('aboutme','blog','webdav','portfolio') {
13984: $userenv{'availabletools.'.$tool} =
13985: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
13986: undef,\%userenv,\%domdef,\%is_adv);
13987: }
13988:
13989: foreach my $crstype ('official','unofficial','community') {
13990: $userenv{'canrequest.'.$crstype} =
13991: &Apache::lonnet::usertools_access($username,$domain,$crstype,
13992: 'reload','requestcourses',
13993: \%userenv,\%domdef,\%is_adv);
13994: }
13995:
13996: $userenv{'canrequest.author'} =
13997: &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
13998: 'reload','requestauthor',
13999: \%userenv,\%domdef,\%is_adv);
14000: my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
14001: $domain,$username);
14002: my $reqstatus = $reqauthor{'author_status'};
14003: if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
14004: if (ref($reqauthor{'author'}) eq 'HASH') {
14005: $userenv{'requestauthorqueued'} = $reqstatus.':'.
14006: $reqauthor{'author'}{'timestamp'};
14007: }
14008: }
14009:
14010: $env{'user.environment'} = "$lonids/$cookie.id";
14011:
14012: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
14013: &GDBM_WRCREAT(),0640)) {
14014: &_add_to_env(\%disk_env,\%initial_env);
14015: &_add_to_env(\%disk_env,\%userenv,'environment.');
14016: &_add_to_env(\%disk_env,$userroles);
14017: if (ref($firstaccenv) eq 'HASH') {
14018: &_add_to_env(\%disk_env,$firstaccenv);
14019: }
14020: if (ref($timerintenv) eq 'HASH') {
14021: &_add_to_env(\%disk_env,$timerintenv);
14022: }
14023: if (ref($args->{'extra_env'})) {
14024: &_add_to_env(\%disk_env,$args->{'extra_env'});
14025: }
14026: untie(%disk_env);
14027: } else {
14028: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
14029: 'Could not create environment storage in lonauth: '.$!.'</span>');
14030: return 'error: '.$!;
14031: }
14032: }
14033: $env{'request.role'}='cm';
14034: $env{'request.role.adv'}=$env{'user.adv'};
14035: $env{'browser.type'}=$clientbrowser;
14036:
14037: return $cookie;
14038:
14039: }
14040:
14041: sub _add_to_env {
14042: my ($idf,$env_data,$prefix) = @_;
14043: if (ref($env_data) eq 'HASH') {
14044: while (my ($key,$value) = each(%$env_data)) {
14045: $idf->{$prefix.$key} = $value;
14046: $env{$prefix.$key} = $value;
14047: }
14048: }
14049: }
14050:
14051: # --- Get the symbolic name of a problem and the url
14052: sub get_symb {
14053: my ($request,$silent) = @_;
14054: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
14055: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
14056: if ($symb eq '') {
14057: if (!$silent) {
14058: if (ref($request)) {
14059: $request->print("Unable to handle ambiguous references:$url:.");
14060: }
14061: return ();
14062: }
14063: }
14064: &Apache::lonenc::check_decrypt(\$symb);
14065: return ($symb);
14066: }
14067:
14068: # --------------------------------------------------------------Get annotation
14069:
14070: sub get_annotation {
14071: my ($symb,$enc) = @_;
14072:
14073: my $key = $symb;
14074: if (!$enc) {
14075: $key =
14076: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
14077: }
14078: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
14079: return $annotation{$key};
14080: }
14081:
14082: sub clean_symb {
14083: my ($symb,$delete_enc) = @_;
14084:
14085: &Apache::lonenc::check_decrypt(\$symb);
14086: my $enc = $env{'request.enc'};
14087: if ($delete_enc) {
14088: delete($env{'request.enc'});
14089: }
14090:
14091: return ($symb,$enc);
14092: }
14093:
14094: sub build_release_hashes {
14095: my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
14096: return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
14097: (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
14098: (ref($randomizetry) eq 'HASH'));
14099: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14100: my ($item,$name,$value) = split(/:/,$key);
14101: if ($item eq 'parameter') {
14102: if (ref($checkparms->{$name}) eq 'ARRAY') {
14103: unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
14104: push(@{$checkparms->{$name}},$value);
14105: }
14106: } else {
14107: push(@{$checkparms->{$name}},$value);
14108: }
14109: } elsif ($item eq 'resourcetag') {
14110: if ($name eq 'responsetype') {
14111: $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
14112: }
14113: } elsif ($item eq 'course') {
14114: if ($name eq 'crstype') {
14115: $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
14116: }
14117: }
14118: }
14119: ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
14120: ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
14121: return;
14122: }
14123:
14124: sub update_content_constraints {
14125: my ($cdom,$cnum,$chome,$cid) = @_;
14126: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
14127: my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
14128: my %checkresponsetypes;
14129: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14130: my ($item,$name,$value) = split(/:/,$key);
14131: if ($item eq 'resourcetag') {
14132: if ($name eq 'responsetype') {
14133: $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
14134: }
14135: }
14136: }
14137: my $navmap = Apache::lonnavmaps::navmap->new();
14138: if (defined($navmap)) {
14139: my %allresponses;
14140: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
14141: my %responses = $res->responseTypes();
14142: foreach my $key (keys(%responses)) {
14143: next unless(exists($checkresponsetypes{$key}));
14144: $allresponses{$key} += $responses{$key};
14145: }
14146: }
14147: foreach my $key (keys(%allresponses)) {
14148: my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
14149: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
14150: ($reqdmajor,$reqdminor) = ($major,$minor);
14151: }
14152: }
14153: undef($navmap);
14154: }
14155: unless (($reqdmajor eq '') && ($reqdminor eq '')) {
14156: &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
14157: }
14158: return;
14159: }
14160:
14161: sub allmaps_incourse {
14162: my ($cdom,$cnum,$chome,$cid) = @_;
14163: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
14164: $cid = $env{'request.course.id'};
14165: $cdom = $env{'course.'.$cid.'.domain'};
14166: $cnum = $env{'course.'.$cid.'.num'};
14167: $chome = $env{'course.'.$cid.'.home'};
14168: }
14169: my %allmaps = ();
14170: my $lastchange =
14171: &Apache::lonnet::get_coursechange($cdom,$cnum);
14172: if ($lastchange > $env{'request.course.tied'}) {
14173: my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
14174: unless ($ferr) {
14175: &update_content_constraints($cdom,$cnum,$chome,$cid);
14176: }
14177: }
14178: my $navmap = Apache::lonnavmaps::navmap->new();
14179: if (defined($navmap)) {
14180: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
14181: $allmaps{$res->src()} = 1;
14182: }
14183: }
14184: return \%allmaps;
14185: }
14186:
14187: sub parse_supplemental_title {
14188: my ($title) = @_;
14189:
14190: my ($foldertitle,$renametitle);
14191: if ($title =~ /&&&/) {
14192: $title = &HTML::Entites::decode($title);
14193: }
14194: if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
14195: $renametitle=$4;
14196: my ($time,$uname,$udom) = ($1,$2,$3);
14197: $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
14198: my $name = &plainname($uname,$udom);
14199: $name = &HTML::Entities::encode($name,'"<>&\'');
14200: $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
14201: $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
14202: $name.': <br />'.$foldertitle;
14203: }
14204: if (wantarray) {
14205: return ($title,$foldertitle,$renametitle);
14206: }
14207: return $title;
14208: }
14209:
14210: sub symb_to_docspath {
14211: my ($symb) = @_;
14212: return unless ($symb);
14213: my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
14214: if ($resurl=~/\.(sequence|page)$/) {
14215: $mapurl=$resurl;
14216: } elsif ($resurl eq 'adm/navmaps') {
14217: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
14218: }
14219: my $mapresobj;
14220: my $navmap = Apache::lonnavmaps::navmap->new();
14221: if (ref($navmap)) {
14222: $mapresobj = $navmap->getResourceByUrl($mapurl);
14223: }
14224: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
14225: my $type=$2;
14226: my $path;
14227: if (ref($mapresobj)) {
14228: my $pcslist = $mapresobj->map_hierarchy();
14229: if ($pcslist ne '') {
14230: foreach my $pc (split(/,/,$pcslist)) {
14231: next if ($pc <= 1);
14232: my $res = $navmap->getByMapPc($pc);
14233: if (ref($res)) {
14234: my $thisurl = $res->src();
14235: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
14236: my $thistitle = $res->title();
14237: $path .= '&'.
14238: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
14239: &Apache::lonhtmlcommon::entity_encode($thistitle).
14240: ':'.$res->randompick().
14241: ':'.$res->randomout().
14242: ':'.$res->encrypted().
14243: ':'.$res->randomorder().
14244: ':'.$res->is_page();
14245: }
14246: }
14247: }
14248: $path =~ s/^\&//;
14249: my $maptitle = $mapresobj->title();
14250: if ($mapurl eq 'default') {
14251: $maptitle = 'Main Course Documents';
14252: }
14253: $path .= (($path ne '')? '&' : '').
14254: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14255: &Apache::lonhtmlcommon::entity_encode($maptitle).
14256: ':'.$mapresobj->randompick().
14257: ':'.$mapresobj->randomout().
14258: ':'.$mapresobj->encrypted().
14259: ':'.$mapresobj->randomorder().
14260: ':'.$mapresobj->is_page();
14261: } else {
14262: my $maptitle = &Apache::lonnet::gettitle($mapurl);
14263: my $ispage = (($type eq 'page')? 1 : '');
14264: if ($mapurl eq 'default') {
14265: $maptitle = 'Main Course Documents';
14266: }
14267: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14268: &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
14269: }
14270: unless ($mapurl eq 'default') {
14271: $path = 'default&'.
14272: &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
14273: ':::::&'.$path;
14274: }
14275: return $path;
14276: }
14277:
14278: sub captcha_display {
14279: my ($context,$lonhost) = @_;
14280: my ($output,$error);
14281: my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14282: if ($captcha eq 'original') {
14283: $output = &create_captcha();
14284: unless ($output) {
14285: $error = 'captcha';
14286: }
14287: } elsif ($captcha eq 'recaptcha') {
14288: $output = &create_recaptcha($pubkey);
14289: unless ($output) {
14290: $error = 'recaptcha';
14291: }
14292: }
14293: return ($output,$error);
14294: }
14295:
14296: sub captcha_response {
14297: my ($context,$lonhost) = @_;
14298: my ($captcha_chk,$captcha_error);
14299: my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14300: if ($captcha eq 'original') {
14301: ($captcha_chk,$captcha_error) = &check_captcha();
14302: } elsif ($captcha eq 'recaptcha') {
14303: $captcha_chk = &check_recaptcha($privkey);
14304: } else {
14305: $captcha_chk = 1;
14306: }
14307: return ($captcha_chk,$captcha_error);
14308: }
14309:
14310: sub get_captcha_config {
14311: my ($context,$lonhost) = @_;
14312: my ($captcha,$pubkey,$privkey,$hashtocheck);
14313: my $hostname = &Apache::lonnet::hostname($lonhost);
14314: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
14315: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
14316: if ($context eq 'usercreation') {
14317: my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
14318: if (ref($domconfig{$context}) eq 'HASH') {
14319: $hashtocheck = $domconfig{$context}{'cancreate'};
14320: if (ref($hashtocheck) eq 'HASH') {
14321: if ($hashtocheck->{'captcha'} eq 'recaptcha') {
14322: if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
14323: $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
14324: $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
14325: }
14326: if ($privkey && $pubkey) {
14327: $captcha = 'recaptcha';
14328: } else {
14329: $captcha = 'original';
14330: }
14331: } elsif ($hashtocheck->{'captcha'} ne 'notused') {
14332: $captcha = 'original';
14333: }
14334: }
14335: } else {
14336: $captcha = 'captcha';
14337: }
14338: } elsif ($context eq 'login') {
14339: my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
14340: if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
14341: $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
14342: $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
14343: if ($privkey && $pubkey) {
14344: $captcha = 'recaptcha';
14345: } else {
14346: $captcha = 'original';
14347: }
14348: } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
14349: $captcha = 'original';
14350: }
14351: }
14352: return ($captcha,$pubkey,$privkey);
14353: }
14354:
14355: sub create_captcha {
14356: my %captcha_params = &captcha_settings();
14357: my ($output,$maxtries,$tries) = ('',10,0);
14358: while ($tries < $maxtries) {
14359: $tries ++;
14360: my $captcha = Authen::Captcha->new (
14361: output_folder => $captcha_params{'output_dir'},
14362: data_folder => $captcha_params{'db_dir'},
14363: );
14364: my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
14365:
14366: if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
14367: $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
14368: &mt('Type in the letters/numbers shown below').' '.
14369: '<input type="text" size="5" name="code" value="" /><br />'.
14370: '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
14371: last;
14372: }
14373: }
14374: return $output;
14375: }
14376:
14377: sub captcha_settings {
14378: my %captcha_params = (
14379: output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'},
14380: www_output_dir => "/captchaspool",
14381: db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'},
14382: numchars => '5',
14383: );
14384: return %captcha_params;
14385: }
14386:
14387: sub check_captcha {
14388: my ($captcha_chk,$captcha_error);
14389: my $code = $env{'form.code'};
14390: my $md5sum = $env{'form.crypt'};
14391: my %captcha_params = &captcha_settings();
14392: my $captcha = Authen::Captcha->new(
14393: output_folder => $captcha_params{'output_dir'},
14394: data_folder => $captcha_params{'db_dir'},
14395: );
14396: $captcha_chk = $captcha->check_code($code,$md5sum);
14397: my %captcha_hash = (
14398: 0 => 'Code not checked (file error)',
14399: -1 => 'Failed: code expired',
14400: -2 => 'Failed: invalid code (not in database)',
14401: -3 => 'Failed: invalid code (code does not match crypt)',
14402: );
14403: if ($captcha_chk != 1) {
14404: $captcha_error = $captcha_hash{$captcha_chk}
14405: }
14406: return ($captcha_chk,$captcha_error);
14407: }
14408:
14409: sub create_recaptcha {
14410: my ($pubkey) = @_;
14411: my $captcha = Captcha::reCAPTCHA->new;
14412: return $captcha->get_options_setter({theme => 'white'})."\n".
14413: $captcha->get_html($pubkey).
14414: &mt('If either word is hard to read, [_1] will replace them.',
14415: '<image src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
14416: '<br /><br />';
14417: }
14418:
14419: sub check_recaptcha {
14420: my ($privkey) = @_;
14421: my $captcha_chk;
14422: my $captcha = Captcha::reCAPTCHA->new;
14423: my $captcha_result =
14424: $captcha->check_answer(
14425: $privkey,
14426: $ENV{'REMOTE_ADDR'},
14427: $env{'form.recaptcha_challenge_field'},
14428: $env{'form.recaptcha_response_field'},
14429: );
14430: if ($captcha_result->{is_valid}) {
14431: $captcha_chk = 1;
14432: }
14433: return $captcha_chk;
14434: }
14435:
14436: =pod
14437:
14438: =back
14439:
14440: =cut
14441:
14442: 1;
14443: __END__;
14444:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>