File:
[LON-CAPA] /
loncom /
interface /
loncommon.pm
Revision
1.1130:
download - view:
text,
annotated -
select for diffs
Sat May 25 21:56:23 2013 UTC (11 years, 3 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Items in "Personal" sub-menu in primary menu moved from a separate item
on right of screen to sub-menu attached to user's fullname on left of
screen.
- "Information" item added (points to user's personal information page)
as first item in sub-menu.
- xhtml for items in Functions bar, displayed when viewing a user's
personal information page in course context.
1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1130 2013/05/25 21:56:23 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: $credits_element) = @_;
536: my $wintitle = 'Course_Browser';
537: if ($crstype eq 'Community') {
538: $wintitle = 'Community_Browser';
539: }
540: my $id_functions = &javascript_index_functions();
541: my $output = '
542: <script type="text/javascript" language="JavaScript">
543: // <![CDATA[
544: var stdeditbrowser;'."\n";
545:
546: $output .= <<"ENDSTDBRW";
547: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
548: var url = '/adm/pickcourse?';
549: var formid = getFormIdByName(formname);
550: var domainfilter = getDomainFromSelectbox(formname,udom);
551: if (domainfilter != null) {
552: if (domainfilter != '') {
553: url += 'domainfilter='+domainfilter+'&';
554: }
555: }
556: url += 'form=' + formname + '&cnumelement='+uname+
557: '&cdomelement='+udom+
558: '&cnameelement='+desc;
559: if (extra_element !=null && extra_element != '') {
560: if (formname == 'rolechoice' || formname == 'studentform') {
561: url += '&roleelement='+extra_element;
562: if (domainfilter == null || domainfilter == '') {
563: url += '&domainfilter='+extra_element;
564: }
565: }
566: else {
567: if (formname == 'portform') {
568: url += '&setroles='+extra_element;
569: } else {
570: if (formname == 'rules') {
571: url += '&fixeddom='+extra_element;
572: }
573: }
574: }
575: }
576: if (type != null && type != '') {
577: url += '&type='+type;
578: }
579: if (type_elem != null && type_elem != '') {
580: url += '&typeelement='+type_elem;
581: }
582: if (formname == 'ccrs') {
583: var ownername = document.forms[formid].ccuname.value;
584: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
585: url += '&cloner='+ownername+':'+ownerdom;
586: }
587: if (multflag !=null && multflag != '') {
588: url += '&multiple='+multflag;
589: }
590: var title = '$wintitle';
591: var options = 'scrollbars=1,resizable=1,menubar=0';
592: options += ',width=700,height=600';
593: stdeditbrowser = open(url,title,options,'1');
594: stdeditbrowser.focus();
595: }
596: $id_functions
597: ENDSTDBRW
598: if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
599: $output .= &setsec_javascript($sec_element,$formname,$role_element,
600: $credits_element);
601: }
602: $output .= '
603: // ]]>
604: </script>';
605: return $output;
606: }
607:
608: sub javascript_index_functions {
609: return <<"ENDJS";
610:
611: function getFormIdByName(formname) {
612: for (var i=0;i<document.forms.length;i++) {
613: if (document.forms[i].name == formname) {
614: return i;
615: }
616: }
617: return -1;
618: }
619:
620: function getIndexByName(formid,item) {
621: for (var i=0;i<document.forms[formid].elements.length;i++) {
622: if (document.forms[formid].elements[i].name == item) {
623: return i;
624: }
625: }
626: return -1;
627: }
628:
629: function getDomainFromSelectbox(formname,udom) {
630: var userdom;
631: var formid = getFormIdByName(formname);
632: if (formid > -1) {
633: var domid = getIndexByName(formid,udom);
634: if (domid > -1) {
635: if (document.forms[formid].elements[domid].type == 'select-one') {
636: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
637: }
638: if (document.forms[formid].elements[domid].type == 'hidden') {
639: userdom=document.forms[formid].elements[domid].value;
640: }
641: }
642: }
643: return userdom;
644: }
645:
646: ENDJS
647:
648: }
649:
650: sub javascript_array_indexof {
651: return <<ENDJS;
652: <script type="text/javascript" language="JavaScript">
653: // <![CDATA[
654:
655: if (!Array.prototype.indexOf) {
656: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
657: "use strict";
658: if (this === void 0 || this === null) {
659: throw new TypeError();
660: }
661: var t = Object(this);
662: var len = t.length >>> 0;
663: if (len === 0) {
664: return -1;
665: }
666: var n = 0;
667: if (arguments.length > 0) {
668: n = Number(arguments[1]);
669: if (n !== n) { // shortcut for verifying if it is NaN
670: n = 0;
671: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
672: n = (n > 0 || -1) * Math.floor(Math.abs(n));
673: }
674: }
675: if (n >= len) {
676: return -1;
677: }
678: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
679: for (; k < len; k++) {
680: if (k in t && t[k] === searchElement) {
681: return k;
682: }
683: }
684: return -1;
685: }
686: }
687:
688: // ]]>
689: </script>
690:
691: ENDJS
692:
693: }
694:
695: sub userbrowser_javascript {
696: my $id_functions = &javascript_index_functions();
697: return <<"ENDUSERBRW";
698:
699: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
700: var url = '/adm/pickuser?';
701: var userdom = getDomainFromSelectbox(formname,udom);
702: if (userdom != null) {
703: if (userdom != '') {
704: url += 'srchdom='+userdom+'&';
705: }
706: }
707: url += 'form=' + formname + '&unameelement='+uname+
708: '&udomelement='+udom+
709: '&ulastelement='+ulast+
710: '&ufirstelement='+ufirst+
711: '&uemailelement='+uemail+
712: '&hideudomelement='+hideudom+
713: '&coursedom='+crsdom;
714: if ((caller != null) && (caller != undefined)) {
715: url += '&caller='+caller;
716: }
717: var title = 'User_Browser';
718: var options = 'scrollbars=1,resizable=1,menubar=0';
719: options += ',width=700,height=600';
720: var stdeditbrowser = open(url,title,options,'1');
721: stdeditbrowser.focus();
722: }
723:
724: function fix_domain (formname,udom,origdom,uname) {
725: var formid = getFormIdByName(formname);
726: if (formid > -1) {
727: var unameid = getIndexByName(formid,uname);
728: var domid = getIndexByName(formid,udom);
729: var hidedomid = getIndexByName(formid,origdom);
730: if (hidedomid > -1) {
731: var fixeddom = document.forms[formid].elements[hidedomid].value;
732: var unameval = document.forms[formid].elements[unameid].value;
733: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
734: if (domid > -1) {
735: var slct = document.forms[formid].elements[domid];
736: if (slct.type == 'select-one') {
737: var i;
738: for (i=0;i<slct.length;i++) {
739: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
740: }
741: }
742: if (slct.type == 'hidden') {
743: slct.value = fixeddom;
744: }
745: }
746: }
747: }
748: }
749: return;
750: }
751:
752: $id_functions
753: ENDUSERBRW
754: }
755:
756: sub setsec_javascript {
757: my ($sec_element,$formname,$role_element,$credits_element) = @_;
758: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
759: $communityrolestr);
760: if ($role_element ne '') {
761: my @allroles = ('st','ta','ep','in','ad');
762: foreach my $crstype ('Course','Community') {
763: if ($crstype eq 'Community') {
764: foreach my $role (@allroles) {
765: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
766: }
767: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
768: } else {
769: foreach my $role (@allroles) {
770: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
771: }
772: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
773: }
774: }
775: $rolestr = '"'.join('","',@allroles).'"';
776: $courserolestr = '"'.join('","',@courserolenames).'"';
777: $communityrolestr = '"'.join('","',@communityrolenames).'"';
778: }
779: my $setsections = qq|
780: function setSect(sectionlist) {
781: var sectionsArray = new Array();
782: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
783: sectionsArray = sectionlist.split(",");
784: }
785: var numSections = sectionsArray.length;
786: document.$formname.$sec_element.length = 0;
787: if (numSections == 0) {
788: document.$formname.$sec_element.multiple=false;
789: document.$formname.$sec_element.size=1;
790: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
791: } else {
792: if (numSections == 1) {
793: document.$formname.$sec_element.multiple=false;
794: document.$formname.$sec_element.size=1;
795: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
796: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
797: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
798: } else {
799: for (var i=0; i<numSections; i++) {
800: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
801: }
802: document.$formname.$sec_element.multiple=true
803: if (numSections < 3) {
804: document.$formname.$sec_element.size=numSections;
805: } else {
806: document.$formname.$sec_element.size=3;
807: }
808: document.$formname.$sec_element.options[0].selected = false
809: }
810: }
811: }
812:
813: function setRole(crstype) {
814: |;
815: if ($role_element eq '') {
816: $setsections .= ' return;
817: }
818: ';
819: } else {
820: $setsections .= qq|
821: var elementLength = document.$formname.$role_element.length;
822: var allroles = Array($rolestr);
823: var courserolenames = Array($courserolestr);
824: var communityrolenames = Array($communityrolestr);
825: if (elementLength != undefined) {
826: if (document.$formname.$role_element.options[5].value == 'cc') {
827: if (crstype == 'Course') {
828: return;
829: } else {
830: allroles[5] = 'co';
831: for (var i=0; i<6; i++) {
832: document.$formname.$role_element.options[i].value = allroles[i];
833: document.$formname.$role_element.options[i].text = communityrolenames[i];
834: }
835: }
836: } else {
837: if (crstype == 'Community') {
838: return;
839: } else {
840: allroles[5] = 'cc';
841: for (var i=0; i<6; i++) {
842: document.$formname.$role_element.options[i].value = allroles[i];
843: document.$formname.$role_element.options[i].text = courserolenames[i];
844: }
845: }
846: }
847: }
848: return;
849: }
850: |;
851: }
852: if ($credits_element) {
853: $setsections .= qq|
854: function setCredits(defaultcredits) {
855: document.$formname.$credits_element.value = defaultcredits;
856: return;
857: }
858: |;
859: }
860: return $setsections;
861: }
862:
863: sub selectcourse_link {
864: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
865: $typeelement) = @_;
866: my $type = $selecttype;
867: my $linktext = &mt('Select Course');
868: if ($selecttype eq 'Community') {
869: $linktext = &mt('Select Community');
870: } elsif ($selecttype eq 'Course/Community') {
871: $linktext = &mt('Select Course/Community');
872: $type = '';
873: } elsif ($selecttype eq 'Select') {
874: $linktext = &mt('Select');
875: $type = '';
876: }
877: return '<span class="LC_nobreak">'
878: ."<a href='"
879: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
880: .'","'.$udomele.'","'.$desc.'","'.$extra_element
881: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
882: ."'>".$linktext.'</a>'
883: .'</span>';
884: }
885:
886: sub selectauthor_link {
887: my ($form,$udom)=@_;
888: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
889: &mt('Select Author').'</a>';
890: }
891:
892: sub selectuser_link {
893: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
894: $coursedom,$linktext,$caller) = @_;
895: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
896: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
897: ');">'.$linktext.'</a>';
898: }
899:
900: sub check_uncheck_jscript {
901: my $jscript = <<"ENDSCRT";
902: function checkAll(field) {
903: if (field.length > 0) {
904: for (i = 0; i < field.length; i++) {
905: if (!field[i].disabled) {
906: field[i].checked = true;
907: }
908: }
909: } else {
910: if (!field.disabled) {
911: field.checked = true;
912: }
913: }
914: }
915:
916: function uncheckAll(field) {
917: if (field.length > 0) {
918: for (i = 0; i < field.length; i++) {
919: field[i].checked = false ;
920: }
921: } else {
922: field.checked = false ;
923: }
924: }
925: ENDSCRT
926: return $jscript;
927: }
928:
929: sub select_timezone {
930: my ($name,$selected,$onchange,$includeempty)=@_;
931: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
932: if ($includeempty) {
933: $output .= '<option value=""';
934: if (($selected eq '') || ($selected eq 'local')) {
935: $output .= ' selected="selected" ';
936: }
937: $output .= '> </option>';
938: }
939: my @timezones = DateTime::TimeZone->all_names;
940: foreach my $tzone (@timezones) {
941: $output.= '<option value="'.$tzone.'"';
942: if ($tzone eq $selected) {
943: $output.=' selected="selected"';
944: }
945: $output.=">$tzone</option>\n";
946: }
947: $output.="</select>";
948: return $output;
949: }
950:
951: sub select_datelocale {
952: my ($name,$selected,$onchange,$includeempty)=@_;
953: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
954: if ($includeempty) {
955: $output .= '<option value=""';
956: if ($selected eq '') {
957: $output .= ' selected="selected" ';
958: }
959: $output .= '> </option>';
960: }
961: my (@possibles,%locale_names);
962: my @locales = DateTime::Locale::Catalog::Locales;
963: foreach my $locale (@locales) {
964: if (ref($locale) eq 'HASH') {
965: my $id = $locale->{'id'};
966: if ($id ne '') {
967: my $en_terr = $locale->{'en_territory'};
968: my $native_terr = $locale->{'native_territory'};
969: my @languages = &Apache::lonlocal::preferred_languages();
970: if (grep(/^en$/,@languages) || !@languages) {
971: if ($en_terr ne '') {
972: $locale_names{$id} = '('.$en_terr.')';
973: } elsif ($native_terr ne '') {
974: $locale_names{$id} = $native_terr;
975: }
976: } else {
977: if ($native_terr ne '') {
978: $locale_names{$id} = $native_terr.' ';
979: } elsif ($en_terr ne '') {
980: $locale_names{$id} = '('.$en_terr.')';
981: }
982: }
983: push (@possibles,$id);
984: }
985: }
986: }
987: foreach my $item (sort(@possibles)) {
988: $output.= '<option value="'.$item.'"';
989: if ($item eq $selected) {
990: $output.=' selected="selected"';
991: }
992: $output.=">$item";
993: if ($locale_names{$item} ne '') {
994: $output.=" $locale_names{$item}</option>\n";
995: }
996: $output.="</option>\n";
997: }
998: $output.="</select>";
999: return $output;
1000: }
1001:
1002: sub select_language {
1003: my ($name,$selected,$includeempty) = @_;
1004: my %langchoices;
1005: if ($includeempty) {
1006: %langchoices = ('' => 'No language preference');
1007: }
1008: foreach my $id (&languageids()) {
1009: my $code = &supportedlanguagecode($id);
1010: if ($code) {
1011: $langchoices{$code} = &plainlanguagedescription($id);
1012: }
1013: }
1014: %langchoices = &Apache::lonlocal::texthash(%langchoices);
1015: return &select_form($selected,$name,\%langchoices);
1016: }
1017:
1018: =pod
1019:
1020:
1021: =item * &list_languages()
1022:
1023: Returns an array reference that is suitable for use in language prompters.
1024: Each array element is itself a two element array. The first element
1025: is the language code. The second element a descsriptiuon of the
1026: language itself. This is suitable for use in e.g.
1027: &Apache::edit::select_arg (once dereferenced that is).
1028:
1029: =cut
1030:
1031: sub list_languages {
1032: my @lang_choices;
1033:
1034: foreach my $id (&languageids()) {
1035: my $code = &supportedlanguagecode($id);
1036: if ($code) {
1037: my $selector = $supported_codes{$id};
1038: my $description = &plainlanguagedescription($id);
1039: push (@lang_choices, [$selector, $description]);
1040: }
1041: }
1042: return \@lang_choices;
1043: }
1044:
1045: =pod
1046:
1047: =item * &linked_select_forms(...)
1048:
1049: linked_select_forms returns a string containing a <script></script> block
1050: and html for two <select> menus. The select menus will be linked in that
1051: changing the value of the first menu will result in new values being placed
1052: in the second menu. The values in the select menu will appear in alphabetical
1053: order unless a defined order is provided.
1054:
1055: linked_select_forms takes the following ordered inputs:
1056:
1057: =over 4
1058:
1059: =item * $formname, the name of the <form> tag
1060:
1061: =item * $middletext, the text which appears between the <select> tags
1062:
1063: =item * $firstdefault, the default value for the first menu
1064:
1065: =item * $firstselectname, the name of the first <select> tag
1066:
1067: =item * $secondselectname, the name of the second <select> tag
1068:
1069: =item * $hashref, a reference to a hash containing the data for the menus.
1070:
1071: =item * $menuorder, the order of values in the first menu
1072:
1073: =item * $onchangefirst, additional javascript call to execute for an onchange
1074: event for the first <select> tag
1075:
1076: =item * $onchangesecond, additional javascript call to execute for an onchange
1077: event for the second <select> tag
1078:
1079: =back
1080:
1081: Below is an example of such a hash. Only the 'text', 'default', and
1082: 'select2' keys must appear as stated. keys(%menu) are the possible
1083: values for the first select menu. The text that coincides with the
1084: first menu value is given in $menu{$choice1}->{'text'}. The values
1085: and text for the second menu are given in the hash pointed to by
1086: $menu{$choice1}->{'select2'}.
1087:
1088: my %menu = ( A1 => { text =>"Choice A1" ,
1089: default => "B3",
1090: select2 => {
1091: B1 => "Choice B1",
1092: B2 => "Choice B2",
1093: B3 => "Choice B3",
1094: B4 => "Choice B4"
1095: },
1096: order => ['B4','B3','B1','B2'],
1097: },
1098: A2 => { text =>"Choice A2" ,
1099: default => "C2",
1100: select2 => {
1101: C1 => "Choice C1",
1102: C2 => "Choice C2",
1103: C3 => "Choice C3"
1104: },
1105: order => ['C2','C1','C3'],
1106: },
1107: A3 => { text =>"Choice A3" ,
1108: default => "D6",
1109: select2 => {
1110: D1 => "Choice D1",
1111: D2 => "Choice D2",
1112: D3 => "Choice D3",
1113: D4 => "Choice D4",
1114: D5 => "Choice D5",
1115: D6 => "Choice D6",
1116: D7 => "Choice D7"
1117: },
1118: order => ['D4','D3','D2','D1','D7','D6','D5'],
1119: }
1120: );
1121:
1122: =cut
1123:
1124: sub linked_select_forms {
1125: my ($formname,
1126: $middletext,
1127: $firstdefault,
1128: $firstselectname,
1129: $secondselectname,
1130: $hashref,
1131: $menuorder,
1132: $onchangefirst,
1133: $onchangesecond
1134: ) = @_;
1135: my $second = "document.$formname.$secondselectname";
1136: my $first = "document.$formname.$firstselectname";
1137: # output the javascript to do the changing
1138: my $result = '';
1139: $result.='<script type="text/javascript" language="JavaScript">'."\n";
1140: $result.="// <![CDATA[\n";
1141: $result.="var select2data = new Object();\n";
1142: $" = '","';
1143: my $debug = '';
1144: foreach my $s1 (sort(keys(%$hashref))) {
1145: $result.="select2data.d_$s1 = new Object();\n";
1146: $result.="select2data.d_$s1.def = new String('".
1147: $hashref->{$s1}->{'default'}."');\n";
1148: $result.="select2data.d_$s1.values = new Array(";
1149: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1150: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1151: @s2values = @{$hashref->{$s1}->{'order'}};
1152: }
1153: $result.="\"@s2values\");\n";
1154: $result.="select2data.d_$s1.texts = new Array(";
1155: my @s2texts;
1156: foreach my $value (@s2values) {
1157: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
1158: }
1159: $result.="\"@s2texts\");\n";
1160: }
1161: $"=' ';
1162: $result.= <<"END";
1163:
1164: function select1_changed() {
1165: // Determine new choice
1166: var newvalue = "d_" + $first.value;
1167: // update select2
1168: var values = select2data[newvalue].values;
1169: var texts = select2data[newvalue].texts;
1170: var select2def = select2data[newvalue].def;
1171: var i;
1172: // out with the old
1173: for (i = 0; i < $second.options.length; i++) {
1174: $second.options[i] = null;
1175: }
1176: // in with the nuclear
1177: for (i=0;i<values.length; i++) {
1178: $second.options[i] = new Option(values[i]);
1179: $second.options[i].value = values[i];
1180: $second.options[i].text = texts[i];
1181: if (values[i] == select2def) {
1182: $second.options[i].selected = true;
1183: }
1184: }
1185: }
1186: // ]]>
1187: </script>
1188: END
1189: # output the initial values for the selection lists
1190: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1191: my @order = sort(keys(%{$hashref}));
1192: if (ref($menuorder) eq 'ARRAY') {
1193: @order = @{$menuorder};
1194: }
1195: foreach my $value (@order) {
1196: $result.=" <option value=\"$value\" ";
1197: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1198: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1199: }
1200: $result .= "</select>\n";
1201: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1202: $result .= $middletext;
1203: $result .= "<select size=\"1\" name=\"$secondselectname\"";
1204: if ($onchangesecond) {
1205: $result .= ' onchange="'.$onchangesecond.'"';
1206: }
1207: $result .= ">\n";
1208: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1209:
1210: my @secondorder = sort(keys(%select2));
1211: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1212: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1213: }
1214: foreach my $value (@secondorder) {
1215: $result.=" <option value=\"$value\" ";
1216: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1217: $result.=">".&mt($select2{$value})."</option>\n";
1218: }
1219: $result .= "</select>\n";
1220: # return $debug;
1221: return $result;
1222: } # end of sub linked_select_forms {
1223:
1224: =pod
1225:
1226: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1227:
1228: Returns a string corresponding to an HTML link to the given help
1229: $topic, where $topic corresponds to the name of a .tex file in
1230: /home/httpd/html/adm/help/tex, with underscores replaced by
1231: spaces.
1232:
1233: $text will optionally be linked to the same topic, allowing you to
1234: link text in addition to the graphic. If you do not want to link
1235: text, but wish to specify one of the later parameters, pass an
1236: empty string.
1237:
1238: $stayOnPage is a value that will be interpreted as a boolean. If true,
1239: the link will not open a new window. If false, the link will open
1240: a new window using Javascript. (Default is false.)
1241:
1242: $width and $height are optional numerical parameters that will
1243: override the width and height of the popped up window, which may
1244: be useful for certain help topics with big pictures included.
1245:
1246: $imgid is the id of the img tag used for the help icon. This may be
1247: used in a javascript call to switch the image src. See
1248: lonhtmlcommon::htmlareaselectactive() for an example.
1249:
1250: =cut
1251:
1252: sub help_open_topic {
1253: my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1254: $text = "" if (not defined $text);
1255: $stayOnPage = 0 if (not defined $stayOnPage);
1256: $width = 500 if (not defined $width);
1257: $height = 400 if (not defined $height);
1258: my $filename = $topic;
1259: $filename =~ s/ /_/g;
1260:
1261: my $template = "";
1262: my $link;
1263:
1264: $topic=~s/\W/\_/g;
1265:
1266: if (!$stayOnPage) {
1267: $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1268: } elsif ($stayOnPage eq 'popup') {
1269: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1270: } else {
1271: $link = "/adm/help/${filename}.hlp";
1272: }
1273:
1274: # Add the text
1275: if ($text ne "") {
1276: $template.='<span class="LC_help_open_topic">'
1277: .'<a target="_top" href="'.$link.'">'
1278: .$text.'</a>';
1279: }
1280:
1281: # (Always) Add the graphic
1282: my $title = &mt('Online Help');
1283: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1284: if ($imgid ne '') {
1285: $imgid = ' id="'.$imgid.'"';
1286: }
1287: $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
1288: .'<img src="'.$helpicon.'" border="0"'
1289: .' alt="'.&mt('Help: [_1]',$topic).'"'
1290: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
1291: .' /></a>';
1292: if ($text ne "") {
1293: $template.='</span>';
1294: }
1295: return $template;
1296:
1297: }
1298:
1299: # This is a quicky function for Latex cheatsheet editing, since it
1300: # appears in at least four places
1301: sub helpLatexCheatsheet {
1302: my ($topic,$text,$not_author,$stayOnPage) = @_;
1303: my $out;
1304: my $addOther = '';
1305: if ($topic) {
1306: $addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1307: }
1308: $out = '<span>' # Start cheatsheet
1309: .$addOther
1310: .'<span>'
1311: .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1312: .'</span> <span>'
1313: .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1314: .'</span>';
1315: unless ($not_author) {
1316: $out .= ' <span>'
1317: .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1318: .'</span>';
1319: }
1320: $out .= '</span>'; # End cheatsheet
1321: return $out;
1322: }
1323:
1324: sub general_help {
1325: my $helptopic='Student_Intro';
1326: if ($env{'request.role'}=~/^(ca|au)/) {
1327: $helptopic='Authoring_Intro';
1328: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1329: $helptopic='Course_Coordination_Intro';
1330: } elsif ($env{'request.role'}=~/^dc/) {
1331: $helptopic='Domain_Coordination_Intro';
1332: }
1333: return $helptopic;
1334: }
1335:
1336: sub update_help_link {
1337: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1338: my $origurl = $ENV{'REQUEST_URI'};
1339: $origurl=~s|^/~|/priv/|;
1340: my $timestamp = time;
1341: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1342: $$datum = &escape($$datum);
1343: }
1344:
1345: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1346: my $output .= <<"ENDOUTPUT";
1347: <script type="text/javascript">
1348: // <![CDATA[
1349: banner_link = '$banner_link';
1350: // ]]>
1351: </script>
1352: ENDOUTPUT
1353: return $output;
1354: }
1355:
1356: # now just updates the help link and generates a blue icon
1357: sub help_open_menu {
1358: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
1359: = @_;
1360: $stayOnPage = 1;
1361: my $output;
1362: if ($component_help) {
1363: if (!$text) {
1364: $output=&help_open_topic($component_help,undef,$stayOnPage,
1365: $width,$height);
1366: } else {
1367: my $help_text;
1368: $help_text=&unescape($topic);
1369: $output='<table><tr><td>'.
1370: &help_open_topic($component_help,$help_text,$stayOnPage,
1371: $width,$height).'</td></tr></table>';
1372: }
1373: }
1374: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1375: return $output.$banner_link;
1376: }
1377:
1378: sub top_nav_help {
1379: my ($text) = @_;
1380: $text = &mt($text);
1381: my $stay_on_page = 1;
1382:
1383: my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1384: : "javascript:helpMenu('open')";
1385: my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1386:
1387: my $title = &mt('Get help');
1388:
1389: return <<"END";
1390: $banner_link
1391: <a href="$link" title="$title">$text</a>
1392: END
1393: }
1394:
1395: sub help_menu_js {
1396: my ($text) = @_;
1397: my $stayOnPage = 1;
1398: my $width = 620;
1399: my $height = 600;
1400: my $helptopic=&general_help();
1401: my $details_link = '/adm/help/'.$helptopic.'.hlp';
1402: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1403: my $start_page =
1404: &Apache::loncommon::start_page('Help Menu', undef,
1405: {'frameset' => 1,
1406: 'js_ready' => 1,
1407: 'add_entries' => {
1408: 'border' => '0',
1409: 'rows' => "110,*",},});
1410: my $end_page =
1411: &Apache::loncommon::end_page({'frameset' => 1,
1412: 'js_ready' => 1,});
1413:
1414: my $template .= <<"ENDTEMPLATE";
1415: <script type="text/javascript">
1416: // <![CDATA[
1417: // <!-- BEGIN LON-CAPA Internal
1418: var banner_link = '';
1419: function helpMenu(target) {
1420: var caller = this;
1421: if (target == 'open') {
1422: var newWindow = null;
1423: try {
1424: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1425: }
1426: catch(error) {
1427: writeHelp(caller);
1428: return;
1429: }
1430: if (newWindow) {
1431: caller = newWindow;
1432: }
1433: }
1434: writeHelp(caller);
1435: return;
1436: }
1437: function writeHelp(caller) {
1438: caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page')
1439: caller.document.close()
1440: caller.focus()
1441: }
1442: // END LON-CAPA Internal -->
1443: // ]]>
1444: </script>
1445: ENDTEMPLATE
1446: return $template;
1447: }
1448:
1449: sub help_open_bug {
1450: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1451: unless ($env{'user.adv'}) { return ''; }
1452: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1453: $text = "" if (not defined $text);
1454: $stayOnPage=1;
1455: $width = 600 if (not defined $width);
1456: $height = 600 if (not defined $height);
1457:
1458: $topic=~s/\W+/\+/g;
1459: my $link='';
1460: my $template='';
1461: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1462: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1463: if (!$stayOnPage)
1464: {
1465: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1466: }
1467: else
1468: {
1469: $link = $url;
1470: }
1471: # Add the text
1472: if ($text ne "")
1473: {
1474: $template .=
1475: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1476: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1477: }
1478:
1479: # Add the graphic
1480: my $title = &mt('Report a Bug');
1481: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1482: $template .= <<"ENDTEMPLATE";
1483: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1484: ENDTEMPLATE
1485: if ($text ne '') { $template.='</td></tr></table>' };
1486: return $template;
1487:
1488: }
1489:
1490: sub help_open_faq {
1491: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1492: unless ($env{'user.adv'}) { return ''; }
1493: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1494: $text = "" if (not defined $text);
1495: $stayOnPage=1;
1496: $width = 350 if (not defined $width);
1497: $height = 400 if (not defined $height);
1498:
1499: $topic=~s/\W+/\+/g;
1500: my $link='';
1501: my $template='';
1502: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1503: if (!$stayOnPage)
1504: {
1505: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1506: }
1507: else
1508: {
1509: $link = $url;
1510: }
1511:
1512: # Add the text
1513: if ($text ne "")
1514: {
1515: $template .=
1516: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1517: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1518: }
1519:
1520: # Add the graphic
1521: my $title = &mt('View the FAQ');
1522: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1523: $template .= <<"ENDTEMPLATE";
1524: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1525: ENDTEMPLATE
1526: if ($text ne '') { $template.='</td></tr></table>' };
1527: return $template;
1528:
1529: }
1530:
1531: ###############################################################
1532: ###############################################################
1533:
1534: =pod
1535:
1536: =item * &change_content_javascript():
1537:
1538: This and the next function allow you to create small sections of an
1539: otherwise static HTML page that you can update on the fly with
1540: Javascript, even in Netscape 4.
1541:
1542: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1543: must be written to the HTML page once. It will prove the Javascript
1544: function "change(name, content)". Calling the change function with the
1545: name of the section
1546: you want to update, matching the name passed to C<changable_area>, and
1547: the new content you want to put in there, will put the content into
1548: that area.
1549:
1550: B<Note>: Netscape 4 only reserves enough space for the changable area
1551: to contain room for the original contents. You need to "make space"
1552: for whatever changes you wish to make, and be B<sure> to check your
1553: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1554: it's adequate for updating a one-line status display, but little more.
1555: This script will set the space to 100% width, so you only need to
1556: worry about height in Netscape 4.
1557:
1558: Modern browsers are much less limiting, and if you can commit to the
1559: user not using Netscape 4, this feature may be used freely with
1560: pretty much any HTML.
1561:
1562: =cut
1563:
1564: sub change_content_javascript {
1565: # If we're on Netscape 4, we need to use Layer-based code
1566: if ($env{'browser.type'} eq 'netscape' &&
1567: $env{'browser.version'} =~ /^4\./) {
1568: return (<<NETSCAPE4);
1569: function change(name, content) {
1570: doc = document.layers[name+"___escape"].layers[0].document;
1571: doc.open();
1572: doc.write(content);
1573: doc.close();
1574: }
1575: NETSCAPE4
1576: } else {
1577: # Otherwise, we need to use semi-standards-compliant code
1578: # (technically, "innerHTML" isn't standard but the equivalent
1579: # is really scary, and every useful browser supports it
1580: return (<<DOMBASED);
1581: function change(name, content) {
1582: element = document.getElementById(name);
1583: element.innerHTML = content;
1584: }
1585: DOMBASED
1586: }
1587: }
1588:
1589: =pod
1590:
1591: =item * &changable_area($name,$origContent):
1592:
1593: This provides a "changable area" that can be modified on the fly via
1594: the Javascript code provided in C<change_content_javascript>. $name is
1595: the name you will use to reference the area later; do not repeat the
1596: same name on a given HTML page more then once. $origContent is what
1597: the area will originally contain, which can be left blank.
1598:
1599: =cut
1600:
1601: sub changable_area {
1602: my ($name, $origContent) = @_;
1603:
1604: if ($env{'browser.type'} eq 'netscape' &&
1605: $env{'browser.version'} =~ /^4\./) {
1606: # If this is netscape 4, we need to use the Layer tag
1607: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1608: } else {
1609: return "<span id='$name'>$origContent</span>";
1610: }
1611: }
1612:
1613: =pod
1614:
1615: =item * &viewport_geometry_js
1616:
1617: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1618:
1619: =cut
1620:
1621:
1622: sub viewport_geometry_js {
1623: return <<"GEOMETRY";
1624: var Geometry = {};
1625: function init_geometry() {
1626: if (Geometry.init) { return };
1627: Geometry.init=1;
1628: if (window.innerHeight) {
1629: Geometry.getViewportHeight = function() { return window.innerHeight; };
1630: Geometry.getViewportWidth = function() { return window.innerWidth; };
1631: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1632: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1633: }
1634: else if (document.documentElement && document.documentElement.clientHeight) {
1635: Geometry.getViewportHeight =
1636: function() { return document.documentElement.clientHeight; };
1637: Geometry.getViewportWidth =
1638: function() { return document.documentElement.clientWidth; };
1639:
1640: Geometry.getHorizontalScroll =
1641: function() { return document.documentElement.scrollLeft; };
1642: Geometry.getVerticalScroll =
1643: function() { return document.documentElement.scrollTop; };
1644: }
1645: else if (document.body.clientHeight) {
1646: Geometry.getViewportHeight =
1647: function() { return document.body.clientHeight; };
1648: Geometry.getViewportWidth =
1649: function() { return document.body.clientWidth; };
1650: Geometry.getHorizontalScroll =
1651: function() { return document.body.scrollLeft; };
1652: Geometry.getVerticalScroll =
1653: function() { return document.body.scrollTop; };
1654: }
1655: }
1656:
1657: GEOMETRY
1658: }
1659:
1660: =pod
1661:
1662: =item * &viewport_size_js()
1663:
1664: 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.
1665:
1666: =cut
1667:
1668: sub viewport_size_js {
1669: my $geometry = &viewport_geometry_js();
1670: return <<"DIMS";
1671:
1672: $geometry
1673:
1674: function getViewportDims(width,height) {
1675: init_geometry();
1676: width.value = Geometry.getViewportWidth();
1677: height.value = Geometry.getViewportHeight();
1678: return;
1679: }
1680:
1681: DIMS
1682: }
1683:
1684: =pod
1685:
1686: =item * &resize_textarea_js()
1687:
1688: emits the needed javascript to resize a textarea to be as big as possible
1689:
1690: creates a function resize_textrea that takes two IDs first should be
1691: the id of the element to resize, second should be the id of a div that
1692: surrounds everything that comes after the textarea, this routine needs
1693: to be attached to the <body> for the onload and onresize events.
1694:
1695: =back
1696:
1697: =cut
1698:
1699: sub resize_textarea_js {
1700: my $geometry = &viewport_geometry_js();
1701: return <<"RESIZE";
1702: <script type="text/javascript">
1703: // <![CDATA[
1704: $geometry
1705:
1706: function getX(element) {
1707: var x = 0;
1708: while (element) {
1709: x += element.offsetLeft;
1710: element = element.offsetParent;
1711: }
1712: return x;
1713: }
1714: function getY(element) {
1715: var y = 0;
1716: while (element) {
1717: y += element.offsetTop;
1718: element = element.offsetParent;
1719: }
1720: return y;
1721: }
1722:
1723:
1724: function resize_textarea(textarea_id,bottom_id) {
1725: init_geometry();
1726: var textarea = document.getElementById(textarea_id);
1727: //alert(textarea);
1728:
1729: var textarea_top = getY(textarea);
1730: var textarea_height = textarea.offsetHeight;
1731: var bottom = document.getElementById(bottom_id);
1732: var bottom_top = getY(bottom);
1733: var bottom_height = bottom.offsetHeight;
1734: var window_height = Geometry.getViewportHeight();
1735: var fudge = 23;
1736: var new_height = window_height-fudge-textarea_top-bottom_height;
1737: if (new_height < 300) {
1738: new_height = 300;
1739: }
1740: textarea.style.height=new_height+'px';
1741: }
1742: // ]]>
1743: </script>
1744: RESIZE
1745:
1746: }
1747:
1748: =pod
1749:
1750: =head1 Excel and CSV file utility routines
1751:
1752: =over 4
1753:
1754: =cut
1755:
1756: ###############################################################
1757: ###############################################################
1758:
1759: =pod
1760:
1761: =item * &csv_translate($text)
1762:
1763: Translate $text to allow it to be output as a 'comma separated values'
1764: format.
1765:
1766: =cut
1767:
1768: ###############################################################
1769: ###############################################################
1770: sub csv_translate {
1771: my $text = shift;
1772: $text =~ s/\"/\"\"/g;
1773: $text =~ s/\n/ /g;
1774: return $text;
1775: }
1776:
1777: ###############################################################
1778: ###############################################################
1779:
1780: =pod
1781:
1782: =item * &define_excel_formats()
1783:
1784: Define some commonly used Excel cell formats.
1785:
1786: Currently supported formats:
1787:
1788: =over 4
1789:
1790: =item header
1791:
1792: =item bold
1793:
1794: =item h1
1795:
1796: =item h2
1797:
1798: =item h3
1799:
1800: =item h4
1801:
1802: =item i
1803:
1804: =item date
1805:
1806: =back
1807:
1808: Inputs: $workbook
1809:
1810: Returns: $format, a hash reference.
1811:
1812:
1813: =cut
1814:
1815: ###############################################################
1816: ###############################################################
1817: sub define_excel_formats {
1818: my ($workbook) = @_;
1819: my $format;
1820: $format->{'header'} = $workbook->add_format(bold => 1,
1821: bottom => 1,
1822: align => 'center');
1823: $format->{'bold'} = $workbook->add_format(bold=>1);
1824: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
1825: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
1826: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
1827: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
1828: $format->{'i'} = $workbook->add_format(italic=>1);
1829: $format->{'date'} = $workbook->add_format(num_format=>
1830: 'mm/dd/yyyy hh:mm:ss');
1831: return $format;
1832: }
1833:
1834: ###############################################################
1835: ###############################################################
1836:
1837: =pod
1838:
1839: =item * &create_workbook()
1840:
1841: Create an Excel worksheet. If it fails, output message on the
1842: request object and return undefs.
1843:
1844: Inputs: Apache request object
1845:
1846: Returns (undef) on failure,
1847: Excel worksheet object, scalar with filename, and formats
1848: from &Apache::loncommon::define_excel_formats on success
1849:
1850: =cut
1851:
1852: ###############################################################
1853: ###############################################################
1854: sub create_workbook {
1855: my ($r) = @_;
1856: #
1857: # Create the excel spreadsheet
1858: my $filename = '/prtspool/'.
1859: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1860: time.'_'.rand(1000000000).'.xls';
1861: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1862: if (! defined($workbook)) {
1863: $r->log_error("Error creating excel spreadsheet $filename: $!");
1864: $r->print(
1865: '<p class="LC_error">'
1866: .&mt('Problems occurred in creating the new Excel file.')
1867: .' '.&mt('This error has been logged.')
1868: .' '.&mt('Please alert your LON-CAPA administrator.')
1869: .'</p>'
1870: );
1871: return (undef);
1872: }
1873: #
1874: $workbook->set_tempdir(LONCAPA::tempdir());
1875: #
1876: my $format = &Apache::loncommon::define_excel_formats($workbook);
1877: return ($workbook,$filename,$format);
1878: }
1879:
1880: ###############################################################
1881: ###############################################################
1882:
1883: =pod
1884:
1885: =item * &create_text_file()
1886:
1887: Create a file to write to and eventually make available to the user.
1888: If file creation fails, outputs an error message on the request object and
1889: return undefs.
1890:
1891: Inputs: Apache request object, and file suffix
1892:
1893: Returns (undef) on failure,
1894: Filehandle and filename on success.
1895:
1896: =cut
1897:
1898: ###############################################################
1899: ###############################################################
1900: sub create_text_file {
1901: my ($r,$suffix) = @_;
1902: if (! defined($suffix)) { $suffix = 'txt'; };
1903: my $fh;
1904: my $filename = '/prtspool/'.
1905: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1906: time.'_'.rand(1000000000).'.'.$suffix;
1907: $fh = Apache::File->new('>/home/httpd'.$filename);
1908: if (! defined($fh)) {
1909: $r->log_error("Couldn't open $filename for output $!");
1910: $r->print(
1911: '<p class="LC_error">'
1912: .&mt('Problems occurred in creating the output file.')
1913: .' '.&mt('This error has been logged.')
1914: .' '.&mt('Please alert your LON-CAPA administrator.')
1915: .'</p>'
1916: );
1917: }
1918: return ($fh,$filename)
1919: }
1920:
1921:
1922: =pod
1923:
1924: =back
1925:
1926: =cut
1927:
1928: ###############################################################
1929: ## Home server <option> list generating code ##
1930: ###############################################################
1931:
1932: # ------------------------------------------
1933:
1934: sub domain_select {
1935: my ($name,$value,$multiple)=@_;
1936: my %domains=map {
1937: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
1938: } &Apache::lonnet::all_domains();
1939: if ($multiple) {
1940: $domains{''}=&mt('Any domain');
1941: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1942: return &multiple_select_form($name,$value,4,\%domains);
1943: } else {
1944: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1945: return &select_form($name,$value,\%domains);
1946: }
1947: }
1948:
1949: #-------------------------------------------
1950:
1951: =pod
1952:
1953: =head1 Routines for form select boxes
1954:
1955: =over 4
1956:
1957: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1958:
1959: Returns a string containing a <select> element int multiple mode
1960:
1961:
1962: Args:
1963: $name - name of the <select> element
1964: $value - scalar or array ref of values that should already be selected
1965: $size - number of rows long the select element is
1966: $hash - the elements should be 'option' => 'shown text'
1967: (shown text should already have been &mt())
1968: $order - (optional) array ref of the order to show the elements in
1969:
1970: =cut
1971:
1972: #-------------------------------------------
1973: sub multiple_select_form {
1974: my ($name,$value,$size,$hash,$order)=@_;
1975: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
1976: my $output='';
1977: if (! defined($size)) {
1978: $size = 4;
1979: if (scalar(keys(%$hash))<4) {
1980: $size = scalar(keys(%$hash));
1981: }
1982: }
1983: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1984: my @order;
1985: if (ref($order) eq 'ARRAY') {
1986: @order = @{$order};
1987: } else {
1988: @order = sort(keys(%$hash));
1989: }
1990: if (exists($$hash{'select_form_order'})) {
1991: @order = @{$$hash{'select_form_order'}};
1992: }
1993:
1994: foreach my $key (@order) {
1995: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1996: $output.='selected="selected" ' if ($selected{$key});
1997: $output.='>'.$hash->{$key}."</option>\n";
1998: }
1999: $output.="</select>\n";
2000: return $output;
2001: }
2002:
2003: #-------------------------------------------
2004:
2005: =pod
2006:
2007: =item * &select_form($defdom,$name,$hashref,$onchange)
2008:
2009: Returns a string containing a <select name='$name' size='1'> form to
2010: allow a user to select options from a ref to a hash containing:
2011: option_name => displayed text. An optional $onchange can include
2012: a javascript onchange item, e.g., onchange="this.form.submit();"
2013:
2014: See lonrights.pm for an example invocation and use.
2015:
2016: =cut
2017:
2018: #-------------------------------------------
2019: sub select_form {
2020: my ($def,$name,$hashref,$onchange) = @_;
2021: return unless (ref($hashref) eq 'HASH');
2022: if ($onchange) {
2023: $onchange = ' onchange="'.$onchange.'"';
2024: }
2025: my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
2026: my @keys;
2027: if (exists($hashref->{'select_form_order'})) {
2028: @keys=@{$hashref->{'select_form_order'}};
2029: } else {
2030: @keys=sort(keys(%{$hashref}));
2031: }
2032: foreach my $key (@keys) {
2033: $selectform.=
2034: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
2035: ($key eq $def ? 'selected="selected" ' : '').
2036: ">".$hashref->{$key}."</option>\n";
2037: }
2038: $selectform.="</select>";
2039: return $selectform;
2040: }
2041:
2042: # For display filters
2043:
2044: sub display_filter {
2045: my ($context) = @_;
2046: if (!$env{'form.show'}) { $env{'form.show'}=10; }
2047: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
2048: my $phraseinput = 'hidden';
2049: my $includeinput = 'hidden';
2050: my ($checked,$includetypestext);
2051: if ($env{'form.displayfilter'} eq 'containing') {
2052: $phraseinput = 'text';
2053: if ($context eq 'parmslog') {
2054: $includeinput = 'checkbox';
2055: if ($env{'form.includetypes'}) {
2056: $checked = ' checked="checked"';
2057: }
2058: $includetypestext = &mt('Include parameter types');
2059: }
2060: } else {
2061: $includetypestext = ' ';
2062: }
2063: my ($additional,$secondid,$thirdid);
2064: if ($context eq 'parmslog') {
2065: $additional =
2066: '<label><input type="'.$includeinput.'" name="includetypes"'.
2067: $checked.' name="includetypes" value="1" id="includetypes" />'.
2068: ' <span id="includetypestext">'.$includetypestext.'</span>'.
2069: '</label>';
2070: $secondid = 'includetypes';
2071: $thirdid = 'includetypestext';
2072: }
2073: my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
2074: '$secondid','$thirdid')";
2075: return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
2076: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
2077: (&mt('all'),10,20,50,100,1000,10000))).
2078: '</label></span> <span class="LC_nobreak">'.
2079: &mt('Filter: [_1]',
2080: &select_form($env{'form.displayfilter'},
2081: 'displayfilter',
2082: {'currentfolder' => 'Current folder/page',
2083: 'containing' => 'Containing phrase',
2084: 'none' => 'None'},$onchange)).' '.
2085: '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
2086: &HTML::Entities::encode($env{'form.containingphrase'}).
2087: '" />'.$additional;
2088: }
2089:
2090: sub display_filter_js {
2091: my $includetext = &mt('Include parameter types');
2092: return <<"ENDJS";
2093:
2094: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
2095: var firstType = 'hidden';
2096: if (setter.options[setter.selectedIndex].value == 'containing') {
2097: firstType = 'text';
2098: }
2099: firstObject = document.getElementById(firstid);
2100: if (typeof(firstObject) == 'object') {
2101: if (firstObject.type != firstType) {
2102: changeInputType(firstObject,firstType);
2103: }
2104: }
2105: if (context == 'parmslog') {
2106: var secondType = 'hidden';
2107: if (firstType == 'text') {
2108: secondType = 'checkbox';
2109: }
2110: secondObject = document.getElementById(secondid);
2111: if (typeof(secondObject) == 'object') {
2112: if (secondObject.type != secondType) {
2113: changeInputType(secondObject,secondType);
2114: }
2115: }
2116: var textItem = document.getElementById(thirdid);
2117: var currtext = textItem.innerHTML;
2118: var newtext;
2119: if (firstType == 'text') {
2120: newtext = '$includetext';
2121: } else {
2122: newtext = ' ';
2123: }
2124: if (currtext != newtext) {
2125: textItem.innerHTML = newtext;
2126: }
2127: }
2128: return;
2129: }
2130:
2131: function changeInputType(oldObject,newType) {
2132: var newObject = document.createElement('input');
2133: newObject.type = newType;
2134: if (oldObject.size) {
2135: newObject.size = oldObject.size;
2136: }
2137: if (oldObject.value) {
2138: newObject.value = oldObject.value;
2139: }
2140: if (oldObject.name) {
2141: newObject.name = oldObject.name;
2142: }
2143: if (oldObject.id) {
2144: newObject.id = oldObject.id;
2145: }
2146: oldObject.parentNode.replaceChild(newObject,oldObject);
2147: return;
2148: }
2149:
2150: ENDJS
2151: }
2152:
2153: sub gradeleveldescription {
2154: my $gradelevel=shift;
2155: my %gradelevels=(0 => 'Not specified',
2156: 1 => 'Grade 1',
2157: 2 => 'Grade 2',
2158: 3 => 'Grade 3',
2159: 4 => 'Grade 4',
2160: 5 => 'Grade 5',
2161: 6 => 'Grade 6',
2162: 7 => 'Grade 7',
2163: 8 => 'Grade 8',
2164: 9 => 'Grade 9',
2165: 10 => 'Grade 10',
2166: 11 => 'Grade 11',
2167: 12 => 'Grade 12',
2168: 13 => 'Grade 13',
2169: 14 => '100 Level',
2170: 15 => '200 Level',
2171: 16 => '300 Level',
2172: 17 => '400 Level',
2173: 18 => 'Graduate Level');
2174: return &mt($gradelevels{$gradelevel});
2175: }
2176:
2177: sub select_level_form {
2178: my ($deflevel,$name)=@_;
2179: unless ($deflevel) { $deflevel=0; }
2180: my $selectform = "<select name=\"$name\" size=\"1\">\n";
2181: for (my $i=0; $i<=18; $i++) {
2182: $selectform.="<option value=\"$i\" ".
2183: ($i==$deflevel ? 'selected="selected" ' : '').
2184: ">".&gradeleveldescription($i)."</option>\n";
2185: }
2186: $selectform.="</select>";
2187: return $selectform;
2188: }
2189:
2190: #-------------------------------------------
2191:
2192: =pod
2193:
2194: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
2195:
2196: Returns a string containing a <select name='$name' size='1'> form to
2197: allow a user to select the domain to preform an operation in.
2198: See loncreateuser.pm for an example invocation and use.
2199:
2200: If the $includeempty flag is set, it also includes an empty choice ("no domain
2201: selected");
2202:
2203: If the $showdomdesc flag is set, the domain name is followed by the domain description.
2204:
2205: 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.
2206:
2207: The optional $incdoms is a reference to an array of domains which will be the only available options.
2208:
2209: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
2210:
2211: =cut
2212:
2213: #-------------------------------------------
2214: sub select_dom_form {
2215: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
2216: if ($onchange) {
2217: $onchange = ' onchange="'.$onchange.'"';
2218: }
2219: my (@domains,%exclude);
2220: if (ref($incdoms) eq 'ARRAY') {
2221: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
2222: } else {
2223: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
2224: }
2225: if ($includeempty) { @domains=('',@domains); }
2226: if (ref($excdoms) eq 'ARRAY') {
2227: map { $exclude{$_} = 1; } @{$excdoms};
2228: }
2229: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
2230: foreach my $dom (@domains) {
2231: next if ($exclude{$dom});
2232: $selectdomain.="<option value=\"$dom\" ".
2233: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
2234: if ($showdomdesc) {
2235: if ($dom ne '') {
2236: my $domdesc = &Apache::lonnet::domain($dom,'description');
2237: if ($domdesc ne '') {
2238: $selectdomain .= ' ('.$domdesc.')';
2239: }
2240: }
2241: }
2242: $selectdomain .= "</option>\n";
2243: }
2244: $selectdomain.="</select>";
2245: return $selectdomain;
2246: }
2247:
2248: #-------------------------------------------
2249:
2250: =pod
2251:
2252: =item * &home_server_form_item($domain,$name,$defaultflag)
2253:
2254: input: 4 arguments (two required, two optional) -
2255: $domain - domain of new user
2256: $name - name of form element
2257: $default - Value of 'default' causes a default item to be first
2258: option, and selected by default.
2259: $hide - Value of 'hide' causes hiding of the name of the server,
2260: if 1 server found, or default, if 0 found.
2261: output: returns 2 items:
2262: (a) form element which contains either:
2263: (i) <select name="$name">
2264: <option value="$hostid1">$hostid $servers{$hostid}</option>
2265: <option value="$hostid2">$hostid $servers{$hostid}</option>
2266: </select>
2267: form item if there are multiple library servers in $domain, or
2268: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2269: if there is only one library server in $domain.
2270:
2271: (b) number of library servers found.
2272:
2273: See loncreateuser.pm for example of use.
2274:
2275: =cut
2276:
2277: #-------------------------------------------
2278: sub home_server_form_item {
2279: my ($domain,$name,$default,$hide) = @_;
2280: my %servers = &Apache::lonnet::get_servers($domain,'library');
2281: my $result;
2282: my $numlib = keys(%servers);
2283: if ($numlib > 1) {
2284: $result .= '<select name="'.$name.'" />'."\n";
2285: if ($default) {
2286: $result .= '<option value="default" selected="selected">'.&mt('default').
2287: '</option>'."\n";
2288: }
2289: foreach my $hostid (sort(keys(%servers))) {
2290: $result.= '<option value="'.$hostid.'">'.
2291: $hostid.' '.$servers{$hostid}."</option>\n";
2292: }
2293: $result .= '</select>'."\n";
2294: } elsif ($numlib == 1) {
2295: my $hostid;
2296: foreach my $item (keys(%servers)) {
2297: $hostid = $item;
2298: }
2299: $result .= '<input type="hidden" name="'.$name.'" value="'.
2300: $hostid.'" />';
2301: if (!$hide) {
2302: $result .= $hostid.' '.$servers{$hostid};
2303: }
2304: $result .= "\n";
2305: } elsif ($default) {
2306: $result .= '<input type="hidden" name="'.$name.
2307: '" value="default" />';
2308: if (!$hide) {
2309: $result .= &mt('default');
2310: }
2311: $result .= "\n";
2312: }
2313: return ($result,$numlib);
2314: }
2315:
2316: =pod
2317:
2318: =back
2319:
2320: =cut
2321:
2322: ###############################################################
2323: ## Decoding User Agent ##
2324: ###############################################################
2325:
2326: =pod
2327:
2328: =head1 Decoding the User Agent
2329:
2330: =over 4
2331:
2332: =item * &decode_user_agent()
2333:
2334: Inputs: $r
2335:
2336: Outputs:
2337:
2338: =over 4
2339:
2340: =item * $httpbrowser
2341:
2342: =item * $clientbrowser
2343:
2344: =item * $clientversion
2345:
2346: =item * $clientmathml
2347:
2348: =item * $clientunicode
2349:
2350: =item * $clientos
2351:
2352: =back
2353:
2354: =back
2355:
2356: =cut
2357:
2358: ###############################################################
2359: ###############################################################
2360: sub decode_user_agent {
2361: my ($r)=@_;
2362: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
2363: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
2364: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
2365: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
2366: my $clientbrowser='unknown';
2367: my $clientversion='0';
2368: my $clientmathml='';
2369: my $clientunicode='0';
2370: for (my $i=0;$i<=$#browsertype;$i++) {
2371: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
2372: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
2373: $clientbrowser=$bname;
2374: $httpbrowser=~/$vreg/i;
2375: $clientversion=$1;
2376: $clientmathml=($clientversion>=$minv);
2377: $clientunicode=($clientversion>=$univ);
2378: }
2379: }
2380: my $clientos='unknown';
2381: if (($httpbrowser=~/linux/i) ||
2382: ($httpbrowser=~/unix/i) ||
2383: ($httpbrowser=~/ux/i) ||
2384: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
2385: if (($httpbrowser=~/vax/i) ||
2386: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
2387: if ($httpbrowser=~/next/i) { $clientos='next'; }
2388: if (($httpbrowser=~/mac/i) ||
2389: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
2390: if ($httpbrowser=~/win/i) { $clientos='win'; }
2391: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
2392: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
2393: $clientunicode,$clientos,);
2394: }
2395:
2396: ###############################################################
2397: ## Authentication changing form generation subroutines ##
2398: ###############################################################
2399: ##
2400: ## All of the authform_xxxxxxx subroutines take their inputs in a
2401: ## hash, and have reasonable default values.
2402: ##
2403: ## formname = the name given in the <form> tag.
2404: #-------------------------------------------
2405:
2406: =pod
2407:
2408: =head1 Authentication Routines
2409:
2410: =over 4
2411:
2412: =item * &authform_xxxxxx()
2413:
2414: The authform_xxxxxx subroutines provide javascript and html forms which
2415: handle some of the conveniences required for authentication forms.
2416: This is not an optimal method, but it works.
2417:
2418: =over 4
2419:
2420: =item * authform_header
2421:
2422: =item * authform_authorwarning
2423:
2424: =item * authform_nochange
2425:
2426: =item * authform_kerberos
2427:
2428: =item * authform_internal
2429:
2430: =item * authform_filesystem
2431:
2432: =back
2433:
2434: See loncreateuser.pm for invocation and use examples.
2435:
2436: =cut
2437:
2438: #-------------------------------------------
2439: sub authform_header{
2440: my %in = (
2441: formname => 'cu',
2442: kerb_def_dom => '',
2443: @_,
2444: );
2445: $in{'formname'} = 'document.' . $in{'formname'};
2446: my $result='';
2447:
2448: #---------------------------------------------- Code for upper case translation
2449: my $Javascript_toUpperCase;
2450: unless ($in{kerb_def_dom}) {
2451: $Javascript_toUpperCase =<<"END";
2452: switch (choice) {
2453: case 'krb': currentform.elements[choicearg].value =
2454: currentform.elements[choicearg].value.toUpperCase();
2455: break;
2456: default:
2457: }
2458: END
2459: } else {
2460: $Javascript_toUpperCase = "";
2461: }
2462:
2463: my $radioval = "'nochange'";
2464: if (defined($in{'curr_authtype'})) {
2465: if ($in{'curr_authtype'} ne '') {
2466: $radioval = "'".$in{'curr_authtype'}."arg'";
2467: }
2468: }
2469: my $argfield = 'null';
2470: if (defined($in{'mode'})) {
2471: if ($in{'mode'} eq 'modifycourse') {
2472: if (defined($in{'curr_autharg'})) {
2473: if ($in{'curr_autharg'} ne '') {
2474: $argfield = "'$in{'curr_autharg'}'";
2475: }
2476: }
2477: }
2478: }
2479:
2480: $result.=<<"END";
2481: var current = new Object();
2482: current.radiovalue = $radioval;
2483: current.argfield = $argfield;
2484:
2485: function changed_radio(choice,currentform) {
2486: var choicearg = choice + 'arg';
2487: // If a radio button in changed, we need to change the argfield
2488: if (current.radiovalue != choice) {
2489: current.radiovalue = choice;
2490: if (current.argfield != null) {
2491: currentform.elements[current.argfield].value = '';
2492: }
2493: if (choice == 'nochange') {
2494: current.argfield = null;
2495: } else {
2496: current.argfield = choicearg;
2497: switch(choice) {
2498: case 'krb':
2499: currentform.elements[current.argfield].value =
2500: "$in{'kerb_def_dom'}";
2501: break;
2502: default:
2503: break;
2504: }
2505: }
2506: }
2507: return;
2508: }
2509:
2510: function changed_text(choice,currentform) {
2511: var choicearg = choice + 'arg';
2512: if (currentform.elements[choicearg].value !='') {
2513: $Javascript_toUpperCase
2514: // clear old field
2515: if ((current.argfield != choicearg) && (current.argfield != null)) {
2516: currentform.elements[current.argfield].value = '';
2517: }
2518: current.argfield = choicearg;
2519: }
2520: set_auth_radio_buttons(choice,currentform);
2521: return;
2522: }
2523:
2524: function set_auth_radio_buttons(newvalue,currentform) {
2525: var numauthchoices = currentform.login.length;
2526: if (typeof numauthchoices == "undefined") {
2527: return;
2528: }
2529: var i=0;
2530: while (i < numauthchoices) {
2531: if (currentform.login[i].value == newvalue) { break; }
2532: i++;
2533: }
2534: if (i == numauthchoices) {
2535: return;
2536: }
2537: current.radiovalue = newvalue;
2538: currentform.login[i].checked = true;
2539: return;
2540: }
2541: END
2542: return $result;
2543: }
2544:
2545: sub authform_authorwarning {
2546: my $result='';
2547: $result='<i>'.
2548: &mt('As a general rule, only authors or co-authors should be '.
2549: 'filesystem authenticated '.
2550: '(which allows access to the server filesystem).')."</i>\n";
2551: return $result;
2552: }
2553:
2554: sub authform_nochange {
2555: my %in = (
2556: formname => 'document.cu',
2557: kerb_def_dom => 'MSU.EDU',
2558: @_,
2559: );
2560: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2561: my $result;
2562: if (!$authnum) {
2563: $result = &mt('Under your current role you are not permitted to change login settings for this user');
2564: } else {
2565: $result = '<label>'.&mt('[_1] Do not change login data',
2566: '<input type="radio" name="login" value="nochange" '.
2567: 'checked="checked" onclick="'.
2568: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
2569: '</label>';
2570: }
2571: return $result;
2572: }
2573:
2574: sub authform_kerberos {
2575: my %in = (
2576: formname => 'document.cu',
2577: kerb_def_dom => 'MSU.EDU',
2578: kerb_def_auth => 'krb4',
2579: @_,
2580: );
2581: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2582: $autharg,$jscall);
2583: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2584: if ($in{'kerb_def_auth'} eq 'krb5') {
2585: $check5 = ' checked="checked"';
2586: } else {
2587: $check4 = ' checked="checked"';
2588: }
2589: $krbarg = $in{'kerb_def_dom'};
2590: if (defined($in{'curr_authtype'})) {
2591: if ($in{'curr_authtype'} eq 'krb') {
2592: $krbcheck = ' checked="checked"';
2593: if (defined($in{'mode'})) {
2594: if ($in{'mode'} eq 'modifyuser') {
2595: $krbcheck = '';
2596: }
2597: }
2598: if (defined($in{'curr_kerb_ver'})) {
2599: if ($in{'curr_krb_ver'} eq '5') {
2600: $check5 = ' checked="checked"';
2601: $check4 = '';
2602: } else {
2603: $check4 = ' checked="checked"';
2604: $check5 = '';
2605: }
2606: }
2607: if (defined($in{'curr_autharg'})) {
2608: $krbarg = $in{'curr_autharg'};
2609: }
2610: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2611: if (defined($in{'curr_autharg'})) {
2612: $result =
2613: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
2614: $in{'curr_autharg'},$krbver);
2615: } else {
2616: $result =
2617: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
2618: }
2619: return $result;
2620: }
2621: }
2622: } else {
2623: if ($authnum == 1) {
2624: $authtype = '<input type="hidden" name="login" value="krb" />';
2625: }
2626: }
2627: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2628: return;
2629: } elsif ($authtype eq '') {
2630: if (defined($in{'mode'})) {
2631: if ($in{'mode'} eq 'modifycourse') {
2632: if ($authnum == 1) {
2633: $authtype = '<input type="radio" name="login" value="krb" />';
2634: }
2635: }
2636: }
2637: }
2638: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
2639: if ($authtype eq '') {
2640: $authtype = '<input type="radio" name="login" value="krb" '.
2641: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
2642: $krbcheck.' />';
2643: }
2644: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
2645: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
2646: $in{'curr_authtype'} eq 'krb5') ||
2647: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
2648: $in{'curr_authtype'} eq 'krb4')) {
2649: $result .= &mt
2650: ('[_1] Kerberos authenticated with domain [_2] '.
2651: '[_3] Version 4 [_4] Version 5 [_5]',
2652: '<label>'.$authtype,
2653: '</label><input type="text" size="10" name="krbarg" '.
2654: 'value="'.$krbarg.'" '.
2655: 'onchange="'.$jscall.'" />',
2656: '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
2657: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
2658: '</label>');
2659: } elsif ($can_assign{'krb4'}) {
2660: $result .= &mt
2661: ('[_1] Kerberos authenticated with domain [_2] '.
2662: '[_3] Version 4 [_4]',
2663: '<label>'.$authtype,
2664: '</label><input type="text" size="10" name="krbarg" '.
2665: 'value="'.$krbarg.'" '.
2666: 'onchange="'.$jscall.'" />',
2667: '<label><input type="hidden" name="krbver" value="4" />',
2668: '</label>');
2669: } elsif ($can_assign{'krb5'}) {
2670: $result .= &mt
2671: ('[_1] Kerberos authenticated with domain [_2] '.
2672: '[_3] Version 5 [_4]',
2673: '<label>'.$authtype,
2674: '</label><input type="text" size="10" name="krbarg" '.
2675: 'value="'.$krbarg.'" '.
2676: 'onchange="'.$jscall.'" />',
2677: '<label><input type="hidden" name="krbver" value="5" />',
2678: '</label>');
2679: }
2680: return $result;
2681: }
2682:
2683: sub authform_internal {
2684: my %in = (
2685: formname => 'document.cu',
2686: kerb_def_dom => 'MSU.EDU',
2687: @_,
2688: );
2689: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
2690: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2691: if (defined($in{'curr_authtype'})) {
2692: if ($in{'curr_authtype'} eq 'int') {
2693: if ($can_assign{'int'}) {
2694: $intcheck = 'checked="checked" ';
2695: if (defined($in{'mode'})) {
2696: if ($in{'mode'} eq 'modifyuser') {
2697: $intcheck = '';
2698: }
2699: }
2700: if (defined($in{'curr_autharg'})) {
2701: $intarg = $in{'curr_autharg'};
2702: }
2703: } else {
2704: $result = &mt('Currently internally authenticated.');
2705: return $result;
2706: }
2707: }
2708: } else {
2709: if ($authnum == 1) {
2710: $authtype = '<input type="hidden" name="login" value="int" />';
2711: }
2712: }
2713: if (!$can_assign{'int'}) {
2714: return;
2715: } elsif ($authtype eq '') {
2716: if (defined($in{'mode'})) {
2717: if ($in{'mode'} eq 'modifycourse') {
2718: if ($authnum == 1) {
2719: $authtype = '<input type="radio" name="login" value="int" />';
2720: }
2721: }
2722: }
2723: }
2724: $jscall = "javascript:changed_radio('int',$in{'formname'});";
2725: if ($authtype eq '') {
2726: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
2727: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
2728: }
2729: $autharg = '<input type="password" size="10" name="intarg" value="'.
2730: $intarg.'" onchange="'.$jscall.'" />';
2731: $result = &mt
2732: ('[_1] Internally authenticated (with initial password [_2])',
2733: '<label>'.$authtype,'</label>'.$autharg);
2734: $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>';
2735: return $result;
2736: }
2737:
2738: sub authform_local {
2739: my %in = (
2740: formname => 'document.cu',
2741: kerb_def_dom => 'MSU.EDU',
2742: @_,
2743: );
2744: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
2745: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2746: if (defined($in{'curr_authtype'})) {
2747: if ($in{'curr_authtype'} eq 'loc') {
2748: if ($can_assign{'loc'}) {
2749: $loccheck = 'checked="checked" ';
2750: if (defined($in{'mode'})) {
2751: if ($in{'mode'} eq 'modifyuser') {
2752: $loccheck = '';
2753: }
2754: }
2755: if (defined($in{'curr_autharg'})) {
2756: $locarg = $in{'curr_autharg'};
2757: }
2758: } else {
2759: $result = &mt('Currently using local (institutional) authentication.');
2760: return $result;
2761: }
2762: }
2763: } else {
2764: if ($authnum == 1) {
2765: $authtype = '<input type="hidden" name="login" value="loc" />';
2766: }
2767: }
2768: if (!$can_assign{'loc'}) {
2769: return;
2770: } elsif ($authtype eq '') {
2771: if (defined($in{'mode'})) {
2772: if ($in{'mode'} eq 'modifycourse') {
2773: if ($authnum == 1) {
2774: $authtype = '<input type="radio" name="login" value="loc" />';
2775: }
2776: }
2777: }
2778: }
2779: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
2780: if ($authtype eq '') {
2781: $authtype = '<input type="radio" name="login" value="loc" '.
2782: $loccheck.' onchange="'.$jscall.'" onclick="'.
2783: $jscall.'" />';
2784: }
2785: $autharg = '<input type="text" size="10" name="locarg" value="'.
2786: $locarg.'" onchange="'.$jscall.'" />';
2787: $result = &mt('[_1] Local Authentication with argument [_2]',
2788: '<label>'.$authtype,'</label>'.$autharg);
2789: return $result;
2790: }
2791:
2792: sub authform_filesystem {
2793: my %in = (
2794: formname => 'document.cu',
2795: kerb_def_dom => 'MSU.EDU',
2796: @_,
2797: );
2798: my ($fsyscheck,$result,$authtype,$autharg,$jscall);
2799: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2800: if (defined($in{'curr_authtype'})) {
2801: if ($in{'curr_authtype'} eq 'fsys') {
2802: if ($can_assign{'fsys'}) {
2803: $fsyscheck = 'checked="checked" ';
2804: if (defined($in{'mode'})) {
2805: if ($in{'mode'} eq 'modifyuser') {
2806: $fsyscheck = '';
2807: }
2808: }
2809: } else {
2810: $result = &mt('Currently Filesystem Authenticated.');
2811: return $result;
2812: }
2813: }
2814: } else {
2815: if ($authnum == 1) {
2816: $authtype = '<input type="hidden" name="login" value="fsys" />';
2817: }
2818: }
2819: if (!$can_assign{'fsys'}) {
2820: return;
2821: } elsif ($authtype eq '') {
2822: if (defined($in{'mode'})) {
2823: if ($in{'mode'} eq 'modifycourse') {
2824: if ($authnum == 1) {
2825: $authtype = '<input type="radio" name="login" value="fsys" />';
2826: }
2827: }
2828: }
2829: }
2830: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
2831: if ($authtype eq '') {
2832: $authtype = '<input type="radio" name="login" value="fsys" '.
2833: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
2834: $jscall.'" />';
2835: }
2836: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
2837: ' onchange="'.$jscall.'" />';
2838: $result = &mt
2839: ('[_1] Filesystem Authenticated (with initial password [_2])',
2840: '<label><input type="radio" name="login" value="fsys" '.
2841: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
2842: '</label><input type="password" size="10" name="fsysarg" value="" '.
2843: 'onchange="'.$jscall.'" />');
2844: return $result;
2845: }
2846:
2847: sub get_assignable_auth {
2848: my ($dom) = @_;
2849: if ($dom eq '') {
2850: $dom = $env{'request.role.domain'};
2851: }
2852: my %can_assign = (
2853: krb4 => 1,
2854: krb5 => 1,
2855: int => 1,
2856: loc => 1,
2857: );
2858: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
2859: if (ref($domconfig{'usercreation'}) eq 'HASH') {
2860: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
2861: my $authhash = $domconfig{'usercreation'}{'authtypes'};
2862: my $context;
2863: if ($env{'request.role'} =~ /^au/) {
2864: $context = 'author';
2865: } elsif ($env{'request.role'} =~ /^dc/) {
2866: $context = 'domain';
2867: } elsif ($env{'request.course.id'}) {
2868: $context = 'course';
2869: }
2870: if ($context) {
2871: if (ref($authhash->{$context}) eq 'HASH') {
2872: %can_assign = %{$authhash->{$context}};
2873: }
2874: }
2875: }
2876: }
2877: my $authnum = 0;
2878: foreach my $key (keys(%can_assign)) {
2879: if ($can_assign{$key}) {
2880: $authnum ++;
2881: }
2882: }
2883: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
2884: $authnum --;
2885: }
2886: return ($authnum,%can_assign);
2887: }
2888:
2889: ###############################################################
2890: ## Get Kerberos Defaults for Domain ##
2891: ###############################################################
2892: ##
2893: ## Returns default kerberos version and an associated argument
2894: ## as listed in file domain.tab. If not listed, provides
2895: ## appropriate default domain and kerberos version.
2896: ##
2897: #-------------------------------------------
2898:
2899: =pod
2900:
2901: =item * &get_kerberos_defaults()
2902:
2903: get_kerberos_defaults($target_domain) returns the default kerberos
2904: version and domain. If not found, it defaults to version 4 and the
2905: domain of the server.
2906:
2907: =over 4
2908:
2909: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
2910:
2911: =back
2912:
2913: =back
2914:
2915: =cut
2916:
2917: #-------------------------------------------
2918: sub get_kerberos_defaults {
2919: my $domain=shift;
2920: my ($krbdef,$krbdefdom);
2921: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
2922: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
2923: $krbdef = $domdefaults{'auth_def'};
2924: $krbdefdom = $domdefaults{'auth_arg_def'};
2925: } else {
2926: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
2927: my $krbdefdom=$1;
2928: $krbdefdom=~tr/a-z/A-Z/;
2929: $krbdef = "krb4";
2930: }
2931: return ($krbdef,$krbdefdom);
2932: }
2933:
2934:
2935: ###############################################################
2936: ## Thesaurus Functions ##
2937: ###############################################################
2938:
2939: =pod
2940:
2941: =head1 Thesaurus Functions
2942:
2943: =over 4
2944:
2945: =item * &initialize_keywords()
2946:
2947: Initializes the package variable %Keywords if it is empty. Uses the
2948: package variable $thesaurus_db_file.
2949:
2950: =cut
2951:
2952: ###################################################
2953:
2954: sub initialize_keywords {
2955: return 1 if (scalar keys(%Keywords));
2956: # If we are here, %Keywords is empty, so fill it up
2957: # Make sure the file we need exists...
2958: if (! -e $thesaurus_db_file) {
2959: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
2960: " failed because it does not exist");
2961: return 0;
2962: }
2963: # Set up the hash as a database
2964: my %thesaurus_db;
2965: if (! tie(%thesaurus_db,'GDBM_File',
2966: $thesaurus_db_file,&GDBM_READER(),0640)){
2967: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
2968: $thesaurus_db_file);
2969: return 0;
2970: }
2971: # Get the average number of appearances of a word.
2972: my $avecount = $thesaurus_db{'average.count'};
2973: # Put keywords (those that appear > average) into %Keywords
2974: while (my ($word,$data)=each (%thesaurus_db)) {
2975: my ($count,undef) = split /:/,$data;
2976: $Keywords{$word}++ if ($count > $avecount);
2977: }
2978: untie %thesaurus_db;
2979: # Remove special values from %Keywords.
2980: foreach my $value ('total.count','average.count') {
2981: delete($Keywords{$value}) if (exists($Keywords{$value}));
2982: }
2983: return 1;
2984: }
2985:
2986: ###################################################
2987:
2988: =pod
2989:
2990: =item * &keyword($word)
2991:
2992: Returns true if $word is a keyword. A keyword is a word that appears more
2993: than the average number of times in the thesaurus database. Calls
2994: &initialize_keywords
2995:
2996: =cut
2997:
2998: ###################################################
2999:
3000: sub keyword {
3001: return if (!&initialize_keywords());
3002: my $word=lc(shift());
3003: $word=~s/\W//g;
3004: return exists($Keywords{$word});
3005: }
3006:
3007: ###############################################################
3008:
3009: =pod
3010:
3011: =item * &get_related_words()
3012:
3013: Look up a word in the thesaurus. Takes a scalar argument and returns
3014: an array of words. If the keyword is not in the thesaurus, an empty array
3015: will be returned. The order of the words returned is determined by the
3016: database which holds them.
3017:
3018: Uses global $thesaurus_db_file.
3019:
3020:
3021: =cut
3022:
3023: ###############################################################
3024: sub get_related_words {
3025: my $keyword = shift;
3026: my %thesaurus_db;
3027: if (! -e $thesaurus_db_file) {
3028: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
3029: "failed because the file does not exist");
3030: return ();
3031: }
3032: if (! tie(%thesaurus_db,'GDBM_File',
3033: $thesaurus_db_file,&GDBM_READER(),0640)){
3034: return ();
3035: }
3036: my @Words=();
3037: my $count=0;
3038: if (exists($thesaurus_db{$keyword})) {
3039: # The first element is the number of times
3040: # the word appears. We do not need it now.
3041: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
3042: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
3043: my $threshold=$mostfrequentcount/10;
3044: foreach my $possibleword (@RelatedWords) {
3045: my ($word,$wordcount)=split(/\,/,$possibleword);
3046: if ($wordcount>$threshold) {
3047: push(@Words,$word);
3048: $count++;
3049: if ($count>10) { last; }
3050: }
3051: }
3052: }
3053: untie %thesaurus_db;
3054: return @Words;
3055: }
3056: ###############################################################
3057: #
3058: # Spell checking
3059: #
3060:
3061: =pod
3062:
3063: =head1 Spell checking
3064:
3065: =over 4
3066:
3067: =item * &check_spelling($wordlist $language)
3068:
3069: Takes a string containing words and feeds it to an external
3070: spellcheck program via a pipeline. Returns a string containing
3071: them mis-spelled words.
3072:
3073: Parameters:
3074:
3075: =over 4
3076:
3077: =item - $wordlist
3078:
3079: String that will be fed into the spellcheck program.
3080:
3081: =item - $language
3082:
3083: Language string that specifies the language for which the spell
3084: check will be performed.
3085:
3086: =back
3087:
3088: =back
3089:
3090: Note: This sub assumes that aspell is installed.
3091:
3092:
3093: =cut
3094:
3095:
3096: =pod
3097:
3098: =back
3099:
3100: =cut
3101:
3102: sub check_spelling {
3103: my ($wordlist, $language) = @_;
3104: my @misspellings;
3105:
3106: # Generate the speller and set the langauge.
3107: # if explicitly selected:
3108:
3109: my $speller = Text::Aspell->new;
3110: if ($language) {
3111: $speller->set_option('lang', $language);
3112: }
3113:
3114: # Turn the word list into an array of words by splittingon whitespace
3115:
3116: my @words = split(/\s+/, $wordlist);
3117:
3118: foreach my $word (@words) {
3119: if(! $speller->check($word)) {
3120: push(@misspellings, $word);
3121: }
3122: }
3123: return join(' ', @misspellings);
3124:
3125: }
3126:
3127: # -------------------------------------------------------------- Plaintext name
3128: =pod
3129:
3130: =head1 User Name Functions
3131:
3132: =over 4
3133:
3134: =item * &plainname($uname,$udom,$first)
3135:
3136: Takes a users logon name and returns it as a string in
3137: "first middle last generation" form
3138: if $first is set to 'lastname' then it returns it as
3139: 'lastname generation, firstname middlename' if their is a lastname
3140:
3141: =cut
3142:
3143:
3144: ###############################################################
3145: sub plainname {
3146: my ($uname,$udom,$first)=@_;
3147: return if (!defined($uname) || !defined($udom));
3148: my %names=&getnames($uname,$udom);
3149: my $name=&Apache::lonnet::format_name($names{'firstname'},
3150: $names{'middlename'},
3151: $names{'lastname'},
3152: $names{'generation'},$first);
3153: $name=~s/^\s+//;
3154: $name=~s/\s+$//;
3155: $name=~s/\s+/ /g;
3156: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
3157: return $name;
3158: }
3159:
3160: # -------------------------------------------------------------------- Nickname
3161: =pod
3162:
3163: =item * &nickname($uname,$udom)
3164:
3165: Gets a users name and returns it as a string as
3166:
3167: ""nickname""
3168:
3169: if the user has a nickname or
3170:
3171: "first middle last generation"
3172:
3173: if the user does not
3174:
3175: =cut
3176:
3177: sub nickname {
3178: my ($uname,$udom)=@_;
3179: return if (!defined($uname) || !defined($udom));
3180: my %names=&getnames($uname,$udom);
3181: my $name=$names{'nickname'};
3182: if ($name) {
3183: $name='"'.$name.'"';
3184: } else {
3185: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
3186: $names{'lastname'}.' '.$names{'generation'};
3187: $name=~s/\s+$//;
3188: $name=~s/\s+/ /g;
3189: }
3190: return $name;
3191: }
3192:
3193: sub getnames {
3194: my ($uname,$udom)=@_;
3195: return if (!defined($uname) || !defined($udom));
3196: if ($udom eq 'public' && $uname eq 'public') {
3197: return ('lastname' => &mt('Public'));
3198: }
3199: my $id=$uname.':'.$udom;
3200: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
3201: if ($cached) {
3202: return %{$names};
3203: } else {
3204: my %loadnames=&Apache::lonnet::get('environment',
3205: ['firstname','middlename','lastname','generation','nickname'],
3206: $udom,$uname);
3207: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
3208: return %loadnames;
3209: }
3210: }
3211:
3212: # -------------------------------------------------------------------- getemails
3213:
3214: =pod
3215:
3216: =item * &getemails($uname,$udom)
3217:
3218: Gets a user's email information and returns it as a hash with keys:
3219: notification, critnotification, permanentemail
3220:
3221: For notification and critnotification, values are comma-separated lists
3222: of e-mail addresses; for permanentemail, value is a single e-mail address.
3223:
3224:
3225: =cut
3226:
3227:
3228: sub getemails {
3229: my ($uname,$udom)=@_;
3230: if ($udom eq 'public' && $uname eq 'public') {
3231: return;
3232: }
3233: if (!$udom) { $udom=$env{'user.domain'}; }
3234: if (!$uname) { $uname=$env{'user.name'}; }
3235: my $id=$uname.':'.$udom;
3236: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
3237: if ($cached) {
3238: return %{$names};
3239: } else {
3240: my %loadnames=&Apache::lonnet::get('environment',
3241: ['notification','critnotification',
3242: 'permanentemail'],
3243: $udom,$uname);
3244: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
3245: return %loadnames;
3246: }
3247: }
3248:
3249: sub flush_email_cache {
3250: my ($uname,$udom)=@_;
3251: if (!$udom) { $udom =$env{'user.domain'}; }
3252: if (!$uname) { $uname=$env{'user.name'}; }
3253: return if ($udom eq 'public' && $uname eq 'public');
3254: my $id=$uname.':'.$udom;
3255: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
3256: }
3257:
3258: # -------------------------------------------------------------------- getlangs
3259:
3260: =pod
3261:
3262: =item * &getlangs($uname,$udom)
3263:
3264: Gets a user's language preference and returns it as a hash with key:
3265: language.
3266:
3267: =cut
3268:
3269:
3270: sub getlangs {
3271: my ($uname,$udom) = @_;
3272: if (!$udom) { $udom =$env{'user.domain'}; }
3273: if (!$uname) { $uname=$env{'user.name'}; }
3274: my $id=$uname.':'.$udom;
3275: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
3276: if ($cached) {
3277: return %{$langs};
3278: } else {
3279: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
3280: $udom,$uname);
3281: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
3282: return %loadlangs;
3283: }
3284: }
3285:
3286: sub flush_langs_cache {
3287: my ($uname,$udom)=@_;
3288: if (!$udom) { $udom =$env{'user.domain'}; }
3289: if (!$uname) { $uname=$env{'user.name'}; }
3290: return if ($udom eq 'public' && $uname eq 'public');
3291: my $id=$uname.':'.$udom;
3292: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
3293: }
3294:
3295: # ------------------------------------------------------------------ Screenname
3296:
3297: =pod
3298:
3299: =item * &screenname($uname,$udom)
3300:
3301: Gets a users screenname and returns it as a string
3302:
3303: =cut
3304:
3305: sub screenname {
3306: my ($uname,$udom)=@_;
3307: if ($uname eq $env{'user.name'} &&
3308: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
3309: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
3310: return $names{'screenname'};
3311: }
3312:
3313:
3314: # ------------------------------------------------------------- Confirm Wrapper
3315: =pod
3316:
3317: =item confirmwrapper
3318:
3319: Wrap messages about completion of operation in box
3320:
3321: =cut
3322:
3323: sub confirmwrapper {
3324: my ($message)=@_;
3325: if ($message) {
3326: return "\n".'<div class="LC_confirm_box">'."\n"
3327: .$message."\n"
3328: .'</div>'."\n";
3329: } else {
3330: return $message;
3331: }
3332: }
3333:
3334: # ------------------------------------------------------------- Message Wrapper
3335:
3336: sub messagewrapper {
3337: my ($link,$username,$domain,$subject,$text)=@_;
3338: return
3339: '<a href="/adm/email?compose=individual&'.
3340: 'recname='.$username.'&recdom='.$domain.
3341: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
3342: 'title="'.&mt('Send message').'">'.$link.'</a>';
3343: }
3344:
3345: # --------------------------------------------------------------- Notes Wrapper
3346:
3347: sub noteswrapper {
3348: my ($link,$un,$do)=@_;
3349: return
3350: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
3351: }
3352:
3353: # ------------------------------------------------------------- Aboutme Wrapper
3354:
3355: sub aboutmewrapper {
3356: my ($link,$username,$domain,$target,$class)=@_;
3357: if (!defined($username) && !defined($domain)) {
3358: return;
3359: }
3360: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
3361: ($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
3362: }
3363:
3364: # ------------------------------------------------------------ Syllabus Wrapper
3365:
3366: sub syllabuswrapper {
3367: my ($linktext,$coursedir,$domain)=@_;
3368: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
3369: }
3370:
3371: # -----------------------------------------------------------------------------
3372:
3373: sub track_student_link {
3374: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
3375: my $link ="/adm/trackstudent?";
3376: my $title = 'View recent activity';
3377: if (defined($sname) && $sname !~ /^\s*$/ &&
3378: defined($sdom) && $sdom !~ /^\s*$/) {
3379: $link .= "selected_student=$sname:$sdom";
3380: $title .= ' of this student';
3381: }
3382: if (defined($target) && $target !~ /^\s*$/) {
3383: $target = qq{target="$target"};
3384: } else {
3385: $target = '';
3386: }
3387: if ($start) { $link.='&start='.$start; }
3388: if ($only_body) { $link .= '&only_body=1'; }
3389: $title = &mt($title);
3390: $linktext = &mt($linktext);
3391: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
3392: &help_open_topic('View_recent_activity');
3393: }
3394:
3395: sub slot_reservations_link {
3396: my ($linktext,$sname,$sdom,$target) = @_;
3397: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
3398: my $title = 'View slot reservation history';
3399: if (defined($sname) && $sname !~ /^\s*$/ &&
3400: defined($sdom) && $sdom !~ /^\s*$/) {
3401: $link .= "&uname=$sname&udom=$sdom";
3402: $title .= ' of this student';
3403: }
3404: if (defined($target) && $target !~ /^\s*$/) {
3405: $target = qq{target="$target"};
3406: } else {
3407: $target = '';
3408: }
3409: $title = &mt($title);
3410: $linktext = &mt($linktext);
3411: return qq{<a href="$link" title="$title" $target>$linktext</a>};
3412: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
3413:
3414: }
3415:
3416: # ===================================================== Display a student photo
3417:
3418:
3419: sub student_image_tag {
3420: my ($domain,$user)=@_;
3421: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
3422: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
3423: return '<img src="'.$imgsrc.'" align="right" />';
3424: } else {
3425: return '';
3426: }
3427: }
3428:
3429: =pod
3430:
3431: =back
3432:
3433: =head1 Access .tab File Data
3434:
3435: =over 4
3436:
3437: =item * &languageids()
3438:
3439: returns list of all language ids
3440:
3441: =cut
3442:
3443: sub languageids {
3444: return sort(keys(%language));
3445: }
3446:
3447: =pod
3448:
3449: =item * &languagedescription()
3450:
3451: returns description of a specified language id
3452:
3453: =cut
3454:
3455: sub languagedescription {
3456: my $code=shift;
3457: return ($supported_language{$code}?'* ':'').
3458: $language{$code}.
3459: ($supported_language{$code}?' ('.&mt('interface available').')':'');
3460: }
3461:
3462: =pod
3463:
3464: =item * &plainlanguagedescription
3465:
3466: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
3467: and the language character encoding (e.g. ISO) separated by a ' - ' string.
3468:
3469: =cut
3470:
3471: sub plainlanguagedescription {
3472: my $code=shift;
3473: return $language{$code};
3474: }
3475:
3476: =pod
3477:
3478: =item * &supportedlanguagecode
3479:
3480: Returns the supported language code (e.g. sptutf maps to pt) given a language
3481: code.
3482:
3483: =cut
3484:
3485: sub supportedlanguagecode {
3486: my $code=shift;
3487: return $supported_language{$code};
3488: }
3489:
3490: =pod
3491:
3492: =item * &latexlanguage()
3493:
3494: Given a language key code returns the correspondnig language to use
3495: to select the correct hyphenation on LaTeX printouts. This is undef if there
3496: is no supported hyphenation for the language code.
3497:
3498: =cut
3499:
3500: sub latexlanguage {
3501: my $code = shift;
3502: return $latex_language{$code};
3503: }
3504:
3505: =pod
3506:
3507: =item * &latexhyphenation()
3508:
3509: Same as above but what's supplied is the language as it might be stored
3510: in the metadata.
3511:
3512: =cut
3513:
3514: sub latexhyphenation {
3515: my $key = shift;
3516: return $latex_language_bykey{$key};
3517: }
3518:
3519: =pod
3520:
3521: =item * ©rightids()
3522:
3523: returns list of all copyrights
3524:
3525: =cut
3526:
3527: sub copyrightids {
3528: return sort(keys(%cprtag));
3529: }
3530:
3531: =pod
3532:
3533: =item * ©rightdescription()
3534:
3535: returns description of a specified copyright id
3536:
3537: =cut
3538:
3539: sub copyrightdescription {
3540: return &mt($cprtag{shift(@_)});
3541: }
3542:
3543: =pod
3544:
3545: =item * &source_copyrightids()
3546:
3547: returns list of all source copyrights
3548:
3549: =cut
3550:
3551: sub source_copyrightids {
3552: return sort(keys(%scprtag));
3553: }
3554:
3555: =pod
3556:
3557: =item * &source_copyrightdescription()
3558:
3559: returns description of a specified source copyright id
3560:
3561: =cut
3562:
3563: sub source_copyrightdescription {
3564: return &mt($scprtag{shift(@_)});
3565: }
3566:
3567: =pod
3568:
3569: =item * &filecategories()
3570:
3571: returns list of all file categories
3572:
3573: =cut
3574:
3575: sub filecategories {
3576: return sort(keys(%category_extensions));
3577: }
3578:
3579: =pod
3580:
3581: =item * &filecategorytypes()
3582:
3583: returns list of file types belonging to a given file
3584: category
3585:
3586: =cut
3587:
3588: sub filecategorytypes {
3589: my ($cat) = @_;
3590: return @{$category_extensions{lc($cat)}};
3591: }
3592:
3593: =pod
3594:
3595: =item * &fileembstyle()
3596:
3597: returns embedding style for a specified file type
3598:
3599: =cut
3600:
3601: sub fileembstyle {
3602: return $fe{lc(shift(@_))};
3603: }
3604:
3605: sub filemimetype {
3606: return $fm{lc(shift(@_))};
3607: }
3608:
3609:
3610: sub filecategoryselect {
3611: my ($name,$value)=@_;
3612: return &select_form($value,$name,
3613: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
3614: }
3615:
3616: =pod
3617:
3618: =item * &filedescription()
3619:
3620: returns description for a specified file type
3621:
3622: =cut
3623:
3624: sub filedescription {
3625: my $file_description = $fd{lc(shift())};
3626: $file_description =~ s:([\[\]]):~$1:g;
3627: return &mt($file_description);
3628: }
3629:
3630: =pod
3631:
3632: =item * &filedescriptionex()
3633:
3634: returns description for a specified file type with
3635: extra formatting
3636:
3637: =cut
3638:
3639: sub filedescriptionex {
3640: my $ex=shift;
3641: my $file_description = $fd{lc($ex)};
3642: $file_description =~ s:([\[\]]):~$1:g;
3643: return '.'.$ex.' '.&mt($file_description);
3644: }
3645:
3646: # End of .tab access
3647: =pod
3648:
3649: =back
3650:
3651: =cut
3652:
3653: # ------------------------------------------------------------------ File Types
3654: sub fileextensions {
3655: return sort(keys(%fe));
3656: }
3657:
3658: # ----------------------------------------------------------- Display Languages
3659: # returns a hash with all desired display languages
3660: #
3661:
3662: sub display_languages {
3663: my %languages=();
3664: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
3665: $languages{$lang}=1;
3666: }
3667: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3668: if ($env{'form.displaylanguage'}) {
3669: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3670: $languages{$lang}=1;
3671: }
3672: }
3673: return %languages;
3674: }
3675:
3676: sub languages {
3677: my ($possible_langs) = @_;
3678: my @preferred_langs = &Apache::lonlocal::preferred_languages();
3679: if (!ref($possible_langs)) {
3680: if( wantarray ) {
3681: return @preferred_langs;
3682: } else {
3683: return $preferred_langs[0];
3684: }
3685: }
3686: my %possibilities = map { $_ => 1 } (@$possible_langs);
3687: my @preferred_possibilities;
3688: foreach my $preferred_lang (@preferred_langs) {
3689: if (exists($possibilities{$preferred_lang})) {
3690: push(@preferred_possibilities, $preferred_lang);
3691: }
3692: }
3693: if( wantarray ) {
3694: return @preferred_possibilities;
3695: }
3696: return $preferred_possibilities[0];
3697: }
3698:
3699: sub user_lang {
3700: my ($touname,$toudom,$fromcid) = @_;
3701: my @userlangs;
3702: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
3703: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
3704: $env{'course.'.$fromcid.'.languages'}));
3705: } else {
3706: my %langhash = &getlangs($touname,$toudom);
3707: if ($langhash{'languages'} ne '') {
3708: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
3709: } else {
3710: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
3711: if ($domdefs{'lang_def'} ne '') {
3712: @userlangs = ($domdefs{'lang_def'});
3713: }
3714: }
3715: }
3716: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
3717: my $user_lh = Apache::localize->get_handle(@languages);
3718: return $user_lh;
3719: }
3720:
3721:
3722: ###############################################################
3723: ## Student Answer Attempts ##
3724: ###############################################################
3725:
3726: =pod
3727:
3728: =head1 Alternate Problem Views
3729:
3730: =over 4
3731:
3732: =item * &get_previous_attempt($symb, $username, $domain, $course,
3733: $getattempt, $regexp, $gradesub)
3734:
3735: Return string with previous attempt on problem. Arguments:
3736:
3737: =over 4
3738:
3739: =item * $symb: Problem, including path
3740:
3741: =item * $username: username of the desired student
3742:
3743: =item * $domain: domain of the desired student
3744:
3745: =item * $course: Course ID
3746:
3747: =item * $getattempt: Leave blank for all attempts, otherwise put
3748: something
3749:
3750: =item * $regexp: if string matches this regexp, the string will be
3751: sent to $gradesub
3752:
3753: =item * $gradesub: routine that processes the string if it matches $regexp
3754:
3755: =back
3756:
3757: The output string is a table containing all desired attempts, if any.
3758:
3759: =cut
3760:
3761: sub get_previous_attempt {
3762: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
3763: my $prevattempts='';
3764: no strict 'refs';
3765: if ($symb) {
3766: my (%returnhash)=
3767: &Apache::lonnet::restore($symb,$course,$domain,$username);
3768: if ($returnhash{'version'}) {
3769: my %lasthash=();
3770: my $version;
3771: for ($version=1;$version<=$returnhash{'version'};$version++) {
3772: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
3773: $lasthash{$key}=$returnhash{$version.':'.$key};
3774: }
3775: }
3776: $prevattempts=&start_data_table().&start_data_table_header_row();
3777: $prevattempts.='<th>'.&mt('History').'</th>';
3778: my (%typeparts,%lasthidden);
3779: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
3780: foreach my $key (sort(keys(%lasthash))) {
3781: my ($ign,@parts) = split(/\./,$key);
3782: if ($#parts > 0) {
3783: my $data=$parts[-1];
3784: next if ($data eq 'foilorder');
3785: pop(@parts);
3786: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
3787: if ($data eq 'type') {
3788: unless ($showsurv) {
3789: my $id = join(',',@parts);
3790: $typeparts{$ign.'.'.$id} = $lasthash{$key};
3791: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
3792: $lasthidden{$ign.'.'.$id} = 1;
3793: }
3794: }
3795: }
3796: } else {
3797: if ($#parts == 0) {
3798: $prevattempts.='<th>'.$parts[0].'</th>';
3799: } else {
3800: $prevattempts.='<th>'.$ign.'</th>';
3801: }
3802: }
3803: }
3804: $prevattempts.=&end_data_table_header_row();
3805: if ($getattempt eq '') {
3806: for ($version=1;$version<=$returnhash{'version'};$version++) {
3807: my @hidden;
3808: if (%typeparts) {
3809: foreach my $id (keys(%typeparts)) {
3810: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
3811: push(@hidden,$id);
3812: }
3813: }
3814: }
3815: $prevattempts.=&start_data_table_row().
3816: '<td>'.&mt('Transaction [_1]',$version).'</td>';
3817: if (@hidden) {
3818: foreach my $key (sort(keys(%lasthash))) {
3819: next if ($key =~ /\.foilorder$/);
3820: my $hide;
3821: foreach my $id (@hidden) {
3822: if ($key =~ /^\Q$id\E/) {
3823: $hide = 1;
3824: last;
3825: }
3826: }
3827: if ($hide) {
3828: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
3829: if (($data eq 'award') || ($data eq 'awarddetail')) {
3830: my $value = &format_previous_attempt_value($key,
3831: $returnhash{$version.':'.$key});
3832: $prevattempts.='<td>'.$value.' </td>';
3833: } else {
3834: $prevattempts.='<td> </td>';
3835: }
3836: } else {
3837: if ($key =~ /\./) {
3838: my $value = &format_previous_attempt_value($key,
3839: $returnhash{$version.':'.$key});
3840: $prevattempts.='<td>'.$value.' </td>';
3841: } else {
3842: $prevattempts.='<td> </td>';
3843: }
3844: }
3845: }
3846: } else {
3847: foreach my $key (sort(keys(%lasthash))) {
3848: next if ($key =~ /\.foilorder$/);
3849: my $value = &format_previous_attempt_value($key,
3850: $returnhash{$version.':'.$key});
3851: $prevattempts.='<td>'.$value.' </td>';
3852: }
3853: }
3854: $prevattempts.=&end_data_table_row();
3855: }
3856: }
3857: my @currhidden = keys(%lasthidden);
3858: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
3859: foreach my $key (sort(keys(%lasthash))) {
3860: next if ($key =~ /\.foilorder$/);
3861: if (%typeparts) {
3862: my $hidden;
3863: foreach my $id (@currhidden) {
3864: if ($key =~ /^\Q$id\E/) {
3865: $hidden = 1;
3866: last;
3867: }
3868: }
3869: if ($hidden) {
3870: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
3871: if (($data eq 'award') || ($data eq 'awarddetail')) {
3872: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3873: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3874: $value = &$gradesub($value);
3875: }
3876: $prevattempts.='<td>'.$value.' </td>';
3877: } else {
3878: $prevattempts.='<td> </td>';
3879: }
3880: } else {
3881: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3882: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3883: $value = &$gradesub($value);
3884: }
3885: $prevattempts.='<td>'.$value.' </td>';
3886: }
3887: } else {
3888: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3889: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3890: $value = &$gradesub($value);
3891: }
3892: $prevattempts.='<td>'.$value.' </td>';
3893: }
3894: }
3895: $prevattempts.= &end_data_table_row().&end_data_table();
3896: } else {
3897: $prevattempts=
3898: &start_data_table().&start_data_table_row().
3899: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
3900: &end_data_table_row().&end_data_table();
3901: }
3902: } else {
3903: $prevattempts=
3904: &start_data_table().&start_data_table_row().
3905: '<td>'.&mt('No data.').'</td>'.
3906: &end_data_table_row().&end_data_table();
3907: }
3908: }
3909:
3910: sub format_previous_attempt_value {
3911: my ($key,$value) = @_;
3912: if (($key =~ /timestamp/) || ($key=~/duedate/)) {
3913: $value = &Apache::lonlocal::locallocaltime($value);
3914: } elsif (ref($value) eq 'ARRAY') {
3915: $value = '('.join(', ', @{ $value }).')';
3916: } elsif ($key =~ /answerstring$/) {
3917: my %answers = &Apache::lonnet::str2hash($value);
3918: my @anskeys = sort(keys(%answers));
3919: if (@anskeys == 1) {
3920: my $answer = $answers{$anskeys[0]};
3921: if ($answer =~ m{\0}) {
3922: $answer =~ s{\0}{,}g;
3923: }
3924: my $tag_internal_answer_name = 'INTERNAL';
3925: if ($anskeys[0] eq $tag_internal_answer_name) {
3926: $value = $answer;
3927: } else {
3928: $value = $anskeys[0].'='.$answer;
3929: }
3930: } else {
3931: foreach my $ans (@anskeys) {
3932: my $answer = $answers{$ans};
3933: if ($answer =~ m{\0}) {
3934: $answer =~ s{\0}{,}g;
3935: }
3936: $value .= $ans.'='.$answer.'<br />';;
3937: }
3938: }
3939: } else {
3940: $value = &unescape($value);
3941: }
3942: return $value;
3943: }
3944:
3945:
3946: sub relative_to_absolute {
3947: my ($url,$output)=@_;
3948: my $parser=HTML::TokeParser->new(\$output);
3949: my $token;
3950: my $thisdir=$url;
3951: my @rlinks=();
3952: while ($token=$parser->get_token) {
3953: if ($token->[0] eq 'S') {
3954: if ($token->[1] eq 'a') {
3955: if ($token->[2]->{'href'}) {
3956: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
3957: }
3958: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
3959: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
3960: } elsif ($token->[1] eq 'base') {
3961: $thisdir=$token->[2]->{'href'};
3962: }
3963: }
3964: }
3965: $thisdir=~s-/[^/]*$--;
3966: foreach my $link (@rlinks) {
3967: unless (($link=~/^https?\:\/\//i) ||
3968: ($link=~/^\//) ||
3969: ($link=~/^javascript:/i) ||
3970: ($link=~/^mailto:/i) ||
3971: ($link=~/^\#/)) {
3972: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
3973: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
3974: }
3975: }
3976: # -------------------------------------------------- Deal with Applet codebases
3977: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
3978: return $output;
3979: }
3980:
3981: =pod
3982:
3983: =item * &get_student_view()
3984:
3985: show a snapshot of what student was looking at
3986:
3987: =cut
3988:
3989: sub get_student_view {
3990: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
3991: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
3992: my (%form);
3993: my @elements=('symb','courseid','domain','username');
3994: foreach my $element (@elements) {
3995: $form{'grade_'.$element}=eval '$'.$element #'
3996: }
3997: if (defined($moreenv)) {
3998: %form=(%form,%{$moreenv});
3999: }
4000: if (defined($target)) { $form{'grade_target'} = $target; }
4001: $feedurl=&Apache::lonnet::clutter($feedurl);
4002: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
4003: $userview=~s/\<body[^\>]*\>//gi;
4004: $userview=~s/\<\/body\>//gi;
4005: $userview=~s/\<html\>//gi;
4006: $userview=~s/\<\/html\>//gi;
4007: $userview=~s/\<head\>//gi;
4008: $userview=~s/\<\/head\>//gi;
4009: $userview=~s/action\s*\=/would_be_action\=/gi;
4010: $userview=&relative_to_absolute($feedurl,$userview);
4011: if (wantarray) {
4012: return ($userview,$response);
4013: } else {
4014: return $userview;
4015: }
4016: }
4017:
4018: sub get_student_view_with_retries {
4019: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
4020:
4021: my $ok = 0; # True if we got a good response.
4022: my $content;
4023: my $response;
4024:
4025: # Try to get the student_view done. within the retries count:
4026:
4027: do {
4028: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
4029: $ok = $response->is_success;
4030: if (!$ok) {
4031: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
4032: }
4033: $retries--;
4034: } while (!$ok && ($retries > 0));
4035:
4036: if (!$ok) {
4037: $content = ''; # On error return an empty content.
4038: }
4039: if (wantarray) {
4040: return ($content, $response);
4041: } else {
4042: return $content;
4043: }
4044: }
4045:
4046: =pod
4047:
4048: =item * &get_student_answers()
4049:
4050: show a snapshot of how student was answering problem
4051:
4052: =cut
4053:
4054: sub get_student_answers {
4055: my ($symb,$username,$domain,$courseid,%form) = @_;
4056: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4057: my (%moreenv);
4058: my @elements=('symb','courseid','domain','username');
4059: foreach my $element (@elements) {
4060: $moreenv{'grade_'.$element}=eval '$'.$element #'
4061: }
4062: $moreenv{'grade_target'}='answer';
4063: %moreenv=(%form,%moreenv);
4064: $feedurl = &Apache::lonnet::clutter($feedurl);
4065: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
4066: return $userview;
4067: }
4068:
4069: =pod
4070:
4071: =item * &submlink()
4072:
4073: Inputs: $text $uname $udom $symb $target
4074:
4075: Returns: A link to grades.pm such as to see the SUBM view of a student
4076:
4077: =cut
4078:
4079: ###############################################
4080: sub submlink {
4081: my ($text,$uname,$udom,$symb,$target)=@_;
4082: if (!($uname && $udom)) {
4083: (my $cursymb, my $courseid,$udom,$uname)=
4084: &Apache::lonnet::whichuser($symb);
4085: if (!$symb) { $symb=$cursymb; }
4086: }
4087: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4088: $symb=&escape($symb);
4089: if ($target) { $target=" target=\"$target\""; }
4090: return
4091: '<a href="/adm/grades?command=submission'.
4092: '&symb='.$symb.
4093: '&student='.$uname.
4094: '&userdom='.$udom.'"'.
4095: $target.'>'.$text.'</a>';
4096: }
4097: ##############################################
4098:
4099: =pod
4100:
4101: =item * &pgrdlink()
4102:
4103: Inputs: $text $uname $udom $symb $target
4104:
4105: Returns: A link to grades.pm such as to see the PGRD view of a student
4106:
4107: =cut
4108:
4109: ###############################################
4110: sub pgrdlink {
4111: my $link=&submlink(@_);
4112: $link=~s/(&command=submission)/$1&showgrading=yes/;
4113: return $link;
4114: }
4115: ##############################################
4116:
4117: =pod
4118:
4119: =item * &pprmlink()
4120:
4121: Inputs: $text $uname $udom $symb $target
4122:
4123: Returns: A link to parmset.pm such as to see the PPRM view of a
4124: student and a specific resource
4125:
4126: =cut
4127:
4128: ###############################################
4129: sub pprmlink {
4130: my ($text,$uname,$udom,$symb,$target)=@_;
4131: if (!($uname && $udom)) {
4132: (my $cursymb, my $courseid,$udom,$uname)=
4133: &Apache::lonnet::whichuser($symb);
4134: if (!$symb) { $symb=$cursymb; }
4135: }
4136: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4137: $symb=&escape($symb);
4138: if ($target) { $target="target=\"$target\""; }
4139: return '<a href="/adm/parmset?command=set&'.
4140: 'symb='.$symb.'&uname='.$uname.
4141: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
4142: }
4143: ##############################################
4144:
4145: =pod
4146:
4147: =back
4148:
4149: =cut
4150:
4151: ###############################################
4152:
4153:
4154: sub timehash {
4155: my ($thistime) = @_;
4156: my $timezone = &Apache::lonlocal::gettimezone();
4157: my $dt = DateTime->from_epoch(epoch => $thistime)
4158: ->set_time_zone($timezone);
4159: my $wday = $dt->day_of_week();
4160: if ($wday == 7) { $wday = 0; }
4161: return ( 'second' => $dt->second(),
4162: 'minute' => $dt->minute(),
4163: 'hour' => $dt->hour(),
4164: 'day' => $dt->day_of_month(),
4165: 'month' => $dt->month(),
4166: 'year' => $dt->year(),
4167: 'weekday' => $wday,
4168: 'dayyear' => $dt->day_of_year(),
4169: 'dlsav' => $dt->is_dst() );
4170: }
4171:
4172: sub utc_string {
4173: my ($date)=@_;
4174: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
4175: }
4176:
4177: sub maketime {
4178: my %th=@_;
4179: my ($epoch_time,$timezone,$dt);
4180: $timezone = &Apache::lonlocal::gettimezone();
4181: eval {
4182: $dt = DateTime->new( year => $th{'year'},
4183: month => $th{'month'},
4184: day => $th{'day'},
4185: hour => $th{'hour'},
4186: minute => $th{'minute'},
4187: second => $th{'second'},
4188: time_zone => $timezone,
4189: );
4190: };
4191: if (!$@) {
4192: $epoch_time = $dt->epoch;
4193: if ($epoch_time) {
4194: return $epoch_time;
4195: }
4196: }
4197: return POSIX::mktime(
4198: ($th{'seconds'},$th{'minutes'},$th{'hours'},
4199: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
4200: }
4201:
4202: #########################################
4203:
4204: sub findallcourses {
4205: my ($roles,$uname,$udom) = @_;
4206: my %roles;
4207: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
4208: my %courses;
4209: my $now=time;
4210: if (!defined($uname)) {
4211: $uname = $env{'user.name'};
4212: }
4213: if (!defined($udom)) {
4214: $udom = $env{'user.domain'};
4215: }
4216: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
4217: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
4218: if (!%roles) {
4219: %roles = (
4220: cc => 1,
4221: co => 1,
4222: in => 1,
4223: ep => 1,
4224: ta => 1,
4225: cr => 1,
4226: st => 1,
4227: );
4228: }
4229: foreach my $entry (keys(%roleshash)) {
4230: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
4231: if ($trole =~ /^cr/) {
4232: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
4233: } else {
4234: next if (!exists($roles{$trole}));
4235: }
4236: if ($tend) {
4237: next if ($tend < $now);
4238: }
4239: if ($tstart) {
4240: next if ($tstart > $now);
4241: }
4242: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
4243: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
4244: my $value = $trole.'/'.$cdom.'/';
4245: if ($secpart eq '') {
4246: ($cnum,$role) = split(/_/,$cnumpart);
4247: $sec = 'none';
4248: $value .= $cnum.'/';
4249: } else {
4250: $cnum = $cnumpart;
4251: ($sec,$role) = split(/_/,$secpart);
4252: $value .= $cnum.'/'.$sec;
4253: }
4254: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4255: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4256: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4257: }
4258: } else {
4259: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4260: }
4261: }
4262: } else {
4263: foreach my $key (keys(%env)) {
4264: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
4265: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
4266: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
4267: next if ($role eq 'ca' || $role eq 'aa');
4268: next if (%roles && !exists($roles{$role}));
4269: my ($starttime,$endtime)=split(/\./,$env{$key});
4270: my $active=1;
4271: if ($starttime) {
4272: if ($now<$starttime) { $active=0; }
4273: }
4274: if ($endtime) {
4275: if ($now>$endtime) { $active=0; }
4276: }
4277: if ($active) {
4278: my $value = $role.'/'.$cdom.'/'.$cnum.'/';
4279: if ($sec eq '') {
4280: $sec = 'none';
4281: } else {
4282: $value .= $sec;
4283: }
4284: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4285: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4286: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4287: }
4288: } else {
4289: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4290: }
4291: }
4292: }
4293: }
4294: }
4295: return %courses;
4296: }
4297:
4298: ###############################################
4299:
4300: sub blockcheck {
4301: my ($setters,$activity,$uname,$udom,$url) = @_;
4302:
4303: if (!defined($udom)) {
4304: $udom = $env{'user.domain'};
4305: }
4306: if (!defined($uname)) {
4307: $uname = $env{'user.name'};
4308: }
4309:
4310: # If uname and udom are for a course, check for blocks in the course.
4311:
4312: if (&Apache::lonnet::is_course($udom,$uname)) {
4313: my ($startblock,$endblock,$triggerblock) =
4314: &get_blocks($setters,$activity,$udom,$uname,$url);
4315: return ($startblock,$endblock,$triggerblock);
4316: }
4317:
4318: my $startblock = 0;
4319: my $endblock = 0;
4320: my $triggerblock = '';
4321: my %live_courses = &findallcourses(undef,$uname,$udom);
4322:
4323: # If uname is for a user, and activity is course-specific, i.e.,
4324: # boards, chat or groups, check for blocking in current course only.
4325:
4326: if (($activity eq 'boards' || $activity eq 'chat' ||
4327: $activity eq 'groups') && ($env{'request.course.id'})) {
4328: foreach my $key (keys(%live_courses)) {
4329: if ($key ne $env{'request.course.id'}) {
4330: delete($live_courses{$key});
4331: }
4332: }
4333: }
4334:
4335: my $otheruser = 0;
4336: my %own_courses;
4337: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
4338: # Resource belongs to user other than current user.
4339: $otheruser = 1;
4340: # Gather courses for current user
4341: %own_courses =
4342: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
4343: }
4344:
4345: # Gather active course roles - course coordinator, instructor,
4346: # exam proctor, ta, student, or custom role.
4347:
4348: foreach my $course (keys(%live_courses)) {
4349: my ($cdom,$cnum);
4350: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
4351: $cdom = $env{'course.'.$course.'.domain'};
4352: $cnum = $env{'course.'.$course.'.num'};
4353: } else {
4354: ($cdom,$cnum) = split(/_/,$course);
4355: }
4356: my $no_ownblock = 0;
4357: my $no_userblock = 0;
4358: if ($otheruser && $activity ne 'com') {
4359: # Check if current user has 'evb' priv for this
4360: if (defined($own_courses{$course})) {
4361: foreach my $sec (keys(%{$own_courses{$course}})) {
4362: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4363: if ($sec ne 'none') {
4364: $checkrole .= '/'.$sec;
4365: }
4366: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4367: $no_ownblock = 1;
4368: last;
4369: }
4370: }
4371: }
4372: # if they have 'evb' priv and are currently not playing student
4373: next if (($no_ownblock) &&
4374: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
4375: }
4376: foreach my $sec (keys(%{$live_courses{$course}})) {
4377: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4378: if ($sec ne 'none') {
4379: $checkrole .= '/'.$sec;
4380: }
4381: if ($otheruser) {
4382: # Resource belongs to user other than current user.
4383: # Assemble privs for that user, and check for 'evb' priv.
4384: my (%allroles,%userroles);
4385: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
4386: foreach my $entry (@{$live_courses{$course}{$sec}}) {
4387: my ($trole,$tdom,$tnum,$tsec);
4388: if ($entry =~ /^cr/) {
4389: ($trole,$tdom,$tnum,$tsec) =
4390: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
4391: } else {
4392: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
4393: }
4394: my ($spec,$area,$trest);
4395: $area = '/'.$tdom.'/'.$tnum;
4396: $trest = $tnum;
4397: if ($tsec ne '') {
4398: $area .= '/'.$tsec;
4399: $trest .= '/'.$tsec;
4400: }
4401: $spec = $trole.'.'.$area;
4402: if ($trole =~ /^cr/) {
4403: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
4404: $tdom,$spec,$trest,$area);
4405: } else {
4406: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
4407: $tdom,$spec,$trest,$area);
4408: }
4409: }
4410: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
4411: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
4412: if ($1) {
4413: $no_userblock = 1;
4414: last;
4415: }
4416: }
4417: }
4418: } else {
4419: # Resource belongs to current user
4420: # Check for 'evb' priv via lonnet::allowed().
4421: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4422: $no_ownblock = 1;
4423: last;
4424: }
4425: }
4426: }
4427: # if they have the evb priv and are currently not playing student
4428: next if (($no_ownblock) &&
4429: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
4430: next if ($no_userblock);
4431:
4432: # Retrieve blocking times and identity of locker for course
4433: # of specified user, unless user has 'evb' privilege.
4434:
4435: my ($start,$end,$trigger) =
4436: &get_blocks($setters,$activity,$cdom,$cnum,$url);
4437: if (($start != 0) &&
4438: (($startblock == 0) || ($startblock > $start))) {
4439: $startblock = $start;
4440: if ($trigger ne '') {
4441: $triggerblock = $trigger;
4442: }
4443: }
4444: if (($end != 0) &&
4445: (($endblock == 0) || ($endblock < $end))) {
4446: $endblock = $end;
4447: if ($trigger ne '') {
4448: $triggerblock = $trigger;
4449: }
4450: }
4451: }
4452: return ($startblock,$endblock,$triggerblock);
4453: }
4454:
4455: sub get_blocks {
4456: my ($setters,$activity,$cdom,$cnum,$url) = @_;
4457: my $startblock = 0;
4458: my $endblock = 0;
4459: my $triggerblock = '';
4460: my $course = $cdom.'_'.$cnum;
4461: $setters->{$course} = {};
4462: $setters->{$course}{'staff'} = [];
4463: $setters->{$course}{'times'} = [];
4464: $setters->{$course}{'triggers'} = [];
4465: my (@blockers,%triggered);
4466: my $now = time;
4467: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
4468: if ($activity eq 'docs') {
4469: @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
4470: foreach my $block (@blockers) {
4471: if ($block =~ /^firstaccess____(.+)$/) {
4472: my $item = $1;
4473: my $type = 'map';
4474: my $timersymb = $item;
4475: if ($item eq 'course') {
4476: $type = 'course';
4477: } elsif ($item =~ /___\d+___/) {
4478: $type = 'resource';
4479: } else {
4480: $timersymb = &Apache::lonnet::symbread($item);
4481: }
4482: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4483: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4484: $triggered{$block} = {
4485: start => $start,
4486: end => $end,
4487: type => $type,
4488: };
4489: }
4490: }
4491: } else {
4492: foreach my $block (keys(%commblocks)) {
4493: if ($block =~ m/^(\d+)____(\d+)$/) {
4494: my ($start,$end) = ($1,$2);
4495: if ($start <= time && $end >= time) {
4496: if (ref($commblocks{$block}) eq 'HASH') {
4497: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
4498: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
4499: unless(grep(/^\Q$block\E$/,@blockers)) {
4500: push(@blockers,$block);
4501: }
4502: }
4503: }
4504: }
4505: }
4506: } elsif ($block =~ /^firstaccess____(.+)$/) {
4507: my $item = $1;
4508: my $timersymb = $item;
4509: my $type = 'map';
4510: if ($item eq 'course') {
4511: $type = 'course';
4512: } elsif ($item =~ /___\d+___/) {
4513: $type = 'resource';
4514: } else {
4515: $timersymb = &Apache::lonnet::symbread($item);
4516: }
4517: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4518: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4519: if ($start && $end) {
4520: if (($start <= time) && ($end >= time)) {
4521: unless (grep(/^\Q$block\E$/,@blockers)) {
4522: push(@blockers,$block);
4523: $triggered{$block} = {
4524: start => $start,
4525: end => $end,
4526: type => $type,
4527: };
4528: }
4529: }
4530: }
4531: }
4532: }
4533: }
4534: foreach my $blocker (@blockers) {
4535: my ($staff_name,$staff_dom,$title,$blocks) =
4536: &parse_block_record($commblocks{$blocker});
4537: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
4538: my ($start,$end,$triggertype);
4539: if ($blocker =~ m/^(\d+)____(\d+)$/) {
4540: ($start,$end) = ($1,$2);
4541: } elsif (ref($triggered{$blocker}) eq 'HASH') {
4542: $start = $triggered{$blocker}{'start'};
4543: $end = $triggered{$blocker}{'end'};
4544: $triggertype = $triggered{$blocker}{'type'};
4545: }
4546: if ($start) {
4547: push(@{$$setters{$course}{'times'}}, [$start,$end]);
4548: if ($triggertype) {
4549: push(@{$$setters{$course}{'triggers'}},$triggertype);
4550: } else {
4551: push(@{$$setters{$course}{'triggers'}},0);
4552: }
4553: if ( ($startblock == 0) || ($startblock > $start) ) {
4554: $startblock = $start;
4555: if ($triggertype) {
4556: $triggerblock = $blocker;
4557: }
4558: }
4559: if ( ($endblock == 0) || ($endblock < $end) ) {
4560: $endblock = $end;
4561: if ($triggertype) {
4562: $triggerblock = $blocker;
4563: }
4564: }
4565: }
4566: }
4567: return ($startblock,$endblock,$triggerblock);
4568: }
4569:
4570: sub parse_block_record {
4571: my ($record) = @_;
4572: my ($setuname,$setudom,$title,$blocks);
4573: if (ref($record) eq 'HASH') {
4574: ($setuname,$setudom) = split(/:/,$record->{'setter'});
4575: $title = &unescape($record->{'event'});
4576: $blocks = $record->{'blocks'};
4577: } else {
4578: my @data = split(/:/,$record,3);
4579: if (scalar(@data) eq 2) {
4580: $title = $data[1];
4581: ($setuname,$setudom) = split(/@/,$data[0]);
4582: } else {
4583: ($setuname,$setudom,$title) = @data;
4584: }
4585: $blocks = { 'com' => 'on' };
4586: }
4587: return ($setuname,$setudom,$title,$blocks);
4588: }
4589:
4590: sub blocking_status {
4591: my ($activity,$uname,$udom,$url) = @_;
4592: my %setters;
4593:
4594: # check for active blocking
4595: my ($startblock,$endblock,$triggerblock) =
4596: &blockcheck(\%setters,$activity,$uname,$udom,$url);
4597: my $blocked = 0;
4598: if ($startblock && $endblock) {
4599: $blocked = 1;
4600: }
4601:
4602: # caller just wants to know whether a block is active
4603: if (!wantarray) { return $blocked; }
4604:
4605: # build a link to a popup window containing the details
4606: my $querystring = "?activity=$activity";
4607: # $uname and $udom decide whose portfolio the user is trying to look at
4608: if ($activity eq 'port') {
4609: $querystring .= "&udom=$udom" if $udom;
4610: $querystring .= "&uname=$uname" if $uname;
4611: } elsif ($activity eq 'docs') {
4612: $querystring .= '&url='.&HTML::Entities::encode($url,'&"');
4613: }
4614:
4615: my $output .= <<'END_MYBLOCK';
4616: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
4617: var options = "width=" + w + ",height=" + h + ",";
4618: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
4619: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
4620: var newWin = window.open(url, wdwName, options);
4621: newWin.focus();
4622: }
4623: END_MYBLOCK
4624:
4625: $output = Apache::lonhtmlcommon::scripttag($output);
4626:
4627: my $popupUrl = "/adm/blockingstatus/$querystring";
4628: my $text = &mt('Communication Blocked');
4629: if ($activity eq 'docs') {
4630: $text = &mt('Content Access Blocked');
4631: } elsif ($activity eq 'printout') {
4632: $text = &mt('Printing Blocked');
4633: }
4634: $output .= <<"END_BLOCK";
4635: <div class='LC_comblock'>
4636: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4637: title='$text'>
4638: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
4639: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4640: title='$text'>$text</a>
4641: </div>
4642:
4643: END_BLOCK
4644:
4645: return ($blocked, $output);
4646: }
4647:
4648: ###############################################
4649:
4650: sub check_ip_acc {
4651: my ($acc)=@_;
4652: &Apache::lonxml::debug("acc is $acc");
4653: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
4654: return 1;
4655: }
4656: my $allowed=0;
4657: my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
4658:
4659: my $name;
4660: foreach my $pattern (split(',',$acc)) {
4661: $pattern =~ s/^\s*//;
4662: $pattern =~ s/\s*$//;
4663: if ($pattern =~ /\*$/) {
4664: #35.8.*
4665: $pattern=~s/\*//;
4666: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4667: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
4668: #35.8.3.[34-56]
4669: my $low=$2;
4670: my $high=$3;
4671: $pattern=$1;
4672: if ($ip =~ /^\Q$pattern\E/) {
4673: my $last=(split(/\./,$ip))[3];
4674: if ($last <=$high && $last >=$low) { $allowed=1; }
4675: }
4676: } elsif ($pattern =~ /^\*/) {
4677: #*.msu.edu
4678: $pattern=~s/\*//;
4679: if (!defined($name)) {
4680: use Socket;
4681: my $netaddr=inet_aton($ip);
4682: ($name)=gethostbyaddr($netaddr,AF_INET);
4683: }
4684: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4685: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
4686: #127.0.0.1
4687: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4688: } else {
4689: #some.name.com
4690: if (!defined($name)) {
4691: use Socket;
4692: my $netaddr=inet_aton($ip);
4693: ($name)=gethostbyaddr($netaddr,AF_INET);
4694: }
4695: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4696: }
4697: if ($allowed) { last; }
4698: }
4699: return $allowed;
4700: }
4701:
4702: ###############################################
4703:
4704: =pod
4705:
4706: =head1 Domain Template Functions
4707:
4708: =over 4
4709:
4710: =item * &determinedomain()
4711:
4712: Inputs: $domain (usually will be undef)
4713:
4714: Returns: Determines which domain should be used for designs
4715:
4716: =cut
4717:
4718: ###############################################
4719: sub determinedomain {
4720: my $domain=shift;
4721: if (! $domain) {
4722: # Determine domain if we have not been given one
4723: $domain = &Apache::lonnet::default_login_domain();
4724: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
4725: if ($env{'request.role.domain'}) {
4726: $domain=$env{'request.role.domain'};
4727: }
4728: }
4729: return $domain;
4730: }
4731: ###############################################
4732:
4733: sub devalidate_domconfig_cache {
4734: my ($udom)=@_;
4735: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
4736: }
4737:
4738: # ---------------------- Get domain configuration for a domain
4739: sub get_domainconf {
4740: my ($udom) = @_;
4741: my $cachetime=1800;
4742: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
4743: if (defined($cached)) { return %{$result}; }
4744:
4745: my %domconfig = &Apache::lonnet::get_dom('configuration',
4746: ['login','rolecolors','autoenroll'],$udom);
4747: my (%designhash,%legacy);
4748: if (keys(%domconfig) > 0) {
4749: if (ref($domconfig{'login'}) eq 'HASH') {
4750: if (keys(%{$domconfig{'login'}})) {
4751: foreach my $key (keys(%{$domconfig{'login'}})) {
4752: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
4753: if ($key eq 'loginvia') {
4754: if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
4755: foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
4756: if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
4757: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
4758: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
4759: $designhash{$udom.'.login.loginvia'} = $server;
4760: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
4761:
4762: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
4763: } else {
4764: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
4765: }
4766: if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
4767: $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
4768: }
4769: }
4770: }
4771: }
4772: }
4773: } else {
4774: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
4775: $designhash{$udom.'.login.'.$key.'_'.$img} =
4776: $domconfig{'login'}{$key}{$img};
4777: }
4778: }
4779: } else {
4780: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
4781: }
4782: }
4783: } else {
4784: $legacy{'login'} = 1;
4785: }
4786: } else {
4787: $legacy{'login'} = 1;
4788: }
4789: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
4790: if (keys(%{$domconfig{'rolecolors'}})) {
4791: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
4792: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
4793: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
4794: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
4795: }
4796: }
4797: }
4798: } else {
4799: $legacy{'rolecolors'} = 1;
4800: }
4801: } else {
4802: $legacy{'rolecolors'} = 1;
4803: }
4804: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
4805: if ($domconfig{'autoenroll'}{'co-owners'}) {
4806: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
4807: }
4808: }
4809: if (keys(%legacy) > 0) {
4810: my %legacyhash = &get_legacy_domconf($udom);
4811: foreach my $item (keys(%legacyhash)) {
4812: if ($item =~ /^\Q$udom\E\.login/) {
4813: if ($legacy{'login'}) {
4814: $designhash{$item} = $legacyhash{$item};
4815: }
4816: } else {
4817: if ($legacy{'rolecolors'}) {
4818: $designhash{$item} = $legacyhash{$item};
4819: }
4820: }
4821: }
4822: }
4823: } else {
4824: %designhash = &get_legacy_domconf($udom);
4825: }
4826: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
4827: $cachetime);
4828: return %designhash;
4829: }
4830:
4831: sub get_legacy_domconf {
4832: my ($udom) = @_;
4833: my %legacyhash;
4834: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
4835: my $designfile = $designdir.'/'.$udom.'.tab';
4836: if (-e $designfile) {
4837: if ( open (my $fh,"<$designfile") ) {
4838: while (my $line = <$fh>) {
4839: next if ($line =~ /^\#/);
4840: chomp($line);
4841: my ($key,$val)=(split(/\=/,$line));
4842: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
4843: }
4844: close($fh);
4845: }
4846: }
4847: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
4848: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
4849: }
4850: return %legacyhash;
4851: }
4852:
4853: =pod
4854:
4855: =item * &domainlogo()
4856:
4857: Inputs: $domain (usually will be undef)
4858:
4859: Returns: A link to a domain logo, if the domain logo exists.
4860: If the domain logo does not exist, a description of the domain.
4861:
4862: =cut
4863:
4864: ###############################################
4865: sub domainlogo {
4866: my $domain = &determinedomain(shift);
4867: my %designhash = &get_domainconf($domain);
4868: # See if there is a logo
4869: if ($designhash{$domain.'.login.domlogo'} ne '') {
4870: my $imgsrc = $designhash{$domain.'.login.domlogo'};
4871: if ($imgsrc =~ m{^/(adm|res)/}) {
4872: if ($imgsrc =~ m{^/res/}) {
4873: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
4874: &Apache::lonnet::repcopy($local_name);
4875: }
4876: $imgsrc = &lonhttpdurl($imgsrc);
4877: }
4878: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
4879: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
4880: return &Apache::lonnet::domain($domain,'description');
4881: } else {
4882: return '';
4883: }
4884: }
4885: ##############################################
4886:
4887: =pod
4888:
4889: =item * &designparm()
4890:
4891: Inputs: $which parameter; $domain (usually will be undef)
4892:
4893: Returns: value of designparamter $which
4894:
4895: =cut
4896:
4897:
4898: ##############################################
4899: sub designparm {
4900: my ($which,$domain)=@_;
4901: if (exists($env{'environment.color.'.$which})) {
4902: return $env{'environment.color.'.$which};
4903: }
4904: $domain=&determinedomain($domain);
4905: my %domdesign;
4906: unless ($domain eq 'public') {
4907: %domdesign = &get_domainconf($domain);
4908: }
4909: my $output;
4910: if ($domdesign{$domain.'.'.$which} ne '') {
4911: $output = $domdesign{$domain.'.'.$which};
4912: } else {
4913: $output = $defaultdesign{$which};
4914: }
4915: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
4916: ($which =~ /login\.(img|logo|domlogo|login)/)) {
4917: if ($output =~ m{^/(adm|res)/}) {
4918: if ($output =~ m{^/res/}) {
4919: my $local_name = &Apache::lonnet::filelocation('',$output);
4920: &Apache::lonnet::repcopy($local_name);
4921: }
4922: $output = &lonhttpdurl($output);
4923: }
4924: }
4925: return $output;
4926: }
4927:
4928: ##############################################
4929: =pod
4930:
4931: =item * &authorspace()
4932:
4933: Inputs: $url (usually will be undef).
4934:
4935: Returns: Path to Construction Space containing the resource or
4936: directory being viewed (or for which action is being taken).
4937: If $url is provided, and begins /priv/<domain>/<uname>
4938: the path will be that portion of the $context argument.
4939: Otherwise the path will be for the author space of the current
4940: user when the current role is author, or for that of the
4941: co-author/assistant co-author space when the current role
4942: is co-author or assistant co-author.
4943:
4944: =cut
4945:
4946: sub authorspace {
4947: my ($url) = @_;
4948: if ($url ne '') {
4949: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
4950: return $1;
4951: }
4952: }
4953: my $caname = '';
4954: my $cadom = '';
4955: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
4956: ($cadom,$caname) =
4957: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
4958: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
4959: $caname = $env{'user.name'};
4960: $cadom = $env{'user.domain'};
4961: }
4962: if (($caname ne '') && ($cadom ne '')) {
4963: return "/priv/$cadom/$caname/";
4964: }
4965: return;
4966: }
4967:
4968: ##############################################
4969: =pod
4970:
4971: =item * &head_subbox()
4972:
4973: Inputs: $content (contains HTML code with page functions, etc.)
4974:
4975: Returns: HTML div with $content
4976: To be included in page header
4977:
4978: =cut
4979:
4980: sub head_subbox {
4981: my ($content)=@_;
4982: my $output =
4983: '<div class="LC_head_subbox">'
4984: .$content
4985: .'</div>'
4986: }
4987:
4988: ##############################################
4989: =pod
4990:
4991: =item * &CSTR_pageheader()
4992:
4993: Input: (optional) filename from which breadcrumb trail is built.
4994: In most cases no input as needed, as $env{'request.filename'}
4995: is appropriate for use in building the breadcrumb trail.
4996:
4997: Returns: HTML div with CSTR path and recent box
4998: To be included on Construction Space pages
4999:
5000: =cut
5001:
5002: sub CSTR_pageheader {
5003: my ($trailfile) = @_;
5004: if ($trailfile eq '') {
5005: $trailfile = $env{'request.filename'};
5006: }
5007:
5008: # this is for resources; directories have customtitle, and crumbs
5009: # and select recent are created in lonpubdir.pm
5010:
5011: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
5012: my ($udom,$uname,$thisdisfn)=
5013: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
5014: my $formaction = "/priv/$udom/$uname/$thisdisfn";
5015: $formaction =~ s{/+}{/}g;
5016:
5017: my $parentpath = '';
5018: my $lastitem = '';
5019: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
5020: $parentpath = $1;
5021: $lastitem = $2;
5022: } else {
5023: $lastitem = $thisdisfn;
5024: }
5025:
5026: my $output =
5027: '<div>'
5028: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
5029: .'<b>'.&mt('Construction Space:').'</b> '
5030: .'<form name="dirs" method="post" action="'.$formaction
5031: .'" target="_top">' #FIXME lonpubdir: target="_parent"
5032: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
5033:
5034: if ($lastitem) {
5035: $output .=
5036: '<span class="LC_filename">'
5037: .$lastitem
5038: .'</span>';
5039: }
5040: $output .=
5041: '<br />'
5042: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
5043: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
5044: .'</form>'
5045: .&Apache::lonmenu::constspaceform()
5046: .'</div>';
5047:
5048: return $output;
5049: }
5050:
5051: ###############################################
5052: ###############################################
5053:
5054: =pod
5055:
5056: =back
5057:
5058: =head1 HTML Helpers
5059:
5060: =over 4
5061:
5062: =item * &bodytag()
5063:
5064: Returns a uniform header for LON-CAPA web pages.
5065:
5066: Inputs:
5067:
5068: =over 4
5069:
5070: =item * $title, A title to be displayed on the page.
5071:
5072: =item * $function, the current role (can be undef).
5073:
5074: =item * $addentries, extra parameters for the <body> tag.
5075:
5076: =item * $bodyonly, if defined, only return the <body> tag.
5077:
5078: =item * $domain, if defined, force a given domain.
5079:
5080: =item * $forcereg, if page should register as content page (relevant for
5081: text interface only)
5082:
5083: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
5084: navigational links
5085:
5086: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
5087:
5088: =item * $args, optional argument valid values are
5089: no_auto_mt_title -> prevents &mt()ing the title arg
5090: inherit_jsmath -> when creating popup window in a page,
5091: should it have jsmath forced on by the
5092: current page
5093:
5094: =item * $advtoolsref, optional argument, ref to an array containing
5095: inlineremote items to be added in "Functions" menu below
5096: breadcrumbs.
5097:
5098: =back
5099:
5100: Returns: A uniform header for LON-CAPA web pages.
5101: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
5102: If $bodyonly is undef or zero, an html string containing a <body> tag and
5103: other decorations will be returned.
5104:
5105: =cut
5106:
5107: sub bodytag {
5108: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
5109: $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
5110:
5111: my $public;
5112: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
5113: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
5114: $public = 1;
5115: }
5116: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
5117:
5118: $function = &get_users_function() if (!$function);
5119: my $img = &designparm($function.'.img',$domain);
5120: my $font = &designparm($function.'.font',$domain);
5121: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
5122:
5123: my %design = ( 'style' => 'margin-top: 0',
5124: 'bgcolor' => $pgbg,
5125: 'text' => $font,
5126: 'alink' => &designparm($function.'.alink',$domain),
5127: 'vlink' => &designparm($function.'.vlink',$domain),
5128: 'link' => &designparm($function.'.link',$domain),);
5129: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
5130:
5131: # role and realm
5132: my ($role,$realm) = split(/\./,$env{'request.role'},2);
5133: if ($role eq 'ca') {
5134: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
5135: $realm = &plainname($rname,$rdom);
5136: }
5137: # realm
5138: if ($env{'request.course.id'}) {
5139: if ($env{'request.role'} !~ /^cr/) {
5140: $role = &Apache::lonnet::plaintext($role,&course_type());
5141: }
5142: if ($env{'request.course.sec'}) {
5143: $role .= (' 'x2).'- '.&mt('section:').' '.$env{'request.course.sec'};
5144: }
5145: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
5146: } else {
5147: $role = &Apache::lonnet::plaintext($role);
5148: }
5149:
5150: if (!$realm) { $realm=' '; }
5151:
5152: my $extra_body_attr = &make_attr_string($forcereg,\%design);
5153:
5154: # construct main body tag
5155: my $bodytag = "<body $extra_body_attr>".
5156: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
5157:
5158: if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
5159: return $bodytag;
5160: }
5161:
5162: if ($public) {
5163: undef($role);
5164: }
5165:
5166: my $titleinfo = '<h1>'.$title.'</h1>';
5167: #
5168: # Extra info if you are the DC
5169: my $dc_info = '';
5170: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
5171: $env{'course.'.$env{'request.course.id'}.
5172: '.domain'}.'/'})) {
5173: my $cid = $env{'request.course.id'};
5174: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
5175: $dc_info =~ s/\s+$//;
5176: }
5177:
5178: $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
5179: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
5180:
5181: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
5182:
5183: # if ($env{'request.state'} eq 'construct') {
5184: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
5185: # }
5186:
5187: $bodytag .= Apache::lonhtmlcommon::scripttag(
5188: Apache::lonmenu::utilityfunctions(), 'start');
5189:
5190: my ($left,$right) = Apache::lonmenu::primary_menu();
5191:
5192: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
5193: if ($dc_info) {
5194: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
5195: }
5196: $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
5197: <em>$realm</em> $dc_info</div>|;
5198: return $bodytag;
5199: }
5200:
5201: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
5202: $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
5203: }
5204:
5205: $bodytag .= $right;
5206:
5207: if ($dc_info) {
5208: $dc_info = &dc_courseid_toggle($dc_info);
5209: }
5210: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
5211:
5212: #don't show menus for public users
5213: if (!$public){
5214: $bodytag .= Apache::lonmenu::secondary_menu();
5215: $bodytag .= Apache::lonmenu::serverform();
5216: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5217: if ($env{'request.state'} eq 'construct') {
5218: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
5219: $args->{'bread_crumbs'});
5220: } elsif ($forcereg) {
5221: $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
5222: $args->{'group'});
5223: } else {
5224: $bodytag .=
5225: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
5226: $forcereg,$args->{'group'},
5227: $args->{'bread_crumbs'},
5228: $advtoolsref);
5229: }
5230: }else{
5231: # this is to seperate menu from content when there's no secondary
5232: # menu. Especially needed for public accessible ressources.
5233: $bodytag .= '<hr style="clear:both" />';
5234: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5235: }
5236:
5237: return $bodytag;
5238: }
5239:
5240: sub dc_courseid_toggle {
5241: my ($dc_info) = @_;
5242: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
5243: '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
5244: &mt('(More ...)').'</a></span>'.
5245: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
5246: }
5247:
5248: sub make_attr_string {
5249: my ($register,$attr_ref) = @_;
5250:
5251: if ($attr_ref && !ref($attr_ref)) {
5252: die("addentries Must be a hash ref ".
5253: join(':',caller(1))." ".
5254: join(':',caller(0))." ");
5255: }
5256:
5257: if ($register) {
5258: my ($on_load,$on_unload);
5259: foreach my $key (keys(%{$attr_ref})) {
5260: if (lc($key) eq 'onload') {
5261: $on_load.=$attr_ref->{$key}.';';
5262: delete($attr_ref->{$key});
5263:
5264: } elsif (lc($key) eq 'onunload') {
5265: $on_unload.=$attr_ref->{$key}.';';
5266: delete($attr_ref->{$key});
5267: }
5268: }
5269: $attr_ref->{'onload'} = $on_load;
5270: $attr_ref->{'onunload'}= $on_unload;
5271: }
5272:
5273: my $attr_string;
5274: foreach my $attr (keys(%$attr_ref)) {
5275: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
5276: }
5277: return $attr_string;
5278: }
5279:
5280:
5281: ###############################################
5282: ###############################################
5283:
5284: =pod
5285:
5286: =item * &endbodytag()
5287:
5288: Returns a uniform footer for LON-CAPA web pages.
5289:
5290: Inputs: 1 - optional reference to an args hash
5291: If in the hash, key for noredirectlink has a value which evaluates to true,
5292: a 'Continue' link is not displayed if the page contains an
5293: internal redirect in the <head></head> section,
5294: i.e., $env{'internal.head.redirect'} exists
5295:
5296: =cut
5297:
5298: sub endbodytag {
5299: my ($args) = @_;
5300: my $endbodytag;
5301: unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
5302: $endbodytag='</body>';
5303: }
5304: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
5305: if ( exists( $env{'internal.head.redirect'} ) ) {
5306: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
5307: $endbodytag=
5308: "<br /><a href=\"$env{'internal.head.redirect'}\">".
5309: &mt('Continue').'</a>'.
5310: $endbodytag;
5311: }
5312: }
5313: return $endbodytag;
5314: }
5315:
5316: =pod
5317:
5318: =item * &standard_css()
5319:
5320: Returns a style sheet
5321:
5322: Inputs: (all optional)
5323: domain -> force to color decorate a page for a specific
5324: domain
5325: function -> force usage of a specific rolish color scheme
5326: bgcolor -> override the default page bgcolor
5327:
5328: =cut
5329:
5330: sub standard_css {
5331: my ($function,$domain,$bgcolor) = @_;
5332: $function = &get_users_function() if (!$function);
5333: my $img = &designparm($function.'.img', $domain);
5334: my $tabbg = &designparm($function.'.tabbg', $domain);
5335: my $font = &designparm($function.'.font', $domain);
5336: my $fontmenu = &designparm($function.'.fontmenu', $domain);
5337: #second colour for later usage
5338: my $sidebg = &designparm($function.'.sidebg',$domain);
5339: my $pgbg_or_bgcolor =
5340: $bgcolor ||
5341: &designparm($function.'.pgbg', $domain);
5342: my $pgbg = &designparm($function.'.pgbg', $domain);
5343: my $alink = &designparm($function.'.alink', $domain);
5344: my $vlink = &designparm($function.'.vlink', $domain);
5345: my $link = &designparm($function.'.link', $domain);
5346:
5347: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
5348: my $mono = 'monospace';
5349: my $data_table_head = $sidebg;
5350: my $data_table_light = '#FAFAFA';
5351: my $data_table_dark = '#E0E0E0';
5352: my $data_table_darker = '#CCCCCC';
5353: my $data_table_highlight = '#FFFF00';
5354: my $mail_new = '#FFBB77';
5355: my $mail_new_hover = '#DD9955';
5356: my $mail_read = '#BBBB77';
5357: my $mail_read_hover = '#999944';
5358: my $mail_replied = '#AAAA88';
5359: my $mail_replied_hover = '#888855';
5360: my $mail_other = '#99BBBB';
5361: my $mail_other_hover = '#669999';
5362: my $table_header = '#DDDDDD';
5363: my $feedback_link_bg = '#BBBBBB';
5364: my $lg_border_color = '#C8C8C8';
5365: my $button_hover = '#BF2317';
5366:
5367: my $border = ($env{'browser.type'} eq 'explorer' ||
5368: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
5369: : '0 3px 0 4px';
5370:
5371:
5372: return <<END;
5373:
5374: /* needed for iframe to allow 100% height in FF */
5375: body, html {
5376: margin: 0;
5377: padding: 0 0.5%;
5378: height: 99%; /* to avoid scrollbars */
5379: }
5380:
5381: body {
5382: font-family: $sans;
5383: line-height:130%;
5384: font-size:0.83em;
5385: color:$font;
5386: }
5387:
5388: a:focus,
5389: a:focus img {
5390: color: red;
5391: }
5392:
5393: form, .inline {
5394: display: inline;
5395: }
5396:
5397: .LC_right {
5398: text-align:right;
5399: }
5400:
5401: .LC_middle {
5402: vertical-align:middle;
5403: }
5404:
5405: .LC_floatleft {
5406: float: left;
5407: }
5408:
5409: .LC_floatright {
5410: float: right;
5411: }
5412:
5413: .LC_400Box {
5414: width:400px;
5415: }
5416:
5417: .LC_iframecontainer {
5418: width: 98%;
5419: margin: 0;
5420: position: fixed;
5421: top: 8.5em;
5422: bottom: 0;
5423: }
5424:
5425: .LC_iframecontainer iframe{
5426: border: none;
5427: width: 100%;
5428: height: 100%;
5429: }
5430:
5431: .LC_filename {
5432: font-family: $mono;
5433: white-space:pre;
5434: font-size: 120%;
5435: }
5436:
5437: .LC_fileicon {
5438: border: none;
5439: height: 1.3em;
5440: vertical-align: text-bottom;
5441: margin-right: 0.3em;
5442: text-decoration:none;
5443: }
5444:
5445: .LC_setting {
5446: text-decoration:underline;
5447: }
5448:
5449: .LC_error {
5450: color: red;
5451: }
5452:
5453: .LC_warning {
5454: color: darkorange;
5455: }
5456:
5457: .LC_diff_removed {
5458: color: red;
5459: }
5460:
5461: .LC_info,
5462: .LC_success,
5463: .LC_diff_added {
5464: color: green;
5465: }
5466:
5467: div.LC_confirm_box {
5468: background-color: #FAFAFA;
5469: border: 1px solid $lg_border_color;
5470: margin-right: 0;
5471: padding: 5px;
5472: }
5473:
5474: div.LC_confirm_box .LC_error img,
5475: div.LC_confirm_box .LC_success img {
5476: vertical-align: middle;
5477: }
5478:
5479: .LC_icon {
5480: border: none;
5481: vertical-align: middle;
5482: }
5483:
5484: .LC_docs_spacer {
5485: width: 25px;
5486: height: 1px;
5487: border: none;
5488: }
5489:
5490: .LC_internal_info {
5491: color: #999999;
5492: }
5493:
5494: .LC_discussion {
5495: background: $data_table_dark;
5496: border: 1px solid black;
5497: margin: 2px;
5498: }
5499:
5500: .LC_disc_action_left {
5501: background: $sidebg;
5502: text-align: left;
5503: padding: 4px;
5504: margin: 2px;
5505: }
5506:
5507: .LC_disc_action_right {
5508: background: $sidebg;
5509: text-align: right;
5510: padding: 4px;
5511: margin: 2px;
5512: }
5513:
5514: .LC_disc_new_item {
5515: background: white;
5516: border: 2px solid red;
5517: margin: 4px;
5518: padding: 4px;
5519: }
5520:
5521: .LC_disc_old_item {
5522: background: white;
5523: margin: 4px;
5524: padding: 4px;
5525: }
5526:
5527: table.LC_pastsubmission {
5528: border: 1px solid black;
5529: margin: 2px;
5530: }
5531:
5532: table#LC_menubuttons {
5533: width: 100%;
5534: background: $pgbg;
5535: border: 2px;
5536: border-collapse: separate;
5537: padding: 0;
5538: }
5539:
5540: table#LC_title_bar a {
5541: color: $fontmenu;
5542: }
5543:
5544: table#LC_title_bar {
5545: clear: both;
5546: display: none;
5547: }
5548:
5549: table#LC_title_bar,
5550: table.LC_breadcrumbs, /* obsolete? */
5551: table#LC_title_bar.LC_with_remote {
5552: width: 100%;
5553: border-color: $pgbg;
5554: border-style: solid;
5555: border-width: $border;
5556: background: $pgbg;
5557: color: $fontmenu;
5558: border-collapse: collapse;
5559: padding: 0;
5560: margin: 0;
5561: }
5562:
5563: ul.LC_breadcrumb_tools_outerlist {
5564: margin: 0;
5565: padding: 0;
5566: position: relative;
5567: list-style: none;
5568: }
5569: ul.LC_breadcrumb_tools_outerlist li {
5570: display: inline;
5571: }
5572:
5573: .LC_breadcrumb_tools_navigation {
5574: padding: 0;
5575: margin: 0;
5576: float: left;
5577: }
5578: .LC_breadcrumb_tools_tools {
5579: padding: 0;
5580: margin: 0;
5581: float: right;
5582: }
5583:
5584: table#LC_title_bar td {
5585: background: $tabbg;
5586: }
5587:
5588: table#LC_menubuttons img {
5589: border: none;
5590: }
5591:
5592: .LC_breadcrumbs_component {
5593: float: right;
5594: margin: 0 1em;
5595: }
5596: .LC_breadcrumbs_component img {
5597: vertical-align: middle;
5598: }
5599:
5600: td.LC_table_cell_checkbox {
5601: text-align: center;
5602: }
5603:
5604: .LC_fontsize_small {
5605: font-size: 70%;
5606: }
5607:
5608: #LC_breadcrumbs {
5609: clear:both;
5610: background: $sidebg;
5611: border-bottom: 1px solid $lg_border_color;
5612: line-height: 2.5em;
5613: overflow: hidden;
5614: margin: 0;
5615: padding: 0;
5616: text-align: left;
5617: }
5618:
5619: .LC_head_subbox, .LC_actionbox {
5620: clear:both;
5621: background: #F8F8F8; /* $sidebg; */
5622: border: 1px solid $sidebg;
5623: margin: 0 0 10px 0;
5624: padding: 3px;
5625: text-align: left;
5626: }
5627:
5628: .LC_fontsize_medium {
5629: font-size: 85%;
5630: }
5631:
5632: .LC_fontsize_large {
5633: font-size: 120%;
5634: }
5635:
5636: .LC_menubuttons_inline_text {
5637: color: $font;
5638: font-size: 90%;
5639: padding-left:3px;
5640: }
5641:
5642: .LC_menubuttons_inline_text img{
5643: vertical-align: middle;
5644: }
5645:
5646: li.LC_menubuttons_inline_text img {
5647: cursor:pointer;
5648: text-decoration: none;
5649: }
5650:
5651: .LC_menubuttons_link {
5652: text-decoration: none;
5653: }
5654:
5655: .LC_menubuttons_category {
5656: color: $font;
5657: background: $pgbg;
5658: font-size: larger;
5659: font-weight: bold;
5660: }
5661:
5662: td.LC_menubuttons_text {
5663: color: $font;
5664: }
5665:
5666: .LC_current_location {
5667: background: $tabbg;
5668: }
5669:
5670: table.LC_data_table {
5671: border: 1px solid #000000;
5672: border-collapse: separate;
5673: border-spacing: 1px;
5674: background: $pgbg;
5675: }
5676:
5677: .LC_data_table_dense {
5678: font-size: small;
5679: }
5680:
5681: table.LC_nested_outer {
5682: border: 1px solid #000000;
5683: border-collapse: collapse;
5684: border-spacing: 0;
5685: width: 100%;
5686: }
5687:
5688: table.LC_innerpickbox,
5689: table.LC_nested {
5690: border: none;
5691: border-collapse: collapse;
5692: border-spacing: 0;
5693: width: 100%;
5694: }
5695:
5696: table.LC_data_table tr th,
5697: table.LC_calendar tr th,
5698: table.LC_prior_tries tr th,
5699: table.LC_innerpickbox tr th {
5700: font-weight: bold;
5701: background-color: $data_table_head;
5702: color:$fontmenu;
5703: font-size:90%;
5704: }
5705:
5706: table.LC_innerpickbox tr th,
5707: table.LC_innerpickbox tr td {
5708: vertical-align: top;
5709: }
5710:
5711: table.LC_data_table tr.LC_info_row > td {
5712: background-color: #CCCCCC;
5713: font-weight: bold;
5714: text-align: left;
5715: }
5716:
5717: table.LC_data_table tr.LC_odd_row > td {
5718: background-color: $data_table_light;
5719: padding: 2px;
5720: vertical-align: top;
5721: }
5722:
5723: table.LC_pick_box tr > td.LC_odd_row {
5724: background-color: $data_table_light;
5725: vertical-align: top;
5726: }
5727:
5728: table.LC_data_table tr.LC_even_row > td {
5729: background-color: $data_table_dark;
5730: padding: 2px;
5731: vertical-align: top;
5732: }
5733:
5734: table.LC_pick_box tr > td.LC_even_row {
5735: background-color: $data_table_dark;
5736: vertical-align: top;
5737: }
5738:
5739: table.LC_data_table tr.LC_data_table_highlight td {
5740: background-color: $data_table_darker;
5741: }
5742:
5743: table.LC_data_table tr td.LC_leftcol_header {
5744: background-color: $data_table_head;
5745: font-weight: bold;
5746: }
5747:
5748: table.LC_data_table tr.LC_empty_row td,
5749: table.LC_nested tr.LC_empty_row td {
5750: font-weight: bold;
5751: font-style: italic;
5752: text-align: center;
5753: padding: 8px;
5754: }
5755:
5756: table.LC_data_table tr.LC_empty_row td,
5757: table.LC_data_table tr.LC_footer_row td {
5758: background-color: $sidebg;
5759: }
5760:
5761: table.LC_nested tr.LC_empty_row td {
5762: background-color: #FFFFFF;
5763: }
5764:
5765: table.LC_caption {
5766: }
5767:
5768: table.LC_nested tr.LC_empty_row td {
5769: padding: 4ex
5770: }
5771:
5772: table.LC_nested_outer tr th {
5773: font-weight: bold;
5774: color:$fontmenu;
5775: background-color: $data_table_head;
5776: font-size: small;
5777: border-bottom: 1px solid #000000;
5778: }
5779:
5780: table.LC_nested_outer tr td.LC_subheader {
5781: background-color: $data_table_head;
5782: font-weight: bold;
5783: font-size: small;
5784: border-bottom: 1px solid #000000;
5785: text-align: right;
5786: }
5787:
5788: table.LC_nested tr.LC_info_row td {
5789: background-color: #CCCCCC;
5790: font-weight: bold;
5791: font-size: small;
5792: text-align: center;
5793: }
5794:
5795: table.LC_nested tr.LC_info_row td.LC_left_item,
5796: table.LC_nested_outer tr th.LC_left_item {
5797: text-align: left;
5798: }
5799:
5800: table.LC_nested td {
5801: background-color: #FFFFFF;
5802: font-size: small;
5803: }
5804:
5805: table.LC_nested_outer tr th.LC_right_item,
5806: table.LC_nested tr.LC_info_row td.LC_right_item,
5807: table.LC_nested tr.LC_odd_row td.LC_right_item,
5808: table.LC_nested tr td.LC_right_item {
5809: text-align: right;
5810: }
5811:
5812: table.LC_nested tr.LC_odd_row td {
5813: background-color: #EEEEEE;
5814: }
5815:
5816: table.LC_createuser {
5817: }
5818:
5819: table.LC_createuser tr.LC_section_row td {
5820: font-size: small;
5821: }
5822:
5823: table.LC_createuser tr.LC_info_row td {
5824: background-color: #CCCCCC;
5825: font-weight: bold;
5826: text-align: center;
5827: }
5828:
5829: table.LC_calendar {
5830: border: 1px solid #000000;
5831: border-collapse: collapse;
5832: width: 98%;
5833: }
5834:
5835: table.LC_calendar_pickdate {
5836: font-size: xx-small;
5837: }
5838:
5839: table.LC_calendar tr td {
5840: border: 1px solid #000000;
5841: vertical-align: top;
5842: width: 14%;
5843: }
5844:
5845: table.LC_calendar tr td.LC_calendar_day_empty {
5846: background-color: $data_table_dark;
5847: }
5848:
5849: table.LC_calendar tr td.LC_calendar_day_current {
5850: background-color: $data_table_highlight;
5851: }
5852:
5853: table.LC_data_table tr td.LC_mail_new {
5854: background-color: $mail_new;
5855: }
5856:
5857: table.LC_data_table tr.LC_mail_new:hover {
5858: background-color: $mail_new_hover;
5859: }
5860:
5861: table.LC_data_table tr td.LC_mail_read {
5862: background-color: $mail_read;
5863: }
5864:
5865: /*
5866: table.LC_data_table tr.LC_mail_read:hover {
5867: background-color: $mail_read_hover;
5868: }
5869: */
5870:
5871: table.LC_data_table tr td.LC_mail_replied {
5872: background-color: $mail_replied;
5873: }
5874:
5875: /*
5876: table.LC_data_table tr.LC_mail_replied:hover {
5877: background-color: $mail_replied_hover;
5878: }
5879: */
5880:
5881: table.LC_data_table tr td.LC_mail_other {
5882: background-color: $mail_other;
5883: }
5884:
5885: /*
5886: table.LC_data_table tr.LC_mail_other:hover {
5887: background-color: $mail_other_hover;
5888: }
5889: */
5890:
5891: table.LC_data_table tr > td.LC_browser_file,
5892: table.LC_data_table tr > td.LC_browser_file_published {
5893: background: #AAEE77;
5894: }
5895:
5896: table.LC_data_table tr > td.LC_browser_file_locked,
5897: table.LC_data_table tr > td.LC_browser_file_unpublished {
5898: background: #FFAA99;
5899: }
5900:
5901: table.LC_data_table tr > td.LC_browser_file_obsolete {
5902: background: #888888;
5903: }
5904:
5905: table.LC_data_table tr > td.LC_browser_file_modified,
5906: table.LC_data_table tr > td.LC_browser_file_metamodified {
5907: background: #F8F866;
5908: }
5909:
5910: table.LC_data_table tr.LC_browser_folder > td {
5911: background: #E0E8FF;
5912: }
5913:
5914: table.LC_data_table tr > td.LC_roles_is {
5915: /* background: #77FF77; */
5916: }
5917:
5918: table.LC_data_table tr > td.LC_roles_future {
5919: border-right: 8px solid #FFFF77;
5920: }
5921:
5922: table.LC_data_table tr > td.LC_roles_will {
5923: border-right: 8px solid #FFAA77;
5924: }
5925:
5926: table.LC_data_table tr > td.LC_roles_expired {
5927: border-right: 8px solid #FF7777;
5928: }
5929:
5930: table.LC_data_table tr > td.LC_roles_will_not {
5931: border-right: 8px solid #AAFF77;
5932: }
5933:
5934: table.LC_data_table tr > td.LC_roles_selected {
5935: border-right: 8px solid #11CC55;
5936: }
5937:
5938: span.LC_current_location {
5939: font-size:larger;
5940: background: $pgbg;
5941: }
5942:
5943: span.LC_current_nav_location {
5944: font-weight:bold;
5945: background: $sidebg;
5946: }
5947:
5948: span.LC_parm_menu_item {
5949: font-size: larger;
5950: }
5951:
5952: span.LC_parm_scope_all {
5953: color: red;
5954: }
5955:
5956: span.LC_parm_scope_folder {
5957: color: green;
5958: }
5959:
5960: span.LC_parm_scope_resource {
5961: color: orange;
5962: }
5963:
5964: span.LC_parm_part {
5965: color: blue;
5966: }
5967:
5968: span.LC_parm_folder,
5969: span.LC_parm_symb {
5970: font-size: x-small;
5971: font-family: $mono;
5972: color: #AAAAAA;
5973: }
5974:
5975: ul.LC_parm_parmlist li {
5976: display: inline-block;
5977: padding: 0.3em 0.8em;
5978: vertical-align: top;
5979: width: 150px;
5980: border-top:1px solid $lg_border_color;
5981: }
5982:
5983: td.LC_parm_overview_level_menu,
5984: td.LC_parm_overview_map_menu,
5985: td.LC_parm_overview_parm_selectors,
5986: td.LC_parm_overview_restrictions {
5987: border: 1px solid black;
5988: border-collapse: collapse;
5989: }
5990:
5991: table.LC_parm_overview_restrictions td {
5992: border-width: 1px 4px 1px 4px;
5993: border-style: solid;
5994: border-color: $pgbg;
5995: text-align: center;
5996: }
5997:
5998: table.LC_parm_overview_restrictions th {
5999: background: $tabbg;
6000: border-width: 1px 4px 1px 4px;
6001: border-style: solid;
6002: border-color: $pgbg;
6003: }
6004:
6005: table#LC_helpmenu {
6006: border: none;
6007: height: 55px;
6008: border-spacing: 0;
6009: }
6010:
6011: table#LC_helpmenu fieldset legend {
6012: font-size: larger;
6013: }
6014:
6015: table#LC_helpmenu_links {
6016: width: 100%;
6017: border: 1px solid black;
6018: background: $pgbg;
6019: padding: 0;
6020: border-spacing: 1px;
6021: }
6022:
6023: table#LC_helpmenu_links tr td {
6024: padding: 1px;
6025: background: $tabbg;
6026: text-align: center;
6027: font-weight: bold;
6028: }
6029:
6030: table#LC_helpmenu_links a:link,
6031: table#LC_helpmenu_links a:visited,
6032: table#LC_helpmenu_links a:active {
6033: text-decoration: none;
6034: color: $font;
6035: }
6036:
6037: table#LC_helpmenu_links a:hover {
6038: text-decoration: underline;
6039: color: $vlink;
6040: }
6041:
6042: .LC_chrt_popup_exists {
6043: border: 1px solid #339933;
6044: margin: -1px;
6045: }
6046:
6047: .LC_chrt_popup_up {
6048: border: 1px solid yellow;
6049: margin: -1px;
6050: }
6051:
6052: .LC_chrt_popup {
6053: border: 1px solid #8888FF;
6054: background: #CCCCFF;
6055: }
6056:
6057: table.LC_pick_box {
6058: border-collapse: separate;
6059: background: white;
6060: border: 1px solid black;
6061: border-spacing: 1px;
6062: }
6063:
6064: table.LC_pick_box td.LC_pick_box_title {
6065: background: $sidebg;
6066: font-weight: bold;
6067: text-align: left;
6068: vertical-align: top;
6069: width: 184px;
6070: padding: 8px;
6071: }
6072:
6073: table.LC_pick_box td.LC_pick_box_value {
6074: text-align: left;
6075: padding: 8px;
6076: }
6077:
6078: table.LC_pick_box td.LC_pick_box_select {
6079: text-align: left;
6080: padding: 8px;
6081: }
6082:
6083: table.LC_pick_box td.LC_pick_box_separator {
6084: padding: 0;
6085: height: 1px;
6086: background: black;
6087: }
6088:
6089: table.LC_pick_box td.LC_pick_box_submit {
6090: text-align: right;
6091: }
6092:
6093: table.LC_pick_box td.LC_evenrow_value {
6094: text-align: left;
6095: padding: 8px;
6096: background-color: $data_table_light;
6097: }
6098:
6099: table.LC_pick_box td.LC_oddrow_value {
6100: text-align: left;
6101: padding: 8px;
6102: background-color: $data_table_light;
6103: }
6104:
6105: span.LC_helpform_receipt_cat {
6106: font-weight: bold;
6107: }
6108:
6109: table.LC_group_priv_box {
6110: background: white;
6111: border: 1px solid black;
6112: border-spacing: 1px;
6113: }
6114:
6115: table.LC_group_priv_box td.LC_pick_box_title {
6116: background: $tabbg;
6117: font-weight: bold;
6118: text-align: right;
6119: width: 184px;
6120: }
6121:
6122: table.LC_group_priv_box td.LC_groups_fixed {
6123: background: $data_table_light;
6124: text-align: center;
6125: }
6126:
6127: table.LC_group_priv_box td.LC_groups_optional {
6128: background: $data_table_dark;
6129: text-align: center;
6130: }
6131:
6132: table.LC_group_priv_box td.LC_groups_functionality {
6133: background: $data_table_darker;
6134: text-align: center;
6135: font-weight: bold;
6136: }
6137:
6138: table.LC_group_priv td {
6139: text-align: left;
6140: padding: 0;
6141: }
6142:
6143: .LC_navbuttons {
6144: margin: 2ex 0ex 2ex 0ex;
6145: }
6146:
6147: .LC_topic_bar {
6148: font-weight: bold;
6149: background: $tabbg;
6150: margin: 1em 0em 1em 2em;
6151: padding: 3px;
6152: font-size: 1.2em;
6153: }
6154:
6155: .LC_topic_bar span {
6156: left: 0.5em;
6157: position: absolute;
6158: vertical-align: middle;
6159: font-size: 1.2em;
6160: }
6161:
6162: table.LC_course_group_status {
6163: margin: 20px;
6164: }
6165:
6166: table.LC_status_selector td {
6167: vertical-align: top;
6168: text-align: center;
6169: padding: 4px;
6170: }
6171:
6172: div.LC_feedback_link {
6173: clear: both;
6174: background: $sidebg;
6175: width: 100%;
6176: padding-bottom: 10px;
6177: border: 1px $tabbg solid;
6178: height: 22px;
6179: line-height: 22px;
6180: padding-top: 5px;
6181: }
6182:
6183: div.LC_feedback_link img {
6184: height: 22px;
6185: vertical-align:middle;
6186: }
6187:
6188: div.LC_feedback_link a {
6189: text-decoration: none;
6190: }
6191:
6192: div.LC_comblock {
6193: display:inline;
6194: color:$font;
6195: font-size:90%;
6196: }
6197:
6198: div.LC_feedback_link div.LC_comblock {
6199: padding-left:5px;
6200: }
6201:
6202: div.LC_feedback_link div.LC_comblock a {
6203: color:$font;
6204: }
6205:
6206: span.LC_feedback_link {
6207: /* background: $feedback_link_bg; */
6208: font-size: larger;
6209: }
6210:
6211: span.LC_message_link {
6212: /* background: $feedback_link_bg; */
6213: font-size: larger;
6214: position: absolute;
6215: right: 1em;
6216: }
6217:
6218: table.LC_prior_tries {
6219: border: 1px solid #000000;
6220: border-collapse: separate;
6221: border-spacing: 1px;
6222: }
6223:
6224: table.LC_prior_tries td {
6225: padding: 2px;
6226: }
6227:
6228: .LC_answer_correct {
6229: background: lightgreen;
6230: color: darkgreen;
6231: padding: 6px;
6232: }
6233:
6234: .LC_answer_charged_try {
6235: background: #FFAAAA;
6236: color: darkred;
6237: padding: 6px;
6238: }
6239:
6240: .LC_answer_not_charged_try,
6241: .LC_answer_no_grade,
6242: .LC_answer_late {
6243: background: lightyellow;
6244: color: black;
6245: padding: 6px;
6246: }
6247:
6248: .LC_answer_previous {
6249: background: lightblue;
6250: color: darkblue;
6251: padding: 6px;
6252: }
6253:
6254: .LC_answer_no_message {
6255: background: #FFFFFF;
6256: color: black;
6257: padding: 6px;
6258: }
6259:
6260: .LC_answer_unknown {
6261: background: orange;
6262: color: black;
6263: padding: 6px;
6264: }
6265:
6266: span.LC_prior_numerical,
6267: span.LC_prior_string,
6268: span.LC_prior_custom,
6269: span.LC_prior_reaction,
6270: span.LC_prior_math {
6271: font-family: $mono;
6272: white-space: pre;
6273: }
6274:
6275: span.LC_prior_string {
6276: font-family: $mono;
6277: white-space: pre;
6278: }
6279:
6280: table.LC_prior_option {
6281: width: 100%;
6282: border-collapse: collapse;
6283: }
6284:
6285: table.LC_prior_rank,
6286: table.LC_prior_match {
6287: border-collapse: collapse;
6288: }
6289:
6290: table.LC_prior_option tr td,
6291: table.LC_prior_rank tr td,
6292: table.LC_prior_match tr td {
6293: border: 1px solid #000000;
6294: }
6295:
6296: .LC_nobreak {
6297: white-space: nowrap;
6298: }
6299:
6300: span.LC_cusr_emph {
6301: font-style: italic;
6302: }
6303:
6304: span.LC_cusr_subheading {
6305: font-weight: normal;
6306: font-size: 85%;
6307: }
6308:
6309: div.LC_docs_entry_move {
6310: border: 1px solid #BBBBBB;
6311: background: #DDDDDD;
6312: width: 22px;
6313: padding: 1px;
6314: margin: 0;
6315: }
6316:
6317: table.LC_data_table tr > td.LC_docs_entry_commands,
6318: table.LC_data_table tr > td.LC_docs_entry_parameter {
6319: font-size: x-small;
6320: }
6321:
6322: .LC_docs_entry_parameter {
6323: white-space: nowrap;
6324: }
6325:
6326: .LC_docs_copy {
6327: color: #000099;
6328: }
6329:
6330: .LC_docs_cut {
6331: color: #550044;
6332: }
6333:
6334: .LC_docs_rename {
6335: color: #009900;
6336: }
6337:
6338: .LC_docs_remove {
6339: color: #990000;
6340: }
6341:
6342: .LC_docs_reinit_warn,
6343: .LC_docs_ext_edit {
6344: font-size: x-small;
6345: }
6346:
6347: table.LC_docs_adddocs td,
6348: table.LC_docs_adddocs th {
6349: border: 1px solid #BBBBBB;
6350: padding: 4px;
6351: background: #DDDDDD;
6352: }
6353:
6354: table.LC_sty_begin {
6355: background: #BBFFBB;
6356: }
6357:
6358: table.LC_sty_end {
6359: background: #FFBBBB;
6360: }
6361:
6362: table.LC_double_column {
6363: border-width: 0;
6364: border-collapse: collapse;
6365: width: 100%;
6366: padding: 2px;
6367: }
6368:
6369: table.LC_double_column tr td.LC_left_col {
6370: top: 2px;
6371: left: 2px;
6372: width: 47%;
6373: vertical-align: top;
6374: }
6375:
6376: table.LC_double_column tr td.LC_right_col {
6377: top: 2px;
6378: right: 2px;
6379: width: 47%;
6380: vertical-align: top;
6381: }
6382:
6383: div.LC_left_float {
6384: float: left;
6385: padding-right: 5%;
6386: padding-bottom: 4px;
6387: }
6388:
6389: div.LC_clear_float_header {
6390: padding-bottom: 2px;
6391: }
6392:
6393: div.LC_clear_float_footer {
6394: padding-top: 10px;
6395: clear: both;
6396: }
6397:
6398: div.LC_grade_show_user {
6399: /* border-left: 5px solid $sidebg; */
6400: border-top: 5px solid #000000;
6401: margin: 50px 0 0 0;
6402: padding: 15px 0 5px 10px;
6403: }
6404:
6405: div.LC_grade_show_user_odd_row {
6406: /* border-left: 5px solid #000000; */
6407: }
6408:
6409: div.LC_grade_show_user div.LC_Box {
6410: margin-right: 50px;
6411: }
6412:
6413: div.LC_grade_submissions,
6414: div.LC_grade_message_center,
6415: div.LC_grade_info_links {
6416: margin: 5px;
6417: width: 99%;
6418: background: #FFFFFF;
6419: }
6420:
6421: div.LC_grade_submissions_header,
6422: div.LC_grade_message_center_header {
6423: font-weight: bold;
6424: font-size: large;
6425: }
6426:
6427: div.LC_grade_submissions_body,
6428: div.LC_grade_message_center_body {
6429: border: 1px solid black;
6430: width: 99%;
6431: background: #FFFFFF;
6432: }
6433:
6434: table.LC_scantron_action {
6435: width: 100%;
6436: }
6437:
6438: table.LC_scantron_action tr th {
6439: font-weight:bold;
6440: font-style:normal;
6441: }
6442:
6443: .LC_edit_problem_header,
6444: div.LC_edit_problem_footer {
6445: font-weight: normal;
6446: font-size: medium;
6447: margin: 2px;
6448: background-color: $sidebg;
6449: }
6450:
6451: div.LC_edit_problem_header,
6452: div.LC_edit_problem_header div,
6453: div.LC_edit_problem_footer,
6454: div.LC_edit_problem_footer div,
6455: div.LC_edit_problem_editxml_header,
6456: div.LC_edit_problem_editxml_header div {
6457: margin-top: 5px;
6458: }
6459:
6460: div.LC_edit_problem_header_title {
6461: font-weight: bold;
6462: font-size: larger;
6463: background: $tabbg;
6464: padding: 3px;
6465: margin: 0 0 5px 0;
6466: }
6467:
6468: table.LC_edit_problem_header_title {
6469: width: 100%;
6470: background: $tabbg;
6471: }
6472:
6473: div.LC_edit_problem_discards {
6474: float: left;
6475: padding-bottom: 5px;
6476: }
6477:
6478: div.LC_edit_problem_saves {
6479: float: right;
6480: padding-bottom: 5px;
6481: }
6482:
6483: .LC_edit_opt {
6484: padding-left: 1em;
6485: white-space: nowrap;
6486: }
6487:
6488: img.stift {
6489: border-width: 0;
6490: vertical-align: middle;
6491: }
6492:
6493: table td.LC_mainmenu_col_fieldset {
6494: vertical-align: top;
6495: }
6496:
6497: div.LC_createcourse {
6498: margin: 10px 10px 10px 10px;
6499: }
6500:
6501: .LC_dccid {
6502: float: right;
6503: margin: 0.2em 0 0 0;
6504: padding: 0;
6505: font-size: 90%;
6506: display:none;
6507: }
6508:
6509: ol.LC_primary_menu a:hover,
6510: ol#LC_MenuBreadcrumbs a:hover,
6511: ol#LC_PathBreadcrumbs a:hover,
6512: ul#LC_secondary_menu a:hover,
6513: .LC_FormSectionClearButton input:hover
6514: ul.LC_TabContent li:hover a {
6515: color:$button_hover;
6516: text-decoration:none;
6517: }
6518:
6519: h1 {
6520: padding: 0;
6521: line-height:130%;
6522: }
6523:
6524: h2,
6525: h3,
6526: h4,
6527: h5,
6528: h6 {
6529: margin: 5px 0 5px 0;
6530: padding: 0;
6531: line-height:130%;
6532: }
6533:
6534: .LC_hcell {
6535: padding:3px 15px 3px 15px;
6536: margin: 0;
6537: background-color:$tabbg;
6538: color:$fontmenu;
6539: border-bottom:solid 1px $lg_border_color;
6540: }
6541:
6542: .LC_Box > .LC_hcell {
6543: margin: 0 -10px 10px -10px;
6544: }
6545:
6546: .LC_noBorder {
6547: border: 0;
6548: }
6549:
6550: .LC_FormSectionClearButton input {
6551: background-color:transparent;
6552: border: none;
6553: cursor:pointer;
6554: text-decoration:underline;
6555: }
6556:
6557: .LC_help_open_topic {
6558: color: #FFFFFF;
6559: background-color: #EEEEFF;
6560: margin: 1px;
6561: padding: 4px;
6562: border: 1px solid #000033;
6563: white-space: nowrap;
6564: /* vertical-align: middle; */
6565: }
6566:
6567: dl,
6568: ul,
6569: div,
6570: fieldset {
6571: margin: 10px 10px 10px 0;
6572: /* overflow: hidden; */
6573: }
6574:
6575: fieldset > legend {
6576: font-weight: bold;
6577: padding: 0 5px 0 5px;
6578: }
6579:
6580: #LC_nav_bar {
6581: float: left;
6582: background-color: $pgbg_or_bgcolor;
6583: margin: 0 0 2px 0;
6584: }
6585:
6586: #LC_realm {
6587: margin: 0.2em 0 0 0;
6588: padding: 0;
6589: font-weight: bold;
6590: text-align: center;
6591: background-color: $pgbg_or_bgcolor;
6592: }
6593:
6594: #LC_nav_bar em {
6595: font-weight: bold;
6596: font-style: normal;
6597: }
6598:
6599: ol.LC_primary_menu {
6600: margin: 0;
6601: padding: 0;
6602: background-color: $pgbg_or_bgcolor;
6603: }
6604:
6605: ol#LC_PathBreadcrumbs {
6606: margin: 0;
6607: }
6608:
6609: ol.LC_primary_menu li {
6610: color: RGB(80, 80, 80);
6611: vertical-align: middle;
6612: text-align: left;
6613: list-style: none;
6614: float: left;
6615: }
6616:
6617: ol.LC_primary_menu li a {
6618: display: block;
6619: margin: 0;
6620: padding: 0 5px 0 10px;
6621: text-decoration: none;
6622: }
6623:
6624: ol.LC_primary_menu li ul {
6625: display: none;
6626: width: 10em;
6627: background-color: $data_table_light;
6628: }
6629:
6630: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
6631: display: block;
6632: position: absolute;
6633: margin: 0;
6634: padding: 0;
6635: z-index: 2;
6636: }
6637:
6638: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
6639: font-size: 90%;
6640: vertical-align: top;
6641: float: none;
6642: border-left: 1px solid black;
6643: border-right: 1px solid black;
6644: }
6645:
6646: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
6647: background-color:$data_table_light;
6648: }
6649:
6650: ol.LC_primary_menu li li a:hover {
6651: color:$button_hover;
6652: background-color:$data_table_dark;
6653: }
6654:
6655: ol.LC_primary_menu li img {
6656: vertical-align: bottom;
6657: height: 1.1em;
6658: margin: 0.2em 0 0 0;
6659: }
6660:
6661: ol.LC_primary_menu a {
6662: color: RGB(80, 80, 80);
6663: text-decoration: none;
6664: }
6665:
6666: ol.LC_primary_menu a.LC_new_message {
6667: font-weight:bold;
6668: color: darkred;
6669: }
6670:
6671: ol.LC_docs_parameters {
6672: margin-left: 0;
6673: padding: 0;
6674: list-style: none;
6675: }
6676:
6677: ol.LC_docs_parameters li {
6678: margin: 0;
6679: padding-right: 20px;
6680: display: inline;
6681: }
6682:
6683: ol.LC_docs_parameters li:before {
6684: content: "\\002022 \\0020";
6685: }
6686:
6687: li.LC_docs_parameters_title {
6688: font-weight: bold;
6689: }
6690:
6691: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
6692: content: "";
6693: }
6694:
6695: ul#LC_secondary_menu {
6696: clear: right;
6697: color: $fontmenu;
6698: background: $tabbg;
6699: list-style: none;
6700: padding: 0;
6701: margin: 0;
6702: width: 100%;
6703: text-align: left;
6704: float: left;
6705: }
6706:
6707: ul#LC_secondary_menu li {
6708: font-weight: bold;
6709: line-height: 1.8em;
6710: border-right: 1px solid black;
6711: float: left;
6712: }
6713:
6714: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
6715: background-color: $data_table_light;
6716: }
6717:
6718: ul#LC_secondary_menu li a {
6719: padding: 0 0.8em;
6720: }
6721:
6722: ul#LC_secondary_menu li ul {
6723: display: none;
6724: }
6725:
6726: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
6727: display: block;
6728: position: absolute;
6729: margin: 0;
6730: padding: 0;
6731: list-style:none;
6732: float: none;
6733: background-color: $data_table_light;
6734: z-index: 2;
6735: margin-left: -1px;
6736: }
6737:
6738: ul#LC_secondary_menu li ul li {
6739: font-size: 90%;
6740: vertical-align: top;
6741: border-left: 1px solid black;
6742: border-right: 1px solid black;
6743: background-color: $data_table_light;
6744: list-style:none;
6745: float: none;
6746: }
6747:
6748: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
6749: background-color: $data_table_dark;
6750: }
6751:
6752: ul.LC_TabContent {
6753: display:block;
6754: background: $sidebg;
6755: border-bottom: solid 1px $lg_border_color;
6756: list-style:none;
6757: margin: -1px -10px 0 -10px;
6758: padding: 0;
6759: }
6760:
6761: ul.LC_TabContent li,
6762: ul.LC_TabContentBigger li {
6763: float:left;
6764: }
6765:
6766: ul#LC_secondary_menu li a {
6767: color: $fontmenu;
6768: text-decoration: none;
6769: }
6770:
6771: ul.LC_TabContent {
6772: min-height:20px;
6773: }
6774:
6775: ul.LC_TabContent li {
6776: vertical-align:middle;
6777: padding: 0 16px 0 10px;
6778: background-color:$tabbg;
6779: border-bottom:solid 1px $lg_border_color;
6780: border-left: solid 1px $font;
6781: }
6782:
6783: ul.LC_TabContent .right {
6784: float:right;
6785: }
6786:
6787: ul.LC_TabContent li a,
6788: ul.LC_TabContent li {
6789: color:rgb(47,47,47);
6790: text-decoration:none;
6791: font-size:95%;
6792: font-weight:bold;
6793: min-height:20px;
6794: }
6795:
6796: ul.LC_TabContent li a:hover,
6797: ul.LC_TabContent li a:focus {
6798: color: $button_hover;
6799: background:none;
6800: outline:none;
6801: }
6802:
6803: ul.LC_TabContent li:hover {
6804: color: $button_hover;
6805: cursor:pointer;
6806: }
6807:
6808: ul.LC_TabContent li.active {
6809: color: $font;
6810: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
6811: border-bottom:solid 1px #FFFFFF;
6812: cursor: default;
6813: }
6814:
6815: ul.LC_TabContent li.active a {
6816: color:$font;
6817: background:#FFFFFF;
6818: outline: none;
6819: }
6820:
6821: ul.LC_TabContent li.goback {
6822: float: left;
6823: border-left: none;
6824: }
6825:
6826: #maincoursedoc {
6827: clear:both;
6828: }
6829:
6830: ul.LC_TabContentBigger {
6831: display:block;
6832: list-style:none;
6833: padding: 0;
6834: }
6835:
6836: ul.LC_TabContentBigger li {
6837: vertical-align:bottom;
6838: height: 30px;
6839: font-size:110%;
6840: font-weight:bold;
6841: color: #737373;
6842: }
6843:
6844: ul.LC_TabContentBigger li.active {
6845: position: relative;
6846: top: 1px;
6847: }
6848:
6849: ul.LC_TabContentBigger li a {
6850: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
6851: height: 30px;
6852: line-height: 30px;
6853: text-align: center;
6854: display: block;
6855: text-decoration: none;
6856: outline: none;
6857: }
6858:
6859: ul.LC_TabContentBigger li.active a {
6860: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
6861: color:$font;
6862: }
6863:
6864: ul.LC_TabContentBigger li b {
6865: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
6866: display: block;
6867: float: left;
6868: padding: 0 30px;
6869: border-bottom: 1px solid $lg_border_color;
6870: }
6871:
6872: ul.LC_TabContentBigger li:hover b {
6873: color:$button_hover;
6874: }
6875:
6876: ul.LC_TabContentBigger li.active b {
6877: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
6878: color:$font;
6879: border: 0;
6880: }
6881:
6882:
6883: ul.LC_CourseBreadcrumbs {
6884: background: $sidebg;
6885: height: 2em;
6886: padding-left: 10px;
6887: margin: 0;
6888: list-style-position: inside;
6889: }
6890:
6891: ol#LC_MenuBreadcrumbs,
6892: ol#LC_PathBreadcrumbs {
6893: padding-left: 10px;
6894: margin: 0;
6895: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
6896: }
6897:
6898: ol#LC_MenuBreadcrumbs li,
6899: ol#LC_PathBreadcrumbs li,
6900: ul.LC_CourseBreadcrumbs li {
6901: display: inline;
6902: white-space: normal;
6903: }
6904:
6905: ol#LC_MenuBreadcrumbs li a,
6906: ul.LC_CourseBreadcrumbs li a {
6907: text-decoration: none;
6908: font-size:90%;
6909: }
6910:
6911: ol#LC_MenuBreadcrumbs h1 {
6912: display: inline;
6913: font-size: 90%;
6914: line-height: 2.5em;
6915: margin: 0;
6916: padding: 0;
6917: }
6918:
6919: ol#LC_PathBreadcrumbs li a {
6920: text-decoration:none;
6921: font-size:100%;
6922: font-weight:bold;
6923: }
6924:
6925: .LC_Box {
6926: border: solid 1px $lg_border_color;
6927: padding: 0 10px 10px 10px;
6928: }
6929:
6930: .LC_DocsBox {
6931: border: solid 1px $lg_border_color;
6932: padding: 0 0 10px 10px;
6933: }
6934:
6935: .LC_AboutMe_Image {
6936: float:left;
6937: margin-right:10px;
6938: }
6939:
6940: .LC_Clear_AboutMe_Image {
6941: clear:left;
6942: }
6943:
6944: dl.LC_ListStyleClean dt {
6945: padding-right: 5px;
6946: display: table-header-group;
6947: }
6948:
6949: dl.LC_ListStyleClean dd {
6950: display: table-row;
6951: }
6952:
6953: .LC_ListStyleClean,
6954: .LC_ListStyleSimple,
6955: .LC_ListStyleNormal,
6956: .LC_ListStyleSpecial {
6957: /* display:block; */
6958: list-style-position: inside;
6959: list-style-type: none;
6960: overflow: hidden;
6961: padding: 0;
6962: }
6963:
6964: .LC_ListStyleSimple li,
6965: .LC_ListStyleSimple dd,
6966: .LC_ListStyleNormal li,
6967: .LC_ListStyleNormal dd,
6968: .LC_ListStyleSpecial li,
6969: .LC_ListStyleSpecial dd {
6970: margin: 0;
6971: padding: 5px 5px 5px 10px;
6972: clear: both;
6973: }
6974:
6975: .LC_ListStyleClean li,
6976: .LC_ListStyleClean dd {
6977: padding-top: 0;
6978: padding-bottom: 0;
6979: }
6980:
6981: .LC_ListStyleSimple dd,
6982: .LC_ListStyleSimple li {
6983: border-bottom: solid 1px $lg_border_color;
6984: }
6985:
6986: .LC_ListStyleSpecial li,
6987: .LC_ListStyleSpecial dd {
6988: list-style-type: none;
6989: background-color: RGB(220, 220, 220);
6990: margin-bottom: 4px;
6991: }
6992:
6993: table.LC_SimpleTable {
6994: margin:5px;
6995: border:solid 1px $lg_border_color;
6996: }
6997:
6998: table.LC_SimpleTable tr {
6999: padding: 0;
7000: border:solid 1px $lg_border_color;
7001: }
7002:
7003: table.LC_SimpleTable thead {
7004: background:rgb(220,220,220);
7005: }
7006:
7007: div.LC_columnSection {
7008: display: block;
7009: clear: both;
7010: overflow: hidden;
7011: margin: 0;
7012: }
7013:
7014: div.LC_columnSection>* {
7015: float: left;
7016: margin: 10px 20px 10px 0;
7017: overflow:hidden;
7018: }
7019:
7020: table em {
7021: font-weight: bold;
7022: font-style: normal;
7023: }
7024:
7025: table.LC_tableBrowseRes,
7026: table.LC_tableOfContent {
7027: border:none;
7028: border-spacing: 1px;
7029: padding: 3px;
7030: background-color: #FFFFFF;
7031: font-size: 90%;
7032: }
7033:
7034: table.LC_tableOfContent {
7035: border-collapse: collapse;
7036: }
7037:
7038: table.LC_tableBrowseRes a,
7039: table.LC_tableOfContent a {
7040: background-color: transparent;
7041: text-decoration: none;
7042: }
7043:
7044: table.LC_tableOfContent img {
7045: border: none;
7046: height: 1.3em;
7047: vertical-align: text-bottom;
7048: margin-right: 0.3em;
7049: }
7050:
7051: a#LC_content_toolbar_firsthomework {
7052: background-image:url(/res/adm/pages/open-first-problem.gif);
7053: }
7054:
7055: a#LC_content_toolbar_everything {
7056: background-image:url(/res/adm/pages/show-all.gif);
7057: }
7058:
7059: a#LC_content_toolbar_uncompleted {
7060: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
7061: }
7062:
7063: #LC_content_toolbar_clearbubbles {
7064: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
7065: }
7066:
7067: a#LC_content_toolbar_changefolder {
7068: background : url(/res/adm/pages/close-all-folders.gif) top center ;
7069: }
7070:
7071: a#LC_content_toolbar_changefolder_toggled {
7072: background-image:url(/res/adm/pages/open-all-folders.gif);
7073: }
7074:
7075: a#LC_content_toolbar_edittoplevel {
7076: background-image:url(/res/adm/pages/edittoplevel.gif);
7077: }
7078:
7079: ul#LC_toolbar li a:hover {
7080: background-position: bottom center;
7081: }
7082:
7083: ul#LC_toolbar {
7084: padding: 0;
7085: margin: 2px;
7086: list-style:none;
7087: position:relative;
7088: background-color:white;
7089: overflow: auto;
7090: }
7091:
7092: ul#LC_toolbar li {
7093: border:1px solid white;
7094: padding: 0;
7095: margin: 0;
7096: float: left;
7097: display:inline;
7098: vertical-align:middle;
7099: white-space: nowrap;
7100: }
7101:
7102:
7103: a.LC_toolbarItem {
7104: display:block;
7105: padding: 0;
7106: margin: 0;
7107: height: 32px;
7108: width: 32px;
7109: color:white;
7110: border: none;
7111: background-repeat:no-repeat;
7112: background-color:transparent;
7113: }
7114:
7115: ul.LC_funclist {
7116: margin: 0;
7117: padding: 0.5em 1em 0.5em 0;
7118: }
7119:
7120: ul.LC_funclist > li:first-child {
7121: font-weight:bold;
7122: margin-left:0.8em;
7123: }
7124:
7125: ul.LC_funclist + ul.LC_funclist {
7126: /*
7127: left border as a seperator if we have more than
7128: one list
7129: */
7130: border-left: 1px solid $sidebg;
7131: /*
7132: this hides the left border behind the border of the
7133: outer box if element is wrapped to the next 'line'
7134: */
7135: margin-left: -1px;
7136: }
7137:
7138: ul.LC_funclist li {
7139: display: inline;
7140: white-space: nowrap;
7141: margin: 0 0 0 25px;
7142: line-height: 150%;
7143: }
7144:
7145: .LC_hidden {
7146: display: none;
7147: }
7148:
7149: .LCmodal-overlay {
7150: position:fixed;
7151: top:0;
7152: right:0;
7153: bottom:0;
7154: left:0;
7155: height:100%;
7156: width:100%;
7157: margin:0;
7158: padding:0;
7159: background:#999;
7160: opacity:.75;
7161: filter: alpha(opacity=75);
7162: -moz-opacity: 0.75;
7163: z-index:101;
7164: }
7165:
7166: * html .LCmodal-overlay {
7167: position: absolute;
7168: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
7169: }
7170:
7171: .LCmodal-window {
7172: position:fixed;
7173: top:50%;
7174: left:50%;
7175: margin:0;
7176: padding:0;
7177: z-index:102;
7178: }
7179:
7180: * html .LCmodal-window {
7181: position:absolute;
7182: }
7183:
7184: .LCclose-window {
7185: position:absolute;
7186: width:32px;
7187: height:32px;
7188: right:8px;
7189: top:8px;
7190: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
7191: text-indent:-99999px;
7192: overflow:hidden;
7193: cursor:pointer;
7194: }
7195:
7196: /*
7197: styles used by TTH when "Default set of options to pass to tth/m
7198: when converting TeX" in course settings has been set
7199:
7200: option passed: -t
7201:
7202: */
7203:
7204: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
7205: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
7206: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
7207: td div.norm {line-height:normal;}
7208:
7209: /*
7210: option passed -y3
7211: */
7212:
7213: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
7214: span.overacc2 {position: relative; left: .8em; top: -1.2ex;}
7215: span.overacc1 {position: relative; left: .6em; top: -1.2ex;}
7216:
7217: END
7218: }
7219:
7220: =pod
7221:
7222: =item * &headtag()
7223:
7224: Returns a uniform footer for LON-CAPA web pages.
7225:
7226: Inputs: $title - optional title for the head
7227: $head_extra - optional extra HTML to put inside the <head>
7228: $args - optional arguments
7229: force_register - if is true call registerurl so the remote is
7230: informed
7231: redirect -> array ref of
7232: 1- seconds before redirect occurs
7233: 2- url to redirect to
7234: 3- whether the side effect should occur
7235: (side effect of setting
7236: $env{'internal.head.redirect'} to the url
7237: redirected too)
7238: domain -> force to color decorate a page for a specific
7239: domain
7240: function -> force usage of a specific rolish color scheme
7241: bgcolor -> override the default page bgcolor
7242: no_auto_mt_title
7243: -> prevent &mt()ing the title arg
7244:
7245: =cut
7246:
7247: sub headtag {
7248: my ($title,$head_extra,$args) = @_;
7249:
7250: my $function = $args->{'function'} || &get_users_function();
7251: my $domain = $args->{'domain'} || &determinedomain();
7252: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
7253: my $url = join(':',$env{'user.name'},$env{'user.domain'},
7254: $Apache::lonnet::perlvar{'lonVersion'},
7255: #time(),
7256: $env{'environment.color.timestamp'},
7257: $function,$domain,$bgcolor);
7258:
7259: $url = '/adm/css/'.&escape($url).'.css';
7260:
7261: my $result =
7262: '<head>'.
7263: &font_settings();
7264:
7265: my $inhibitprint = &print_suppression();
7266:
7267: if (!$args->{'frameset'}) {
7268: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
7269: }
7270: if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
7271: $result .= Apache::lonxml::display_title();
7272: }
7273: if (!$args->{'no_nav_bar'}
7274: && !$args->{'only_body'}
7275: && !$args->{'frameset'}) {
7276: $result .= &help_menu_js();
7277: $result.=&modal_window();
7278: $result.=&togglebox_script();
7279: $result.=&wishlist_window();
7280: $result.=&LCprogressbarUpdate_script();
7281: } else {
7282: if ($args->{'add_modal'}) {
7283: $result.=&modal_window();
7284: }
7285: if ($args->{'add_wishlist'}) {
7286: $result.=&wishlist_window();
7287: }
7288: if ($args->{'add_togglebox'}) {
7289: $result.=&togglebox_script();
7290: }
7291: if ($args->{'add_progressbar'}) {
7292: $result.=&LCprogressbarUpdate_script();
7293: }
7294: }
7295: if (ref($args->{'redirect'})) {
7296: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
7297: $url = &Apache::lonenc::check_encrypt($url);
7298: if (!$inhibit_continue) {
7299: $env{'internal.head.redirect'} = $url;
7300: }
7301: $result.=<<ADDMETA
7302: <meta http-equiv="pragma" content="no-cache" />
7303: <meta http-equiv="Refresh" content="$time; url=$url" />
7304: ADDMETA
7305: }
7306: if (!defined($title)) {
7307: $title = 'The LearningOnline Network with CAPA';
7308: }
7309: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
7310: $result .= '<title> LON-CAPA '.$title.'</title>'
7311: .'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
7312: .$inhibitprint
7313: .$head_extra;
7314: return $result.'</head>';
7315: }
7316:
7317: =pod
7318:
7319: =item * &font_settings()
7320:
7321: Returns neccessary <meta> to set the proper encoding
7322:
7323: Inputs: none
7324:
7325: =cut
7326:
7327: sub font_settings {
7328: my $headerstring='';
7329: if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
7330: $headerstring.=
7331: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
7332: }
7333: return $headerstring;
7334: }
7335:
7336: =pod
7337:
7338: =item * &print_suppression()
7339:
7340: In course context returns css which causes the body to be blank when media="print",
7341: if printout generation is unavailable for the current resource.
7342:
7343: This could be because:
7344:
7345: (a) printstartdate is in the future
7346:
7347: (b) printenddate is in the past
7348:
7349: (c) there is an active exam block with "printout"
7350: functionality blocked
7351:
7352: Users with pav, pfo or evb privileges are exempt.
7353:
7354: Inputs: none
7355:
7356: =cut
7357:
7358:
7359: sub print_suppression {
7360: my $noprint;
7361: if ($env{'request.course.id'}) {
7362: my $scope = $env{'request.course.id'};
7363: if ((&Apache::lonnet::allowed('pav',$scope)) ||
7364: (&Apache::lonnet::allowed('pfo',$scope))) {
7365: return;
7366: }
7367: if ($env{'request.course.sec'} ne '') {
7368: $scope .= "/$env{'request.course.sec'}";
7369: if ((&Apache::lonnet::allowed('pav',$scope)) ||
7370: (&Apache::lonnet::allowed('pfo',$scope))) {
7371: return;
7372: }
7373: }
7374: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7375: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7376: my $blocked = &blocking_status('printout',$cnum,$cdom);
7377: if ($blocked) {
7378: my $checkrole = "cm./$cdom/$cnum";
7379: if ($env{'request.course.sec'} ne '') {
7380: $checkrole .= "/$env{'request.course.sec'}";
7381: }
7382: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
7383: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
7384: $noprint = 1;
7385: }
7386: }
7387: unless ($noprint) {
7388: my $symb = &Apache::lonnet::symbread();
7389: if ($symb ne '') {
7390: my $navmap = Apache::lonnavmaps::navmap->new();
7391: if (ref($navmap)) {
7392: my $res = $navmap->getBySymb($symb);
7393: if (ref($res)) {
7394: if (!$res->resprintable()) {
7395: $noprint = 1;
7396: }
7397: }
7398: }
7399: }
7400: }
7401: if ($noprint) {
7402: return <<"ENDSTYLE";
7403: <style type="text/css" media="print">
7404: body { display:none }
7405: </style>
7406: ENDSTYLE
7407: }
7408: }
7409: return;
7410: }
7411:
7412: =pod
7413:
7414: =item * &xml_begin()
7415:
7416: Returns the needed doctype and <html>
7417:
7418: Inputs: none
7419:
7420: =cut
7421:
7422: sub xml_begin {
7423: my $output='';
7424:
7425: if ($env{'browser.mathml'}) {
7426: $output='<?xml version="1.0"?>'
7427: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
7428: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
7429:
7430: # .'<!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">] >'
7431: .'<!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">'
7432: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
7433: .'xmlns="http://www.w3.org/1999/xhtml">';
7434: } else {
7435: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
7436: .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
7437: }
7438: return $output;
7439: }
7440:
7441: =pod
7442:
7443: =item * &start_page()
7444:
7445: Returns a complete <html> .. <body> section for LON-CAPA web pages.
7446:
7447: Inputs:
7448:
7449: =over 4
7450:
7451: $title - optional title for the page
7452:
7453: $head_extra - optional extra HTML to incude inside the <head>
7454:
7455: $args - additional optional args supported are:
7456:
7457: =over 8
7458:
7459: only_body -> is true will set &bodytag() onlybodytag
7460: arg on
7461: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
7462: add_entries -> additional attributes to add to the <body>
7463: domain -> force to color decorate a page for a
7464: specific domain
7465: function -> force usage of a specific rolish color
7466: scheme
7467: redirect -> see &headtag()
7468: bgcolor -> override the default page bg color
7469: js_ready -> return a string ready for being used in
7470: a javascript writeln
7471: html_encode -> return a string ready for being used in
7472: a html attribute
7473: force_register -> if is true will turn on the &bodytag()
7474: $forcereg arg
7475: frameset -> if true will start with a <frameset>
7476: rather than <body>
7477: skip_phases -> hash ref of
7478: head -> skip the <html><head> generation
7479: body -> skip all <body> generation
7480: no_auto_mt_title -> prevent &mt()ing the title arg
7481: inherit_jsmath -> when creating popup window in a page,
7482: should it have jsmath forced on by the
7483: current page
7484: bread_crumbs -> Array containing breadcrumbs
7485: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
7486: group -> includes the current group, if page is for a
7487: specific group
7488:
7489: =back
7490:
7491: =back
7492:
7493: =cut
7494:
7495: sub start_page {
7496: my ($title,$head_extra,$args) = @_;
7497: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
7498:
7499: $env{'internal.start_page'}++;
7500: my ($result,@advtools);
7501:
7502: if (! exists($args->{'skip_phases'}{'head'}) ) {
7503: $result .= &xml_begin() . &headtag($title, $head_extra, $args);
7504: }
7505:
7506: if (! exists($args->{'skip_phases'}{'body'}) ) {
7507: if ($args->{'frameset'}) {
7508: my $attr_string = &make_attr_string($args->{'force_register'},
7509: $args->{'add_entries'});
7510: $result .= "\n<frameset $attr_string>\n";
7511: } else {
7512: $result .=
7513: &bodytag($title,
7514: $args->{'function'}, $args->{'add_entries'},
7515: $args->{'only_body'}, $args->{'domain'},
7516: $args->{'force_register'}, $args->{'no_nav_bar'},
7517: $args->{'bgcolor'}, $args,
7518: \@advtools);
7519: }
7520: }
7521:
7522: if ($args->{'js_ready'}) {
7523: $result = &js_ready($result);
7524: }
7525: if ($args->{'html_encode'}) {
7526: $result = &html_encode($result);
7527: }
7528:
7529: # Preparation for new and consistent functionlist at top of screen
7530: # if ($args->{'functionlist'}) {
7531: # $result .= &build_functionlist();
7532: #}
7533:
7534: # Don't add anything more if only_body wanted or in const space
7535: return $result if $args->{'only_body'}
7536: || $env{'request.state'} eq 'construct';
7537:
7538: #Breadcrumbs
7539: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
7540: &Apache::lonhtmlcommon::clear_breadcrumbs();
7541: #if any br links exists, add them to the breadcrumbs
7542: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
7543: foreach my $crumb (@{$args->{'bread_crumbs'}}){
7544: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
7545: }
7546: }
7547: # if @advtools array contains items add then to the breadcrumbs
7548: if (@advtools > 0) {
7549: &Apache::lonmenu::advtools_crumbs(@advtools);
7550: }
7551:
7552: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
7553: if(exists($args->{'bread_crumbs_component'})){
7554: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
7555: }else{
7556: $result .= &Apache::lonhtmlcommon::breadcrumbs();
7557: }
7558: }
7559: return $result;
7560: }
7561:
7562: sub end_page {
7563: my ($args) = @_;
7564: $env{'internal.end_page'}++;
7565: my $result;
7566: if ($args->{'discussion'}) {
7567: my ($target,$parser);
7568: if (ref($args->{'discussion'})) {
7569: ($target,$parser) =($args->{'discussion'}{'target'},
7570: $args->{'discussion'}{'parser'});
7571: }
7572: $result .= &Apache::lonxml::xmlend($target,$parser);
7573: }
7574: if ($args->{'frameset'}) {
7575: $result .= '</frameset>';
7576: } else {
7577: $result .= &endbodytag($args);
7578: }
7579: unless ($args->{'notbody'}) {
7580: $result .= "\n</html>";
7581: }
7582:
7583: if ($args->{'js_ready'}) {
7584: $result = &js_ready($result);
7585: }
7586:
7587: if ($args->{'html_encode'}) {
7588: $result = &html_encode($result);
7589: }
7590:
7591: return $result;
7592: }
7593:
7594: sub wishlist_window {
7595: return(<<'ENDWISHLIST');
7596: <script type="text/javascript">
7597: // <![CDATA[
7598: // <!-- BEGIN LON-CAPA Internal
7599: function set_wishlistlink(title, path) {
7600: if (!title) {
7601: title = document.title;
7602: title = title.replace(/^LON-CAPA /,'');
7603: }
7604: if (!path) {
7605: path = location.pathname;
7606: }
7607: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
7608: 'wishlistNewLink','width=560,height=350,scrollbars=0');
7609: }
7610: // END LON-CAPA Internal -->
7611: // ]]>
7612: </script>
7613: ENDWISHLIST
7614: }
7615:
7616: sub modal_window {
7617: return(<<'ENDMODAL');
7618: <script type="text/javascript">
7619: // <![CDATA[
7620: // <!-- BEGIN LON-CAPA Internal
7621: var modalWindow = {
7622: parent:"body",
7623: windowId:null,
7624: content:null,
7625: width:null,
7626: height:null,
7627: close:function()
7628: {
7629: $(".LCmodal-window").remove();
7630: $(".LCmodal-overlay").remove();
7631: },
7632: open:function()
7633: {
7634: var modal = "";
7635: modal += "<div class=\"LCmodal-overlay\"></div>";
7636: 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;\">";
7637: modal += this.content;
7638: modal += "</div>";
7639:
7640: $(this.parent).append(modal);
7641:
7642: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
7643: $(".LCclose-window").click(function(){modalWindow.close();});
7644: $(".LCmodal-overlay").click(function(){modalWindow.close();});
7645: }
7646: };
7647: var openMyModal = function(source,width,height,scrolling)
7648: {
7649: modalWindow.windowId = "myModal";
7650: modalWindow.width = width;
7651: modalWindow.height = height;
7652: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'></iframe>";
7653: modalWindow.open();
7654: };
7655: // END LON-CAPA Internal -->
7656: // ]]>
7657: </script>
7658: ENDMODAL
7659: }
7660:
7661: sub modal_link {
7662: my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_;
7663: unless ($width) { $width=480; }
7664: unless ($height) { $height=400; }
7665: unless ($scrolling) { $scrolling='yes'; }
7666: my $target_attr;
7667: if (defined($target)) {
7668: $target_attr = 'target="'.$target.'"';
7669: }
7670: return <<"ENDLINK";
7671: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling'); return false;">
7672: $linktext</a>
7673: ENDLINK
7674: }
7675:
7676: sub modal_adhoc_script {
7677: my ($funcname,$width,$height,$content)=@_;
7678: return (<<ENDADHOC);
7679: <script type="text/javascript">
7680: // <![CDATA[
7681: var $funcname = function()
7682: {
7683: modalWindow.windowId = "myModal";
7684: modalWindow.width = $width;
7685: modalWindow.height = $height;
7686: modalWindow.content = '$content';
7687: modalWindow.open();
7688: };
7689: // ]]>
7690: </script>
7691: ENDADHOC
7692: }
7693:
7694: sub modal_adhoc_inner {
7695: my ($funcname,$width,$height,$content)=@_;
7696: my $innerwidth=$width-20;
7697: $content=&js_ready(
7698: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
7699: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px').
7700: $content.
7701: &end_scrollbox().
7702: &end_page()
7703: );
7704: return &modal_adhoc_script($funcname,$width,$height,$content);
7705: }
7706:
7707: sub modal_adhoc_window {
7708: my ($funcname,$width,$height,$content,$linktext)=@_;
7709: return &modal_adhoc_inner($funcname,$width,$height,$content).
7710: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
7711: }
7712:
7713: sub modal_adhoc_launch {
7714: my ($funcname,$width,$height,$content)=@_;
7715: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
7716: <script type="text/javascript">
7717: // <![CDATA[
7718: $funcname();
7719: // ]]>
7720: </script>
7721: ENDLAUNCH
7722: }
7723:
7724: sub modal_adhoc_close {
7725: return (<<ENDCLOSE);
7726: <script type="text/javascript">
7727: // <![CDATA[
7728: modalWindow.close();
7729: // ]]>
7730: </script>
7731: ENDCLOSE
7732: }
7733:
7734: sub togglebox_script {
7735: return(<<ENDTOGGLE);
7736: <script type="text/javascript">
7737: // <![CDATA[
7738: function LCtoggleDisplay(id,hidetext,showtext) {
7739: link = document.getElementById(id + "link").childNodes[0];
7740: with (document.getElementById(id).style) {
7741: if (display == "none" ) {
7742: display = "inline";
7743: link.nodeValue = hidetext;
7744: } else {
7745: display = "none";
7746: link.nodeValue = showtext;
7747: }
7748: }
7749: }
7750: // ]]>
7751: </script>
7752: ENDTOGGLE
7753: }
7754:
7755: sub start_togglebox {
7756: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
7757: unless ($heading) { $heading=''; } else { $heading.=' '; }
7758: unless ($showtext) { $showtext=&mt('show'); }
7759: unless ($hidetext) { $hidetext=&mt('hide'); }
7760: unless ($headerbg) { $headerbg='#FFFFFF'; }
7761: return &start_data_table().
7762: &start_data_table_header_row().
7763: '<td bgcolor="'.$headerbg.'">'.$heading.
7764: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
7765: $showtext.'\')">'.$showtext.'</a>]</td>'.
7766: &end_data_table_header_row().
7767: '<tr id="'.$id.'" style="display:none""><td>';
7768: }
7769:
7770: sub end_togglebox {
7771: return '</td></tr>'.&end_data_table();
7772: }
7773:
7774: sub LCprogressbar_script {
7775: my ($id)=@_;
7776: return(<<ENDPROGRESS);
7777: <script type="text/javascript">
7778: // <![CDATA[
7779: \$('#progressbar$id').progressbar({
7780: value: 0,
7781: change: function(event, ui) {
7782: var newVal = \$(this).progressbar('option', 'value');
7783: \$('.pblabel', this).text(LCprogressTxt);
7784: }
7785: });
7786: // ]]>
7787: </script>
7788: ENDPROGRESS
7789: }
7790:
7791: sub LCprogressbarUpdate_script {
7792: return(<<ENDPROGRESSUPDATE);
7793: <style type="text/css">
7794: .ui-progressbar { position:relative; }
7795: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
7796: </style>
7797: <script type="text/javascript">
7798: // <![CDATA[
7799: var LCprogressTxt='---';
7800:
7801: function LCupdateProgress(percent,progresstext,id) {
7802: LCprogressTxt=progresstext;
7803: \$('#progressbar'+id).progressbar('value',percent);
7804: }
7805: // ]]>
7806: </script>
7807: ENDPROGRESSUPDATE
7808: }
7809:
7810: my $LClastpercent;
7811: my $LCidcnt;
7812: my $LCcurrentid;
7813:
7814: sub LCprogressbar {
7815: my ($r)=(@_);
7816: $LClastpercent=0;
7817: $LCidcnt++;
7818: $LCcurrentid=$$.'_'.$LCidcnt;
7819: my $starting=&mt('Starting');
7820: my $content=(<<ENDPROGBAR);
7821: <div id="progressbar$LCcurrentid">
7822: <span class="pblabel">$starting</span>
7823: </div>
7824: ENDPROGBAR
7825: &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
7826: }
7827:
7828: sub LCprogressbarUpdate {
7829: my ($r,$val,$text)=@_;
7830: unless ($val) {
7831: if ($LClastpercent) {
7832: $val=$LClastpercent;
7833: } else {
7834: $val=0;
7835: }
7836: }
7837: if ($val<0) { $val=0; }
7838: if ($val>100) { $val=0; }
7839: $LClastpercent=$val;
7840: unless ($text) { $text=$val.'%'; }
7841: $text=&js_ready($text);
7842: &r_print($r,<<ENDUPDATE);
7843: <script type="text/javascript">
7844: // <![CDATA[
7845: LCupdateProgress($val,'$text','$LCcurrentid');
7846: // ]]>
7847: </script>
7848: ENDUPDATE
7849: }
7850:
7851: sub LCprogressbarClose {
7852: my ($r)=@_;
7853: $LClastpercent=0;
7854: &r_print($r,<<ENDCLOSE);
7855: <script type="text/javascript">
7856: // <![CDATA[
7857: \$("#progressbar$LCcurrentid").hide('slow');
7858: // ]]>
7859: </script>
7860: ENDCLOSE
7861: }
7862:
7863: sub r_print {
7864: my ($r,$to_print)=@_;
7865: if ($r) {
7866: $r->print($to_print);
7867: $r->rflush();
7868: } else {
7869: print($to_print);
7870: }
7871: }
7872:
7873: sub html_encode {
7874: my ($result) = @_;
7875:
7876: $result = &HTML::Entities::encode($result,'<>&"');
7877:
7878: return $result;
7879: }
7880:
7881: sub js_ready {
7882: my ($result) = @_;
7883:
7884: $result =~ s/[\n\r]/ /xmsg;
7885: $result =~ s/\\/\\\\/xmsg;
7886: $result =~ s/'/\\'/xmsg;
7887: $result =~ s{</}{<\\/}xmsg;
7888:
7889: return $result;
7890: }
7891:
7892: sub validate_page {
7893: if ( exists($env{'internal.start_page'})
7894: && $env{'internal.start_page'} > 1) {
7895: &Apache::lonnet::logthis('start_page called multiple times '.
7896: $env{'internal.start_page'}.' '.
7897: $ENV{'request.filename'});
7898: }
7899: if ( exists($env{'internal.end_page'})
7900: && $env{'internal.end_page'} > 1) {
7901: &Apache::lonnet::logthis('end_page called multiple times '.
7902: $env{'internal.end_page'}.' '.
7903: $env{'request.filename'});
7904: }
7905: if ( exists($env{'internal.start_page'})
7906: && ! exists($env{'internal.end_page'})) {
7907: &Apache::lonnet::logthis('start_page called without end_page '.
7908: $env{'request.filename'});
7909: }
7910: if ( ! exists($env{'internal.start_page'})
7911: && exists($env{'internal.end_page'})) {
7912: &Apache::lonnet::logthis('end_page called without start_page'.
7913: $env{'request.filename'});
7914: }
7915: }
7916:
7917:
7918: sub start_scrollbox {
7919: my ($outerwidth,$width,$height,$id,$bgcolor)=@_;
7920: unless ($outerwidth) { $outerwidth='520px'; }
7921: unless ($width) { $width='500px'; }
7922: unless ($height) { $height='200px'; }
7923: my ($table_id,$div_id,$tdcol);
7924: if ($id ne '') {
7925: $table_id = " id='table_$id'";
7926: $div_id = " id='div_$id'";
7927: }
7928: if ($bgcolor ne '') {
7929: $tdcol = "background-color: $bgcolor;";
7930: }
7931: return <<"END";
7932: <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>
7933: END
7934: }
7935:
7936: sub end_scrollbox {
7937: return '</div></td></tr></table>';
7938: }
7939:
7940: sub simple_error_page {
7941: my ($r,$title,$msg) = @_;
7942: my $page =
7943: &Apache::loncommon::start_page($title).
7944: '<p class="LC_error">'.&mt($msg).'</p>'.
7945: &Apache::loncommon::end_page();
7946: if (ref($r)) {
7947: $r->print($page);
7948: return;
7949: }
7950: return $page;
7951: }
7952:
7953: {
7954: my @row_count;
7955:
7956: sub start_data_table_count {
7957: unshift(@row_count, 0);
7958: return;
7959: }
7960:
7961: sub end_data_table_count {
7962: shift(@row_count);
7963: return;
7964: }
7965:
7966: sub start_data_table {
7967: my ($add_class,$id) = @_;
7968: my $css_class = (join(' ','LC_data_table',$add_class));
7969: my $table_id;
7970: if (defined($id)) {
7971: $table_id = ' id="'.$id.'"';
7972: }
7973: &start_data_table_count();
7974: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
7975: }
7976:
7977: sub end_data_table {
7978: &end_data_table_count();
7979: return '</table>'."\n";;
7980: }
7981:
7982: sub start_data_table_row {
7983: my ($add_class, $id) = @_;
7984: $row_count[0]++;
7985: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
7986: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
7987: $id = (' id="'.$id.'"') unless ($id eq '');
7988: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
7989: }
7990:
7991: sub continue_data_table_row {
7992: my ($add_class, $id) = @_;
7993: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
7994: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
7995: $id = (' id="'.$id.'"') unless ($id eq '');
7996: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
7997: }
7998:
7999: sub end_data_table_row {
8000: return '</tr>'."\n";;
8001: }
8002:
8003: sub start_data_table_empty_row {
8004: # $row_count[0]++;
8005: return '<tr class="LC_empty_row" >'."\n";;
8006: }
8007:
8008: sub end_data_table_empty_row {
8009: return '</tr>'."\n";;
8010: }
8011:
8012: sub start_data_table_header_row {
8013: return '<tr class="LC_header_row">'."\n";;
8014: }
8015:
8016: sub end_data_table_header_row {
8017: return '</tr>'."\n";;
8018: }
8019:
8020: sub data_table_caption {
8021: my $caption = shift;
8022: return "<caption class=\"LC_caption\">$caption</caption>";
8023: }
8024: }
8025:
8026: =pod
8027:
8028: =item * &inhibit_menu_check($arg)
8029:
8030: Checks for a inhibitmenu state and generates output to preserve it
8031:
8032: Inputs: $arg - can be any of
8033: - undef - in which case the return value is a string
8034: to add into arguments list of a uri
8035: - 'input' - in which case the return value is a HTML
8036: <form> <input> field of type hidden to
8037: preserve the value
8038: - a url - in which case the return value is the url with
8039: the neccesary cgi args added to preserve the
8040: inhibitmenu state
8041: - a ref to a url - no return value, but the string is
8042: updated to include the neccessary cgi
8043: args to preserve the inhibitmenu state
8044:
8045: =cut
8046:
8047: sub inhibit_menu_check {
8048: my ($arg) = @_;
8049: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
8050: if ($arg eq 'input') {
8051: if ($env{'form.inhibitmenu'}) {
8052: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
8053: } else {
8054: return
8055: }
8056: }
8057: if ($env{'form.inhibitmenu'}) {
8058: if (ref($arg)) {
8059: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
8060: } elsif ($arg eq '') {
8061: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
8062: } else {
8063: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
8064: }
8065: }
8066: if (!ref($arg)) {
8067: return $arg;
8068: }
8069: }
8070:
8071: ###############################################
8072:
8073: =pod
8074:
8075: =back
8076:
8077: =head1 User Information Routines
8078:
8079: =over 4
8080:
8081: =item * &get_users_function()
8082:
8083: Used by &bodytag to determine the current users primary role.
8084: Returns either 'student','coordinator','admin', or 'author'.
8085:
8086: =cut
8087:
8088: ###############################################
8089: sub get_users_function {
8090: my $function = 'norole';
8091: if ($env{'request.role'}=~/^(st)/) {
8092: $function='student';
8093: }
8094: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
8095: $function='coordinator';
8096: }
8097: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
8098: $function='admin';
8099: }
8100: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
8101: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
8102: $function='author';
8103: }
8104: return $function;
8105: }
8106:
8107: ###############################################
8108:
8109: =pod
8110:
8111: =item * &show_course()
8112:
8113: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
8114: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
8115:
8116: Inputs:
8117: None
8118:
8119: Outputs:
8120: Scalar: 1 if 'Course' to be used, 0 otherwise.
8121:
8122: =cut
8123:
8124: ###############################################
8125: sub show_course {
8126: my $course = !$env{'user.adv'};
8127: if (!$env{'user.adv'}) {
8128: foreach my $env (keys(%env)) {
8129: next if ($env !~ m/^user\.priv\./);
8130: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
8131: $course = 0;
8132: last;
8133: }
8134: }
8135: }
8136: return $course;
8137: }
8138:
8139: ###############################################
8140:
8141: =pod
8142:
8143: =item * &check_user_status()
8144:
8145: Determines current status of supplied role for a
8146: specific user. Roles can be active, previous or future.
8147:
8148: Inputs:
8149: user's domain, user's username, course's domain,
8150: course's number, optional section ID.
8151:
8152: Outputs:
8153: role status: active, previous or future.
8154:
8155: =cut
8156:
8157: sub check_user_status {
8158: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
8159: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
8160: my @uroles = keys %userinfo;
8161: my $srchstr;
8162: my $active_chk = 'none';
8163: my $now = time;
8164: if (@uroles > 0) {
8165: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
8166: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
8167: } else {
8168: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
8169: }
8170: if (grep/^\Q$srchstr\E$/,@uroles) {
8171: my $role_end = 0;
8172: my $role_start = 0;
8173: $active_chk = 'active';
8174: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
8175: $role_end = $1;
8176: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
8177: $role_start = $1;
8178: }
8179: }
8180: if ($role_start > 0) {
8181: if ($now < $role_start) {
8182: $active_chk = 'future';
8183: }
8184: }
8185: if ($role_end > 0) {
8186: if ($now > $role_end) {
8187: $active_chk = 'previous';
8188: }
8189: }
8190: }
8191: }
8192: return $active_chk;
8193: }
8194:
8195: ###############################################
8196:
8197: =pod
8198:
8199: =item * &get_sections()
8200:
8201: Determines all the sections for a course including
8202: sections with students and sections containing other roles.
8203: Incoming parameters:
8204:
8205: 1. domain
8206: 2. course number
8207: 3. reference to array containing roles for which sections should
8208: be gathered (optional).
8209: 4. reference to array containing status types for which sections
8210: should be gathered (optional).
8211:
8212: If the third argument is undefined, sections are gathered for any role.
8213: If the fourth argument is undefined, sections are gathered for any status.
8214: Permissible values are 'active' or 'future' or 'previous'.
8215:
8216: Returns section hash (keys are section IDs, values are
8217: number of users in each section), subject to the
8218: optional roles filter, optional status filter
8219:
8220: =cut
8221:
8222: ###############################################
8223: sub get_sections {
8224: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
8225: if (!defined($cdom) || !defined($cnum)) {
8226: my $cid = $env{'request.course.id'};
8227:
8228: return if (!defined($cid));
8229:
8230: $cdom = $env{'course.'.$cid.'.domain'};
8231: $cnum = $env{'course.'.$cid.'.num'};
8232: }
8233:
8234: my %sectioncount;
8235: my $now = time;
8236:
8237: my $check_students = 1;
8238: my $only_students = 0;
8239: if (ref($possible_roles) eq 'ARRAY') {
8240: if (grep(/^st$/,@{$possible_roles})) {
8241: if (@{$possible_roles} == 1) {
8242: $only_students = 1;
8243: }
8244: } else {
8245: $check_students = 0;
8246: }
8247: }
8248:
8249: if ($check_students) {
8250: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
8251: my $sec_index = &Apache::loncoursedata::CL_SECTION();
8252: my $status_index = &Apache::loncoursedata::CL_STATUS();
8253: my $start_index = &Apache::loncoursedata::CL_START();
8254: my $end_index = &Apache::loncoursedata::CL_END();
8255: my $status;
8256: while (my ($student,$data) = each(%$classlist)) {
8257: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
8258: $data->[$status_index],
8259: $data->[$start_index],
8260: $data->[$end_index]);
8261: if ($stu_status eq 'Active') {
8262: $status = 'active';
8263: } elsif ($end < $now) {
8264: $status = 'previous';
8265: } elsif ($start > $now) {
8266: $status = 'future';
8267: }
8268: if ($section ne '-1' && $section !~ /^\s*$/) {
8269: if ((!defined($possible_status)) || (($status ne '') &&
8270: (grep/^\Q$status\E$/,@{$possible_status}))) {
8271: $sectioncount{$section}++;
8272: }
8273: }
8274: }
8275: }
8276: if ($only_students) {
8277: return %sectioncount;
8278: }
8279: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
8280: foreach my $user (sort(keys(%courseroles))) {
8281: if ($user !~ /^(\w{2})/) { next; }
8282: my ($role) = ($user =~ /^(\w{2})/);
8283: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
8284: my ($section,$status);
8285: if ($role eq 'cr' &&
8286: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
8287: $section=$1;
8288: }
8289: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
8290: if (!defined($section) || $section eq '-1') { next; }
8291: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
8292: if ($end == -1 && $start == -1) {
8293: next; #deleted role
8294: }
8295: if (!defined($possible_status)) {
8296: $sectioncount{$section}++;
8297: } else {
8298: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
8299: $status = 'active';
8300: } elsif ($end < $now) {
8301: $status = 'future';
8302: } elsif ($start > $now) {
8303: $status = 'previous';
8304: }
8305: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
8306: $sectioncount{$section}++;
8307: }
8308: }
8309: }
8310: return %sectioncount;
8311: }
8312:
8313: ###############################################
8314:
8315: =pod
8316:
8317: =item * &get_course_users()
8318:
8319: Retrieves usernames:domains for users in the specified course
8320: with specific role(s), and access status.
8321:
8322: Incoming parameters:
8323: 1. course domain
8324: 2. course number
8325: 3. access status: users must have - either active,
8326: previous, future, or all.
8327: 4. reference to array of permissible roles
8328: 5. reference to array of section restrictions (optional)
8329: 6. reference to results object (hash of hashes).
8330: 7. reference to optional userdata hash
8331: 8. reference to optional statushash
8332: 9. flag if privileged users (except those set to unhide in
8333: course settings) should be excluded
8334: Keys of top level results hash are roles.
8335: Keys of inner hashes are username:domain, with
8336: values set to access type.
8337: Optional userdata hash returns an array with arguments in the
8338: same order as loncoursedata::get_classlist() for student data.
8339:
8340: Optional statushash returns
8341:
8342: Entries for end, start, section and status are blank because
8343: of the possibility of multiple values for non-student roles.
8344:
8345: =cut
8346:
8347: ###############################################
8348:
8349: sub get_course_users {
8350: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
8351: my %idx = ();
8352: my %seclists;
8353:
8354: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
8355: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
8356: $idx{end} = &Apache::loncoursedata::CL_END();
8357: $idx{start} = &Apache::loncoursedata::CL_START();
8358: $idx{id} = &Apache::loncoursedata::CL_ID();
8359: $idx{section} = &Apache::loncoursedata::CL_SECTION();
8360: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
8361: $idx{status} = &Apache::loncoursedata::CL_STATUS();
8362:
8363: if (grep(/^st$/,@{$roles})) {
8364: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
8365: my $now = time;
8366: foreach my $student (keys(%{$classlist})) {
8367: my $match = 0;
8368: my $secmatch = 0;
8369: my $section = $$classlist{$student}[$idx{section}];
8370: my $status = $$classlist{$student}[$idx{status}];
8371: if ($section eq '') {
8372: $section = 'none';
8373: }
8374: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
8375: if (grep(/^all$/,@{$sections})) {
8376: $secmatch = 1;
8377: } elsif ($$classlist{$student}[$idx{section}] eq '') {
8378: if (grep(/^none$/,@{$sections})) {
8379: $secmatch = 1;
8380: }
8381: } else {
8382: if (grep(/^\Q$section\E$/,@{$sections})) {
8383: $secmatch = 1;
8384: }
8385: }
8386: if (!$secmatch) {
8387: next;
8388: }
8389: }
8390: if (defined($$types{'active'})) {
8391: if ($$classlist{$student}[$idx{status}] eq 'Active') {
8392: push(@{$$users{st}{$student}},'active');
8393: $match = 1;
8394: }
8395: }
8396: if (defined($$types{'previous'})) {
8397: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
8398: push(@{$$users{st}{$student}},'previous');
8399: $match = 1;
8400: }
8401: }
8402: if (defined($$types{'future'})) {
8403: if ($$classlist{$student}[$idx{status}] eq 'Future') {
8404: push(@{$$users{st}{$student}},'future');
8405: $match = 1;
8406: }
8407: }
8408: if ($match) {
8409: push(@{$seclists{$student}},$section);
8410: if (ref($userdata) eq 'HASH') {
8411: $$userdata{$student} = $$classlist{$student};
8412: }
8413: if (ref($statushash) eq 'HASH') {
8414: $statushash->{$student}{'st'}{$section} = $status;
8415: }
8416: }
8417: }
8418: }
8419: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
8420: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
8421: my $now = time;
8422: my %displaystatus = ( previous => 'Expired',
8423: active => 'Active',
8424: future => 'Future',
8425: );
8426: my (%nothide,@possdoms);
8427: if ($hidepriv) {
8428: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
8429: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
8430: if ($user !~ /:/) {
8431: $nothide{join(':',split(/[\@]/,$user))}=1;
8432: } else {
8433: $nothide{$user} = 1;
8434: }
8435: }
8436: my @possdoms = ($cdom);
8437: if ($coursehash{'checkforpriv'}) {
8438: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
8439: }
8440: }
8441: foreach my $person (sort(keys(%coursepersonnel))) {
8442: my $match = 0;
8443: my $secmatch = 0;
8444: my $status;
8445: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
8446: $user =~ s/:$//;
8447: my ($end,$start) = split(/:/,$coursepersonnel{$person});
8448: if ($end == -1 || $start == -1) {
8449: next;
8450: }
8451: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
8452: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
8453: my ($uname,$udom) = split(/:/,$user);
8454: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
8455: if (grep(/^all$/,@{$sections})) {
8456: $secmatch = 1;
8457: } elsif ($usec eq '') {
8458: if (grep(/^none$/,@{$sections})) {
8459: $secmatch = 1;
8460: }
8461: } else {
8462: if (grep(/^\Q$usec\E$/,@{$sections})) {
8463: $secmatch = 1;
8464: }
8465: }
8466: if (!$secmatch) {
8467: next;
8468: }
8469: }
8470: if ($usec eq '') {
8471: $usec = 'none';
8472: }
8473: if ($uname ne '' && $udom ne '') {
8474: if ($hidepriv) {
8475: if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
8476: (!$nothide{$uname.':'.$udom})) {
8477: next;
8478: }
8479: }
8480: if ($end > 0 && $end < $now) {
8481: $status = 'previous';
8482: } elsif ($start > $now) {
8483: $status = 'future';
8484: } else {
8485: $status = 'active';
8486: }
8487: foreach my $type (keys(%{$types})) {
8488: if ($status eq $type) {
8489: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
8490: push(@{$$users{$role}{$user}},$type);
8491: }
8492: $match = 1;
8493: }
8494: }
8495: if (($match) && (ref($userdata) eq 'HASH')) {
8496: if (!exists($$userdata{$uname.':'.$udom})) {
8497: &get_user_info($udom,$uname,\%idx,$userdata);
8498: }
8499: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
8500: push(@{$seclists{$uname.':'.$udom}},$usec);
8501: }
8502: if (ref($statushash) eq 'HASH') {
8503: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
8504: }
8505: }
8506: }
8507: }
8508: }
8509: if (grep(/^ow$/,@{$roles})) {
8510: if ((defined($cdom)) && (defined($cnum))) {
8511: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
8512: if ( defined($csettings{'internal.courseowner'}) ) {
8513: my $owner = $csettings{'internal.courseowner'};
8514: next if ($owner eq '');
8515: my ($ownername,$ownerdom);
8516: if ($owner =~ /^([^:]+):([^:]+)$/) {
8517: $ownername = $1;
8518: $ownerdom = $2;
8519: } else {
8520: $ownername = $owner;
8521: $ownerdom = $cdom;
8522: $owner = $ownername.':'.$ownerdom;
8523: }
8524: @{$$users{'ow'}{$owner}} = 'any';
8525: if (defined($userdata) &&
8526: !exists($$userdata{$owner})) {
8527: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
8528: if (!grep(/^none$/,@{$seclists{$owner}})) {
8529: push(@{$seclists{$owner}},'none');
8530: }
8531: if (ref($statushash) eq 'HASH') {
8532: $statushash->{$owner}{'ow'}{'none'} = 'Any';
8533: }
8534: }
8535: }
8536: }
8537: }
8538: foreach my $user (keys(%seclists)) {
8539: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
8540: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
8541: }
8542: }
8543: return;
8544: }
8545:
8546: sub get_user_info {
8547: my ($udom,$uname,$idx,$userdata) = @_;
8548: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
8549: &plainname($uname,$udom,'lastname');
8550: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
8551: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
8552: my %idhash = &Apache::lonnet::idrget($udom,($uname));
8553: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
8554: return;
8555: }
8556:
8557: ###############################################
8558:
8559: =pod
8560:
8561: =item * &get_user_quota()
8562:
8563: Retrieves quota assigned for storage of portfolio files for a user
8564:
8565: Incoming parameters:
8566: 1. user's username
8567: 2. user's domain
8568:
8569: Returns:
8570: 1. Disk quota (in Mb) assigned to student.
8571: 2. (Optional) Type of setting: custom or default
8572: (individually assigned or default for user's
8573: institutional status).
8574: 3. (Optional) - User's institutional status (e.g., faculty, staff
8575: or student - types as defined in localenroll::inst_usertypes
8576: for user's domain, which determines default quota for user.
8577: 4. (Optional) - Default quota which would apply to the user.
8578:
8579: If a value has been stored in the user's environment,
8580: it will return that, otherwise it returns the maximal default
8581: defined for the user's instituional status(es) in the domain.
8582:
8583: =cut
8584:
8585: ###############################################
8586:
8587:
8588: sub get_user_quota {
8589: my ($uname,$udom) = @_;
8590: my ($quota,$quotatype,$settingstatus,$defquota);
8591: if (!defined($udom)) {
8592: $udom = $env{'user.domain'};
8593: }
8594: if (!defined($uname)) {
8595: $uname = $env{'user.name'};
8596: }
8597: if (($udom eq '' || $uname eq '') ||
8598: ($udom eq 'public') && ($uname eq 'public')) {
8599: $quota = 0;
8600: $quotatype = 'default';
8601: $defquota = 0;
8602: } else {
8603: my $inststatus;
8604: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
8605: $quota = $env{'environment.portfolioquota'};
8606: $inststatus = $env{'environment.inststatus'};
8607: } else {
8608: my %userenv =
8609: &Apache::lonnet::get('environment',['portfolioquota',
8610: 'inststatus'],$udom,$uname);
8611: my ($tmp) = keys(%userenv);
8612: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8613: $quota = $userenv{'portfolioquota'};
8614: $inststatus = $userenv{'inststatus'};
8615: } else {
8616: undef(%userenv);
8617: }
8618: }
8619: ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
8620: if ($quota eq '') {
8621: $quota = $defquota;
8622: $quotatype = 'default';
8623: } else {
8624: $quotatype = 'custom';
8625: }
8626: }
8627: if (wantarray) {
8628: return ($quota,$quotatype,$settingstatus,$defquota);
8629: } else {
8630: return $quota;
8631: }
8632: }
8633:
8634: ###############################################
8635:
8636: =pod
8637:
8638: =item * &default_quota()
8639:
8640: Retrieves default quota assigned for storage of user portfolio files,
8641: given an (optional) user's institutional status.
8642:
8643: Incoming parameters:
8644: 1. domain
8645: 2. (Optional) institutional status(es). This is a : separated list of
8646: status types (e.g., faculty, staff, student etc.)
8647: which apply to the user for whom the default is being retrieved.
8648: If the institutional status string in undefined, the domain
8649: default quota will be returned.
8650:
8651: Returns:
8652: 1. Default disk quota (in Mb) for user portfolios in the domain.
8653: 2. (Optional) institutional type which determined the value of the
8654: default quota.
8655:
8656: If a value has been stored in the domain's configuration db,
8657: it will return that, otherwise it returns 20 (for backwards
8658: compatibility with domains which have not set up a configuration
8659: db file; the original statically defined portfolio quota was 20 Mb).
8660:
8661: If the user's status includes multiple types (e.g., staff and student),
8662: the largest default quota which applies to the user determines the
8663: default quota returned.
8664:
8665: =back
8666:
8667: =cut
8668:
8669: ###############################################
8670:
8671:
8672: sub default_quota {
8673: my ($udom,$inststatus) = @_;
8674: my ($defquota,$settingstatus);
8675: my %quotahash = &Apache::lonnet::get_dom('configuration',
8676: ['quotas'],$udom);
8677: if (ref($quotahash{'quotas'}) eq 'HASH') {
8678: if ($inststatus ne '') {
8679: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
8680: foreach my $item (@statuses) {
8681: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
8682: if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
8683: if ($defquota eq '') {
8684: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
8685: $settingstatus = $item;
8686: } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
8687: $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
8688: $settingstatus = $item;
8689: }
8690: }
8691: } else {
8692: if ($quotahash{'quotas'}{$item} ne '') {
8693: if ($defquota eq '') {
8694: $defquota = $quotahash{'quotas'}{$item};
8695: $settingstatus = $item;
8696: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
8697: $defquota = $quotahash{'quotas'}{$item};
8698: $settingstatus = $item;
8699: }
8700: }
8701: }
8702: }
8703: }
8704: if ($defquota eq '') {
8705: if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
8706: $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
8707: } else {
8708: $defquota = $quotahash{'quotas'}{'default'};
8709: }
8710: $settingstatus = 'default';
8711: }
8712: } else {
8713: $settingstatus = 'default';
8714: $defquota = 20;
8715: }
8716: if (wantarray) {
8717: return ($defquota,$settingstatus);
8718: } else {
8719: return $defquota;
8720: }
8721: }
8722:
8723: sub get_secgrprole_info {
8724: my ($cdom,$cnum,$needroles,$type) = @_;
8725: my %sections_count = &get_sections($cdom,$cnum);
8726: my @sections = (sort {$a <=> $b} keys(%sections_count));
8727: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
8728: my @groups = sort(keys(%curr_groups));
8729: my $allroles = [];
8730: my $rolehash;
8731: my $accesshash = {
8732: active => 'Currently has access',
8733: future => 'Will have future access',
8734: previous => 'Previously had access',
8735: };
8736: if ($needroles) {
8737: $rolehash = {'all' => 'all'};
8738: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
8739: if (&Apache::lonnet::error(%user_roles)) {
8740: undef(%user_roles);
8741: }
8742: foreach my $item (keys(%user_roles)) {
8743: my ($role)=split(/\:/,$item,2);
8744: if ($role eq 'cr') { next; }
8745: if ($role =~ /^cr/) {
8746: $$rolehash{$role} = (split('/',$role))[3];
8747: } else {
8748: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
8749: }
8750: }
8751: foreach my $key (sort(keys(%{$rolehash}))) {
8752: push(@{$allroles},$key);
8753: }
8754: push (@{$allroles},'st');
8755: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
8756: }
8757: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
8758: }
8759:
8760: sub user_picker {
8761: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
8762: my $currdom = $dom;
8763: my %curr_selected = (
8764: srchin => 'dom',
8765: srchby => 'lastname',
8766: );
8767: my $srchterm;
8768: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
8769: if ($srch->{'srchby'} ne '') {
8770: $curr_selected{'srchby'} = $srch->{'srchby'};
8771: }
8772: if ($srch->{'srchin'} ne '') {
8773: $curr_selected{'srchin'} = $srch->{'srchin'};
8774: }
8775: if ($srch->{'srchtype'} ne '') {
8776: $curr_selected{'srchtype'} = $srch->{'srchtype'};
8777: }
8778: if ($srch->{'srchdomain'} ne '') {
8779: $currdom = $srch->{'srchdomain'};
8780: }
8781: $srchterm = $srch->{'srchterm'};
8782: }
8783: my %lt=&Apache::lonlocal::texthash(
8784: 'usr' => 'Search criteria',
8785: 'doma' => 'Domain/institution to search',
8786: 'uname' => 'username',
8787: 'lastname' => 'last name',
8788: 'lastfirst' => 'last name, first name',
8789: 'crs' => 'in this course',
8790: 'dom' => 'in selected LON-CAPA domain',
8791: 'alc' => 'all LON-CAPA',
8792: 'instd' => 'in institutional directory for selected domain',
8793: 'exact' => 'is',
8794: 'contains' => 'contains',
8795: 'begins' => 'begins with',
8796: 'youm' => "You must include some text to search for.",
8797: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
8798: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
8799: 'yomc' => "You must choose a domain when using an institutional directory search.",
8800: 'ymcd' => "You must choose a domain when using a domain search.",
8801: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
8802: 'whse' => "When searching by last,first you must include at least one character in the first name.",
8803: 'thfo' => "The following need to be corrected before the search can be run:",
8804: );
8805: my $domform = &select_dom_form($currdom,'srchdomain',1,1);
8806: my $srchinsel = ' <select name="srchin">';
8807:
8808: my @srchins = ('crs','dom','alc','instd');
8809:
8810: foreach my $option (@srchins) {
8811: # FIXME 'alc' option unavailable until
8812: # loncreateuser::print_user_query_page()
8813: # has been completed.
8814: next if ($option eq 'alc');
8815: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
8816: next if ($option eq 'crs' && !$env{'request.course.id'});
8817: if ($curr_selected{'srchin'} eq $option) {
8818: $srchinsel .= '
8819: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
8820: } else {
8821: $srchinsel .= '
8822: <option value="'.$option.'">'.$lt{$option}.'</option>';
8823: }
8824: }
8825: $srchinsel .= "\n </select>\n";
8826:
8827: my $srchbysel = ' <select name="srchby">';
8828: foreach my $option ('lastname','lastfirst','uname') {
8829: if ($curr_selected{'srchby'} eq $option) {
8830: $srchbysel .= '
8831: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
8832: } else {
8833: $srchbysel .= '
8834: <option value="'.$option.'">'.$lt{$option}.'</option>';
8835: }
8836: }
8837: $srchbysel .= "\n </select>\n";
8838:
8839: my $srchtypesel = ' <select name="srchtype">';
8840: foreach my $option ('begins','contains','exact') {
8841: if ($curr_selected{'srchtype'} eq $option) {
8842: $srchtypesel .= '
8843: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
8844: } else {
8845: $srchtypesel .= '
8846: <option value="'.$option.'">'.$lt{$option}.'</option>';
8847: }
8848: }
8849: $srchtypesel .= "\n </select>\n";
8850:
8851: my ($newuserscript,$new_user_create);
8852: my $context_dom = $env{'request.role.domain'};
8853: if ($context eq 'requestcrs') {
8854: if ($env{'form.coursedom'} ne '') {
8855: $context_dom = $env{'form.coursedom'};
8856: }
8857: }
8858: if ($forcenewuser) {
8859: if (ref($srch) eq 'HASH') {
8860: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
8861: if ($cancreate) {
8862: $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>';
8863: } else {
8864: my $helplink = 'javascript:helpMenu('."'display'".')';
8865: my %usertypetext = (
8866: official => 'institutional',
8867: unofficial => 'non-institutional',
8868: );
8869: $new_user_create = '<p class="LC_warning">'
8870: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
8871: .' '
8872: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
8873: ,'<a href="'.$helplink.'">','</a>')
8874: .'</p><br />';
8875: }
8876: }
8877: }
8878:
8879: $newuserscript = <<"ENDSCRIPT";
8880:
8881: function setSearch(createnew,callingForm) {
8882: if (createnew == 1) {
8883: for (var i=0; i<callingForm.srchby.length; i++) {
8884: if (callingForm.srchby.options[i].value == 'uname') {
8885: callingForm.srchby.selectedIndex = i;
8886: }
8887: }
8888: for (var i=0; i<callingForm.srchin.length; i++) {
8889: if ( callingForm.srchin.options[i].value == 'dom') {
8890: callingForm.srchin.selectedIndex = i;
8891: }
8892: }
8893: for (var i=0; i<callingForm.srchtype.length; i++) {
8894: if (callingForm.srchtype.options[i].value == 'exact') {
8895: callingForm.srchtype.selectedIndex = i;
8896: }
8897: }
8898: for (var i=0; i<callingForm.srchdomain.length; i++) {
8899: if (callingForm.srchdomain.options[i].value == '$context_dom') {
8900: callingForm.srchdomain.selectedIndex = i;
8901: }
8902: }
8903: }
8904: }
8905: ENDSCRIPT
8906:
8907: }
8908:
8909: my $output = <<"END_BLOCK";
8910: <script type="text/javascript">
8911: // <![CDATA[
8912: function validateEntry(callingForm) {
8913:
8914: var checkok = 1;
8915: var srchin;
8916: for (var i=0; i<callingForm.srchin.length; i++) {
8917: if ( callingForm.srchin[i].checked ) {
8918: srchin = callingForm.srchin[i].value;
8919: }
8920: }
8921:
8922: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
8923: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
8924: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
8925: var srchterm = callingForm.srchterm.value;
8926: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
8927: var msg = "";
8928:
8929: if (srchterm == "") {
8930: checkok = 0;
8931: msg += "$lt{'youm'}\\n";
8932: }
8933:
8934: if (srchtype== 'begins') {
8935: if (srchterm.length < 2) {
8936: checkok = 0;
8937: msg += "$lt{'thte'}\\n";
8938: }
8939: }
8940:
8941: if (srchtype== 'contains') {
8942: if (srchterm.length < 3) {
8943: checkok = 0;
8944: msg += "$lt{'thet'}\\n";
8945: }
8946: }
8947: if (srchin == 'instd') {
8948: if (srchdomain == '') {
8949: checkok = 0;
8950: msg += "$lt{'yomc'}\\n";
8951: }
8952: }
8953: if (srchin == 'dom') {
8954: if (srchdomain == '') {
8955: checkok = 0;
8956: msg += "$lt{'ymcd'}\\n";
8957: }
8958: }
8959: if (srchby == 'lastfirst') {
8960: if (srchterm.indexOf(",") == -1) {
8961: checkok = 0;
8962: msg += "$lt{'whus'}\\n";
8963: }
8964: if (srchterm.indexOf(",") == srchterm.length -1) {
8965: checkok = 0;
8966: msg += "$lt{'whse'}\\n";
8967: }
8968: }
8969: if (checkok == 0) {
8970: alert("$lt{'thfo'}\\n"+msg);
8971: return;
8972: }
8973: if (checkok == 1) {
8974: callingForm.submit();
8975: }
8976: }
8977:
8978: $newuserscript
8979:
8980: // ]]>
8981: </script>
8982:
8983: $new_user_create
8984:
8985: END_BLOCK
8986:
8987: $output .= &Apache::lonhtmlcommon::start_pick_box().
8988: &Apache::lonhtmlcommon::row_title($lt{'doma'}).
8989: $domform.
8990: &Apache::lonhtmlcommon::row_closure().
8991: &Apache::lonhtmlcommon::row_title($lt{'usr'}).
8992: $srchbysel.
8993: $srchtypesel.
8994: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
8995: $srchinsel.
8996: &Apache::lonhtmlcommon::row_closure(1).
8997: &Apache::lonhtmlcommon::end_pick_box().
8998: '<br />';
8999: return $output;
9000: }
9001:
9002: sub user_rule_check {
9003: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
9004: my $response;
9005: if (ref($usershash) eq 'HASH') {
9006: foreach my $user (keys(%{$usershash})) {
9007: my ($uname,$udom) = split(/:/,$user);
9008: next if ($udom eq '' || $uname eq '');
9009: my ($id,$newuser);
9010: if (ref($usershash->{$user}) eq 'HASH') {
9011: $newuser = $usershash->{$user}->{'newuser'};
9012: $id = $usershash->{$user}->{'id'};
9013: }
9014: my $inst_response;
9015: if (ref($checks) eq 'HASH') {
9016: if (defined($checks->{'username'})) {
9017: ($inst_response,%{$inst_results->{$user}}) =
9018: &Apache::lonnet::get_instuser($udom,$uname);
9019: } elsif (defined($checks->{'id'})) {
9020: ($inst_response,%{$inst_results->{$user}}) =
9021: &Apache::lonnet::get_instuser($udom,undef,$id);
9022: }
9023: } else {
9024: ($inst_response,%{$inst_results->{$user}}) =
9025: &Apache::lonnet::get_instuser($udom,$uname);
9026: return;
9027: }
9028: if (!$got_rules->{$udom}) {
9029: my %domconfig = &Apache::lonnet::get_dom('configuration',
9030: ['usercreation'],$udom);
9031: if (ref($domconfig{'usercreation'}) eq 'HASH') {
9032: foreach my $item ('username','id') {
9033: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
9034: $$curr_rules{$udom}{$item} =
9035: $domconfig{'usercreation'}{$item.'_rule'};
9036: }
9037: }
9038: }
9039: $got_rules->{$udom} = 1;
9040: }
9041: foreach my $item (keys(%{$checks})) {
9042: if (ref($$curr_rules{$udom}) eq 'HASH') {
9043: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
9044: if (@{$$curr_rules{$udom}{$item}} > 0) {
9045: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
9046: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
9047: if ($rule_check{$rule}) {
9048: $$rulematch{$user}{$item} = $rule;
9049: if ($inst_response eq 'ok') {
9050: if (ref($inst_results) eq 'HASH') {
9051: if (ref($inst_results->{$user}) eq 'HASH') {
9052: if (keys(%{$inst_results->{$user}}) == 0) {
9053: $$alerts{$item}{$udom}{$uname} = 1;
9054: }
9055: }
9056: }
9057: }
9058: last;
9059: }
9060: }
9061: }
9062: }
9063: }
9064: }
9065: }
9066: }
9067: return;
9068: }
9069:
9070: sub user_rule_formats {
9071: my ($domain,$domdesc,$curr_rules,$check) = @_;
9072: my %text = (
9073: 'username' => 'Usernames',
9074: 'id' => 'IDs',
9075: );
9076: my $output;
9077: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
9078: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
9079: if (@{$ruleorder} > 0) {
9080: $output = '<br />'.
9081: &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
9082: '<span class="LC_cusr_emph">','</span>',$domdesc).
9083: ' <ul>';
9084: foreach my $rule (@{$ruleorder}) {
9085: if (ref($curr_rules) eq 'ARRAY') {
9086: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
9087: if (ref($rules->{$rule}) eq 'HASH') {
9088: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
9089: $rules->{$rule}{'desc'}.'</li>';
9090: }
9091: }
9092: }
9093: }
9094: $output .= '</ul>';
9095: }
9096: }
9097: return $output;
9098: }
9099:
9100: sub instrule_disallow_msg {
9101: my ($checkitem,$domdesc,$count,$mode) = @_;
9102: my $response;
9103: my %text = (
9104: item => 'username',
9105: items => 'usernames',
9106: match => 'matches',
9107: do => 'does',
9108: action => 'a username',
9109: one => 'one',
9110: );
9111: if ($count > 1) {
9112: $text{'item'} = 'usernames';
9113: $text{'match'} ='match';
9114: $text{'do'} = 'do';
9115: $text{'action'} = 'usernames',
9116: $text{'one'} = 'ones';
9117: }
9118: if ($checkitem eq 'id') {
9119: $text{'items'} = 'IDs';
9120: $text{'item'} = 'ID';
9121: $text{'action'} = 'an ID';
9122: if ($count > 1) {
9123: $text{'item'} = 'IDs';
9124: $text{'action'} = 'IDs';
9125: }
9126: }
9127: $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 />';
9128: if ($mode eq 'upload') {
9129: if ($checkitem eq 'username') {
9130: $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'}.");
9131: } elsif ($checkitem eq 'id') {
9132: $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.");
9133: }
9134: } elsif ($mode eq 'selfcreate') {
9135: if ($checkitem eq 'id') {
9136: $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.");
9137: }
9138: } else {
9139: if ($checkitem eq 'username') {
9140: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
9141: } elsif ($checkitem eq 'id') {
9142: $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.");
9143: }
9144: }
9145: return $response;
9146: }
9147:
9148: sub personal_data_fieldtitles {
9149: my %fieldtitles = &Apache::lonlocal::texthash (
9150: id => 'Student/Employee ID',
9151: permanentemail => 'E-mail address',
9152: lastname => 'Last Name',
9153: firstname => 'First Name',
9154: middlename => 'Middle Name',
9155: generation => 'Generation',
9156: gen => 'Generation',
9157: inststatus => 'Affiliation',
9158: );
9159: return %fieldtitles;
9160: }
9161:
9162: sub sorted_inst_types {
9163: my ($dom) = @_;
9164: my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
9165: my $othertitle = &mt('All users');
9166: if ($env{'request.course.id'}) {
9167: $othertitle = &mt('Any users');
9168: }
9169: my @types;
9170: if (ref($order) eq 'ARRAY') {
9171: @types = @{$order};
9172: }
9173: if (@types == 0) {
9174: if (ref($usertypes) eq 'HASH') {
9175: @types = sort(keys(%{$usertypes}));
9176: }
9177: }
9178: if (keys(%{$usertypes}) > 0) {
9179: $othertitle = &mt('Other users');
9180: }
9181: return ($othertitle,$usertypes,\@types);
9182: }
9183:
9184: sub get_institutional_codes {
9185: my ($settings,$allcourses,$LC_code) = @_;
9186: # Get complete list of course sections to update
9187: my @currsections = ();
9188: my @currxlists = ();
9189: my $coursecode = $$settings{'internal.coursecode'};
9190:
9191: if ($$settings{'internal.sectionnums'} ne '') {
9192: @currsections = split(/,/,$$settings{'internal.sectionnums'});
9193: }
9194:
9195: if ($$settings{'internal.crosslistings'} ne '') {
9196: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
9197: }
9198:
9199: if (@currxlists > 0) {
9200: foreach (@currxlists) {
9201: if (m/^([^:]+):(\w*)$/) {
9202: unless (grep/^$1$/,@{$allcourses}) {
9203: push @{$allcourses},$1;
9204: $$LC_code{$1} = $2;
9205: }
9206: }
9207: }
9208: }
9209:
9210: if (@currsections > 0) {
9211: foreach (@currsections) {
9212: if (m/^(\w+):(\w*)$/) {
9213: my $sec = $coursecode.$1;
9214: my $lc_sec = $2;
9215: unless (grep/^$sec$/,@{$allcourses}) {
9216: push @{$allcourses},$sec;
9217: $$LC_code{$sec} = $lc_sec;
9218: }
9219: }
9220: }
9221: }
9222: return;
9223: }
9224:
9225: sub get_standard_codeitems {
9226: return ('Year','Semester','Department','Number','Section');
9227: }
9228:
9229: =pod
9230:
9231: =head1 Slot Helpers
9232:
9233: =over 4
9234:
9235: =item * sorted_slots()
9236:
9237: Sorts an array of slot names in order of an optional sort key,
9238: default sort is by slot start time (earliest first).
9239:
9240: Inputs:
9241:
9242: =over 4
9243:
9244: slotsarr - Reference to array of unsorted slot names.
9245:
9246: slots - Reference to hash of hash, where outer hash keys are slot names.
9247:
9248: sortkey - Name of key in inner hash to be sorted on (e.g., starttime).
9249:
9250: =back
9251:
9252: Returns:
9253:
9254: =over 4
9255:
9256: sorted - An array of slot names sorted by a specified sort key
9257: (default sort key is start time of the slot).
9258:
9259: =back
9260:
9261: =cut
9262:
9263:
9264: sub sorted_slots {
9265: my ($slotsarr,$slots,$sortkey) = @_;
9266: if ($sortkey eq '') {
9267: $sortkey = 'starttime';
9268: }
9269: my @sorted;
9270: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
9271: @sorted =
9272: sort {
9273: if (ref($slots->{$a}) && ref($slots->{$b})) {
9274: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
9275: }
9276: if (ref($slots->{$a})) { return -1;}
9277: if (ref($slots->{$b})) { return 1;}
9278: return 0;
9279: } @{$slotsarr};
9280: }
9281: return @sorted;
9282: }
9283:
9284: =pod
9285:
9286: =item * get_future_slots()
9287:
9288: Inputs:
9289:
9290: =over 4
9291:
9292: cnum - course number
9293:
9294: cdom - course domain
9295:
9296: now - current UNIX time
9297:
9298: symb - optional symb
9299:
9300: =back
9301:
9302: Returns:
9303:
9304: =over 4
9305:
9306: sorted_reservable - ref to array of student_schedulable slots currently
9307: reservable, ordered by end date of reservation period.
9308:
9309: reservable_now - ref to hash of student_schedulable slots currently
9310: reservable.
9311:
9312: Keys in inner hash are:
9313: (a) symb: either blank or symb to which slot use is restricted.
9314: (b) endreserve: end date of reservation period.
9315:
9316: sorted_future - ref to array of student_schedulable slots reservable in
9317: the future, ordered by start date of reservation period.
9318:
9319: future_reservable - ref to hash of student_schedulable slots reservable
9320: in the future.
9321:
9322: Keys in inner hash are:
9323: (a) symb: either blank or symb to which slot use is restricted.
9324: (b) startreserve: start date of reservation period.
9325:
9326: =back
9327:
9328: =cut
9329:
9330: sub get_future_slots {
9331: my ($cnum,$cdom,$now,$symb) = @_;
9332: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
9333: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
9334: foreach my $slot (keys(%slots)) {
9335: next unless($slots{$slot}->{'type'} eq 'schedulable_student');
9336: if ($symb) {
9337: next if (($slots{$slot}->{'symb'} ne '') &&
9338: ($slots{$slot}->{'symb'} ne $symb));
9339: }
9340: if (($slots{$slot}->{'starttime'} > $now) &&
9341: ($slots{$slot}->{'endtime'} > $now)) {
9342: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
9343: my $userallowed = 0;
9344: if ($slots{$slot}->{'allowedsections'}) {
9345: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
9346: if (!defined($env{'request.role.sec'})
9347: && grep(/^No section assigned$/,@allowed_sec)) {
9348: $userallowed=1;
9349: } else {
9350: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
9351: $userallowed=1;
9352: }
9353: }
9354: unless ($userallowed) {
9355: if (defined($env{'request.course.groups'})) {
9356: my @groups = split(/:/,$env{'request.course.groups'});
9357: foreach my $group (@groups) {
9358: if (grep(/^\Q$group\E$/,@allowed_sec)) {
9359: $userallowed=1;
9360: last;
9361: }
9362: }
9363: }
9364: }
9365: }
9366: if ($slots{$slot}->{'allowedusers'}) {
9367: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
9368: my $user = $env{'user.name'}.':'.$env{'user.domain'};
9369: if (grep(/^\Q$user\E$/,@allowed_users)) {
9370: $userallowed = 1;
9371: }
9372: }
9373: next unless($userallowed);
9374: }
9375: my $startreserve = $slots{$slot}->{'startreserve'};
9376: my $endreserve = $slots{$slot}->{'endreserve'};
9377: my $symb = $slots{$slot}->{'symb'};
9378: if (($startreserve < $now) &&
9379: (!$endreserve || $endreserve > $now)) {
9380: my $lastres = $endreserve;
9381: if (!$lastres) {
9382: $lastres = $slots{$slot}->{'starttime'};
9383: }
9384: $reservable_now{$slot} = {
9385: symb => $symb,
9386: endreserve => $lastres
9387: };
9388: } elsif (($startreserve > $now) &&
9389: (!$endreserve || $endreserve > $startreserve)) {
9390: $future_reservable{$slot} = {
9391: symb => $symb,
9392: startreserve => $startreserve
9393: };
9394: }
9395: }
9396: }
9397: my @unsorted_reservable = keys(%reservable_now);
9398: if (@unsorted_reservable > 0) {
9399: @sorted_reservable =
9400: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
9401: }
9402: my @unsorted_future = keys(%future_reservable);
9403: if (@unsorted_future > 0) {
9404: @sorted_future =
9405: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
9406: }
9407: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
9408: }
9409:
9410: =pod
9411:
9412: =back
9413:
9414: =head1 HTTP Helpers
9415:
9416: =over 4
9417:
9418: =item * &get_unprocessed_cgi($query,$possible_names)
9419:
9420: Modify the %env hash to contain unprocessed CGI form parameters held in
9421: $query. The parameters listed in $possible_names (an array reference),
9422: will be set in $env{'form.name'} if they do not already exist.
9423:
9424: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
9425: $possible_names is an ref to an array of form element names. As an example:
9426: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
9427: will result in $env{'form.uname'} and $env{'form.udom'} being set.
9428:
9429: =cut
9430:
9431: sub get_unprocessed_cgi {
9432: my ($query,$possible_names)= @_;
9433: # $Apache::lonxml::debug=1;
9434: foreach my $pair (split(/&/,$query)) {
9435: my ($name, $value) = split(/=/,$pair);
9436: $name = &unescape($name);
9437: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
9438: $value =~ tr/+/ /;
9439: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
9440: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
9441: }
9442: }
9443: }
9444:
9445: =pod
9446:
9447: =item * &cacheheader()
9448:
9449: returns cache-controlling header code
9450:
9451: =cut
9452:
9453: sub cacheheader {
9454: unless ($env{'request.method'} eq 'GET') { return ''; }
9455: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
9456: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
9457: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
9458: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
9459: return $output;
9460: }
9461:
9462: =pod
9463:
9464: =item * &no_cache($r)
9465:
9466: specifies header code to not have cache
9467:
9468: =cut
9469:
9470: sub no_cache {
9471: my ($r) = @_;
9472: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
9473: $env{'request.method'} ne 'GET') { return ''; }
9474: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
9475: $r->no_cache(1);
9476: $r->header_out("Expires" => $date);
9477: $r->header_out("Pragma" => "no-cache");
9478: }
9479:
9480: sub content_type {
9481: my ($r,$type,$charset) = @_;
9482: if ($r) {
9483: # Note that printout.pl calls this with undef for $r.
9484: &no_cache($r);
9485: }
9486: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
9487: unless ($charset) {
9488: $charset=&Apache::lonlocal::current_encoding;
9489: }
9490: if ($charset) { $type.='; charset='.$charset; }
9491: if ($r) {
9492: $r->content_type($type);
9493: } else {
9494: print("Content-type: $type\n\n");
9495: }
9496: }
9497:
9498: =pod
9499:
9500: =item * &add_to_env($name,$value)
9501:
9502: adds $name to the %env hash with value
9503: $value, if $name already exists, the entry is converted to an array
9504: reference and $value is added to the array.
9505:
9506: =cut
9507:
9508: sub add_to_env {
9509: my ($name,$value)=@_;
9510: if (defined($env{$name})) {
9511: if (ref($env{$name})) {
9512: #already have multiple values
9513: push(@{ $env{$name} },$value);
9514: } else {
9515: #first time seeing multiple values, convert hash entry to an arrayref
9516: my $first=$env{$name};
9517: undef($env{$name});
9518: push(@{ $env{$name} },$first,$value);
9519: }
9520: } else {
9521: $env{$name}=$value;
9522: }
9523: }
9524:
9525: =pod
9526:
9527: =item * &get_env_multiple($name)
9528:
9529: gets $name from the %env hash, it seemlessly handles the cases where multiple
9530: values may be defined and end up as an array ref.
9531:
9532: returns an array of values
9533:
9534: =cut
9535:
9536: sub get_env_multiple {
9537: my ($name) = @_;
9538: my @values;
9539: if (defined($env{$name})) {
9540: # exists is it an array
9541: if (ref($env{$name})) {
9542: @values=@{ $env{$name} };
9543: } else {
9544: $values[0]=$env{$name};
9545: }
9546: }
9547: return(@values);
9548: }
9549:
9550: sub ask_for_embedded_content {
9551: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
9552: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
9553: %currsubfile,%unused,$rem);
9554: my $counter = 0;
9555: my $numnew = 0;
9556: my $numremref = 0;
9557: my $numinvalid = 0;
9558: my $numpathchg = 0;
9559: my $numexisting = 0;
9560: my $numunused = 0;
9561: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
9562: $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path);
9563: my $heading = &mt('Upload embedded files');
9564: my $buttontext = &mt('Upload');
9565:
9566: my ($navmap,$cdom,$cnum);
9567: if ($env{'request.course.id'}) {
9568: if ($actionurl eq '/adm/dependencies') {
9569: $navmap = Apache::lonnavmaps::navmap->new();
9570: }
9571: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9572: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9573: }
9574: if (($actionurl eq '/adm/portfolio') ||
9575: ($actionurl eq '/adm/coursegrp_portfolio')) {
9576: my $current_path='/';
9577: if ($env{'form.currentpath'}) {
9578: $current_path = $env{'form.currentpath'};
9579: }
9580: if ($actionurl eq '/adm/coursegrp_portfolio') {
9581: $udom = $cdom;
9582: $uname = $cnum;
9583: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
9584: } else {
9585: $udom = $env{'user.domain'};
9586: $uname = $env{'user.name'};
9587: $url = '/userfiles/portfolio';
9588: }
9589: $toplevel = $url.'/';
9590: $url .= $current_path;
9591: $getpropath = 1;
9592: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
9593: ($actionurl eq '/adm/imsimport')) {
9594: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
9595: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
9596: $toplevel = $url;
9597: if ($rest ne '') {
9598: $url .= $rest;
9599: }
9600: } elsif ($actionurl eq '/adm/coursedocs') {
9601: if (ref($args) eq 'HASH') {
9602: $url = $args->{'docs_url'};
9603: $toplevel = $url;
9604: if ($args->{'context'} eq 'paste') {
9605: ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
9606: ($path) =
9607: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
9608: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
9609: $fileloc =~ s{^/}{};
9610: }
9611: }
9612: } elsif ($actionurl eq '/adm/dependencies') {
9613: if ($env{'request.course.id'} ne '') {
9614: if (ref($args) eq 'HASH') {
9615: $url = $args->{'docs_url'};
9616: $title = $args->{'docs_title'};
9617: $toplevel = $url;
9618: unless ($toplevel =~ m{^/}) {
9619: $toplevel = "/$url";
9620: }
9621: ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
9622: if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
9623: $path = $1;
9624: } else {
9625: ($path) =
9626: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
9627: }
9628: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
9629: $fileloc =~ s{^/}{};
9630: ($filename) = ($fileloc =~ m{.+/([^/]+)$});
9631: $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
9632: }
9633: }
9634: } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
9635: $udom = $cdom;
9636: $uname = $cnum;
9637: $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
9638: $toplevel = $url;
9639: $path = $url;
9640: $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
9641: $fileloc =~ s{^/}{};
9642: }
9643: foreach my $file (keys(%{$allfiles})) {
9644: my $embed_file;
9645: if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
9646: $embed_file = $1;
9647: } else {
9648: $embed_file = $file;
9649: }
9650: my $absolutepath;
9651: if ($embed_file =~ m{^\w+://}) {
9652: $newfiles{$embed_file} = 1;
9653: $mapping{$embed_file} = $embed_file;
9654: } else {
9655: if ($embed_file =~ m{^/}) {
9656: $absolutepath = $embed_file;
9657: $embed_file =~ s{^(/+)}{};
9658: }
9659: if ($embed_file =~ m{/}) {
9660: my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
9661: $path = &check_for_traversal($path,$url,$toplevel);
9662: my $item = $fname;
9663: if ($path ne '') {
9664: $item = $path.'/'.$fname;
9665: $subdependencies{$path}{$fname} = 1;
9666: } else {
9667: $dependencies{$item} = 1;
9668: }
9669: if ($absolutepath) {
9670: $mapping{$item} = $absolutepath;
9671: } else {
9672: $mapping{$item} = $embed_file;
9673: }
9674: } else {
9675: $dependencies{$embed_file} = 1;
9676: if ($absolutepath) {
9677: $mapping{$embed_file} = $absolutepath;
9678: } else {
9679: $mapping{$embed_file} = $embed_file;
9680: }
9681: }
9682: }
9683: }
9684: my $dirptr = 16384;
9685: foreach my $path (keys(%subdependencies)) {
9686: $currsubfile{$path} = {};
9687: if (($actionurl eq '/adm/portfolio') ||
9688: ($actionurl eq '/adm/coursegrp_portfolio')) {
9689: my ($sublistref,$listerror) =
9690: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
9691: if (ref($sublistref) eq 'ARRAY') {
9692: foreach my $line (@{$sublistref}) {
9693: my ($file_name,$rest) = split(/\&/,$line,2);
9694: $currsubfile{$path}{$file_name} = 1;
9695: }
9696: }
9697: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
9698: if (opendir(my $dir,$url.'/'.$path)) {
9699: my @subdir_list = grep(!/^\./,readdir($dir));
9700: map {$currsubfile{$path}{$_} = 1;} @subdir_list;
9701: }
9702: } elsif (($actionurl eq '/adm/dependencies') ||
9703: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
9704: ($args->{'context'} eq 'paste')) ||
9705: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
9706: if ($env{'request.course.id'} ne '') {
9707: my $dir;
9708: if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
9709: $dir = $fileloc;
9710: } else {
9711: ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
9712: }
9713: if ($dir ne '') {
9714: my ($sublistref,$listerror) =
9715: &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
9716: if (ref($sublistref) eq 'ARRAY') {
9717: foreach my $line (@{$sublistref}) {
9718: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
9719: undef,$mtime)=split(/\&/,$line,12);
9720: unless (($testdir&$dirptr) ||
9721: ($file_name =~ /^\.\.?$/)) {
9722: $currsubfile{$path}{$file_name} = [$size,$mtime];
9723: }
9724: }
9725: }
9726: }
9727: }
9728: }
9729: foreach my $file (keys(%{$subdependencies{$path}})) {
9730: if (exists($currsubfile{$path}{$file})) {
9731: my $item = $path.'/'.$file;
9732: unless ($mapping{$item} eq $item) {
9733: $pathchanges{$item} = 1;
9734: }
9735: $existing{$item} = 1;
9736: $numexisting ++;
9737: } else {
9738: $newfiles{$path.'/'.$file} = 1;
9739: }
9740: }
9741: if ($actionurl eq '/adm/dependencies') {
9742: foreach my $path (keys(%currsubfile)) {
9743: if (ref($currsubfile{$path}) eq 'HASH') {
9744: foreach my $file (keys(%{$currsubfile{$path}})) {
9745: unless ($subdependencies{$path}{$file}) {
9746: next if (($rem ne '') &&
9747: (($env{"httpref.$rem"."$path/$file"} ne '') ||
9748: (ref($navmap) &&
9749: (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
9750: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
9751: ($navmap->getResourceByUrl($rem."$path/$1")))))));
9752: $unused{$path.'/'.$file} = 1;
9753: }
9754: }
9755: }
9756: }
9757: }
9758: }
9759: my %currfile;
9760: if (($actionurl eq '/adm/portfolio') ||
9761: ($actionurl eq '/adm/coursegrp_portfolio')) {
9762: my ($dirlistref,$listerror) =
9763: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
9764: if (ref($dirlistref) eq 'ARRAY') {
9765: foreach my $line (@{$dirlistref}) {
9766: my ($file_name,$rest) = split(/\&/,$line,2);
9767: $currfile{$file_name} = 1;
9768: }
9769: }
9770: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
9771: if (opendir(my $dir,$url)) {
9772: my @dir_list = grep(!/^\./,readdir($dir));
9773: map {$currfile{$_} = 1;} @dir_list;
9774: }
9775: } elsif (($actionurl eq '/adm/dependencies') ||
9776: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
9777: ($args->{'context'} eq 'paste')) ||
9778: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
9779: if ($env{'request.course.id'} ne '') {
9780: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
9781: if ($dir ne '') {
9782: my ($dirlistref,$listerror) =
9783: &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
9784: if (ref($dirlistref) eq 'ARRAY') {
9785: foreach my $line (@{$dirlistref}) {
9786: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
9787: $size,undef,$mtime)=split(/\&/,$line,12);
9788: unless (($testdir&$dirptr) ||
9789: ($file_name =~ /^\.\.?$/)) {
9790: $currfile{$file_name} = [$size,$mtime];
9791: }
9792: }
9793: }
9794: }
9795: }
9796: }
9797: foreach my $file (keys(%dependencies)) {
9798: if (exists($currfile{$file})) {
9799: unless ($mapping{$file} eq $file) {
9800: $pathchanges{$file} = 1;
9801: }
9802: $existing{$file} = 1;
9803: $numexisting ++;
9804: } else {
9805: $newfiles{$file} = 1;
9806: }
9807: }
9808: foreach my $file (keys(%currfile)) {
9809: unless (($file eq $filename) ||
9810: ($file eq $filename.'.bak') ||
9811: ($dependencies{$file})) {
9812: if ($actionurl eq '/adm/dependencies') {
9813: unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
9814: next if (($rem ne '') &&
9815: (($env{"httpref.$rem".$file} ne '') ||
9816: (ref($navmap) &&
9817: (($navmap->getResourceByUrl($rem.$file) ne '') ||
9818: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
9819: ($navmap->getResourceByUrl($rem.$1)))))));
9820: }
9821: }
9822: $unused{$file} = 1;
9823: }
9824: }
9825: if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
9826: ($args->{'context'} eq 'paste')) {
9827: $counter = scalar(keys(%existing));
9828: $numpathchg = scalar(keys(%pathchanges));
9829: return ($output,$counter,$numpathchg,\%existing);
9830: } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
9831: (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
9832: $counter = scalar(keys(%existing));
9833: $numpathchg = scalar(keys(%pathchanges));
9834: return ($output,$counter,$numpathchg,\%existing,\%mapping);
9835: }
9836: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
9837: if ($actionurl eq '/adm/dependencies') {
9838: next if ($embed_file =~ m{^\w+://});
9839: }
9840: $upload_output .= &start_data_table_row().
9841: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
9842: '<span class="LC_filename">'.$embed_file.'</span>';
9843: unless ($mapping{$embed_file} eq $embed_file) {
9844: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
9845: &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
9846: }
9847: $upload_output .= '</td>';
9848: if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) {
9849: $upload_output.='<td align="right">'.
9850: '<span class="LC_info LC_fontsize_medium">'.
9851: &mt("URL points to web address").'</span>';
9852: $numremref++;
9853: } elsif ($args->{'error_on_invalid_names'}
9854: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
9855: $upload_output.='<td align="right"><span class="LC_warning">'.
9856: &mt('Invalid characters').'</span>';
9857: $numinvalid++;
9858: } else {
9859: $upload_output .= '<td>'.
9860: &embedded_file_element('upload_embedded',$counter,
9861: $embed_file,\%mapping,
9862: $allfiles,$codebase,'upload');
9863: $counter ++;
9864: $numnew ++;
9865: }
9866: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
9867: }
9868: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
9869: if ($actionurl eq '/adm/dependencies') {
9870: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
9871: $modify_output .= &start_data_table_row().
9872: '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
9873: '<img src="'.&icon($embed_file).'" border="0" />'.
9874: ' <span class="LC_filename">'.$embed_file.'</span></a></td>'.
9875: '<td>'.$size.'</td>'.
9876: '<td>'.$mtime.'</td>'.
9877: '<td><label><input type="checkbox" name="mod_upload_dep" '.
9878: 'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
9879: $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
9880: '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
9881: &embedded_file_element('upload_embedded',$counter,
9882: $embed_file,\%mapping,
9883: $allfiles,$codebase,'modify').
9884: '</div></td>'.
9885: &end_data_table_row()."\n";
9886: $counter ++;
9887: } else {
9888: $upload_output .= &start_data_table_row().
9889: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
9890: '<span class="LC_filename">'.$embed_file.'</span></td>'.
9891: '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
9892: &Apache::loncommon::end_data_table_row()."\n";
9893: }
9894: }
9895: my $delidx = $counter;
9896: foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
9897: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
9898: $delete_output .= &start_data_table_row().
9899: '<td><img src="'.&icon($oldfile).'" />'.
9900: ' <span class="LC_filename">'.$oldfile.'</span></td>'.
9901: '<td>'.$size.'</td>'.
9902: '<td>'.$mtime.'</td>'.
9903: '<td><label><input type="checkbox" name="del_upload_dep" '.
9904: ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
9905: &embedded_file_element('upload_embedded',$delidx,
9906: $oldfile,\%mapping,$allfiles,
9907: $codebase,'delete').'</td>'.
9908: &end_data_table_row()."\n";
9909: $numunused ++;
9910: $delidx ++;
9911: }
9912: if ($upload_output) {
9913: $upload_output = &start_data_table().
9914: $upload_output.
9915: &end_data_table()."\n";
9916: }
9917: if ($modify_output) {
9918: $modify_output = &start_data_table().
9919: &start_data_table_header_row().
9920: '<th>'.&mt('File').'</th>'.
9921: '<th>'.&mt('Size (KB)').'</th>'.
9922: '<th>'.&mt('Modified').'</th>'.
9923: '<th>'.&mt('Upload replacement?').'</th>'.
9924: &end_data_table_header_row().
9925: $modify_output.
9926: &end_data_table()."\n";
9927: }
9928: if ($delete_output) {
9929: $delete_output = &start_data_table().
9930: &start_data_table_header_row().
9931: '<th>'.&mt('File').'</th>'.
9932: '<th>'.&mt('Size (KB)').'</th>'.
9933: '<th>'.&mt('Modified').'</th>'.
9934: '<th>'.&mt('Delete?').'</th>'.
9935: &end_data_table_header_row().
9936: $delete_output.
9937: &end_data_table()."\n";
9938: }
9939: my $applies = 0;
9940: if ($numremref) {
9941: $applies ++;
9942: }
9943: if ($numinvalid) {
9944: $applies ++;
9945: }
9946: if ($numexisting) {
9947: $applies ++;
9948: }
9949: if ($counter || $numunused) {
9950: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
9951: ' method="post" enctype="multipart/form-data">'."\n".
9952: $state.'<h3>'.$heading.'</h3>';
9953: if ($actionurl eq '/adm/dependencies') {
9954: if ($numnew) {
9955: $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
9956: '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
9957: $upload_output.'<br />'."\n";
9958: }
9959: if ($numexisting) {
9960: $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
9961: '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
9962: $modify_output.'<br />'."\n";
9963: $buttontext = &mt('Save changes');
9964: }
9965: if ($numunused) {
9966: $output .= '<h4>'.&mt('Unused files').'</h4>'.
9967: '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
9968: $delete_output.'<br />'."\n";
9969: $buttontext = &mt('Save changes');
9970: }
9971: } else {
9972: $output .= $upload_output.'<br />'."\n";
9973: }
9974: $output .= '<input type ="hidden" name="number_embedded_items" value="'.
9975: $counter.'" />'."\n";
9976: if ($actionurl eq '/adm/dependencies') {
9977: $output .= '<input type ="hidden" name="number_newemb_items" value="'.
9978: $numnew.'" />'."\n";
9979: } elsif ($actionurl eq '') {
9980: $output .= '<input type="hidden" name="phase" value="three" />';
9981: }
9982: } elsif ($applies) {
9983: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
9984: if ($applies > 1) {
9985: $output .=
9986: &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
9987: if ($numremref) {
9988: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
9989: }
9990: if ($numinvalid) {
9991: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
9992: }
9993: if ($numexisting) {
9994: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
9995: }
9996: $output .= '</ul><br />';
9997: } elsif ($numremref) {
9998: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
9999: } elsif ($numinvalid) {
10000: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
10001: } elsif ($numexisting) {
10002: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
10003: }
10004: $output .= $upload_output.'<br />';
10005: }
10006: my ($pathchange_output,$chgcount);
10007: $chgcount = $counter;
10008: if (keys(%pathchanges) > 0) {
10009: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
10010: if ($counter) {
10011: $output .= &embedded_file_element('pathchange',$chgcount,
10012: $embed_file,\%mapping,
10013: $allfiles,$codebase,'change');
10014: } else {
10015: $pathchange_output .=
10016: &start_data_table_row().
10017: '<td><input type ="checkbox" name="namechange" value="'.
10018: $chgcount.'" checked="checked" /></td>'.
10019: '<td>'.$mapping{$embed_file}.'</td>'.
10020: '<td>'.$embed_file.
10021: &embedded_file_element('pathchange',$numpathchg,$embed_file,
10022: \%mapping,$allfiles,$codebase,'change').
10023: '</td>'.&end_data_table_row();
10024: }
10025: $numpathchg ++;
10026: $chgcount ++;
10027: }
10028: }
10029: if (($counter) || ($numunused)) {
10030: if ($numpathchg) {
10031: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
10032: $numpathchg.'" />'."\n";
10033: }
10034: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10035: ($actionurl eq '/adm/imsimport')) {
10036: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
10037: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
10038: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
10039: } elsif ($actionurl eq '/adm/dependencies') {
10040: $output .= '<input type="hidden" name="action" value="process_changes" />';
10041: }
10042: $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
10043: } elsif ($numpathchg) {
10044: my %pathchange = ();
10045: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
10046: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10047: $output .= '<p>'.&mt('or').'</p>';
10048: }
10049: }
10050: return ($output,$counter,$numpathchg);
10051: }
10052:
10053: sub embedded_file_element {
10054: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
10055: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
10056: (ref($codebase) eq 'HASH'));
10057: my $output;
10058: if (($context eq 'upload_embedded') && ($type ne 'delete')) {
10059: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
10060: }
10061: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
10062: &escape($embed_file).'" />';
10063: unless (($context eq 'upload_embedded') &&
10064: ($mapping->{$embed_file} eq $embed_file)) {
10065: $output .='
10066: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
10067: }
10068: my $attrib;
10069: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
10070: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
10071: }
10072: $output .=
10073: "\n\t\t".
10074: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
10075: $attrib.'" />';
10076: if (exists($codebase->{$mapping->{$embed_file}})) {
10077: $output .=
10078: "\n\t\t".
10079: '<input name="codebase_'.$num.'" type="hidden" value="'.
10080: &escape($codebase->{$mapping->{$embed_file}}).'" />';
10081: }
10082: return $output;
10083: }
10084:
10085: sub get_dependency_details {
10086: my ($currfile,$currsubfile,$embed_file) = @_;
10087: my ($size,$mtime,$showsize,$showmtime);
10088: if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
10089: if ($embed_file =~ m{/}) {
10090: my ($path,$fname) = split(/\//,$embed_file);
10091: if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
10092: ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
10093: }
10094: } else {
10095: if (ref($currfile->{$embed_file}) eq 'ARRAY') {
10096: ($size,$mtime) = @{$currfile->{$embed_file}};
10097: }
10098: }
10099: $showsize = $size/1024.0;
10100: $showsize = sprintf("%.1f",$showsize);
10101: if ($mtime > 0) {
10102: $showmtime = &Apache::lonlocal::locallocaltime($mtime);
10103: }
10104: }
10105: return ($showsize,$showmtime);
10106: }
10107:
10108: sub ask_embedded_js {
10109: return <<"END";
10110: <script type="text/javascript"">
10111: // <![CDATA[
10112: function toggleBrowse(counter) {
10113: var chkboxid = document.getElementById('mod_upload_dep_'+counter);
10114: var fileid = document.getElementById('embedded_item_'+counter);
10115: var uploaddivid = document.getElementById('moduploaddep_'+counter);
10116: if (chkboxid.checked == true) {
10117: uploaddivid.style.display='block';
10118: } else {
10119: uploaddivid.style.display='none';
10120: fileid.value = '';
10121: }
10122: }
10123: // ]]>
10124: </script>
10125:
10126: END
10127: }
10128:
10129: sub upload_embedded {
10130: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
10131: $current_disk_usage,$hiddenstate,$actionurl) = @_;
10132: my (%pathchange,$output,$modifyform,$footer,$returnflag);
10133: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
10134: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
10135: my $orig_uploaded_filename =
10136: $env{'form.embedded_item_'.$i.'.filename'};
10137: foreach my $type ('orig','ref','attrib','codebase') {
10138: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
10139: $env{'form.embedded_'.$type.'_'.$i} =
10140: &unescape($env{'form.embedded_'.$type.'_'.$i});
10141: }
10142: }
10143: my ($path,$fname) =
10144: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
10145: # no path, whole string is fname
10146: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
10147: $fname = &Apache::lonnet::clean_filename($fname);
10148: # See if there is anything left
10149: next if ($fname eq '');
10150:
10151: # Check if file already exists as a file or directory.
10152: my ($state,$msg);
10153: if ($context eq 'portfolio') {
10154: my $port_path = $dirpath;
10155: if ($group ne '') {
10156: $port_path = "groups/$group/$port_path";
10157: }
10158: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
10159: $fname,$group,'embedded_item_'.$i,
10160: $dir_root,$port_path,$disk_quota,
10161: $current_disk_usage,$uname,$udom);
10162: if ($state eq 'will_exceed_quota'
10163: || $state eq 'file_locked') {
10164: $output .= $msg;
10165: next;
10166: }
10167: } elsif (($context eq 'author') || ($context eq 'testbank')) {
10168: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
10169: if ($state eq 'exists') {
10170: $output .= $msg;
10171: next;
10172: }
10173: }
10174: # Check if extension is valid
10175: if (($fname =~ /\.(\w+)$/) &&
10176: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10177: $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
10178: next;
10179: } elsif (($fname =~ /\.(\w+)$/) &&
10180: (!defined(&Apache::loncommon::fileembstyle($1)))) {
10181: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10182: next;
10183: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10184: $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10185: next;
10186: }
10187: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10188: my $subdir = $path;
10189: $subdir =~ s{/+$}{};
10190: if ($context eq 'portfolio') {
10191: my $result;
10192: if ($state eq 'existingfile') {
10193: $result=
10194: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10195: $dirpath.$env{'form.currentpath'}.$subdir);
10196: } else {
10197: $result=
10198: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10199: $dirpath.
10200: $env{'form.currentpath'}.$subdir);
10201: if ($result !~ m|^/uploaded/|) {
10202: $output .= '<span class="LC_error">'
10203: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10204: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10205: .'</span><br />';
10206: next;
10207: } else {
10208: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10209: $path.$fname.'</span>').'<br />';
10210: }
10211: }
10212: } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
10213: my $extendedsubdir = $dirpath.'/'.$subdir;
10214: $extendedsubdir =~ s{/+$}{};
10215: my $result =
10216: &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
10217: if ($result !~ m|^/uploaded/|) {
10218: $output .= '<span class="LC_error">'
10219: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10220: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10221: .'</span><br />';
10222: next;
10223: } else {
10224: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10225: $path.$fname.'</span>').'<br />';
10226: if ($context eq 'syllabus') {
10227: &Apache::lonnet::make_public_indefinitely($result);
10228: }
10229: }
10230: } else {
10231: # Save the file
10232: my $target = $env{'form.embedded_item_'.$i};
10233: my $fullpath = $dir_root.$dirpath.'/'.$path;
10234: my $dest = $fullpath.$fname;
10235: my $url = $url_root.$dirpath.'/'.$path.$fname;
10236: my @parts=split(/\//,"$dirpath/$path");
10237: my $count;
10238: my $filepath = $dir_root;
10239: foreach my $subdir (@parts) {
10240: $filepath .= "/$subdir";
10241: if (!-e $filepath) {
10242: mkdir($filepath,0770);
10243: }
10244: }
10245: my $fh;
10246: if (!open($fh,'>'.$dest)) {
10247: &Apache::lonnet::logthis('Failed to create '.$dest);
10248: $output .= '<span class="LC_error">'.
10249: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10250: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10251: '</span><br />';
10252: } else {
10253: if (!print $fh $env{'form.embedded_item_'.$i}) {
10254: &Apache::lonnet::logthis('Failed to write to '.$dest);
10255: $output .= '<span class="LC_error">'.
10256: &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10257: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10258: '</span><br />';
10259: } else {
10260: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10261: $url.'</span>').'<br />';
10262: unless ($context eq 'testbank') {
10263: $footer .= &mt('View embedded file: [_1]',
10264: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10265: }
10266: }
10267: close($fh);
10268: }
10269: }
10270: if ($env{'form.embedded_ref_'.$i}) {
10271: $pathchange{$i} = 1;
10272: }
10273: }
10274: if ($output) {
10275: $output = '<p>'.$output.'</p>';
10276: }
10277: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10278: $returnflag = 'ok';
10279: my $numpathchgs = scalar(keys(%pathchange));
10280: if ($numpathchgs > 0) {
10281: if ($context eq 'portfolio') {
10282: $output .= '<p>'.&mt('or').'</p>';
10283: } elsif ($context eq 'testbank') {
10284: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10285: '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10286: $returnflag = 'modify_orightml';
10287: }
10288: }
10289: return ($output.$footer,$returnflag,$numpathchgs);
10290: }
10291:
10292: sub modify_html_form {
10293: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10294: my $end = 0;
10295: my $modifyform;
10296: if ($context eq 'upload_embedded') {
10297: return unless (ref($pathchange) eq 'HASH');
10298: if ($env{'form.number_embedded_items'}) {
10299: $end += $env{'form.number_embedded_items'};
10300: }
10301: if ($env{'form.number_pathchange_items'}) {
10302: $end += $env{'form.number_pathchange_items'};
10303: }
10304: if ($end) {
10305: for (my $i=0; $i<$end; $i++) {
10306: if ($i < $env{'form.number_embedded_items'}) {
10307: next unless($pathchange->{$i});
10308: }
10309: $modifyform .=
10310: &start_data_table_row().
10311: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10312: 'checked="checked" /></td>'.
10313: '<td>'.$env{'form.embedded_ref_'.$i}.
10314: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10315: &escape($env{'form.embedded_ref_'.$i}).'" />'.
10316: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10317: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10318: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10319: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10320: '<td>'.$env{'form.embedded_orig_'.$i}.
10321: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10322: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10323: &end_data_table_row();
10324: }
10325: }
10326: } else {
10327: $modifyform = $pathchgtable;
10328: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10329: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10330: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10331: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10332: }
10333: }
10334: if ($modifyform) {
10335: if ($actionurl eq '/adm/dependencies') {
10336: $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10337: }
10338: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10339: '<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".
10340: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10341: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10342: '</ol></p>'."\n".'<p>'.
10343: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10344: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10345: &start_data_table()."\n".
10346: &start_data_table_header_row().
10347: '<th>'.&mt('Change?').'</th>'.
10348: '<th>'.&mt('Current reference').'</th>'.
10349: '<th>'.&mt('Required reference').'</th>'.
10350: &end_data_table_header_row()."\n".
10351: $modifyform.
10352: &end_data_table().'<br />'."\n".$hiddenstate.
10353: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10354: '</form>'."\n";
10355: }
10356: return;
10357: }
10358:
10359: sub modify_html_refs {
10360: my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
10361: my $container;
10362: if ($context eq 'portfolio') {
10363: $container = $env{'form.container'};
10364: } elsif ($context eq 'coursedoc') {
10365: $container = $env{'form.primaryurl'};
10366: } elsif ($context eq 'manage_dependencies') {
10367: (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10368: $container = "/$container";
10369: } elsif ($context eq 'syllabus') {
10370: $container = $url;
10371: } else {
10372: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10373: }
10374: my (%allfiles,%codebase,$output,$content);
10375: my @changes = &get_env_multiple('form.namechange');
10376: unless ((@changes > 0) || ($context eq 'syllabus')) {
10377: if (wantarray) {
10378: return ('',0,0);
10379: } else {
10380: return;
10381: }
10382: }
10383: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
10384: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10385: unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10386: if (wantarray) {
10387: return ('',0,0);
10388: } else {
10389: return;
10390: }
10391: }
10392: $content = &Apache::lonnet::getfile($container);
10393: if ($content eq '-1') {
10394: if (wantarray) {
10395: return ('',0,0);
10396: } else {
10397: return;
10398: }
10399: }
10400: } else {
10401: unless ($container =~ /^\Q$dir_root\E/) {
10402: if (wantarray) {
10403: return ('',0,0);
10404: } else {
10405: return;
10406: }
10407: }
10408: if (open(my $fh,"<$container")) {
10409: $content = join('', <$fh>);
10410: close($fh);
10411: } else {
10412: if (wantarray) {
10413: return ('',0,0);
10414: } else {
10415: return;
10416: }
10417: }
10418: }
10419: my ($count,$codebasecount) = (0,0);
10420: my $mm = new File::MMagic;
10421: my $mime_type = $mm->checktype_contents($content);
10422: if ($mime_type eq 'text/html') {
10423: my $parse_result =
10424: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
10425: \%codebase,\$content);
10426: if ($parse_result eq 'ok') {
10427: foreach my $i (@changes) {
10428: my $orig = &unescape($env{'form.embedded_orig_'.$i});
10429: my $ref = &unescape($env{'form.embedded_ref_'.$i});
10430: if ($allfiles{$ref}) {
10431: my $newname = $orig;
10432: my ($attrib_regexp,$codebase);
10433: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
10434: if ($attrib_regexp =~ /:/) {
10435: $attrib_regexp =~ s/\:/|/g;
10436: }
10437: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10438: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10439: $count += $numchg;
10440: $allfiles{$newname} = $allfiles{$ref};
10441: }
10442: if ($env{'form.embedded_codebase_'.$i} ne '') {
10443: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
10444: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
10445: $codebasecount ++;
10446: }
10447: }
10448: }
10449: my $skiprewrites;
10450: if ($count || $codebasecount) {
10451: my $saveresult;
10452: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
10453: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10454: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10455: if ($url eq $container) {
10456: my ($fname) = ($container =~ m{/([^/]+)$});
10457: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10458: $count,'<span class="LC_filename">'.
10459: $fname.'</span>').'</p>';
10460: } else {
10461: $output = '<p class="LC_error">'.
10462: &mt('Error: update failed for: [_1].',
10463: '<span class="LC_filename">'.
10464: $container.'</span>').'</p>';
10465: }
10466: if ($context eq 'syllabus') {
10467: unless ($saveresult eq 'ok') {
10468: $skiprewrites = 1;
10469: }
10470: }
10471: } else {
10472: if (open(my $fh,">$container")) {
10473: print $fh $content;
10474: close($fh);
10475: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10476: $count,'<span class="LC_filename">'.
10477: $container.'</span>').'</p>';
10478: } else {
10479: $output = '<p class="LC_error">'.
10480: &mt('Error: could not update [_1].',
10481: '<span class="LC_filename">'.
10482: $container.'</span>').'</p>';
10483: }
10484: }
10485: }
10486: if (($context eq 'syllabus') && (!$skiprewrites)) {
10487: my ($actionurl,$state);
10488: $actionurl = "/public/$udom/$uname/syllabus";
10489: my ($ignore,$num,$numpathchanges,$existing,$mapping) =
10490: &ask_for_embedded_content($actionurl,$state,\%allfiles,
10491: \%codebase,
10492: {'context' => 'rewrites',
10493: 'ignore_remote_references' => 1,});
10494: if (ref($mapping) eq 'HASH') {
10495: my $rewrites = 0;
10496: foreach my $key (keys(%{$mapping})) {
10497: next if ($key =~ m{^https?://});
10498: my $ref = $mapping->{$key};
10499: my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
10500: my $attrib;
10501: if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
10502: $attrib = join('|',@{$allfiles{$mapping->{$key}}});
10503: }
10504: if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10505: my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10506: $rewrites += $numchg;
10507: }
10508: }
10509: if ($rewrites) {
10510: my $saveresult;
10511: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10512: if ($url eq $container) {
10513: my ($fname) = ($container =~ m{/([^/]+)$});
10514: $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
10515: $count,'<span class="LC_filename">'.
10516: $fname.'</span>').'</p>';
10517: } else {
10518: $output .= '<p class="LC_error">'.
10519: &mt('Error: could not update links in [_1].',
10520: '<span class="LC_filename">'.
10521: $container.'</span>').'</p>';
10522:
10523: }
10524: }
10525: }
10526: }
10527: } else {
10528: &logthis('Failed to parse '.$container.
10529: ' to modify references: '.$parse_result);
10530: }
10531: }
10532: if (wantarray) {
10533: return ($output,$count,$codebasecount);
10534: } else {
10535: return $output;
10536: }
10537: }
10538:
10539: sub check_for_existing {
10540: my ($path,$fname,$element) = @_;
10541: my ($state,$msg);
10542: if (-d $path.'/'.$fname) {
10543: $state = 'exists';
10544: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10545: } elsif (-e $path.'/'.$fname) {
10546: $state = 'exists';
10547: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10548: }
10549: if ($state eq 'exists') {
10550: $msg = '<span class="LC_error">'.$msg.'</span><br />';
10551: }
10552: return ($state,$msg);
10553: }
10554:
10555: sub check_for_upload {
10556: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
10557: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
10558: my $filesize = length($env{'form.'.$element});
10559: if (!$filesize) {
10560: my $msg = '<span class="LC_error">'.
10561: &mt('Unable to upload [_1]. (size = [_2] bytes)',
10562: '<span class="LC_filename">'.$fname.'</span>',
10563: $filesize).'<br />'.
10564: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
10565: '</span>';
10566: return ('zero_bytes',$msg);
10567: }
10568: $filesize = $filesize/1000; #express in k (1024?)
10569: my $getpropath = 1;
10570: my ($dirlistref,$listerror) =
10571: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
10572: my $found_file = 0;
10573: my $locked_file = 0;
10574: my @lockers;
10575: my $navmap;
10576: if ($env{'request.course.id'}) {
10577: $navmap = Apache::lonnavmaps::navmap->new();
10578: }
10579: if (ref($dirlistref) eq 'ARRAY') {
10580: foreach my $line (@{$dirlistref}) {
10581: my ($file_name,$rest)=split(/\&/,$line,2);
10582: if ($file_name eq $fname){
10583: $file_name = $path.$file_name;
10584: if ($group ne '') {
10585: $file_name = $group.$file_name;
10586: }
10587: $found_file = 1;
10588: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
10589: foreach my $lock (@lockers) {
10590: if (ref($lock) eq 'ARRAY') {
10591: my ($symb,$crsid) = @{$lock};
10592: if ($crsid eq $env{'request.course.id'}) {
10593: if (ref($navmap)) {
10594: my $res = $navmap->getBySymb($symb);
10595: foreach my $part (@{$res->parts()}) {
10596: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
10597: unless (($slot_status == $res->RESERVED) ||
10598: ($slot_status == $res->RESERVED_LOCATION)) {
10599: $locked_file = 1;
10600: }
10601: }
10602: } else {
10603: $locked_file = 1;
10604: }
10605: } else {
10606: $locked_file = 1;
10607: }
10608: }
10609: }
10610: } else {
10611: my @info = split(/\&/,$rest);
10612: my $currsize = $info[6]/1000;
10613: if ($currsize < $filesize) {
10614: my $extra = $filesize - $currsize;
10615: if (($current_disk_usage + $extra) > $disk_quota) {
10616: my $msg = '<span class="LC_error">'.
10617: &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.',
10618: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
10619: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10620: $disk_quota,$current_disk_usage);
10621: return ('will_exceed_quota',$msg);
10622: }
10623: }
10624: }
10625: }
10626: }
10627: }
10628: if (($current_disk_usage + $filesize) > $disk_quota){
10629: my $msg = '<span class="LC_error">'.
10630: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
10631: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
10632: return ('will_exceed_quota',$msg);
10633: } elsif ($found_file) {
10634: if ($locked_file) {
10635: my $msg = '<span class="LC_error">';
10636: $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>');
10637: $msg .= '</span><br />';
10638: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
10639: return ('file_locked',$msg);
10640: } else {
10641: my $msg = '<span class="LC_error">';
10642: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
10643: $msg .= '</span>';
10644: return ('existingfile',$msg);
10645: }
10646: }
10647: }
10648:
10649: sub check_for_traversal {
10650: my ($path,$url,$toplevel) = @_;
10651: my @parts=split(/\//,$path);
10652: my $cleanpath;
10653: my $fullpath = $url;
10654: for (my $i=0;$i<@parts;$i++) {
10655: next if ($parts[$i] eq '.');
10656: if ($parts[$i] eq '..') {
10657: $fullpath =~ s{([^/]+/)$}{};
10658: } else {
10659: $fullpath .= $parts[$i].'/';
10660: }
10661: }
10662: if ($fullpath =~ /^\Q$url\E(.*)$/) {
10663: $cleanpath = $1;
10664: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
10665: my $curr_toprel = $1;
10666: my @parts = split(/\//,$curr_toprel);
10667: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
10668: my @urlparts = split(/\//,$url_toprel);
10669: my $doubledots;
10670: my $startdiff = -1;
10671: for (my $i=0; $i<@urlparts; $i++) {
10672: if ($startdiff == -1) {
10673: unless ($urlparts[$i] eq $parts[$i]) {
10674: $startdiff = $i;
10675: $doubledots .= '../';
10676: }
10677: } else {
10678: $doubledots .= '../';
10679: }
10680: }
10681: if ($startdiff > -1) {
10682: $cleanpath = $doubledots;
10683: for (my $i=$startdiff; $i<@parts; $i++) {
10684: $cleanpath .= $parts[$i].'/';
10685: }
10686: }
10687: }
10688: $cleanpath =~ s{(/)$}{};
10689: return $cleanpath;
10690: }
10691:
10692: sub is_archive_file {
10693: my ($mimetype) = @_;
10694: if (($mimetype eq 'application/octet-stream') ||
10695: ($mimetype eq 'application/x-stuffit') ||
10696: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
10697: return 1;
10698: }
10699: return;
10700: }
10701:
10702: sub decompress_form {
10703: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
10704: my %lt = &Apache::lonlocal::texthash (
10705: this => 'This file is an archive file.',
10706: camt => 'This file is a Camtasia archive file.',
10707: itsc => 'Its contents are as follows:',
10708: youm => 'You may wish to extract its contents.',
10709: extr => 'Extract contents',
10710: auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
10711: proa => 'Process automatically?',
10712: yes => 'Yes',
10713: no => 'No',
10714: fold => 'Title for folder containing movie',
10715: movi => 'Title for page containing embedded movie',
10716: );
10717: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
10718: my ($is_camtasia,$topdir,%toplevel,@paths);
10719: my $info = &list_archive_contents($fileloc,\@paths);
10720: if (@paths) {
10721: foreach my $path (@paths) {
10722: $path =~ s{^/}{};
10723: if ($path =~ m{^([^/]+)/$}) {
10724: $topdir = $1;
10725: }
10726: if ($path =~ m{^([^/]+)/}) {
10727: $toplevel{$1} = $path;
10728: } else {
10729: $toplevel{$path} = $path;
10730: }
10731: }
10732: }
10733: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
10734: my @camtasia = ("$topdir/","$topdir/index.html",
10735: "$topdir/media/",
10736: "$topdir/media/$topdir.mp4",
10737: "$topdir/media/FirstFrame.png",
10738: "$topdir/media/player.swf",
10739: "$topdir/media/swfobject.js",
10740: "$topdir/media/expressInstall.swf");
10741: my @diffs = &compare_arrays(\@paths,\@camtasia);
10742: if (@diffs == 0) {
10743: $is_camtasia = 1;
10744: }
10745: }
10746: my $output;
10747: if ($is_camtasia) {
10748: $output = <<"ENDCAM";
10749: <script type="text/javascript" language="Javascript">
10750: // <![CDATA[
10751:
10752: function camtasiaToggle() {
10753: for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
10754: if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
10755: if (document.uploaded_decompress.autoextract_camtasia[i].value == 1) {
10756:
10757: document.getElementById('camtasia_titles').style.display='block';
10758: } else {
10759: document.getElementById('camtasia_titles').style.display='none';
10760: }
10761: }
10762: }
10763: return;
10764: }
10765:
10766: // ]]>
10767: </script>
10768: <p>$lt{'camt'}</p>
10769: ENDCAM
10770: } else {
10771: $output = '<p>'.$lt{'this'};
10772: if ($info eq '') {
10773: $output .= ' '.$lt{'youm'}.'</p>'."\n";
10774: } else {
10775: $output .= ' '.$lt{'itsc'}.'</p>'."\n".
10776: '<div><pre>'.$info.'</pre></div>';
10777: }
10778: }
10779: $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
10780: my $duplicates;
10781: my $num = 0;
10782: if (ref($dirlist) eq 'ARRAY') {
10783: foreach my $item (@{$dirlist}) {
10784: if (ref($item) eq 'ARRAY') {
10785: if (exists($toplevel{$item->[0]})) {
10786: $duplicates .=
10787: &start_data_table_row().
10788: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
10789: 'value="0" checked="checked" />'.&mt('No').'</label>'.
10790: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '.
10791: 'value="1" />'.&mt('Yes').'</label>'.
10792: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
10793: '<td>'.$item->[0].'</td>';
10794: if ($item->[2]) {
10795: $duplicates .= '<td>'.&mt('Directory').'</td>';
10796: } else {
10797: $duplicates .= '<td>'.&mt('File').'</td>';
10798: }
10799: $duplicates .= '<td>'.$item->[3].'</td>'.
10800: '<td>'.
10801: &Apache::lonlocal::locallocaltime($item->[4]).
10802: '</td>'.
10803: &end_data_table_row();
10804: $num ++;
10805: }
10806: }
10807: }
10808: }
10809: my $itemcount;
10810: if (@paths > 0) {
10811: $itemcount = scalar(@paths);
10812: } else {
10813: $itemcount = 1;
10814: }
10815: if ($is_camtasia) {
10816: $output .= $lt{'auto'}.'<br />'.
10817: '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
10818: '<input type="radio" name="autoextract_camtasia" value="1" onclick="javascript:camtasiaToggle();" checked="checked" />'.
10819: $lt{'yes'}.'</label> <label>'.
10820: '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
10821: $lt{'no'}.'</label></span><br />'.
10822: '<div id="camtasia_titles" style="display:block">'.
10823: &Apache::lonhtmlcommon::start_pick_box().
10824: &Apache::lonhtmlcommon::row_title($lt{'fold'}).
10825: '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
10826: &Apache::lonhtmlcommon::row_closure().
10827: &Apache::lonhtmlcommon::row_title($lt{'movi'}).
10828: '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
10829: &Apache::lonhtmlcommon::row_closure(1).
10830: &Apache::lonhtmlcommon::end_pick_box().
10831: '</div>';
10832: }
10833: $output .=
10834: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
10835: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
10836: "\n";
10837: if ($duplicates ne '') {
10838: $output .= '<p><span class="LC_warning">'.
10839: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.
10840: &start_data_table().
10841: &start_data_table_header_row().
10842: '<th>'.&mt('Overwrite?').'</th>'.
10843: '<th>'.&mt('Name').'</th>'.
10844: '<th>'.&mt('Type').'</th>'.
10845: '<th>'.&mt('Size').'</th>'.
10846: '<th>'.&mt('Last modified').'</th>'.
10847: &end_data_table_header_row().
10848: $duplicates.
10849: &end_data_table().
10850: '</p>';
10851: }
10852: $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
10853: if (ref($hiddenelements) eq 'HASH') {
10854: foreach my $hidden (sort(keys(%{$hiddenelements}))) {
10855: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
10856: }
10857: }
10858: $output .= <<"END";
10859: <br />
10860: <input type="submit" name="decompress" value="$lt{'extr'}" />
10861: </form>
10862: $noextract
10863: END
10864: return $output;
10865: }
10866:
10867: sub decompression_utility {
10868: my ($program) = @_;
10869: my @utilities = ('tar','gunzip','bunzip2','unzip');
10870: my $location;
10871: if (grep(/^\Q$program\E$/,@utilities)) {
10872: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
10873: '/usr/sbin/') {
10874: if (-x $dir.$program) {
10875: $location = $dir.$program;
10876: last;
10877: }
10878: }
10879: }
10880: return $location;
10881: }
10882:
10883: sub list_archive_contents {
10884: my ($file,$pathsref) = @_;
10885: my (@cmd,$output);
10886: my $needsregexp;
10887: if ($file =~ /\.zip$/) {
10888: @cmd = (&decompression_utility('unzip'),"-l");
10889: $needsregexp = 1;
10890: } elsif (($file =~ m/\.tar\.gz$/) ||
10891: ($file =~ /\.tgz$/)) {
10892: @cmd = (&decompression_utility('tar'),"-ztf");
10893: } elsif ($file =~ /\.tar\.bz2$/) {
10894: @cmd = (&decompression_utility('tar'),"-jtf");
10895: } elsif ($file =~ m|\.tar$|) {
10896: @cmd = (&decompression_utility('tar'),"-tf");
10897: }
10898: if (@cmd) {
10899: undef($!);
10900: undef($@);
10901: if (open(my $fh,"-|", @cmd, $file)) {
10902: while (my $line = <$fh>) {
10903: $output .= $line;
10904: chomp($line);
10905: my $item;
10906: if ($needsregexp) {
10907: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/);
10908: } else {
10909: $item = $line;
10910: }
10911: if ($item ne '') {
10912: unless (grep(/^\Q$item\E$/,@{$pathsref})) {
10913: push(@{$pathsref},$item);
10914: }
10915: }
10916: }
10917: close($fh);
10918: }
10919: }
10920: return $output;
10921: }
10922:
10923: sub decompress_uploaded_file {
10924: my ($file,$dir) = @_;
10925: &Apache::lonnet::appenv({'cgi.file' => $file});
10926: &Apache::lonnet::appenv({'cgi.dir' => $dir});
10927: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
10928: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
10929: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
10930: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
10931: my $decompressed = $env{'cgi.decompressed'};
10932: &Apache::lonnet::delenv('cgi.file');
10933: &Apache::lonnet::delenv('cgi.dir');
10934: &Apache::lonnet::delenv('cgi.decompressed');
10935: return ($decompressed,$result);
10936: }
10937:
10938: sub process_decompression {
10939: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
10940: my ($dir,$error,$warning,$output);
10941: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
10942: $error = &mt('Filename not a supported archive file type.').
10943: '<br />'.&mt('Filename should end with one of: [_1].',
10944: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
10945: } else {
10946: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
10947: if ($docuhome eq 'no_host') {
10948: $error = &mt('Could not determine home server for course.');
10949: } else {
10950: my @ids=&Apache::lonnet::current_machine_ids();
10951: my $currdir = "$dir_root/$destination";
10952: if (grep(/^\Q$docuhome\E$/,@ids)) {
10953: $dir = &LONCAPA::propath($docudom,$docuname).
10954: "$dir_root/$destination";
10955: } else {
10956: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
10957: "$dir_root/$docudom/$docuname/$destination";
10958: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
10959: $error = &mt('Archive file not found.');
10960: }
10961: }
10962: my (@to_overwrite,@to_skip);
10963: if ($env{'form.archive_overwrite_total'} > 0) {
10964: my $total = $env{'form.archive_overwrite_total'};
10965: for (my $i=0; $i<$total; $i++) {
10966: if ($env{'form.archive_overwrite_'.$i} == 1) {
10967: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
10968: } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
10969: push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
10970: }
10971: }
10972: }
10973: my $numskip = scalar(@to_skip);
10974: if (($numskip > 0) &&
10975: ($numskip == $env{'form.archive_itemcount'})) {
10976: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');
10977: } elsif ($dir eq '') {
10978: $error = &mt('Directory containing archive file unavailable.');
10979: } elsif (!$error) {
10980: my ($decompressed,$display);
10981: if ($numskip > 0) {
10982: my $tempdir = time.'_'.$$.int(rand(10000));
10983: mkdir("$dir/$tempdir",0755);
10984: system("mv $dir/$file $dir/$tempdir/$file");
10985: ($decompressed,$display) =
10986: &decompress_uploaded_file($file,"$dir/$tempdir");
10987: foreach my $item (@to_skip) {
10988: if (($item ne '') && ($item !~ /\.\./)) {
10989: if (-f "$dir/$tempdir/$item") {
10990: unlink("$dir/$tempdir/$item");
10991: } elsif (-d "$dir/$tempdir/$item") {
10992: system("rm -rf $dir/$tempdir/$item");
10993: }
10994: }
10995: }
10996: system("mv $dir/$tempdir/* $dir");
10997: rmdir("$dir/$tempdir");
10998: } else {
10999: ($decompressed,$display) =
11000: &decompress_uploaded_file($file,$dir);
11001: }
11002: if ($decompressed eq 'ok') {
11003: $output = '<p class="LC_info">'.
11004: &mt('Files extracted successfully from archive.').
11005: '</p>'."\n";
11006: my ($warning,$result,@contents);
11007: my ($newdirlistref,$newlisterror) =
11008: &Apache::lonnet::dirlist($currdir,$docudom,
11009: $docuname,1);
11010: my (%is_dir,%changes,@newitems);
11011: my $dirptr = 16384;
11012: if (ref($newdirlistref) eq 'ARRAY') {
11013: foreach my $dir_line (@{$newdirlistref}) {
11014: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11015: unless (($item =~ /^\.+$/) || ($item eq $file) ||
11016: ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
11017: push(@newitems,$item);
11018: if ($dirptr&$testdir) {
11019: $is_dir{$item} = 1;
11020: }
11021: $changes{$item} = 1;
11022: }
11023: }
11024: }
11025: if (keys(%changes) > 0) {
11026: foreach my $item (sort(@newitems)) {
11027: if ($changes{$item}) {
11028: push(@contents,$item);
11029: }
11030: }
11031: }
11032: if (@contents > 0) {
11033: my $wantform;
11034: unless ($env{'form.autoextract_camtasia'}) {
11035: $wantform = 1;
11036: }
11037: my (%children,%parent,%dirorder,%titles);
11038: my ($count,$datatable) = &get_extracted($docudom,$docuname,
11039: $currdir,\%is_dir,
11040: \%children,\%parent,
11041: \@contents,\%dirorder,
11042: \%titles,$wantform);
11043: if ($datatable ne '') {
11044: $output .= &archive_options_form('decompressed',$datatable,
11045: $count,$hiddenelem);
11046: my $startcount = 6;
11047: $output .= &archive_javascript($startcount,$count,
11048: \%titles,\%children);
11049: }
11050: if ($env{'form.autoextract_camtasia'}) {
11051: my %displayed;
11052: my $total = 1;
11053: $env{'form.archive_directory'} = [];
11054: foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
11055: my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
11056: $path =~ s{/$}{};
11057: my $item;
11058: if ($path ne '') {
11059: $item = "$path/$titles{$i}";
11060: } else {
11061: $item = $titles{$i};
11062: }
11063: $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
11064: if ($item eq $contents[0]) {
11065: push(@{$env{'form.archive_directory'}},$i);
11066: $env{'form.archive_'.$i} = 'display';
11067: $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
11068: $displayed{'folder'} = $i;
11069: } elsif ($item eq "$contents[0]/index.html") {
11070: $env{'form.archive_'.$i} = 'display';
11071: $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
11072: $displayed{'web'} = $i;
11073: } else {
11074: if ($item eq "$contents[0]/media") {
11075: push(@{$env{'form.archive_directory'}},$i);
11076: }
11077: $env{'form.archive_'.$i} = 'dependency';
11078: }
11079: $total ++;
11080: }
11081: for (my $i=1; $i<$total; $i++) {
11082: next if ($i == $displayed{'web'});
11083: next if ($i == $displayed{'folder'});
11084: $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
11085: }
11086: $env{'form.phase'} = 'decompress_cleanup';
11087: $env{'form.archivedelete'} = 1;
11088: $env{'form.archive_count'} = $total-1;
11089: $output .=
11090: &process_extracted_files('coursedocs',$docudom,
11091: $docuname,$destination,
11092: $dir_root,$hiddenelem);
11093: }
11094: } else {
11095: $warning = &mt('No new items extracted from archive file.');
11096: }
11097: } else {
11098: $output = $display;
11099: $error = &mt('An error occurred during extraction from the archive file.');
11100: }
11101: }
11102: }
11103: }
11104: if ($error) {
11105: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11106: $error.'</p>'."\n";
11107: }
11108: if ($warning) {
11109: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11110: }
11111: return $output;
11112: }
11113:
11114: sub get_extracted {
11115: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
11116: $titles,$wantform) = @_;
11117: my $count = 0;
11118: my $depth = 0;
11119: my $datatable;
11120: my @hierarchy;
11121: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
11122: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
11123: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
11124: foreach my $item (@{$contents}) {
11125: $count ++;
11126: @{$dirorder->{$count}} = @hierarchy;
11127: $titles->{$count} = $item;
11128: &archive_hierarchy($depth,$count,$parent,$children);
11129: if ($wantform) {
11130: $datatable .= &archive_row($is_dir->{$item},$item,
11131: $currdir,$depth,$count);
11132: }
11133: if ($is_dir->{$item}) {
11134: $depth ++;
11135: push(@hierarchy,$count);
11136: $parent->{$depth} = $count;
11137: $datatable .=
11138: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
11139: \$depth,\$count,\@hierarchy,$dirorder,
11140: $children,$parent,$titles,$wantform);
11141: $depth --;
11142: pop(@hierarchy);
11143: }
11144: }
11145: return ($count,$datatable);
11146: }
11147:
11148: sub recurse_extracted_archive {
11149: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
11150: $children,$parent,$titles,$wantform) = @_;
11151: my $result='';
11152: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
11153: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
11154: (ref($dirorder) eq 'HASH')) {
11155: return $result;
11156: }
11157: my $dirptr = 16384;
11158: my ($newdirlistref,$newlisterror) =
11159: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
11160: if (ref($newdirlistref) eq 'ARRAY') {
11161: foreach my $dir_line (@{$newdirlistref}) {
11162: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11163: unless ($item =~ /^\.+$/) {
11164: $$count ++;
11165: @{$dirorder->{$$count}} = @{$hierarchy};
11166: $titles->{$$count} = $item;
11167: &archive_hierarchy($$depth,$$count,$parent,$children);
11168:
11169: my $is_dir;
11170: if ($dirptr&$testdir) {
11171: $is_dir = 1;
11172: }
11173: if ($wantform) {
11174: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
11175: }
11176: if ($is_dir) {
11177: $$depth ++;
11178: push(@{$hierarchy},$$count);
11179: $parent->{$$depth} = $$count;
11180: $result .=
11181: &recurse_extracted_archive("$currdir/$item",$docudom,
11182: $docuname,$depth,$count,
11183: $hierarchy,$dirorder,$children,
11184: $parent,$titles,$wantform);
11185: $$depth --;
11186: pop(@{$hierarchy});
11187: }
11188: }
11189: }
11190: }
11191: return $result;
11192: }
11193:
11194: sub archive_hierarchy {
11195: my ($depth,$count,$parent,$children) =@_;
11196: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
11197: if (exists($parent->{$depth})) {
11198: $children->{$parent->{$depth}} .= $count.':';
11199: }
11200: }
11201: return;
11202: }
11203:
11204: sub archive_row {
11205: my ($is_dir,$item,$currdir,$depth,$count) = @_;
11206: my ($name) = ($item =~ m{([^/]+)$});
11207: my %choices = &Apache::lonlocal::texthash (
11208: 'display' => 'Add as file',
11209: 'dependency' => 'Include as dependency',
11210: 'discard' => 'Discard',
11211: );
11212: if ($is_dir) {
11213: $choices{'display'} = &mt('Add as folder');
11214: }
11215: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
11216: my $offset = 0;
11217: foreach my $action ('display','dependency','discard') {
11218: $offset ++;
11219: if ($action ne 'display') {
11220: $offset ++;
11221: }
11222: $output .= '<td><span class="LC_nobreak">'.
11223: '<label><input type="radio" name="archive_'.$count.
11224: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
11225: my $text = $choices{$action};
11226: if ($is_dir) {
11227: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
11228: if ($action eq 'display') {
11229: $text = &mt('Add as folder');
11230: }
11231: } else {
11232: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
11233:
11234: }
11235: $output .= ' /> '.$choices{$action}.'</label></span>';
11236: if ($action eq 'dependency') {
11237: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
11238: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '.
11239: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
11240: '<option value=""></option>'."\n".
11241: '</select>'."\n".
11242: '</div>';
11243: } elsif ($action eq 'display') {
11244: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11245: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11246: '</div>';
11247: }
11248: $output .= '</td>';
11249: }
11250: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11251: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2);
11252: for (my $i=0; $i<$depth; $i++) {
11253: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11254: }
11255: if ($is_dir) {
11256: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n".
11257: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11258: } else {
11259: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11260: }
11261: $output .= ' '.$name.'</td>'."\n".
11262: &end_data_table_row();
11263: return $output;
11264: }
11265:
11266: sub archive_options_form {
11267: my ($form,$display,$count,$hiddenelem) = @_;
11268: my %lt = &Apache::lonlocal::texthash(
11269: perm => 'Permanently remove archive file?',
11270: hows => 'How should each extracted item be incorporated in the course?',
11271: cont => 'Content actions for all',
11272: addf => 'Add as folder/file',
11273: incd => 'Include as dependency for a displayed file',
11274: disc => 'Discard',
11275: no => 'No',
11276: yes => 'Yes',
11277: save => 'Save',
11278: );
11279: my $output = <<"END";
11280: <form name="$form" method="post" action="">
11281: <p><span class="LC_nobreak">$lt{'perm'}
11282: <label>
11283: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11284: </label>
11285:
11286: <label>
11287: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11288: </span>
11289: </p>
11290: <input type="hidden" name="phase" value="decompress_cleanup" />
11291: <br />$lt{'hows'}
11292: <div class="LC_columnSection">
11293: <fieldset>
11294: <legend>$lt{'cont'}</legend>
11295: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" />
11296: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11297: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11298: </fieldset>
11299: </div>
11300: END
11301: return $output.
11302: &start_data_table()."\n".
11303: $display."\n".
11304: &end_data_table()."\n".
11305: '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11306: $hiddenelem.
11307: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11308: '</form>';
11309: }
11310:
11311: sub archive_javascript {
11312: my ($startcount,$numitems,$titles,$children) = @_;
11313: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11314: my $maintitle = $env{'form.comment'};
11315: my $scripttag = <<START;
11316: <script type="text/javascript">
11317: // <![CDATA[
11318:
11319: function checkAll(form,prefix) {
11320: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$");
11321: for (var i=0; i < form.elements.length; i++) {
11322: var id = form.elements[i].id;
11323: if ((id != '') && (id != undefined)) {
11324: if (idstr.test(id)) {
11325: if (form.elements[i].type == 'radio') {
11326: form.elements[i].checked = true;
11327: var nostart = i-$startcount;
11328: var offset = nostart%7;
11329: var count = (nostart-offset)/7;
11330: dependencyCheck(form,count,offset);
11331: }
11332: }
11333: }
11334: }
11335: }
11336:
11337: function propagateCheck(form,count) {
11338: if (count > 0) {
11339: var startelement = $startcount + ((count-1) * 7);
11340: for (var j=1; j<6; j++) {
11341: if ((j != 2) && (j != 4)) {
11342: var item = startelement + j;
11343: if (form.elements[item].type == 'radio') {
11344: if (form.elements[item].checked) {
11345: containerCheck(form,count,j);
11346: break;
11347: }
11348: }
11349: }
11350: }
11351: }
11352: }
11353:
11354: numitems = $numitems
11355: var titles = new Array(numitems);
11356: var parents = new Array(numitems);
11357: for (var i=0; i<numitems; i++) {
11358: parents[i] = new Array;
11359: }
11360: var maintitle = '$maintitle';
11361:
11362: START
11363:
11364: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
11365: my @contents = split(/:/,$children->{$container});
11366: for (my $i=0; $i<@contents; $i ++) {
11367: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
11368: }
11369: }
11370:
11371: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
11372: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
11373: }
11374:
11375: $scripttag .= <<END;
11376:
11377: function containerCheck(form,count,offset) {
11378: if (count > 0) {
11379: dependencyCheck(form,count,offset);
11380: var item = (offset+$startcount)+7*(count-1);
11381: form.elements[item].checked = true;
11382: if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
11383: if (parents[count].length > 0) {
11384: for (var j=0; j<parents[count].length; j++) {
11385: containerCheck(form,parents[count][j],offset);
11386: }
11387: }
11388: }
11389: }
11390: }
11391:
11392: function dependencyCheck(form,count,offset) {
11393: if (count > 0) {
11394: var chosen = (offset+$startcount)+7*(count-1);
11395: var depitem = $startcount + ((count-1) * 7) + 4;
11396: var currtype = form.elements[depitem].type;
11397: if (form.elements[chosen].value == 'dependency') {
11398: document.getElementById('arc_depon_'+count).style.display='block';
11399: form.elements[depitem].options.length = 0;
11400: form.elements[depitem].options[0] = new Option('Select','',true,true);
11401: for (var i=1; i<=numitems; i++) {
11402: if (i == count) {
11403: continue;
11404: }
11405: var startelement = $startcount + (i-1) * 7;
11406: for (var j=1; j<6; j++) {
11407: if ((j != 2) && (j!= 4)) {
11408: var item = startelement + j;
11409: if (form.elements[item].type == 'radio') {
11410: if (form.elements[item].checked) {
11411: if (form.elements[item].value == 'display') {
11412: var n = form.elements[depitem].options.length;
11413: form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
11414: }
11415: }
11416: }
11417: }
11418: }
11419: }
11420: } else {
11421: document.getElementById('arc_depon_'+count).style.display='none';
11422: form.elements[depitem].options.length = 0;
11423: form.elements[depitem].options[0] = new Option('Select','',true,true);
11424: }
11425: titleCheck(form,count,offset);
11426: }
11427: }
11428:
11429: function propagateSelect(form,count,offset) {
11430: if (count > 0) {
11431: var item = (1+offset+$startcount)+7*(count-1);
11432: var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
11433: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11434: if (parents[count].length > 0) {
11435: for (var j=0; j<parents[count].length; j++) {
11436: containerSelect(form,parents[count][j],offset,picked);
11437: }
11438: }
11439: }
11440: }
11441: }
11442:
11443: function containerSelect(form,count,offset,picked) {
11444: if (count > 0) {
11445: var item = (offset+$startcount)+7*(count-1);
11446: if (form.elements[item].type == 'radio') {
11447: if (form.elements[item].value == 'dependency') {
11448: if (form.elements[item+1].type == 'select-one') {
11449: for (var i=0; i<form.elements[item+1].options.length; i++) {
11450: if (form.elements[item+1].options[i].value == picked) {
11451: form.elements[item+1].selectedIndex = i;
11452: break;
11453: }
11454: }
11455: }
11456: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11457: if (parents[count].length > 0) {
11458: for (var j=0; j<parents[count].length; j++) {
11459: containerSelect(form,parents[count][j],offset,picked);
11460: }
11461: }
11462: }
11463: }
11464: }
11465: }
11466: }
11467:
11468: function titleCheck(form,count,offset) {
11469: if (count > 0) {
11470: var chosen = (offset+$startcount)+7*(count-1);
11471: var depitem = $startcount + ((count-1) * 7) + 2;
11472: var currtype = form.elements[depitem].type;
11473: if (form.elements[chosen].value == 'display') {
11474: document.getElementById('arc_title_'+count).style.display='block';
11475: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
11476: document.getElementById('archive_title_'+count).value=maintitle;
11477: }
11478: } else {
11479: document.getElementById('arc_title_'+count).style.display='none';
11480: if (currtype == 'text') {
11481: document.getElementById('archive_title_'+count).value='';
11482: }
11483: }
11484: }
11485: return;
11486: }
11487:
11488: // ]]>
11489: </script>
11490: END
11491: return $scripttag;
11492: }
11493:
11494: sub process_extracted_files {
11495: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
11496: my $numitems = $env{'form.archive_count'};
11497: return unless ($numitems);
11498: my @ids=&Apache::lonnet::current_machine_ids();
11499: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
11500: %folders,%containers,%mapinner,%prompttofetch);
11501: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11502: if (grep(/^\Q$docuhome\E$/,@ids)) {
11503: $prefix = &LONCAPA::propath($docudom,$docuname);
11504: $pathtocheck = "$dir_root/$destination";
11505: $dir = $dir_root;
11506: $ishome = 1;
11507: } else {
11508: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
11509: $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
11510: $dir = "$dir_root/$docudom/$docuname";
11511: }
11512: my $currdir = "$dir_root/$destination";
11513: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
11514: if ($env{'form.folderpath'}) {
11515: my @items = split('&',$env{'form.folderpath'});
11516: $folders{'0'} = $items[-2];
11517: if ($env{'form.folderpath'} =~ /\:1$/) {
11518: $containers{'0'}='page';
11519: } else {
11520: $containers{'0'}='sequence';
11521: }
11522: }
11523: my @archdirs = &get_env_multiple('form.archive_directory');
11524: if ($numitems) {
11525: for (my $i=1; $i<=$numitems; $i++) {
11526: my $path = $env{'form.archive_content_'.$i};
11527: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
11528: my $item = $1;
11529: $toplevelitems{$item} = $i;
11530: if (grep(/^\Q$i\E$/,@archdirs)) {
11531: $is_dir{$item} = 1;
11532: }
11533: }
11534: }
11535: }
11536: my ($output,%children,%parent,%titles,%dirorder,$result);
11537: if (keys(%toplevelitems) > 0) {
11538: my @contents = sort(keys(%toplevelitems));
11539: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
11540: \%parent,\@contents,\%dirorder,\%titles);
11541: }
11542: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
11543: if ($numitems) {
11544: for (my $i=1; $i<=$numitems; $i++) {
11545: next if ($env{'form.archive_'.$i} eq 'dependency');
11546: my $path = $env{'form.archive_content_'.$i};
11547: if ($path =~ /^\Q$pathtocheck\E/) {
11548: if ($env{'form.archive_'.$i} eq 'discard') {
11549: if ($prefix ne '' && $path ne '') {
11550: if (-e $prefix.$path) {
11551: if ((@archdirs > 0) &&
11552: (grep(/^\Q$i\E$/,@archdirs))) {
11553: $todeletedir{$prefix.$path} = 1;
11554: } else {
11555: $todelete{$prefix.$path} = 1;
11556: }
11557: }
11558: }
11559: } elsif ($env{'form.archive_'.$i} eq 'display') {
11560: my ($docstitle,$title,$url,$outer);
11561: ($title) = ($path =~ m{/([^/]+)$});
11562: $docstitle = $env{'form.archive_title_'.$i};
11563: if ($docstitle eq '') {
11564: $docstitle = $title;
11565: }
11566: $outer = 0;
11567: if (ref($dirorder{$i}) eq 'ARRAY') {
11568: if (@{$dirorder{$i}} > 0) {
11569: foreach my $item (reverse(@{$dirorder{$i}})) {
11570: if ($env{'form.archive_'.$item} eq 'display') {
11571: $outer = $item;
11572: last;
11573: }
11574: }
11575: }
11576: }
11577: my ($errtext,$fatal) =
11578: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
11579: '/'.$folders{$outer}.'.'.
11580: $containers{$outer});
11581: next if ($fatal);
11582: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
11583: if ($context eq 'coursedocs') {
11584: $mapinner{$i} = time;
11585: $folders{$i} = 'default_'.$mapinner{$i};
11586: $containers{$i} = 'sequence';
11587: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11588: $folders{$i}.'.'.$containers{$i};
11589: my $newidx = &LONCAPA::map::getresidx();
11590: $LONCAPA::map::resources[$newidx]=
11591: $docstitle.':'.$url.':false:normal:res';
11592: push(@LONCAPA::map::order,$newidx);
11593: my ($outtext,$errtext) =
11594: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11595: $docuname.'/'.$folders{$outer}.
11596: '.'.$containers{$outer},1,1);
11597: $newseqid{$i} = $newidx;
11598: unless ($errtext) {
11599: $result .= '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
11600: }
11601: }
11602: } else {
11603: if ($context eq 'coursedocs') {
11604: my $newidx=&LONCAPA::map::getresidx();
11605: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11606: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
11607: $title;
11608: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
11609: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
11610: }
11611: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11612: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
11613: }
11614: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11615: system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
11616: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
11617: unless ($ishome) {
11618: my $fetch = "$newdest{$i}/$title";
11619: $fetch =~ s/^\Q$prefix$dir\E//;
11620: $prompttofetch{$fetch} = 1;
11621: }
11622: }
11623: $LONCAPA::map::resources[$newidx]=
11624: $docstitle.':'.$url.':false:normal:res';
11625: push(@LONCAPA::map::order, $newidx);
11626: my ($outtext,$errtext)=
11627: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11628: $docuname.'/'.$folders{$outer}.
11629: '.'.$containers{$outer},1,1);
11630: unless ($errtext) {
11631: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
11632: $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
11633: }
11634: }
11635: }
11636: }
11637: }
11638: } else {
11639: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
11640: }
11641: }
11642: for (my $i=1; $i<=$numitems; $i++) {
11643: next unless ($env{'form.archive_'.$i} eq 'dependency');
11644: my $path = $env{'form.archive_content_'.$i};
11645: if ($path =~ /^\Q$pathtocheck\E/) {
11646: my ($title) = ($path =~ m{/([^/]+)$});
11647: $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
11648: if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
11649: if (ref($dirorder{$i}) eq 'ARRAY') {
11650: my ($itemidx,$fullpath,$relpath);
11651: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
11652: my $container = $dirorder{$referrer{$i}}->[-1];
11653: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
11654: if ($dirorder{$i}->[$j] eq $container) {
11655: $itemidx = $j;
11656: }
11657: }
11658: }
11659: if ($itemidx eq '') {
11660: $itemidx = 0;
11661: }
11662: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
11663: if ($mapinner{$referrer{$i}}) {
11664: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
11665: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11666: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11667: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11668: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11669: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11670: if (!-e $fullpath) {
11671: mkdir($fullpath,0755);
11672: }
11673: }
11674: } else {
11675: last;
11676: }
11677: }
11678: }
11679: } elsif ($newdest{$referrer{$i}}) {
11680: $fullpath = $newdest{$referrer{$i}};
11681: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11682: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
11683: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
11684: last;
11685: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11686: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11687: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11688: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11689: if (!-e $fullpath) {
11690: mkdir($fullpath,0755);
11691: }
11692: }
11693: } else {
11694: last;
11695: }
11696: }
11697: }
11698: if ($fullpath ne '') {
11699: if (-e "$prefix$path") {
11700: system("mv $prefix$path $fullpath/$title");
11701: }
11702: if (-e "$fullpath/$title") {
11703: my $showpath;
11704: if ($relpath ne '') {
11705: $showpath = "$relpath/$title";
11706: } else {
11707: $showpath = "/$title";
11708: }
11709: $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
11710: }
11711: unless ($ishome) {
11712: my $fetch = "$fullpath/$title";
11713: $fetch =~ s/^\Q$prefix$dir\E//;
11714: $prompttofetch{$fetch} = 1;
11715: }
11716: }
11717: }
11718: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
11719: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
11720: $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
11721: }
11722: } else {
11723: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
11724: }
11725: }
11726: if (keys(%todelete)) {
11727: foreach my $key (keys(%todelete)) {
11728: unlink($key);
11729: }
11730: }
11731: if (keys(%todeletedir)) {
11732: foreach my $key (keys(%todeletedir)) {
11733: rmdir($key);
11734: }
11735: }
11736: foreach my $dir (sort(keys(%is_dir))) {
11737: if (($pathtocheck ne '') && ($dir ne '')) {
11738: &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
11739: }
11740: }
11741: if ($result ne '') {
11742: $output .= '<ul>'."\n".
11743: $result."\n".
11744: '</ul>';
11745: }
11746: unless ($ishome) {
11747: my $replicationfail;
11748: foreach my $item (keys(%prompttofetch)) {
11749: my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
11750: unless ($fetchresult eq 'ok') {
11751: $replicationfail .= '<li>'.$item.'</li>'."\n";
11752: }
11753: }
11754: if ($replicationfail) {
11755: $output .= '<p class="LC_error">'.
11756: &mt('Course home server failed to retrieve:').'<ul>'.
11757: $replicationfail.
11758: '</ul></p>';
11759: }
11760: }
11761: } else {
11762: $warning = &mt('No items found in archive.');
11763: }
11764: if ($error) {
11765: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11766: $error.'</p>'."\n";
11767: }
11768: if ($warning) {
11769: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11770: }
11771: return $output;
11772: }
11773:
11774: sub cleanup_empty_dirs {
11775: my ($path) = @_;
11776: if (($path ne '') && (-d $path)) {
11777: if (opendir(my $dirh,$path)) {
11778: my @dircontents = grep(!/^\./,readdir($dirh));
11779: my $numitems = 0;
11780: foreach my $item (@dircontents) {
11781: if (-d "$path/$item") {
11782: &cleanup_empty_dirs("$path/$item");
11783: if (-e "$path/$item") {
11784: $numitems ++;
11785: }
11786: } else {
11787: $numitems ++;
11788: }
11789: }
11790: if ($numitems == 0) {
11791: rmdir($path);
11792: }
11793: closedir($dirh);
11794: }
11795: }
11796: return;
11797: }
11798:
11799: =pod
11800:
11801: =item &get_folder_hierarchy()
11802:
11803: Provides hierarchy of names of folders/sub-folders containing the current
11804: item,
11805:
11806: Inputs: 3
11807: - $navmap - navmaps object
11808:
11809: - $map - url for map (either the trigger itself, or map containing
11810: the resource, which is the trigger).
11811:
11812: - $showitem - 1 => show title for map itself; 0 => do not show.
11813:
11814: Outputs: 1 @pathitems - array of folder/subfolder names.
11815:
11816: =cut
11817:
11818: sub get_folder_hierarchy {
11819: my ($navmap,$map,$showitem) = @_;
11820: my @pathitems;
11821: if (ref($navmap)) {
11822: my $mapres = $navmap->getResourceByUrl($map);
11823: if (ref($mapres)) {
11824: my $pcslist = $mapres->map_hierarchy();
11825: if ($pcslist ne '') {
11826: my @pcs = split(/,/,$pcslist);
11827: foreach my $pc (@pcs) {
11828: if ($pc == 1) {
11829: push(@pathitems,&mt('Main Content'));
11830: } else {
11831: my $res = $navmap->getByMapPc($pc);
11832: if (ref($res)) {
11833: my $title = $res->compTitle();
11834: $title =~ s/\W+/_/g;
11835: if ($title ne '') {
11836: push(@pathitems,$title);
11837: }
11838: }
11839: }
11840: }
11841: }
11842: if ($showitem) {
11843: if ($mapres->{ID} eq '0.0') {
11844: push(@pathitems,&mt('Main Content'));
11845: } else {
11846: my $maptitle = $mapres->compTitle();
11847: $maptitle =~ s/\W+/_/g;
11848: if ($maptitle ne '') {
11849: push(@pathitems,$maptitle);
11850: }
11851: }
11852: }
11853: }
11854: }
11855: return @pathitems;
11856: }
11857:
11858: =pod
11859:
11860: =item * &get_turnedin_filepath()
11861:
11862: Determines path in a user's portfolio file for storage of files uploaded
11863: to a specific essayresponse or dropbox item.
11864:
11865: Inputs: 3 required + 1 optional.
11866: $symb is symb for resource, $uname and $udom are for current user (required).
11867: $caller is optional (can be "submission", if routine is called when storing
11868: an upoaded file when "Submit Answer" button was pressed).
11869:
11870: Returns array containing $path and $multiresp.
11871: $path is path in portfolio. $multiresp is 1 if this resource contains more
11872: than one file upload item. Callers of routine should append partid as a
11873: subdirectory to $path in cases where $multiresp is 1.
11874:
11875: Called by: homework/essayresponse.pm and homework/structuretags.pm
11876:
11877: =cut
11878:
11879: sub get_turnedin_filepath {
11880: my ($symb,$uname,$udom,$caller) = @_;
11881: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
11882: my $turnindir;
11883: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
11884: $turnindir = $userhash{'turnindir'};
11885: my ($path,$multiresp);
11886: if ($turnindir eq '') {
11887: if ($caller eq 'submission') {
11888: $turnindir = &mt('turned in');
11889: $turnindir =~ s/\W+/_/g;
11890: my %newhash = (
11891: 'turnindir' => $turnindir,
11892: );
11893: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
11894: }
11895: }
11896: if ($turnindir ne '') {
11897: $path = '/'.$turnindir.'/';
11898: my ($multipart,$turnin,@pathitems);
11899: my $navmap = Apache::lonnavmaps::navmap->new();
11900: if (defined($navmap)) {
11901: my $mapres = $navmap->getResourceByUrl($map);
11902: if (ref($mapres)) {
11903: my $pcslist = $mapres->map_hierarchy();
11904: if ($pcslist ne '') {
11905: foreach my $pc (split(/,/,$pcslist)) {
11906: my $res = $navmap->getByMapPc($pc);
11907: if (ref($res)) {
11908: my $title = $res->compTitle();
11909: $title =~ s/\W+/_/g;
11910: if ($title ne '') {
11911: push(@pathitems,$title);
11912: }
11913: }
11914: }
11915: }
11916: my $maptitle = $mapres->compTitle();
11917: $maptitle =~ s/\W+/_/g;
11918: if ($maptitle ne '') {
11919: push(@pathitems,$maptitle);
11920: }
11921: unless ($env{'request.state'} eq 'construct') {
11922: my $res = $navmap->getBySymb($symb);
11923: if (ref($res)) {
11924: my $partlist = $res->parts();
11925: my $totaluploads = 0;
11926: if (ref($partlist) eq 'ARRAY') {
11927: foreach my $part (@{$partlist}) {
11928: my @types = $res->responseType($part);
11929: my @ids = $res->responseIds($part);
11930: for (my $i=0; $i < scalar(@ids); $i++) {
11931: if ($types[$i] eq 'essay') {
11932: my $partid = $part.'_'.$ids[$i];
11933: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
11934: $totaluploads ++;
11935: }
11936: }
11937: }
11938: }
11939: if ($totaluploads > 1) {
11940: $multiresp = 1;
11941: }
11942: }
11943: }
11944: }
11945: } else {
11946: return;
11947: }
11948: } else {
11949: return;
11950: }
11951: my $restitle=&Apache::lonnet::gettitle($symb);
11952: $restitle =~ s/\W+/_/g;
11953: if ($restitle eq '') {
11954: $restitle = ($resurl =~ m{/[^/]+$});
11955: if ($restitle eq '') {
11956: $restitle = time;
11957: }
11958: }
11959: push(@pathitems,$restitle);
11960: $path .= join('/',@pathitems);
11961: }
11962: return ($path,$multiresp);
11963: }
11964:
11965: =pod
11966:
11967: =back
11968:
11969: =head1 CSV Upload/Handling functions
11970:
11971: =over 4
11972:
11973: =item * &upfile_store($r)
11974:
11975: Store uploaded file, $r should be the HTTP Request object,
11976: needs $env{'form.upfile'}
11977: returns $datatoken to be put into hidden field
11978:
11979: =cut
11980:
11981: sub upfile_store {
11982: my $r=shift;
11983: $env{'form.upfile'}=~s/\r/\n/gs;
11984: $env{'form.upfile'}=~s/\f/\n/gs;
11985: $env{'form.upfile'}=~s/\n+/\n/gs;
11986: $env{'form.upfile'}=~s/\n+$//gs;
11987:
11988: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
11989: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
11990: {
11991: my $datafile = $r->dir_config('lonDaemons').
11992: '/tmp/'.$datatoken.'.tmp';
11993: if ( open(my $fh,">$datafile") ) {
11994: print $fh $env{'form.upfile'};
11995: close($fh);
11996: }
11997: }
11998: return $datatoken;
11999: }
12000:
12001: =pod
12002:
12003: =item * &load_tmp_file($r)
12004:
12005: Load uploaded file from tmp, $r should be the HTTP Request object,
12006: needs $env{'form.datatoken'},
12007: sets $env{'form.upfile'} to the contents of the file
12008:
12009: =cut
12010:
12011: sub load_tmp_file {
12012: my $r=shift;
12013: my @studentdata=();
12014: {
12015: my $studentfile = $r->dir_config('lonDaemons').
12016: '/tmp/'.$env{'form.datatoken'}.'.tmp';
12017: if ( open(my $fh,"<$studentfile") ) {
12018: @studentdata=<$fh>;
12019: close($fh);
12020: }
12021: }
12022: $env{'form.upfile'}=join('',@studentdata);
12023: }
12024:
12025: =pod
12026:
12027: =item * &upfile_record_sep()
12028:
12029: Separate uploaded file into records
12030: returns array of records,
12031: needs $env{'form.upfile'} and $env{'form.upfiletype'}
12032:
12033: =cut
12034:
12035: sub upfile_record_sep {
12036: if ($env{'form.upfiletype'} eq 'xml') {
12037: } else {
12038: my @records;
12039: foreach my $line (split(/\n/,$env{'form.upfile'})) {
12040: if ($line=~/^\s*$/) { next; }
12041: push(@records,$line);
12042: }
12043: return @records;
12044: }
12045: }
12046:
12047: =pod
12048:
12049: =item * &record_sep($record)
12050:
12051: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
12052:
12053: =cut
12054:
12055: sub takeleft {
12056: my $index=shift;
12057: return substr('0000'.$index,-4,4);
12058: }
12059:
12060: sub record_sep {
12061: my $record=shift;
12062: my %components=();
12063: if ($env{'form.upfiletype'} eq 'xml') {
12064: } elsif ($env{'form.upfiletype'} eq 'space') {
12065: my $i=0;
12066: foreach my $field (split(/\s+/,$record)) {
12067: $field=~s/^(\"|\')//;
12068: $field=~s/(\"|\')$//;
12069: $components{&takeleft($i)}=$field;
12070: $i++;
12071: }
12072: } elsif ($env{'form.upfiletype'} eq 'tab') {
12073: my $i=0;
12074: foreach my $field (split(/\t/,$record)) {
12075: $field=~s/^(\"|\')//;
12076: $field=~s/(\"|\')$//;
12077: $components{&takeleft($i)}=$field;
12078: $i++;
12079: }
12080: } else {
12081: my $separator=',';
12082: if ($env{'form.upfiletype'} eq 'semisv') {
12083: $separator=';';
12084: }
12085: my $i=0;
12086: # the character we are looking for to indicate the end of a quote or a record
12087: my $looking_for=$separator;
12088: # do not add the characters to the fields
12089: my $ignore=0;
12090: # we just encountered a separator (or the beginning of the record)
12091: my $just_found_separator=1;
12092: # store the field we are working on here
12093: my $field='';
12094: # work our way through all characters in record
12095: foreach my $character ($record=~/(.)/g) {
12096: if ($character eq $looking_for) {
12097: if ($character ne $separator) {
12098: # Found the end of a quote, again looking for separator
12099: $looking_for=$separator;
12100: $ignore=1;
12101: } else {
12102: # Found a separator, store away what we got
12103: $components{&takeleft($i)}=$field;
12104: $i++;
12105: $just_found_separator=1;
12106: $ignore=0;
12107: $field='';
12108: }
12109: next;
12110: }
12111: # single or double quotation marks after a separator indicate beginning of a quote
12112: # we are now looking for the end of the quote and need to ignore separators
12113: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
12114: $looking_for=$character;
12115: next;
12116: }
12117: # ignore would be true after we reached the end of a quote
12118: if ($ignore) { next; }
12119: if (($just_found_separator) && ($character=~/\s/)) { next; }
12120: $field.=$character;
12121: $just_found_separator=0;
12122: }
12123: # catch the very last entry, since we never encountered the separator
12124: $components{&takeleft($i)}=$field;
12125: }
12126: return %components;
12127: }
12128:
12129: ######################################################
12130: ######################################################
12131:
12132: =pod
12133:
12134: =item * &upfile_select_html()
12135:
12136: Return HTML code to select a file from the users machine and specify
12137: the file type.
12138:
12139: =cut
12140:
12141: ######################################################
12142: ######################################################
12143: sub upfile_select_html {
12144: my %Types = (
12145: csv => &mt('CSV (comma separated values, spreadsheet)'),
12146: semisv => &mt('Semicolon separated values'),
12147: space => &mt('Space separated'),
12148: tab => &mt('Tabulator separated'),
12149: # xml => &mt('HTML/XML'),
12150: );
12151: my $Str = '<input type="file" name="upfile" size="50" />'.
12152: '<br />'.&mt('Type').': <select name="upfiletype">';
12153: foreach my $type (sort(keys(%Types))) {
12154: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
12155: }
12156: $Str .= "</select>\n";
12157: return $Str;
12158: }
12159:
12160: sub get_samples {
12161: my ($records,$toget) = @_;
12162: my @samples=({});
12163: my $got=0;
12164: foreach my $rec (@$records) {
12165: my %temp = &record_sep($rec);
12166: if (! grep(/\S/, values(%temp))) { next; }
12167: if (%temp) {
12168: $samples[$got]=\%temp;
12169: $got++;
12170: if ($got == $toget) { last; }
12171: }
12172: }
12173: return \@samples;
12174: }
12175:
12176: ######################################################
12177: ######################################################
12178:
12179: =pod
12180:
12181: =item * &csv_print_samples($r,$records)
12182:
12183: Prints a table of sample values from each column uploaded $r is an
12184: Apache Request ref, $records is an arrayref from
12185: &Apache::loncommon::upfile_record_sep
12186:
12187: =cut
12188:
12189: ######################################################
12190: ######################################################
12191: sub csv_print_samples {
12192: my ($r,$records) = @_;
12193: my $samples = &get_samples($records,5);
12194:
12195: $r->print(&mt('Samples').'<br />'.&start_data_table().
12196: &start_data_table_header_row());
12197: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12198: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
12199: $r->print(&end_data_table_header_row());
12200: foreach my $hash (@$samples) {
12201: $r->print(&start_data_table_row());
12202: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12203: $r->print('<td>');
12204: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
12205: $r->print('</td>');
12206: }
12207: $r->print(&end_data_table_row());
12208: }
12209: $r->print(&end_data_table().'<br />'."\n");
12210: }
12211:
12212: ######################################################
12213: ######################################################
12214:
12215: =pod
12216:
12217: =item * &csv_print_select_table($r,$records,$d)
12218:
12219: Prints a table to create associations between values and table columns.
12220:
12221: $r is an Apache Request ref,
12222: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12223: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
12224:
12225: =cut
12226:
12227: ######################################################
12228: ######################################################
12229: sub csv_print_select_table {
12230: my ($r,$records,$d) = @_;
12231: my $i=0;
12232: my $samples = &get_samples($records,1);
12233: $r->print(&mt('Associate columns with student attributes.')."\n".
12234: &start_data_table().&start_data_table_header_row().
12235: '<th>'.&mt('Attribute').'</th>'.
12236: '<th>'.&mt('Column').'</th>'.
12237: &end_data_table_header_row()."\n");
12238: foreach my $array_ref (@$d) {
12239: my ($value,$display,$defaultcol)=@{ $array_ref };
12240: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
12241:
12242: $r->print('<td><select name="f'.$i.'"'.
12243: ' onchange="javascript:flip(this.form,'.$i.');">');
12244: $r->print('<option value="none"></option>');
12245: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12246: $r->print('<option value="'.$sample.'"'.
12247: ($sample eq $defaultcol ? ' selected="selected" ' : '').
12248: '>'.&mt('Column [_1]',($sample+1)).'</option>');
12249: }
12250: $r->print('</select></td>'.&end_data_table_row()."\n");
12251: $i++;
12252: }
12253: $r->print(&end_data_table());
12254: $i--;
12255: return $i;
12256: }
12257:
12258: ######################################################
12259: ######################################################
12260:
12261: =pod
12262:
12263: =item * &csv_samples_select_table($r,$records,$d)
12264:
12265: Prints a table of sample values from the upload and can make associate samples to internal names.
12266:
12267: $r is an Apache Request ref,
12268: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12269: $d is an array of 2 element arrays (internal name, displayed name)
12270:
12271: =cut
12272:
12273: ######################################################
12274: ######################################################
12275: sub csv_samples_select_table {
12276: my ($r,$records,$d) = @_;
12277: my $i=0;
12278: #
12279: my $max_samples = 5;
12280: my $samples = &get_samples($records,$max_samples);
12281: $r->print(&start_data_table().
12282: &start_data_table_header_row().'<th>'.
12283: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12284: &end_data_table_header_row());
12285:
12286: foreach my $key (sort(keys(%{ $samples->[0] }))) {
12287: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12288: ' onchange="javascript:flip(this.form,'.$i.');">');
12289: foreach my $option (@$d) {
12290: my ($value,$display,$defaultcol)=@{ $option };
12291: $r->print('<option value="'.$value.'"'.
12292: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12293: $display.'</option>');
12294: }
12295: $r->print('</select></td><td>');
12296: foreach my $line (0..($max_samples-1)) {
12297: if (defined($samples->[$line]{$key})) {
12298: $r->print($samples->[$line]{$key}."<br />\n");
12299: }
12300: }
12301: $r->print('</td>'.&end_data_table_row());
12302: $i++;
12303: }
12304: $r->print(&end_data_table());
12305: $i--;
12306: return($i);
12307: }
12308:
12309: ######################################################
12310: ######################################################
12311:
12312: =pod
12313:
12314: =item * &clean_excel_name($name)
12315:
12316: Returns a replacement for $name which does not contain any illegal characters.
12317:
12318: =cut
12319:
12320: ######################################################
12321: ######################################################
12322: sub clean_excel_name {
12323: my ($name) = @_;
12324: $name =~ s/[:\*\?\/\\]//g;
12325: if (length($name) > 31) {
12326: $name = substr($name,0,31);
12327: }
12328: return $name;
12329: }
12330:
12331: =pod
12332:
12333: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
12334:
12335: Returns either 1 or undef
12336:
12337: 1 if the part is to be hidden, undef if it is to be shown
12338:
12339: Arguments are:
12340:
12341: $id the id of the part to be checked
12342: $symb, optional the symb of the resource to check
12343: $udom, optional the domain of the user to check for
12344: $uname, optional the username of the user to check for
12345:
12346: =cut
12347:
12348: sub check_if_partid_hidden {
12349: my ($id,$symb,$udom,$uname) = @_;
12350: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
12351: $symb,$udom,$uname);
12352: my $truth=1;
12353: #if the string starts with !, then the list is the list to show not hide
12354: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
12355: my @hiddenlist=split(/,/,$hiddenparts);
12356: foreach my $checkid (@hiddenlist) {
12357: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
12358: }
12359: return !$truth;
12360: }
12361:
12362:
12363: ############################################################
12364: ############################################################
12365:
12366: =pod
12367:
12368: =back
12369:
12370: =head1 cgi-bin script and graphing routines
12371:
12372: =over 4
12373:
12374: =item * &get_cgi_id()
12375:
12376: Inputs: none
12377:
12378: Returns an id which can be used to pass environment variables
12379: to various cgi-bin scripts. These environment variables will
12380: be removed from the users environment after a given time by
12381: the routine &Apache::lonnet::transfer_profile_to_env.
12382:
12383: =cut
12384:
12385: ############################################################
12386: ############################################################
12387: my $uniq=0;
12388: sub get_cgi_id {
12389: $uniq=($uniq+1)%100000;
12390: return (time.'_'.$$.'_'.$uniq);
12391: }
12392:
12393: ############################################################
12394: ############################################################
12395:
12396: =pod
12397:
12398: =item * &DrawBarGraph()
12399:
12400: Facilitates the plotting of data in a (stacked) bar graph.
12401: Puts plot definition data into the users environment in order for
12402: graph.png to plot it. Returns an <img> tag for the plot.
12403: The bars on the plot are labeled '1','2',...,'n'.
12404:
12405: Inputs:
12406:
12407: =over 4
12408:
12409: =item $Title: string, the title of the plot
12410:
12411: =item $xlabel: string, text describing the X-axis of the plot
12412:
12413: =item $ylabel: string, text describing the Y-axis of the plot
12414:
12415: =item $Max: scalar, the maximum Y value to use in the plot
12416: If $Max is < any data point, the graph will not be rendered.
12417:
12418: =item $colors: array ref holding the colors to be used for the data sets when
12419: they are plotted. If undefined, default values will be used.
12420:
12421: =item $labels: array ref holding the labels to use on the x-axis for the bars.
12422:
12423: =item @Values: An array of array references. Each array reference holds data
12424: to be plotted in a stacked bar chart.
12425:
12426: =item If the final element of @Values is a hash reference the key/value
12427: pairs will be added to the graph definition.
12428:
12429: =back
12430:
12431: Returns:
12432:
12433: An <img> tag which references graph.png and the appropriate identifying
12434: information for the plot.
12435:
12436: =cut
12437:
12438: ############################################################
12439: ############################################################
12440: sub DrawBarGraph {
12441: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
12442: #
12443: if (! defined($colors)) {
12444: $colors = ['#33ff00',
12445: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
12446: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
12447: ];
12448: }
12449: my $extra_settings = {};
12450: if (ref($Values[-1]) eq 'HASH') {
12451: $extra_settings = pop(@Values);
12452: }
12453: #
12454: my $identifier = &get_cgi_id();
12455: my $id = 'cgi.'.$identifier;
12456: if (! @Values || ref($Values[0]) ne 'ARRAY') {
12457: return '';
12458: }
12459: #
12460: my @Labels;
12461: if (defined($labels)) {
12462: @Labels = @$labels;
12463: } else {
12464: for (my $i=0;$i<@{$Values[0]};$i++) {
12465: push (@Labels,$i+1);
12466: }
12467: }
12468: #
12469: my $NumBars = scalar(@{$Values[0]});
12470: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
12471: my %ValuesHash;
12472: my $NumSets=1;
12473: foreach my $array (@Values) {
12474: next if (! ref($array));
12475: $ValuesHash{$id.'.data.'.$NumSets++} =
12476: join(',',@$array);
12477: }
12478: #
12479: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
12480: if ($NumBars < 3) {
12481: $width = 120+$NumBars*32;
12482: $xskip = 1;
12483: $bar_width = 30;
12484: } elsif ($NumBars < 5) {
12485: $width = 120+$NumBars*20;
12486: $xskip = 1;
12487: $bar_width = 20;
12488: } elsif ($NumBars < 10) {
12489: $width = 120+$NumBars*15;
12490: $xskip = 1;
12491: $bar_width = 15;
12492: } elsif ($NumBars <= 25) {
12493: $width = 120+$NumBars*11;
12494: $xskip = 5;
12495: $bar_width = 8;
12496: } elsif ($NumBars <= 50) {
12497: $width = 120+$NumBars*8;
12498: $xskip = 5;
12499: $bar_width = 4;
12500: } else {
12501: $width = 120+$NumBars*8;
12502: $xskip = 5;
12503: $bar_width = 4;
12504: }
12505: #
12506: $Max = 1 if ($Max < 1);
12507: if ( int($Max) < $Max ) {
12508: $Max++;
12509: $Max = int($Max);
12510: }
12511: $Title = '' if (! defined($Title));
12512: $xlabel = '' if (! defined($xlabel));
12513: $ylabel = '' if (! defined($ylabel));
12514: $ValuesHash{$id.'.title'} = &escape($Title);
12515: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
12516: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
12517: $ValuesHash{$id.'.y_max_value'} = $Max;
12518: $ValuesHash{$id.'.NumBars'} = $NumBars;
12519: $ValuesHash{$id.'.NumSets'} = $NumSets;
12520: $ValuesHash{$id.'.PlotType'} = 'bar';
12521: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
12522: $ValuesHash{$id.'.height'} = $height;
12523: $ValuesHash{$id.'.width'} = $width;
12524: $ValuesHash{$id.'.xskip'} = $xskip;
12525: $ValuesHash{$id.'.bar_width'} = $bar_width;
12526: $ValuesHash{$id.'.labels'} = join(',',@Labels);
12527: #
12528: # Deal with other parameters
12529: while (my ($key,$value) = each(%$extra_settings)) {
12530: $ValuesHash{$id.'.'.$key} = $value;
12531: }
12532: #
12533: &Apache::lonnet::appenv(\%ValuesHash);
12534: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12535: }
12536:
12537: ############################################################
12538: ############################################################
12539:
12540: =pod
12541:
12542: =item * &DrawXYGraph()
12543:
12544: Facilitates the plotting of data in an XY graph.
12545: Puts plot definition data into the users environment in order for
12546: graph.png to plot it. Returns an <img> tag for the plot.
12547:
12548: Inputs:
12549:
12550: =over 4
12551:
12552: =item $Title: string, the title of the plot
12553:
12554: =item $xlabel: string, text describing the X-axis of the plot
12555:
12556: =item $ylabel: string, text describing the Y-axis of the plot
12557:
12558: =item $Max: scalar, the maximum Y value to use in the plot
12559: If $Max is < any data point, the graph will not be rendered.
12560:
12561: =item $colors: Array ref containing the hex color codes for the data to be
12562: plotted in. If undefined, default values will be used.
12563:
12564: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12565:
12566: =item $Ydata: Array ref containing Array refs.
12567: Each of the contained arrays will be plotted as a separate curve.
12568:
12569: =item %Values: hash indicating or overriding any default values which are
12570: passed to graph.png.
12571: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12572:
12573: =back
12574:
12575: Returns:
12576:
12577: An <img> tag which references graph.png and the appropriate identifying
12578: information for the plot.
12579:
12580: =cut
12581:
12582: ############################################################
12583: ############################################################
12584: sub DrawXYGraph {
12585: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
12586: #
12587: # Create the identifier for the graph
12588: my $identifier = &get_cgi_id();
12589: my $id = 'cgi.'.$identifier;
12590: #
12591: $Title = '' if (! defined($Title));
12592: $xlabel = '' if (! defined($xlabel));
12593: $ylabel = '' if (! defined($ylabel));
12594: my %ValuesHash =
12595: (
12596: $id.'.title' => &escape($Title),
12597: $id.'.xlabel' => &escape($xlabel),
12598: $id.'.ylabel' => &escape($ylabel),
12599: $id.'.y_max_value'=> $Max,
12600: $id.'.labels' => join(',',@$Xlabels),
12601: $id.'.PlotType' => 'XY',
12602: );
12603: #
12604: if (defined($colors) && ref($colors) eq 'ARRAY') {
12605: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
12606: }
12607: #
12608: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
12609: return '';
12610: }
12611: my $NumSets=1;
12612: foreach my $array (@{$Ydata}){
12613: next if (! ref($array));
12614: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12615: }
12616: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
12617: #
12618: # Deal with other parameters
12619: while (my ($key,$value) = each(%Values)) {
12620: $ValuesHash{$id.'.'.$key} = $value;
12621: }
12622: #
12623: &Apache::lonnet::appenv(\%ValuesHash);
12624: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12625: }
12626:
12627: ############################################################
12628: ############################################################
12629:
12630: =pod
12631:
12632: =item * &DrawXYYGraph()
12633:
12634: Facilitates the plotting of data in an XY graph with two Y axes.
12635: Puts plot definition data into the users environment in order for
12636: graph.png to plot it. Returns an <img> tag for the plot.
12637:
12638: Inputs:
12639:
12640: =over 4
12641:
12642: =item $Title: string, the title of the plot
12643:
12644: =item $xlabel: string, text describing the X-axis of the plot
12645:
12646: =item $ylabel: string, text describing the Y-axis of the plot
12647:
12648: =item $colors: Array ref containing the hex color codes for the data to be
12649: plotted in. If undefined, default values will be used.
12650:
12651: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12652:
12653: =item $Ydata1: The first data set
12654:
12655: =item $Min1: The minimum value of the left Y-axis
12656:
12657: =item $Max1: The maximum value of the left Y-axis
12658:
12659: =item $Ydata2: The second data set
12660:
12661: =item $Min2: The minimum value of the right Y-axis
12662:
12663: =item $Max2: The maximum value of the left Y-axis
12664:
12665: =item %Values: hash indicating or overriding any default values which are
12666: passed to graph.png.
12667: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12668:
12669: =back
12670:
12671: Returns:
12672:
12673: An <img> tag which references graph.png and the appropriate identifying
12674: information for the plot.
12675:
12676: =cut
12677:
12678: ############################################################
12679: ############################################################
12680: sub DrawXYYGraph {
12681: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
12682: $Ydata2,$Min2,$Max2,%Values)=@_;
12683: #
12684: # Create the identifier for the graph
12685: my $identifier = &get_cgi_id();
12686: my $id = 'cgi.'.$identifier;
12687: #
12688: $Title = '' if (! defined($Title));
12689: $xlabel = '' if (! defined($xlabel));
12690: $ylabel = '' if (! defined($ylabel));
12691: my %ValuesHash =
12692: (
12693: $id.'.title' => &escape($Title),
12694: $id.'.xlabel' => &escape($xlabel),
12695: $id.'.ylabel' => &escape($ylabel),
12696: $id.'.labels' => join(',',@$Xlabels),
12697: $id.'.PlotType' => 'XY',
12698: $id.'.NumSets' => 2,
12699: $id.'.two_axes' => 1,
12700: $id.'.y1_max_value' => $Max1,
12701: $id.'.y1_min_value' => $Min1,
12702: $id.'.y2_max_value' => $Max2,
12703: $id.'.y2_min_value' => $Min2,
12704: );
12705: #
12706: if (defined($colors) && ref($colors) eq 'ARRAY') {
12707: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
12708: }
12709: #
12710: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
12711: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
12712: return '';
12713: }
12714: my $NumSets=1;
12715: foreach my $array ($Ydata1,$Ydata2){
12716: next if (! ref($array));
12717: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12718: }
12719: #
12720: # Deal with other parameters
12721: while (my ($key,$value) = each(%Values)) {
12722: $ValuesHash{$id.'.'.$key} = $value;
12723: }
12724: #
12725: &Apache::lonnet::appenv(\%ValuesHash);
12726: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12727: }
12728:
12729: ############################################################
12730: ############################################################
12731:
12732: =pod
12733:
12734: =back
12735:
12736: =head1 Statistics helper routines?
12737:
12738: Bad place for them but what the hell.
12739:
12740: =over 4
12741:
12742: =item * &chartlink()
12743:
12744: Returns a link to the chart for a specific student.
12745:
12746: Inputs:
12747:
12748: =over 4
12749:
12750: =item $linktext: The text of the link
12751:
12752: =item $sname: The students username
12753:
12754: =item $sdomain: The students domain
12755:
12756: =back
12757:
12758: =back
12759:
12760: =cut
12761:
12762: ############################################################
12763: ############################################################
12764: sub chartlink {
12765: my ($linktext, $sname, $sdomain) = @_;
12766: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
12767: '&SelectedStudent='.&escape($sname.':'.$sdomain).
12768: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
12769: '">'.$linktext.'</a>';
12770: }
12771:
12772: #######################################################
12773: #######################################################
12774:
12775: =pod
12776:
12777: =head1 Course Environment Routines
12778:
12779: =over 4
12780:
12781: =item * &restore_course_settings()
12782:
12783: =item * &store_course_settings()
12784:
12785: Restores/Store indicated form parameters from the course environment.
12786: Will not overwrite existing values of the form parameters.
12787:
12788: Inputs:
12789: a scalar describing the data (e.g. 'chart', 'problem_analysis')
12790:
12791: a hash ref describing the data to be stored. For example:
12792:
12793: %Save_Parameters = ('Status' => 'scalar',
12794: 'chartoutputmode' => 'scalar',
12795: 'chartoutputdata' => 'scalar',
12796: 'Section' => 'array',
12797: 'Group' => 'array',
12798: 'StudentData' => 'array',
12799: 'Maps' => 'array');
12800:
12801: Returns: both routines return nothing
12802:
12803: =back
12804:
12805: =cut
12806:
12807: #######################################################
12808: #######################################################
12809: sub store_course_settings {
12810: return &store_settings($env{'request.course.id'},@_);
12811: }
12812:
12813: sub store_settings {
12814: # save to the environment
12815: # appenv the same items, just to be safe
12816: my $udom = $env{'user.domain'};
12817: my $uname = $env{'user.name'};
12818: my ($context,$prefix,$Settings) = @_;
12819: my %SaveHash;
12820: my %AppHash;
12821: while (my ($setting,$type) = each(%$Settings)) {
12822: my $basename = join('.','internal',$context,$prefix,$setting);
12823: my $envname = 'environment.'.$basename;
12824: if (exists($env{'form.'.$setting})) {
12825: # Save this value away
12826: if ($type eq 'scalar' &&
12827: (! exists($env{$envname}) ||
12828: $env{$envname} ne $env{'form.'.$setting})) {
12829: $SaveHash{$basename} = $env{'form.'.$setting};
12830: $AppHash{$envname} = $env{'form.'.$setting};
12831: } elsif ($type eq 'array') {
12832: my $stored_form;
12833: if (ref($env{'form.'.$setting})) {
12834: $stored_form = join(',',
12835: map {
12836: &escape($_);
12837: } sort(@{$env{'form.'.$setting}}));
12838: } else {
12839: $stored_form =
12840: &escape($env{'form.'.$setting});
12841: }
12842: # Determine if the array contents are the same.
12843: if ($stored_form ne $env{$envname}) {
12844: $SaveHash{$basename} = $stored_form;
12845: $AppHash{$envname} = $stored_form;
12846: }
12847: }
12848: }
12849: }
12850: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
12851: $udom,$uname);
12852: if ($put_result !~ /^(ok|delayed)/) {
12853: &Apache::lonnet::logthis('unable to save form parameters, '.
12854: 'got error:'.$put_result);
12855: }
12856: # Make sure these settings stick around in this session, too
12857: &Apache::lonnet::appenv(\%AppHash);
12858: return;
12859: }
12860:
12861: sub restore_course_settings {
12862: return &restore_settings($env{'request.course.id'},@_);
12863: }
12864:
12865: sub restore_settings {
12866: my ($context,$prefix,$Settings) = @_;
12867: while (my ($setting,$type) = each(%$Settings)) {
12868: next if (exists($env{'form.'.$setting}));
12869: my $envname = 'environment.internal.'.$context.'.'.$prefix.
12870: '.'.$setting;
12871: if (exists($env{$envname})) {
12872: if ($type eq 'scalar') {
12873: $env{'form.'.$setting} = $env{$envname};
12874: } elsif ($type eq 'array') {
12875: $env{'form.'.$setting} = [
12876: map {
12877: &unescape($_);
12878: } split(',',$env{$envname})
12879: ];
12880: }
12881: }
12882: }
12883: }
12884:
12885: #######################################################
12886: #######################################################
12887:
12888: =pod
12889:
12890: =head1 Domain E-mail Routines
12891:
12892: =over 4
12893:
12894: =item * &build_recipient_list()
12895:
12896: Build recipient lists for five types of e-mail:
12897: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
12898: (d) Help requests, (e) Course requests needing approval, generated by
12899: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
12900: loncoursequeueadmin.pm respectively.
12901:
12902: Inputs:
12903: defmail (scalar - email address of default recipient),
12904: mailing type (scalar - errormail, packagesmail, or helpdeskmail),
12905: defdom (domain for which to retrieve configuration settings),
12906: origmail (scalar - email address of recipient from loncapa.conf,
12907: i.e., predates configuration by DC via domainprefs.pm
12908:
12909: Returns: comma separated list of addresses to which to send e-mail.
12910:
12911: =back
12912:
12913: =cut
12914:
12915: ############################################################
12916: ############################################################
12917: sub build_recipient_list {
12918: my ($defmail,$mailing,$defdom,$origmail) = @_;
12919: my @recipients;
12920: my $otheremails;
12921: my %domconfig =
12922: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
12923: if (ref($domconfig{'contacts'}) eq 'HASH') {
12924: if (exists($domconfig{'contacts'}{$mailing})) {
12925: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
12926: my @contacts = ('adminemail','supportemail');
12927: foreach my $item (@contacts) {
12928: if ($domconfig{'contacts'}{$mailing}{$item}) {
12929: my $addr = $domconfig{'contacts'}{$item};
12930: if (!grep(/^\Q$addr\E$/,@recipients)) {
12931: push(@recipients,$addr);
12932: }
12933: }
12934: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
12935: }
12936: }
12937: } elsif ($origmail ne '') {
12938: push(@recipients,$origmail);
12939: }
12940: } elsif ($origmail ne '') {
12941: push(@recipients,$origmail);
12942: }
12943: if (defined($defmail)) {
12944: if ($defmail ne '') {
12945: push(@recipients,$defmail);
12946: }
12947: }
12948: if ($otheremails) {
12949: my @others;
12950: if ($otheremails =~ /,/) {
12951: @others = split(/,/,$otheremails);
12952: } else {
12953: push(@others,$otheremails);
12954: }
12955: foreach my $addr (@others) {
12956: if (!grep(/^\Q$addr\E$/,@recipients)) {
12957: push(@recipients,$addr);
12958: }
12959: }
12960: }
12961: my $recipientlist = join(',',@recipients);
12962: return $recipientlist;
12963: }
12964:
12965: ############################################################
12966: ############################################################
12967:
12968: =pod
12969:
12970: =head1 Course Catalog Routines
12971:
12972: =over 4
12973:
12974: =item * &gather_categories()
12975:
12976: Converts category definitions - keys of categories hash stored in
12977: coursecategories in configuration.db on the primary library server in a
12978: domain - to an array. Also generates javascript and idx hash used to
12979: generate Domain Coordinator interface for editing Course Categories.
12980:
12981: Inputs:
12982:
12983: categories (reference to hash of category definitions).
12984:
12985: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12986: categories and subcategories).
12987:
12988: idx (reference to hash of counters used in Domain Coordinator interface for
12989: editing Course Categories).
12990:
12991: jsarray (reference to array of categories used to create Javascript arrays for
12992: Domain Coordinator interface for editing Course Categories).
12993:
12994: Returns: nothing
12995:
12996: Side effects: populates cats, idx and jsarray.
12997:
12998: =cut
12999:
13000: sub gather_categories {
13001: my ($categories,$cats,$idx,$jsarray) = @_;
13002: my %counters;
13003: my $num = 0;
13004: foreach my $item (keys(%{$categories})) {
13005: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
13006: if ($container eq '' && $depth == 0) {
13007: $cats->[$depth][$categories->{$item}] = $cat;
13008: } else {
13009: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
13010: }
13011: my ($escitem,$tail) = split(/:/,$item,2);
13012: if ($counters{$tail} eq '') {
13013: $counters{$tail} = $num;
13014: $num ++;
13015: }
13016: if (ref($idx) eq 'HASH') {
13017: $idx->{$item} = $counters{$tail};
13018: }
13019: if (ref($jsarray) eq 'ARRAY') {
13020: push(@{$jsarray->[$counters{$tail}]},$item);
13021: }
13022: }
13023: return;
13024: }
13025:
13026: =pod
13027:
13028: =item * &extract_categories()
13029:
13030: Used to generate breadcrumb trails for course categories.
13031:
13032: Inputs:
13033:
13034: categories (reference to hash of category definitions).
13035:
13036: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13037: categories and subcategories).
13038:
13039: trails (reference to array of breacrumb trails for each category).
13040:
13041: allitems (reference to hash - key is category key
13042: (format: escaped(name):escaped(parent category):depth in hierarchy).
13043:
13044: idx (reference to hash of counters used in Domain Coordinator interface for
13045: editing Course Categories).
13046:
13047: jsarray (reference to array of categories used to create Javascript arrays for
13048: Domain Coordinator interface for editing Course Categories).
13049:
13050: subcats (reference to hash of arrays containing all subcategories within each
13051: category, -recursive)
13052:
13053: Returns: nothing
13054:
13055: Side effects: populates trails and allitems hash references.
13056:
13057: =cut
13058:
13059: sub extract_categories {
13060: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
13061: if (ref($categories) eq 'HASH') {
13062: &gather_categories($categories,$cats,$idx,$jsarray);
13063: if (ref($cats->[0]) eq 'ARRAY') {
13064: for (my $i=0; $i<@{$cats->[0]}; $i++) {
13065: my $name = $cats->[0][$i];
13066: my $item = &escape($name).'::0';
13067: my $trailstr;
13068: if ($name eq 'instcode') {
13069: $trailstr = &mt('Official courses (with institutional codes)');
13070: } elsif ($name eq 'communities') {
13071: $trailstr = &mt('Communities');
13072: } else {
13073: $trailstr = $name;
13074: }
13075: if ($allitems->{$item} eq '') {
13076: push(@{$trails},$trailstr);
13077: $allitems->{$item} = scalar(@{$trails})-1;
13078: }
13079: my @parents = ($name);
13080: if (ref($cats->[1]{$name}) eq 'ARRAY') {
13081: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
13082: my $category = $cats->[1]{$name}[$j];
13083: if (ref($subcats) eq 'HASH') {
13084: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
13085: }
13086: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
13087: }
13088: } else {
13089: if (ref($subcats) eq 'HASH') {
13090: $subcats->{$item} = [];
13091: }
13092: }
13093: }
13094: }
13095: }
13096: return;
13097: }
13098:
13099: =pod
13100:
13101: =item *&recurse_categories()
13102:
13103: Recursively used to generate breadcrumb trails for course categories.
13104:
13105: Inputs:
13106:
13107: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13108: categories and subcategories).
13109:
13110: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
13111:
13112: category (current course category, for which breadcrumb trail is being generated).
13113:
13114: trails (reference to array of breadcrumb trails for each category).
13115:
13116: allitems (reference to hash - key is category key
13117: (format: escaped(name):escaped(parent category):depth in hierarchy).
13118:
13119: parents (array containing containers directories for current category,
13120: back to top level).
13121:
13122: Returns: nothing
13123:
13124: Side effects: populates trails and allitems hash references
13125:
13126: =cut
13127:
13128: sub recurse_categories {
13129: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
13130: my $shallower = $depth - 1;
13131: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
13132: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
13133: my $name = $cats->[$depth]{$category}[$k];
13134: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13135: my $trailstr = join(' -> ',(@{$parents},$category));
13136: if ($allitems->{$item} eq '') {
13137: push(@{$trails},$trailstr);
13138: $allitems->{$item} = scalar(@{$trails})-1;
13139: }
13140: my $deeper = $depth+1;
13141: push(@{$parents},$category);
13142: if (ref($subcats) eq 'HASH') {
13143: my $subcat = &escape($name).':'.$category.':'.$depth;
13144: for (my $j=@{$parents}; $j>=0; $j--) {
13145: my $higher;
13146: if ($j > 0) {
13147: $higher = &escape($parents->[$j]).':'.
13148: &escape($parents->[$j-1]).':'.$j;
13149: } else {
13150: $higher = &escape($parents->[$j]).'::'.$j;
13151: }
13152: push(@{$subcats->{$higher}},$subcat);
13153: }
13154: }
13155: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
13156: $subcats);
13157: pop(@{$parents});
13158: }
13159: } else {
13160: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13161: my $trailstr = join(' -> ',(@{$parents},$category));
13162: if ($allitems->{$item} eq '') {
13163: push(@{$trails},$trailstr);
13164: $allitems->{$item} = scalar(@{$trails})-1;
13165: }
13166: }
13167: return;
13168: }
13169:
13170: =pod
13171:
13172: =item *&assign_categories_table()
13173:
13174: Create a datatable for display of hierarchical categories in a domain,
13175: with checkboxes to allow a course to be categorized.
13176:
13177: Inputs:
13178:
13179: cathash - reference to hash of categories defined for the domain (from
13180: configuration.db)
13181:
13182: currcat - scalar with an & separated list of categories assigned to a course.
13183:
13184: type - scalar contains course type (Course or Community).
13185:
13186: Returns: $output (markup to be displayed)
13187:
13188: =cut
13189:
13190: sub assign_categories_table {
13191: my ($cathash,$currcat,$type) = @_;
13192: my $output;
13193: if (ref($cathash) eq 'HASH') {
13194: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
13195: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
13196: $maxdepth = scalar(@cats);
13197: if (@cats > 0) {
13198: my $itemcount = 0;
13199: if (ref($cats[0]) eq 'ARRAY') {
13200: my @currcategories;
13201: if ($currcat ne '') {
13202: @currcategories = split('&',$currcat);
13203: }
13204: my $table;
13205: for (my $i=0; $i<@{$cats[0]}; $i++) {
13206: my $parent = $cats[0][$i];
13207: next if ($parent eq 'instcode');
13208: if ($type eq 'Community') {
13209: next unless ($parent eq 'communities');
13210: } else {
13211: next if ($parent eq 'communities');
13212: }
13213: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13214: my $item = &escape($parent).'::0';
13215: my $checked = '';
13216: if (@currcategories > 0) {
13217: if (grep(/^\Q$item\E$/,@currcategories)) {
13218: $checked = ' checked="checked"';
13219: }
13220: }
13221: my $parent_title = $parent;
13222: if ($parent eq 'communities') {
13223: $parent_title = &mt('Communities');
13224: }
13225: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
13226: '<input type="checkbox" name="usecategory" value="'.
13227: $item.'"'.$checked.' />'.$parent_title.'</span>'.
13228: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
13229: my $depth = 1;
13230: push(@path,$parent);
13231: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
13232: pop(@path);
13233: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
13234: $itemcount ++;
13235: }
13236: if ($itemcount) {
13237: $output = &Apache::loncommon::start_data_table().
13238: $table.
13239: &Apache::loncommon::end_data_table();
13240: }
13241: }
13242: }
13243: }
13244: return $output;
13245: }
13246:
13247: =pod
13248:
13249: =item *&assign_category_rows()
13250:
13251: Create a datatable row for display of nested categories in a domain,
13252: with checkboxes to allow a course to be categorized,called recursively.
13253:
13254: Inputs:
13255:
13256: itemcount - track row number for alternating colors
13257:
13258: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13259: categories and subcategories.
13260:
13261: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13262:
13263: parent - parent of current category item
13264:
13265: path - Array containing all categories back up through the hierarchy from the
13266: current category to the top level.
13267:
13268: currcategories - reference to array of current categories assigned to the course
13269:
13270: Returns: $output (markup to be displayed).
13271:
13272: =cut
13273:
13274: sub assign_category_rows {
13275: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13276: my ($text,$name,$item,$chgstr);
13277: if (ref($cats) eq 'ARRAY') {
13278: my $maxdepth = scalar(@{$cats});
13279: if (ref($cats->[$depth]) eq 'HASH') {
13280: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13281: my $numchildren = @{$cats->[$depth]{$parent}};
13282: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13283: $text .= '<td><table class="LC_datatable">';
13284: for (my $j=0; $j<$numchildren; $j++) {
13285: $name = $cats->[$depth]{$parent}[$j];
13286: $item = &escape($name).':'.&escape($parent).':'.$depth;
13287: my $deeper = $depth+1;
13288: my $checked = '';
13289: if (ref($currcategories) eq 'ARRAY') {
13290: if (@{$currcategories} > 0) {
13291: if (grep(/^\Q$item\E$/,@{$currcategories})) {
13292: $checked = ' checked="checked"';
13293: }
13294: }
13295: }
13296: $text .= '<tr><td><span class="LC_nobreak"><label>'.
13297: '<input type="checkbox" name="usecategory" value="'.
13298: $item.'"'.$checked.' />'.$name.'</label></span>'.
13299: '<input type="hidden" name="catname" value="'.$name.'" />'.
13300: '</td><td>';
13301: if (ref($path) eq 'ARRAY') {
13302: push(@{$path},$name);
13303: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13304: pop(@{$path});
13305: }
13306: $text .= '</td></tr>';
13307: }
13308: $text .= '</table></td>';
13309: }
13310: }
13311: }
13312: return $text;
13313: }
13314:
13315: ############################################################
13316: ############################################################
13317:
13318:
13319: sub commit_customrole {
13320: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
13321: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
13322: ($start?', '.&mt('starting').' '.localtime($start):'').
13323: ($end?', ending '.localtime($end):'').': <b>'.
13324: &Apache::lonnet::assigncustomrole(
13325: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
13326: '</b><br />';
13327: return $output;
13328: }
13329:
13330: sub commit_standardrole {
13331: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
13332: my ($output,$logmsg,$linefeed);
13333: if ($context eq 'auto') {
13334: $linefeed = "\n";
13335: } else {
13336: $linefeed = "<br />\n";
13337: }
13338: if ($three eq 'st') {
13339: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
13340: $one,$two,$sec,$context,$credits);
13341: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
13342: ($result eq 'unknown_course') || ($result eq 'refused')) {
13343: $output = $logmsg.' '.&mt('Error: ').$result."\n";
13344: } else {
13345: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
13346: ($start?', '.&mt('starting').' '.localtime($start):'').
13347: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13348: if ($context eq 'auto') {
13349: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
13350: } else {
13351: $output .= '<b>'.$result.'</b>'.$linefeed.
13352: &mt('Add to classlist').': <b>ok</b>';
13353: }
13354: $output .= $linefeed;
13355: }
13356: } else {
13357: $output = &mt('Assigning').' '.$three.' in '.$url.
13358: ($start?', '.&mt('starting').' '.localtime($start):'').
13359: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13360: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
13361: if ($context eq 'auto') {
13362: $output .= $result.$linefeed;
13363: } else {
13364: $output .= '<b>'.$result.'</b>'.$linefeed;
13365: }
13366: }
13367: return $output;
13368: }
13369:
13370: sub commit_studentrole {
13371: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
13372: $credits) = @_;
13373: my ($result,$linefeed,$oldsecurl,$newsecurl);
13374: if ($context eq 'auto') {
13375: $linefeed = "\n";
13376: } else {
13377: $linefeed = '<br />'."\n";
13378: }
13379: if (defined($one) && defined($two)) {
13380: my $cid=$one.'_'.$two;
13381: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
13382: my $secchange = 0;
13383: my $expire_role_result;
13384: my $modify_section_result;
13385: if ($oldsec ne '-1') {
13386: if ($oldsec ne $sec) {
13387: $secchange = 1;
13388: my $now = time;
13389: my $uurl='/'.$cid;
13390: $uurl=~s/\_/\//g;
13391: if ($oldsec) {
13392: $uurl.='/'.$oldsec;
13393: }
13394: $oldsecurl = $uurl;
13395: $expire_role_result =
13396: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
13397: if ($env{'request.course.sec'} ne '') {
13398: if ($expire_role_result eq 'refused') {
13399: my @roles = ('st');
13400: my @statuses = ('previous');
13401: my @roledoms = ($one);
13402: my $withsec = 1;
13403: my %roleshash =
13404: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
13405: \@statuses,\@roles,\@roledoms,$withsec);
13406: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
13407: my ($oldstart,$oldend) =
13408: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
13409: if ($oldend > 0 && $oldend <= $now) {
13410: $expire_role_result = 'ok';
13411: }
13412: }
13413: }
13414: }
13415: $result = $expire_role_result;
13416: }
13417: }
13418: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
13419: $modify_section_result =
13420: &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
13421: undef,undef,undef,$sec,
13422: $end,$start,'','',$cid,
13423: '',$context,$credits);
13424: if ($modify_section_result =~ /^ok/) {
13425: if ($secchange == 1) {
13426: if ($sec eq '') {
13427: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
13428: } else {
13429: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
13430: }
13431: } elsif ($oldsec eq '-1') {
13432: if ($sec eq '') {
13433: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
13434: } else {
13435: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13436: }
13437: } else {
13438: if ($sec eq '') {
13439: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
13440: } else {
13441: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13442: }
13443: }
13444: } else {
13445: if ($secchange) {
13446: $$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;
13447: } else {
13448: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
13449: }
13450: }
13451: $result = $modify_section_result;
13452: } elsif ($secchange == 1) {
13453: if ($oldsec eq '') {
13454: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
13455: } else {
13456: $$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;
13457: }
13458: if ($expire_role_result eq 'refused') {
13459: my $newsecurl = '/'.$cid;
13460: $newsecurl =~ s/\_/\//g;
13461: if ($sec ne '') {
13462: $newsecurl.='/'.$sec;
13463: }
13464: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
13465: if ($sec eq '') {
13466: $$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;
13467: } else {
13468: $$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;
13469: }
13470: }
13471: }
13472: }
13473: } else {
13474: $$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;
13475: $result = "error: incomplete course id\n";
13476: }
13477: return $result;
13478: }
13479:
13480: sub show_role_extent {
13481: my ($scope,$context,$role) = @_;
13482: $scope =~ s{^/}{};
13483: my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
13484: push(@courseroles,'co');
13485: my @authorroles = &Apache::lonuserutils::roles_by_context('author');
13486: if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
13487: $scope =~ s{/}{_};
13488: return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
13489: } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
13490: my ($audom,$auname) = split(/\//,$scope);
13491: return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
13492: &Apache::loncommon::plainname($auname,$audom).'</span>');
13493: } else {
13494: $scope =~ s{/$}{};
13495: return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
13496: &Apache::lonnet::domain($scope,'description').'</span>');
13497: }
13498: }
13499:
13500: ############################################################
13501: ############################################################
13502:
13503: sub check_clone {
13504: my ($args,$linefeed) = @_;
13505: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
13506: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
13507: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
13508: my $clonemsg;
13509: my $can_clone = 0;
13510: my $lctype = lc($args->{'crstype'});
13511: if ($lctype ne 'community') {
13512: $lctype = 'course';
13513: }
13514: if ($clonehome eq 'no_host') {
13515: if ($args->{'crstype'} eq 'Community') {
13516: $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'});
13517: } else {
13518: $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'});
13519: }
13520: } else {
13521: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
13522: if ($args->{'crstype'} eq 'Community') {
13523: if ($clonedesc{'type'} ne 'Community') {
13524: $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'});
13525: return ($can_clone, $clonemsg, $cloneid, $clonehome);
13526: }
13527: }
13528: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
13529: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
13530: $can_clone = 1;
13531: } else {
13532: my %clonehash = &Apache::lonnet::get('environment',['cloners'],
13533: $args->{'clonedomain'},$args->{'clonecourse'});
13534: my @cloners = split(/,/,$clonehash{'cloners'});
13535: if (grep(/^\*$/,@cloners)) {
13536: $can_clone = 1;
13537: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
13538: $can_clone = 1;
13539: } else {
13540: my $ccrole = 'cc';
13541: if ($args->{'crstype'} eq 'Community') {
13542: $ccrole = 'co';
13543: }
13544: my %roleshash =
13545: &Apache::lonnet::get_my_roles($args->{'ccuname'},
13546: $args->{'ccdomain'},
13547: 'userroles',['active'],[$ccrole],
13548: [$args->{'clonedomain'}]);
13549: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
13550: $can_clone = 1;
13551: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
13552: $can_clone = 1;
13553: } else {
13554: if ($args->{'crstype'} eq 'Community') {
13555: $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'});
13556: } else {
13557: $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'});
13558: }
13559: }
13560: }
13561: }
13562: }
13563: return ($can_clone, $clonemsg, $cloneid, $clonehome);
13564: }
13565:
13566: sub construct_course {
13567: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
13568: my $outcome;
13569: my $linefeed = '<br />'."\n";
13570: if ($context eq 'auto') {
13571: $linefeed = "\n";
13572: }
13573:
13574: #
13575: # Are we cloning?
13576: #
13577: my ($can_clone, $clonemsg, $cloneid, $clonehome);
13578: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
13579: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
13580: if ($context ne 'auto') {
13581: if ($clonemsg ne '') {
13582: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
13583: }
13584: }
13585: $outcome .= $clonemsg.$linefeed;
13586:
13587: if (!$can_clone) {
13588: return (0,$outcome);
13589: }
13590: }
13591:
13592: #
13593: # Open course
13594: #
13595: my $crstype = lc($args->{'crstype'});
13596: my %cenv=();
13597: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
13598: $args->{'cdescr'},
13599: $args->{'curl'},
13600: $args->{'course_home'},
13601: $args->{'nonstandard'},
13602: $args->{'crscode'},
13603: $args->{'ccuname'}.':'.
13604: $args->{'ccdomain'},
13605: $args->{'crstype'},
13606: $cnum,$context,$category);
13607:
13608: # Note: The testing routines depend on this being output; see
13609: # Utils::Course. This needs to at least be output as a comment
13610: # if anyone ever decides to not show this, and Utils::Course::new
13611: # will need to be suitably modified.
13612: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
13613: if ($$courseid =~ /^error:/) {
13614: return (0,$outcome);
13615: }
13616:
13617: #
13618: # Check if created correctly
13619: #
13620: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
13621: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
13622: if ($crsuhome eq 'no_host') {
13623: $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
13624: return (0,$outcome);
13625: }
13626: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
13627:
13628: #
13629: # Do the cloning
13630: #
13631: if ($can_clone && $cloneid) {
13632: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
13633: if ($context ne 'auto') {
13634: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
13635: }
13636: $outcome .= $clonemsg.$linefeed;
13637: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
13638: # Copy all files
13639: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
13640: # Restore URL
13641: $cenv{'url'}=$oldcenv{'url'};
13642: # Restore title
13643: $cenv{'description'}=$oldcenv{'description'};
13644: # Restore creation date, creator and creation context.
13645: $cenv{'internal.created'}=$oldcenv{'internal.created'};
13646: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
13647: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
13648: # Mark as cloned
13649: $cenv{'clonedfrom'}=$cloneid;
13650: # Need to clone grading mode
13651: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
13652: $cenv{'grading'}=$newenv{'grading'};
13653: # Do not clone these environment entries
13654: &Apache::lonnet::del('environment',
13655: ['default_enrollment_start_date',
13656: 'default_enrollment_end_date',
13657: 'question.email',
13658: 'policy.email',
13659: 'comment.email',
13660: 'pch.users.denied',
13661: 'plc.users.denied',
13662: 'hidefromcat',
13663: 'checkforpriv',
13664: 'categories'],
13665: $$crsudom,$$crsunum);
13666: }
13667:
13668: #
13669: # Set environment (will override cloned, if existing)
13670: #
13671: my @sections = ();
13672: my @xlists = ();
13673: if ($args->{'crstype'}) {
13674: $cenv{'type'}=$args->{'crstype'};
13675: }
13676: if ($args->{'crsid'}) {
13677: $cenv{'courseid'}=$args->{'crsid'};
13678: }
13679: if ($args->{'crscode'}) {
13680: $cenv{'internal.coursecode'}=$args->{'crscode'};
13681: }
13682: if ($args->{'crsquota'} ne '') {
13683: $cenv{'internal.coursequota'}=$args->{'crsquota'};
13684: } else {
13685: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
13686: }
13687: if ($args->{'ccuname'}) {
13688: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
13689: ':'.$args->{'ccdomain'};
13690: } else {
13691: $cenv{'internal.courseowner'} = $args->{'curruser'};
13692: }
13693: if ($args->{'defaultcredits'}) {
13694: $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
13695: }
13696: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
13697: if ($args->{'crssections'}) {
13698: $cenv{'internal.sectionnums'} = '';
13699: if ($args->{'crssections'} =~ m/,/) {
13700: @sections = split/,/,$args->{'crssections'};
13701: } else {
13702: $sections[0] = $args->{'crssections'};
13703: }
13704: if (@sections > 0) {
13705: foreach my $item (@sections) {
13706: my ($sec,$gp) = split/:/,$item;
13707: my $class = $args->{'crscode'}.$sec;
13708: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
13709: $cenv{'internal.sectionnums'} .= $item.',';
13710: unless ($addcheck eq 'ok') {
13711: push @badclasses, $class;
13712: }
13713: }
13714: $cenv{'internal.sectionnums'} =~ s/,$//;
13715: }
13716: }
13717: # do not hide course coordinator from staff listing,
13718: # even if privileged
13719: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13720: # add course coordinator's domain to domains to check for privileged users
13721: # if different to course domain
13722: if ($$crsudom ne $args->{'ccdomain'}) {
13723: $cenv{'checkforpriv'} = $args->{'ccdomain'};
13724: }
13725: # add crosslistings
13726: if ($args->{'crsxlist'}) {
13727: $cenv{'internal.crosslistings'}='';
13728: if ($args->{'crsxlist'} =~ m/,/) {
13729: @xlists = split/,/,$args->{'crsxlist'};
13730: } else {
13731: $xlists[0] = $args->{'crsxlist'};
13732: }
13733: if (@xlists > 0) {
13734: foreach my $item (@xlists) {
13735: my ($xl,$gp) = split/:/,$item;
13736: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
13737: $cenv{'internal.crosslistings'} .= $item.',';
13738: unless ($addcheck eq 'ok') {
13739: push @badclasses, $xl;
13740: }
13741: }
13742: $cenv{'internal.crosslistings'} =~ s/,$//;
13743: }
13744: }
13745: if ($args->{'autoadds'}) {
13746: $cenv{'internal.autoadds'}=$args->{'autoadds'};
13747: }
13748: if ($args->{'autodrops'}) {
13749: $cenv{'internal.autodrops'}=$args->{'autodrops'};
13750: }
13751: # check for notification of enrollment changes
13752: my @notified = ();
13753: if ($args->{'notify_owner'}) {
13754: if ($args->{'ccuname'} ne '') {
13755: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
13756: }
13757: }
13758: if ($args->{'notify_dc'}) {
13759: if ($uname ne '') {
13760: push(@notified,$uname.':'.$udom);
13761: }
13762: }
13763: if (@notified > 0) {
13764: my $notifylist;
13765: if (@notified > 1) {
13766: $notifylist = join(',',@notified);
13767: } else {
13768: $notifylist = $notified[0];
13769: }
13770: $cenv{'internal.notifylist'} = $notifylist;
13771: }
13772: if (@badclasses > 0) {
13773: my %lt=&Apache::lonlocal::texthash(
13774: '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',
13775: 'dnhr' => 'does not have rights to access enrollment in these classes',
13776: 'adby' => 'as determined by the policies of your institution on access to official classlists'
13777: );
13778: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
13779: ' ('.$lt{'adby'}.')';
13780: if ($context eq 'auto') {
13781: $outcome .= $badclass_msg.$linefeed;
13782: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
13783: foreach my $item (@badclasses) {
13784: if ($context eq 'auto') {
13785: $outcome .= " - $item\n";
13786: } else {
13787: $outcome .= "<li>$item</li>\n";
13788: }
13789: }
13790: if ($context eq 'auto') {
13791: $outcome .= $linefeed;
13792: } else {
13793: $outcome .= "</ul><br /><br /></div>\n";
13794: }
13795: }
13796: }
13797: if ($args->{'no_end_date'}) {
13798: $args->{'endaccess'} = 0;
13799: }
13800: $cenv{'internal.autostart'}=$args->{'enrollstart'};
13801: $cenv{'internal.autoend'}=$args->{'enrollend'};
13802: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
13803: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
13804: if ($args->{'showphotos'}) {
13805: $cenv{'internal.showphotos'}=$args->{'showphotos'};
13806: }
13807: $cenv{'internal.authtype'} = $args->{'authtype'};
13808: $cenv{'internal.autharg'} = $args->{'autharg'};
13809: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
13810: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
13811: 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');
13812: if ($context eq 'auto') {
13813: $outcome .= $krb_msg;
13814: } else {
13815: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
13816: }
13817: $outcome .= $linefeed;
13818: }
13819: }
13820: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
13821: if ($args->{'setpolicy'}) {
13822: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13823: }
13824: if ($args->{'setcontent'}) {
13825: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13826: }
13827: }
13828: if ($args->{'reshome'}) {
13829: $cenv{'reshome'}=$args->{'reshome'}.'/';
13830: $cenv{'reshome'}=~s/\/+$/\//;
13831: }
13832: #
13833: # course has keyed access
13834: #
13835: if ($args->{'setkeys'}) {
13836: $cenv{'keyaccess'}='yes';
13837: }
13838: # if specified, key authority is not course, but user
13839: # only active if keyaccess is yes
13840: if ($args->{'keyauth'}) {
13841: my ($user,$domain) = split(':',$args->{'keyauth'});
13842: $user = &LONCAPA::clean_username($user);
13843: $domain = &LONCAPA::clean_username($domain);
13844: if ($user ne '' && $domain ne '') {
13845: $cenv{'keyauth'}=$user.':'.$domain;
13846: }
13847: }
13848:
13849: if ($args->{'disresdis'}) {
13850: $cenv{'pch.roles.denied'}='st';
13851: }
13852: if ($args->{'disablechat'}) {
13853: $cenv{'plc.roles.denied'}='st';
13854: }
13855:
13856: # Record we've not yet viewed the Course Initialization Helper for this
13857: # course
13858: $cenv{'course.helper.not.run'} = 1;
13859: #
13860: # Use new Randomseed
13861: #
13862: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
13863: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
13864: #
13865: # The encryption code and receipt prefix for this course
13866: #
13867: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
13868: $cenv{'internal.encpref'}=100+int(9*rand(99));
13869: #
13870: # By default, use standard grading
13871: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
13872:
13873: $outcome .= $linefeed.&mt('Setting environment').': '.
13874: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
13875: #
13876: # Open all assignments
13877: #
13878: if ($args->{'openall'}) {
13879: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
13880: my %storecontent = ($storeunder => time,
13881: $storeunder.'.type' => 'date_start');
13882:
13883: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
13884: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
13885: }
13886: #
13887: # Set first page
13888: #
13889: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
13890: || ($cloneid)) {
13891: use LONCAPA::map;
13892: $outcome .= &mt('Setting first resource').': ';
13893:
13894: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
13895: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
13896:
13897: $outcome .= ($fatal?$errtext:'read ok').' - ';
13898: my $title; my $url;
13899: if ($args->{'firstres'} eq 'syl') {
13900: $title=&mt('Syllabus');
13901: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
13902: } else {
13903: $title=&mt('Table of Contents');
13904: $url='/adm/navmaps';
13905: }
13906:
13907: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
13908: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
13909:
13910: if ($errtext) { $fatal=2; }
13911: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
13912: }
13913:
13914: return (1,$outcome);
13915: }
13916:
13917: ############################################################
13918: ############################################################
13919:
13920: #SD
13921: # only Community and Course, or anything else?
13922: sub course_type {
13923: my ($cid) = @_;
13924: if (!defined($cid)) {
13925: $cid = $env{'request.course.id'};
13926: }
13927: if (defined($env{'course.'.$cid.'.type'})) {
13928: return $env{'course.'.$cid.'.type'};
13929: } else {
13930: return 'Course';
13931: }
13932: }
13933:
13934: sub group_term {
13935: my $crstype = &course_type();
13936: my %names = (
13937: 'Course' => 'group',
13938: 'Community' => 'group',
13939: );
13940: return $names{$crstype};
13941: }
13942:
13943: sub course_types {
13944: my @types = ('official','unofficial','community');
13945: my %typename = (
13946: official => 'Official course',
13947: unofficial => 'Unofficial course',
13948: community => 'Community',
13949: );
13950: return (\@types,\%typename);
13951: }
13952:
13953: sub icon {
13954: my ($file)=@_;
13955: my $curfext = lc((split(/\./,$file))[-1]);
13956: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
13957: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
13958: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
13959: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
13960: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
13961: $curfext.".gif") {
13962: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
13963: $curfext.".gif";
13964: }
13965: }
13966: return &lonhttpdurl($iconname);
13967: }
13968:
13969: sub lonhttpdurl {
13970: #
13971: # Had been used for "small fry" static images on separate port 8080.
13972: # Modify here if lightweight http functionality desired again.
13973: # Currently eliminated due to increasing firewall issues.
13974: #
13975: my ($url)=@_;
13976: return $url;
13977: }
13978:
13979: sub connection_aborted {
13980: my ($r)=@_;
13981: $r->print(" ");$r->rflush();
13982: my $c = $r->connection;
13983: return $c->aborted();
13984: }
13985:
13986: # Escapes strings that may have embedded 's that will be put into
13987: # strings as 'strings'.
13988: sub escape_single {
13989: my ($input) = @_;
13990: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
13991: $input =~ s/\'/\\\'/g; # Esacpe the 's....
13992: return $input;
13993: }
13994:
13995: # Same as escape_single, but escape's "'s This
13996: # can be used for "strings"
13997: sub escape_double {
13998: my ($input) = @_;
13999: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
14000: $input =~ s/\"/\\\"/g; # Esacpe the "s....
14001: return $input;
14002: }
14003:
14004: # Escapes the last element of a full URL.
14005: sub escape_url {
14006: my ($url) = @_;
14007: my @urlslices = split(/\//, $url,-1);
14008: my $lastitem = &escape(pop(@urlslices));
14009: return join('/',@urlslices).'/'.$lastitem;
14010: }
14011:
14012: sub compare_arrays {
14013: my ($arrayref1,$arrayref2) = @_;
14014: my (@difference,%count);
14015: @difference = ();
14016: %count = ();
14017: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
14018: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
14019: foreach my $element (keys(%count)) {
14020: if ($count{$element} == 1) {
14021: push(@difference,$element);
14022: }
14023: }
14024: }
14025: return @difference;
14026: }
14027:
14028: # -------------------------------------------------------- Initialize user login
14029: sub init_user_environment {
14030: my ($r, $username, $domain, $authhost, $form, $args) = @_;
14031: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
14032:
14033: my $public=($username eq 'public' && $domain eq 'public');
14034:
14035: # See if old ID present, if so, remove
14036:
14037: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
14038: my $now=time;
14039:
14040: if ($public) {
14041: my $max_public=100;
14042: my $oldest;
14043: my $oldest_time=0;
14044: for(my $next=1;$next<=$max_public;$next++) {
14045: if (-e $lonids."/publicuser_$next.id") {
14046: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
14047: if ($mtime<$oldest_time || !$oldest_time) {
14048: $oldest_time=$mtime;
14049: $oldest=$next;
14050: }
14051: } else {
14052: $cookie="publicuser_$next";
14053: last;
14054: }
14055: }
14056: if (!$cookie) { $cookie="publicuser_$oldest"; }
14057: } else {
14058: # if this isn't a robot, kill any existing non-robot sessions
14059: if (!$args->{'robot'}) {
14060: opendir(DIR,$lonids);
14061: while ($filename=readdir(DIR)) {
14062: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
14063: unlink($lonids.'/'.$filename);
14064: }
14065: }
14066: closedir(DIR);
14067: }
14068: # Give them a new cookie
14069: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
14070: : $now.$$.int(rand(10000)));
14071: $cookie="$username\_$id\_$domain\_$authhost";
14072:
14073: # Initialize roles
14074:
14075: ($userroles,$firstaccenv,$timerintenv) =
14076: &Apache::lonnet::rolesinit($domain,$username,$authhost);
14077: }
14078: # ------------------------------------ Check browser type and MathML capability
14079:
14080: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
14081: $clientunicode,$clientos) = &decode_user_agent($r);
14082:
14083: # ------------------------------------------------------------- Get environment
14084:
14085: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
14086: my ($tmp) = keys(%userenv);
14087: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14088: } else {
14089: undef(%userenv);
14090: }
14091: if (($userenv{'interface'}) && (!$form->{'interface'})) {
14092: $form->{'interface'}=$userenv{'interface'};
14093: }
14094: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
14095:
14096: # --------------- Do not trust query string to be put directly into environment
14097: foreach my $option ('interface','localpath','localres') {
14098: $form->{$option}=~s/[\n\r\=]//gs;
14099: }
14100: # --------------------------------------------------------- Write first profile
14101:
14102: {
14103: my %initial_env =
14104: ("user.name" => $username,
14105: "user.domain" => $domain,
14106: "user.home" => $authhost,
14107: "browser.type" => $clientbrowser,
14108: "browser.version" => $clientversion,
14109: "browser.mathml" => $clientmathml,
14110: "browser.unicode" => $clientunicode,
14111: "browser.os" => $clientos,
14112: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
14113: "request.course.fn" => '',
14114: "request.course.uri" => '',
14115: "request.course.sec" => '',
14116: "request.role" => 'cm',
14117: "request.role.adv" => $env{'user.adv'},
14118: "request.host" => $ENV{'REMOTE_ADDR'},);
14119:
14120: if ($form->{'localpath'}) {
14121: $initial_env{"browser.localpath"} = $form->{'localpath'};
14122: $initial_env{"browser.localres"} = $form->{'localres'};
14123: }
14124:
14125: if ($form->{'interface'}) {
14126: $form->{'interface'}=~s/\W//gs;
14127: $initial_env{"browser.interface"} = $form->{'interface'};
14128: $env{'browser.interface'}=$form->{'interface'};
14129: }
14130:
14131: my %is_adv = ( is_adv => $env{'user.adv'} );
14132: my %domdef;
14133: unless ($domain eq 'public') {
14134: %domdef = &Apache::lonnet::get_domain_defaults($domain);
14135: }
14136:
14137: foreach my $tool ('aboutme','blog','webdav','portfolio') {
14138: $userenv{'availabletools.'.$tool} =
14139: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
14140: undef,\%userenv,\%domdef,\%is_adv);
14141: }
14142:
14143: foreach my $crstype ('official','unofficial','community') {
14144: $userenv{'canrequest.'.$crstype} =
14145: &Apache::lonnet::usertools_access($username,$domain,$crstype,
14146: 'reload','requestcourses',
14147: \%userenv,\%domdef,\%is_adv);
14148: }
14149:
14150: $userenv{'canrequest.author'} =
14151: &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
14152: 'reload','requestauthor',
14153: \%userenv,\%domdef,\%is_adv);
14154: my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
14155: $domain,$username);
14156: my $reqstatus = $reqauthor{'author_status'};
14157: if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
14158: if (ref($reqauthor{'author'}) eq 'HASH') {
14159: $userenv{'requestauthorqueued'} = $reqstatus.':'.
14160: $reqauthor{'author'}{'timestamp'};
14161: }
14162: }
14163:
14164: $env{'user.environment'} = "$lonids/$cookie.id";
14165:
14166: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
14167: &GDBM_WRCREAT(),0640)) {
14168: &_add_to_env(\%disk_env,\%initial_env);
14169: &_add_to_env(\%disk_env,\%userenv,'environment.');
14170: &_add_to_env(\%disk_env,$userroles);
14171: if (ref($firstaccenv) eq 'HASH') {
14172: &_add_to_env(\%disk_env,$firstaccenv);
14173: }
14174: if (ref($timerintenv) eq 'HASH') {
14175: &_add_to_env(\%disk_env,$timerintenv);
14176: }
14177: if (ref($args->{'extra_env'})) {
14178: &_add_to_env(\%disk_env,$args->{'extra_env'});
14179: }
14180: untie(%disk_env);
14181: } else {
14182: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
14183: 'Could not create environment storage in lonauth: '.$!.'</span>');
14184: return 'error: '.$!;
14185: }
14186: }
14187: $env{'request.role'}='cm';
14188: $env{'request.role.adv'}=$env{'user.adv'};
14189: $env{'browser.type'}=$clientbrowser;
14190:
14191: return $cookie;
14192:
14193: }
14194:
14195: sub _add_to_env {
14196: my ($idf,$env_data,$prefix) = @_;
14197: if (ref($env_data) eq 'HASH') {
14198: while (my ($key,$value) = each(%$env_data)) {
14199: $idf->{$prefix.$key} = $value;
14200: $env{$prefix.$key} = $value;
14201: }
14202: }
14203: }
14204:
14205: # --- Get the symbolic name of a problem and the url
14206: sub get_symb {
14207: my ($request,$silent) = @_;
14208: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
14209: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
14210: if ($symb eq '') {
14211: if (!$silent) {
14212: if (ref($request)) {
14213: $request->print("Unable to handle ambiguous references:$url:.");
14214: }
14215: return ();
14216: }
14217: }
14218: &Apache::lonenc::check_decrypt(\$symb);
14219: return ($symb);
14220: }
14221:
14222: # --------------------------------------------------------------Get annotation
14223:
14224: sub get_annotation {
14225: my ($symb,$enc) = @_;
14226:
14227: my $key = $symb;
14228: if (!$enc) {
14229: $key =
14230: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
14231: }
14232: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
14233: return $annotation{$key};
14234: }
14235:
14236: sub clean_symb {
14237: my ($symb,$delete_enc) = @_;
14238:
14239: &Apache::lonenc::check_decrypt(\$symb);
14240: my $enc = $env{'request.enc'};
14241: if ($delete_enc) {
14242: delete($env{'request.enc'});
14243: }
14244:
14245: return ($symb,$enc);
14246: }
14247:
14248: sub build_release_hashes {
14249: my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
14250: return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
14251: (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
14252: (ref($randomizetry) eq 'HASH'));
14253: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14254: my ($item,$name,$value) = split(/:/,$key);
14255: if ($item eq 'parameter') {
14256: if (ref($checkparms->{$name}) eq 'ARRAY') {
14257: unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
14258: push(@{$checkparms->{$name}},$value);
14259: }
14260: } else {
14261: push(@{$checkparms->{$name}},$value);
14262: }
14263: } elsif ($item eq 'resourcetag') {
14264: if ($name eq 'responsetype') {
14265: $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
14266: }
14267: } elsif ($item eq 'course') {
14268: if ($name eq 'crstype') {
14269: $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
14270: }
14271: }
14272: }
14273: ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
14274: ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
14275: return;
14276: }
14277:
14278: sub update_content_constraints {
14279: my ($cdom,$cnum,$chome,$cid) = @_;
14280: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
14281: my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
14282: my %checkresponsetypes;
14283: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14284: my ($item,$name,$value) = split(/:/,$key);
14285: if ($item eq 'resourcetag') {
14286: if ($name eq 'responsetype') {
14287: $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
14288: }
14289: }
14290: }
14291: my $navmap = Apache::lonnavmaps::navmap->new();
14292: if (defined($navmap)) {
14293: my %allresponses;
14294: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
14295: my %responses = $res->responseTypes();
14296: foreach my $key (keys(%responses)) {
14297: next unless(exists($checkresponsetypes{$key}));
14298: $allresponses{$key} += $responses{$key};
14299: }
14300: }
14301: foreach my $key (keys(%allresponses)) {
14302: my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
14303: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
14304: ($reqdmajor,$reqdminor) = ($major,$minor);
14305: }
14306: }
14307: undef($navmap);
14308: }
14309: unless (($reqdmajor eq '') && ($reqdminor eq '')) {
14310: &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
14311: }
14312: return;
14313: }
14314:
14315: sub allmaps_incourse {
14316: my ($cdom,$cnum,$chome,$cid) = @_;
14317: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
14318: $cid = $env{'request.course.id'};
14319: $cdom = $env{'course.'.$cid.'.domain'};
14320: $cnum = $env{'course.'.$cid.'.num'};
14321: $chome = $env{'course.'.$cid.'.home'};
14322: }
14323: my %allmaps = ();
14324: my $lastchange =
14325: &Apache::lonnet::get_coursechange($cdom,$cnum);
14326: if ($lastchange > $env{'request.course.tied'}) {
14327: my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
14328: unless ($ferr) {
14329: &update_content_constraints($cdom,$cnum,$chome,$cid);
14330: }
14331: }
14332: my $navmap = Apache::lonnavmaps::navmap->new();
14333: if (defined($navmap)) {
14334: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
14335: $allmaps{$res->src()} = 1;
14336: }
14337: }
14338: return \%allmaps;
14339: }
14340:
14341: sub parse_supplemental_title {
14342: my ($title) = @_;
14343:
14344: my ($foldertitle,$renametitle);
14345: if ($title =~ /&&&/) {
14346: $title = &HTML::Entites::decode($title);
14347: }
14348: if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
14349: $renametitle=$4;
14350: my ($time,$uname,$udom) = ($1,$2,$3);
14351: $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
14352: my $name = &plainname($uname,$udom);
14353: $name = &HTML::Entities::encode($name,'"<>&\'');
14354: $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
14355: $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
14356: $name.': <br />'.$foldertitle;
14357: }
14358: if (wantarray) {
14359: return ($title,$foldertitle,$renametitle);
14360: }
14361: return $title;
14362: }
14363:
14364: sub symb_to_docspath {
14365: my ($symb) = @_;
14366: return unless ($symb);
14367: my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
14368: if ($resurl=~/\.(sequence|page)$/) {
14369: $mapurl=$resurl;
14370: } elsif ($resurl eq 'adm/navmaps') {
14371: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
14372: }
14373: my $mapresobj;
14374: my $navmap = Apache::lonnavmaps::navmap->new();
14375: if (ref($navmap)) {
14376: $mapresobj = $navmap->getResourceByUrl($mapurl);
14377: }
14378: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
14379: my $type=$2;
14380: my $path;
14381: if (ref($mapresobj)) {
14382: my $pcslist = $mapresobj->map_hierarchy();
14383: if ($pcslist ne '') {
14384: foreach my $pc (split(/,/,$pcslist)) {
14385: next if ($pc <= 1);
14386: my $res = $navmap->getByMapPc($pc);
14387: if (ref($res)) {
14388: my $thisurl = $res->src();
14389: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
14390: my $thistitle = $res->title();
14391: $path .= '&'.
14392: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
14393: &Apache::lonhtmlcommon::entity_encode($thistitle).
14394: ':'.$res->randompick().
14395: ':'.$res->randomout().
14396: ':'.$res->encrypted().
14397: ':'.$res->randomorder().
14398: ':'.$res->is_page();
14399: }
14400: }
14401: }
14402: $path =~ s/^\&//;
14403: my $maptitle = $mapresobj->title();
14404: if ($mapurl eq 'default') {
14405: $maptitle = 'Main Content';
14406: }
14407: $path .= (($path ne '')? '&' : '').
14408: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14409: &Apache::lonhtmlcommon::entity_encode($maptitle).
14410: ':'.$mapresobj->randompick().
14411: ':'.$mapresobj->randomout().
14412: ':'.$mapresobj->encrypted().
14413: ':'.$mapresobj->randomorder().
14414: ':'.$mapresobj->is_page();
14415: } else {
14416: my $maptitle = &Apache::lonnet::gettitle($mapurl);
14417: my $ispage = (($type eq 'page')? 1 : '');
14418: if ($mapurl eq 'default') {
14419: $maptitle = 'Main Content';
14420: }
14421: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14422: &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
14423: }
14424: unless ($mapurl eq 'default') {
14425: $path = 'default&'.
14426: &Apache::lonhtmlcommon::entity_encode('Main Content').
14427: ':::::&'.$path;
14428: }
14429: return $path;
14430: }
14431:
14432: sub captcha_display {
14433: my ($context,$lonhost) = @_;
14434: my ($output,$error);
14435: my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14436: if ($captcha eq 'original') {
14437: $output = &create_captcha();
14438: unless ($output) {
14439: $error = 'captcha';
14440: }
14441: } elsif ($captcha eq 'recaptcha') {
14442: $output = &create_recaptcha($pubkey);
14443: unless ($output) {
14444: $error = 'recaptcha';
14445: }
14446: }
14447: return ($output,$error);
14448: }
14449:
14450: sub captcha_response {
14451: my ($context,$lonhost) = @_;
14452: my ($captcha_chk,$captcha_error);
14453: my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14454: if ($captcha eq 'original') {
14455: ($captcha_chk,$captcha_error) = &check_captcha();
14456: } elsif ($captcha eq 'recaptcha') {
14457: $captcha_chk = &check_recaptcha($privkey);
14458: } else {
14459: $captcha_chk = 1;
14460: }
14461: return ($captcha_chk,$captcha_error);
14462: }
14463:
14464: sub get_captcha_config {
14465: my ($context,$lonhost) = @_;
14466: my ($captcha,$pubkey,$privkey,$hashtocheck);
14467: my $hostname = &Apache::lonnet::hostname($lonhost);
14468: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
14469: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
14470: if ($context eq 'usercreation') {
14471: my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
14472: if (ref($domconfig{$context}) eq 'HASH') {
14473: $hashtocheck = $domconfig{$context}{'cancreate'};
14474: if (ref($hashtocheck) eq 'HASH') {
14475: if ($hashtocheck->{'captcha'} eq 'recaptcha') {
14476: if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
14477: $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
14478: $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
14479: }
14480: if ($privkey && $pubkey) {
14481: $captcha = 'recaptcha';
14482: } else {
14483: $captcha = 'original';
14484: }
14485: } elsif ($hashtocheck->{'captcha'} ne 'notused') {
14486: $captcha = 'original';
14487: }
14488: }
14489: } else {
14490: $captcha = 'captcha';
14491: }
14492: } elsif ($context eq 'login') {
14493: my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
14494: if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
14495: $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
14496: $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
14497: if ($privkey && $pubkey) {
14498: $captcha = 'recaptcha';
14499: } else {
14500: $captcha = 'original';
14501: }
14502: } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
14503: $captcha = 'original';
14504: }
14505: }
14506: return ($captcha,$pubkey,$privkey);
14507: }
14508:
14509: sub create_captcha {
14510: my %captcha_params = &captcha_settings();
14511: my ($output,$maxtries,$tries) = ('',10,0);
14512: while ($tries < $maxtries) {
14513: $tries ++;
14514: my $captcha = Authen::Captcha->new (
14515: output_folder => $captcha_params{'output_dir'},
14516: data_folder => $captcha_params{'db_dir'},
14517: );
14518: my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
14519:
14520: if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
14521: $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
14522: &mt('Type in the letters/numbers shown below').' '.
14523: '<input type="text" size="5" name="code" value="" /><br />'.
14524: '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
14525: last;
14526: }
14527: }
14528: return $output;
14529: }
14530:
14531: sub captcha_settings {
14532: my %captcha_params = (
14533: output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'},
14534: www_output_dir => "/captchaspool",
14535: db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'},
14536: numchars => '5',
14537: );
14538: return %captcha_params;
14539: }
14540:
14541: sub check_captcha {
14542: my ($captcha_chk,$captcha_error);
14543: my $code = $env{'form.code'};
14544: my $md5sum = $env{'form.crypt'};
14545: my %captcha_params = &captcha_settings();
14546: my $captcha = Authen::Captcha->new(
14547: output_folder => $captcha_params{'output_dir'},
14548: data_folder => $captcha_params{'db_dir'},
14549: );
14550: $captcha_chk = $captcha->check_code($code,$md5sum);
14551: my %captcha_hash = (
14552: 0 => 'Code not checked (file error)',
14553: -1 => 'Failed: code expired',
14554: -2 => 'Failed: invalid code (not in database)',
14555: -3 => 'Failed: invalid code (code does not match crypt)',
14556: );
14557: if ($captcha_chk != 1) {
14558: $captcha_error = $captcha_hash{$captcha_chk}
14559: }
14560: return ($captcha_chk,$captcha_error);
14561: }
14562:
14563: sub create_recaptcha {
14564: my ($pubkey) = @_;
14565: my $captcha = Captcha::reCAPTCHA->new;
14566: return $captcha->get_options_setter({theme => 'white'})."\n".
14567: $captcha->get_html($pubkey).
14568: &mt('If either word is hard to read, [_1] will replace them.',
14569: '<image src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
14570: '<br /><br />';
14571: }
14572:
14573: sub check_recaptcha {
14574: my ($privkey) = @_;
14575: my $captcha_chk;
14576: my $captcha = Captcha::reCAPTCHA->new;
14577: my $captcha_result =
14578: $captcha->check_answer(
14579: $privkey,
14580: $ENV{'REMOTE_ADDR'},
14581: $env{'form.recaptcha_challenge_field'},
14582: $env{'form.recaptcha_response_field'},
14583: );
14584: if ($captcha_result->{is_valid}) {
14585: $captcha_chk = 1;
14586: }
14587: return $captcha_chk;
14588: }
14589:
14590: =pod
14591:
14592: =back
14593:
14594: =cut
14595:
14596: 1;
14597: __END__;
14598:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>