File:
[LON-CAPA] /
loncom /
interface /
loncommon.pm
Revision
1.1168:
download - view:
text,
annotated -
select for diffs
Mon Dec 30 00:34:49 2013 UTC (10 years, 9 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Set DOCTYPE of DTD HTML 4.01 Frameset for frameset.
- Self-closing <meta>, <link> tags not validated for DTD HTML 4.01 Frameset.
- When displaying help menu where "stayonpage" is true, make page look more
like the rest of LON-CAPA by providing primary menu items.
- "Help" item not a link when primary menu items displayed for help menu.
- Add drop down items for Course Coordination and Authoring manuals to
help menu, where "stayonpage" is true, for users who need them.
- Use domain configuration when checking whether a support e-mail address
is set for "Ask Helpdesk", in place of previous check of lonSupportEMail
perlvar.
- xhtml for help menu frame to satisfy w3c validation.
1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1168 2013/12/30 00:34:49 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,$banner_link);
1384: unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
1385: $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1386: : "javascript:helpMenu('open')";
1387: $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1388: }
1389: my $title = &mt('Get help');
1390: if ($link) {
1391: return <<"END";
1392: $banner_link
1393: <a href="$link" title="$title">$text</a>
1394: END
1395: } else {
1396: return ' '.$text.' ';
1397: }
1398: }
1399:
1400: sub help_menu_js {
1401: my ($httphost) = @_;
1402: my $stayOnPage = 1;
1403: my $width = 620;
1404: my $height = 600;
1405: my $helptopic=&general_help();
1406: my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1407: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1408: my $start_page =
1409: &Apache::loncommon::start_page('Help Menu', undef,
1410: {'frameset' => 1,
1411: 'js_ready' => 1,
1412: 'use_absolute' => $httphost,
1413: 'add_entries' => {
1414: 'border' => '0',
1415: 'rows' => "110,*",},});
1416: my $end_page =
1417: &Apache::loncommon::end_page({'frameset' => 1,
1418: 'js_ready' => 1,});
1419:
1420: my $template .= <<"ENDTEMPLATE";
1421: <script type="text/javascript">
1422: // <![CDATA[
1423: // <!-- BEGIN LON-CAPA Internal
1424: var banner_link = '';
1425: function helpMenu(target) {
1426: var caller = this;
1427: if (target == 'open') {
1428: var newWindow = null;
1429: try {
1430: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1431: }
1432: catch(error) {
1433: writeHelp(caller);
1434: return;
1435: }
1436: if (newWindow) {
1437: caller = newWindow;
1438: }
1439: }
1440: writeHelp(caller);
1441: return;
1442: }
1443: function writeHelp(caller) {
1444: caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
1445: caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
1446: caller.document.close();
1447: caller.focus();
1448: }
1449: // END LON-CAPA Internal -->
1450: // ]]>
1451: </script>
1452: ENDTEMPLATE
1453: return $template;
1454: }
1455:
1456: sub help_open_bug {
1457: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1458: unless ($env{'user.adv'}) { return ''; }
1459: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1460: $text = "" if (not defined $text);
1461: $stayOnPage=1;
1462: $width = 600 if (not defined $width);
1463: $height = 600 if (not defined $height);
1464:
1465: $topic=~s/\W+/\+/g;
1466: my $link='';
1467: my $template='';
1468: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1469: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1470: if (!$stayOnPage)
1471: {
1472: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1473: }
1474: else
1475: {
1476: $link = $url;
1477: }
1478: # Add the text
1479: if ($text ne "")
1480: {
1481: $template .=
1482: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1483: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1484: }
1485:
1486: # Add the graphic
1487: my $title = &mt('Report a Bug');
1488: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1489: $template .= <<"ENDTEMPLATE";
1490: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1491: ENDTEMPLATE
1492: if ($text ne '') { $template.='</td></tr></table>' };
1493: return $template;
1494:
1495: }
1496:
1497: sub help_open_faq {
1498: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1499: unless ($env{'user.adv'}) { return ''; }
1500: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1501: $text = "" if (not defined $text);
1502: $stayOnPage=1;
1503: $width = 350 if (not defined $width);
1504: $height = 400 if (not defined $height);
1505:
1506: $topic=~s/\W+/\+/g;
1507: my $link='';
1508: my $template='';
1509: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1510: if (!$stayOnPage)
1511: {
1512: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1513: }
1514: else
1515: {
1516: $link = $url;
1517: }
1518:
1519: # Add the text
1520: if ($text ne "")
1521: {
1522: $template .=
1523: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1524: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1525: }
1526:
1527: # Add the graphic
1528: my $title = &mt('View the FAQ');
1529: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1530: $template .= <<"ENDTEMPLATE";
1531: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1532: ENDTEMPLATE
1533: if ($text ne '') { $template.='</td></tr></table>' };
1534: return $template;
1535:
1536: }
1537:
1538: ###############################################################
1539: ###############################################################
1540:
1541: =pod
1542:
1543: =item * &change_content_javascript():
1544:
1545: This and the next function allow you to create small sections of an
1546: otherwise static HTML page that you can update on the fly with
1547: Javascript, even in Netscape 4.
1548:
1549: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1550: must be written to the HTML page once. It will prove the Javascript
1551: function "change(name, content)". Calling the change function with the
1552: name of the section
1553: you want to update, matching the name passed to C<changable_area>, and
1554: the new content you want to put in there, will put the content into
1555: that area.
1556:
1557: B<Note>: Netscape 4 only reserves enough space for the changable area
1558: to contain room for the original contents. You need to "make space"
1559: for whatever changes you wish to make, and be B<sure> to check your
1560: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1561: it's adequate for updating a one-line status display, but little more.
1562: This script will set the space to 100% width, so you only need to
1563: worry about height in Netscape 4.
1564:
1565: Modern browsers are much less limiting, and if you can commit to the
1566: user not using Netscape 4, this feature may be used freely with
1567: pretty much any HTML.
1568:
1569: =cut
1570:
1571: sub change_content_javascript {
1572: # If we're on Netscape 4, we need to use Layer-based code
1573: if ($env{'browser.type'} eq 'netscape' &&
1574: $env{'browser.version'} =~ /^4\./) {
1575: return (<<NETSCAPE4);
1576: function change(name, content) {
1577: doc = document.layers[name+"___escape"].layers[0].document;
1578: doc.open();
1579: doc.write(content);
1580: doc.close();
1581: }
1582: NETSCAPE4
1583: } else {
1584: # Otherwise, we need to use semi-standards-compliant code
1585: # (technically, "innerHTML" isn't standard but the equivalent
1586: # is really scary, and every useful browser supports it
1587: return (<<DOMBASED);
1588: function change(name, content) {
1589: element = document.getElementById(name);
1590: element.innerHTML = content;
1591: }
1592: DOMBASED
1593: }
1594: }
1595:
1596: =pod
1597:
1598: =item * &changable_area($name,$origContent):
1599:
1600: This provides a "changable area" that can be modified on the fly via
1601: the Javascript code provided in C<change_content_javascript>. $name is
1602: the name you will use to reference the area later; do not repeat the
1603: same name on a given HTML page more then once. $origContent is what
1604: the area will originally contain, which can be left blank.
1605:
1606: =cut
1607:
1608: sub changable_area {
1609: my ($name, $origContent) = @_;
1610:
1611: if ($env{'browser.type'} eq 'netscape' &&
1612: $env{'browser.version'} =~ /^4\./) {
1613: # If this is netscape 4, we need to use the Layer tag
1614: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1615: } else {
1616: return "<span id='$name'>$origContent</span>";
1617: }
1618: }
1619:
1620: =pod
1621:
1622: =item * &viewport_geometry_js
1623:
1624: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1625:
1626: =cut
1627:
1628:
1629: sub viewport_geometry_js {
1630: return <<"GEOMETRY";
1631: var Geometry = {};
1632: function init_geometry() {
1633: if (Geometry.init) { return };
1634: Geometry.init=1;
1635: if (window.innerHeight) {
1636: Geometry.getViewportHeight = function() { return window.innerHeight; };
1637: Geometry.getViewportWidth = function() { return window.innerWidth; };
1638: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1639: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1640: }
1641: else if (document.documentElement && document.documentElement.clientHeight) {
1642: Geometry.getViewportHeight =
1643: function() { return document.documentElement.clientHeight; };
1644: Geometry.getViewportWidth =
1645: function() { return document.documentElement.clientWidth; };
1646:
1647: Geometry.getHorizontalScroll =
1648: function() { return document.documentElement.scrollLeft; };
1649: Geometry.getVerticalScroll =
1650: function() { return document.documentElement.scrollTop; };
1651: }
1652: else if (document.body.clientHeight) {
1653: Geometry.getViewportHeight =
1654: function() { return document.body.clientHeight; };
1655: Geometry.getViewportWidth =
1656: function() { return document.body.clientWidth; };
1657: Geometry.getHorizontalScroll =
1658: function() { return document.body.scrollLeft; };
1659: Geometry.getVerticalScroll =
1660: function() { return document.body.scrollTop; };
1661: }
1662: }
1663:
1664: GEOMETRY
1665: }
1666:
1667: =pod
1668:
1669: =item * &viewport_size_js()
1670:
1671: 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.
1672:
1673: =cut
1674:
1675: sub viewport_size_js {
1676: my $geometry = &viewport_geometry_js();
1677: return <<"DIMS";
1678:
1679: $geometry
1680:
1681: function getViewportDims(width,height) {
1682: init_geometry();
1683: width.value = Geometry.getViewportWidth();
1684: height.value = Geometry.getViewportHeight();
1685: return;
1686: }
1687:
1688: DIMS
1689: }
1690:
1691: =pod
1692:
1693: =item * &resize_textarea_js()
1694:
1695: emits the needed javascript to resize a textarea to be as big as possible
1696:
1697: creates a function resize_textrea that takes two IDs first should be
1698: the id of the element to resize, second should be the id of a div that
1699: surrounds everything that comes after the textarea, this routine needs
1700: to be attached to the <body> for the onload and onresize events.
1701:
1702: =back
1703:
1704: =cut
1705:
1706: sub resize_textarea_js {
1707: my $geometry = &viewport_geometry_js();
1708: return <<"RESIZE";
1709: <script type="text/javascript">
1710: // <![CDATA[
1711: $geometry
1712:
1713: function getX(element) {
1714: var x = 0;
1715: while (element) {
1716: x += element.offsetLeft;
1717: element = element.offsetParent;
1718: }
1719: return x;
1720: }
1721: function getY(element) {
1722: var y = 0;
1723: while (element) {
1724: y += element.offsetTop;
1725: element = element.offsetParent;
1726: }
1727: return y;
1728: }
1729:
1730:
1731: function resize_textarea(textarea_id,bottom_id) {
1732: init_geometry();
1733: var textarea = document.getElementById(textarea_id);
1734: //alert(textarea);
1735:
1736: var textarea_top = getY(textarea);
1737: var textarea_height = textarea.offsetHeight;
1738: var bottom = document.getElementById(bottom_id);
1739: var bottom_top = getY(bottom);
1740: var bottom_height = bottom.offsetHeight;
1741: var window_height = Geometry.getViewportHeight();
1742: var fudge = 23;
1743: var new_height = window_height-fudge-textarea_top-bottom_height;
1744: if (new_height < 300) {
1745: new_height = 300;
1746: }
1747: textarea.style.height=new_height+'px';
1748: }
1749: // ]]>
1750: </script>
1751: RESIZE
1752:
1753: }
1754:
1755: =pod
1756:
1757: =head1 Excel and CSV file utility routines
1758:
1759: =cut
1760:
1761: ###############################################################
1762: ###############################################################
1763:
1764: =pod
1765:
1766: =over 4
1767:
1768: =item * &csv_translate($text)
1769:
1770: Translate $text to allow it to be output as a 'comma separated values'
1771: format.
1772:
1773: =cut
1774:
1775: ###############################################################
1776: ###############################################################
1777: sub csv_translate {
1778: my $text = shift;
1779: $text =~ s/\"/\"\"/g;
1780: $text =~ s/\n/ /g;
1781: return $text;
1782: }
1783:
1784: ###############################################################
1785: ###############################################################
1786:
1787: =pod
1788:
1789: =item * &define_excel_formats()
1790:
1791: Define some commonly used Excel cell formats.
1792:
1793: Currently supported formats:
1794:
1795: =over 4
1796:
1797: =item header
1798:
1799: =item bold
1800:
1801: =item h1
1802:
1803: =item h2
1804:
1805: =item h3
1806:
1807: =item h4
1808:
1809: =item i
1810:
1811: =item date
1812:
1813: =back
1814:
1815: Inputs: $workbook
1816:
1817: Returns: $format, a hash reference.
1818:
1819:
1820: =cut
1821:
1822: ###############################################################
1823: ###############################################################
1824: sub define_excel_formats {
1825: my ($workbook) = @_;
1826: my $format;
1827: $format->{'header'} = $workbook->add_format(bold => 1,
1828: bottom => 1,
1829: align => 'center');
1830: $format->{'bold'} = $workbook->add_format(bold=>1);
1831: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
1832: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
1833: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
1834: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
1835: $format->{'i'} = $workbook->add_format(italic=>1);
1836: $format->{'date'} = $workbook->add_format(num_format=>
1837: 'mm/dd/yyyy hh:mm:ss');
1838: return $format;
1839: }
1840:
1841: ###############################################################
1842: ###############################################################
1843:
1844: =pod
1845:
1846: =item * &create_workbook()
1847:
1848: Create an Excel worksheet. If it fails, output message on the
1849: request object and return undefs.
1850:
1851: Inputs: Apache request object
1852:
1853: Returns (undef) on failure,
1854: Excel worksheet object, scalar with filename, and formats
1855: from &Apache::loncommon::define_excel_formats on success
1856:
1857: =cut
1858:
1859: ###############################################################
1860: ###############################################################
1861: sub create_workbook {
1862: my ($r) = @_;
1863: #
1864: # Create the excel spreadsheet
1865: my $filename = '/prtspool/'.
1866: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1867: time.'_'.rand(1000000000).'.xls';
1868: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1869: if (! defined($workbook)) {
1870: $r->log_error("Error creating excel spreadsheet $filename: $!");
1871: $r->print(
1872: '<p class="LC_error">'
1873: .&mt('Problems occurred in creating the new Excel file.')
1874: .' '.&mt('This error has been logged.')
1875: .' '.&mt('Please alert your LON-CAPA administrator.')
1876: .'</p>'
1877: );
1878: return (undef);
1879: }
1880: #
1881: $workbook->set_tempdir(LONCAPA::tempdir());
1882: #
1883: my $format = &Apache::loncommon::define_excel_formats($workbook);
1884: return ($workbook,$filename,$format);
1885: }
1886:
1887: ###############################################################
1888: ###############################################################
1889:
1890: =pod
1891:
1892: =item * &create_text_file()
1893:
1894: Create a file to write to and eventually make available to the user.
1895: If file creation fails, outputs an error message on the request object and
1896: return undefs.
1897:
1898: Inputs: Apache request object, and file suffix
1899:
1900: Returns (undef) on failure,
1901: Filehandle and filename on success.
1902:
1903: =cut
1904:
1905: ###############################################################
1906: ###############################################################
1907: sub create_text_file {
1908: my ($r,$suffix) = @_;
1909: if (! defined($suffix)) { $suffix = 'txt'; };
1910: my $fh;
1911: my $filename = '/prtspool/'.
1912: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1913: time.'_'.rand(1000000000).'.'.$suffix;
1914: $fh = Apache::File->new('>/home/httpd'.$filename);
1915: if (! defined($fh)) {
1916: $r->log_error("Couldn't open $filename for output $!");
1917: $r->print(
1918: '<p class="LC_error">'
1919: .&mt('Problems occurred in creating the output file.')
1920: .' '.&mt('This error has been logged.')
1921: .' '.&mt('Please alert your LON-CAPA administrator.')
1922: .'</p>'
1923: );
1924: }
1925: return ($fh,$filename)
1926: }
1927:
1928:
1929: =pod
1930:
1931: =back
1932:
1933: =cut
1934:
1935: ###############################################################
1936: ## Home server <option> list generating code ##
1937: ###############################################################
1938:
1939: # ------------------------------------------
1940:
1941: sub domain_select {
1942: my ($name,$value,$multiple)=@_;
1943: my %domains=map {
1944: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
1945: } &Apache::lonnet::all_domains();
1946: if ($multiple) {
1947: $domains{''}=&mt('Any domain');
1948: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1949: return &multiple_select_form($name,$value,4,\%domains);
1950: } else {
1951: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1952: return &select_form($name,$value,\%domains);
1953: }
1954: }
1955:
1956: #-------------------------------------------
1957:
1958: =pod
1959:
1960: =head1 Routines for form select boxes
1961:
1962: =over 4
1963:
1964: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1965:
1966: Returns a string containing a <select> element int multiple mode
1967:
1968:
1969: Args:
1970: $name - name of the <select> element
1971: $value - scalar or array ref of values that should already be selected
1972: $size - number of rows long the select element is
1973: $hash - the elements should be 'option' => 'shown text'
1974: (shown text should already have been &mt())
1975: $order - (optional) array ref of the order to show the elements in
1976:
1977: =cut
1978:
1979: #-------------------------------------------
1980: sub multiple_select_form {
1981: my ($name,$value,$size,$hash,$order)=@_;
1982: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
1983: my $output='';
1984: if (! defined($size)) {
1985: $size = 4;
1986: if (scalar(keys(%$hash))<4) {
1987: $size = scalar(keys(%$hash));
1988: }
1989: }
1990: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1991: my @order;
1992: if (ref($order) eq 'ARRAY') {
1993: @order = @{$order};
1994: } else {
1995: @order = sort(keys(%$hash));
1996: }
1997: if (exists($$hash{'select_form_order'})) {
1998: @order = @{$$hash{'select_form_order'}};
1999: }
2000:
2001: foreach my $key (@order) {
2002: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
2003: $output.='selected="selected" ' if ($selected{$key});
2004: $output.='>'.$hash->{$key}."</option>\n";
2005: }
2006: $output.="</select>\n";
2007: return $output;
2008: }
2009:
2010: #-------------------------------------------
2011:
2012: =pod
2013:
2014: =item * &select_form($defdom,$name,$hashref,$onchange)
2015:
2016: Returns a string containing a <select name='$name' size='1'> form to
2017: allow a user to select options from a ref to a hash containing:
2018: option_name => displayed text. An optional $onchange can include
2019: a javascript onchange item, e.g., onchange="this.form.submit();"
2020:
2021: See lonrights.pm for an example invocation and use.
2022:
2023: =cut
2024:
2025: #-------------------------------------------
2026: sub select_form {
2027: my ($def,$name,$hashref,$onchange) = @_;
2028: return unless (ref($hashref) eq 'HASH');
2029: if ($onchange) {
2030: $onchange = ' onchange="'.$onchange.'"';
2031: }
2032: my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
2033: my @keys;
2034: if (exists($hashref->{'select_form_order'})) {
2035: @keys=@{$hashref->{'select_form_order'}};
2036: } else {
2037: @keys=sort(keys(%{$hashref}));
2038: }
2039: foreach my $key (@keys) {
2040: $selectform.=
2041: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
2042: ($key eq $def ? 'selected="selected" ' : '').
2043: ">".$hashref->{$key}."</option>\n";
2044: }
2045: $selectform.="</select>";
2046: return $selectform;
2047: }
2048:
2049: # For display filters
2050:
2051: sub display_filter {
2052: my ($context) = @_;
2053: if (!$env{'form.show'}) { $env{'form.show'}=10; }
2054: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
2055: my $phraseinput = 'hidden';
2056: my $includeinput = 'hidden';
2057: my ($checked,$includetypestext);
2058: if ($env{'form.displayfilter'} eq 'containing') {
2059: $phraseinput = 'text';
2060: if ($context eq 'parmslog') {
2061: $includeinput = 'checkbox';
2062: if ($env{'form.includetypes'}) {
2063: $checked = ' checked="checked"';
2064: }
2065: $includetypestext = &mt('Include parameter types');
2066: }
2067: } else {
2068: $includetypestext = ' ';
2069: }
2070: my ($additional,$secondid,$thirdid);
2071: if ($context eq 'parmslog') {
2072: $additional =
2073: '<label><input type="'.$includeinput.'" name="includetypes"'.
2074: $checked.' name="includetypes" value="1" id="includetypes" />'.
2075: ' <span id="includetypestext">'.$includetypestext.'</span>'.
2076: '</label>';
2077: $secondid = 'includetypes';
2078: $thirdid = 'includetypestext';
2079: }
2080: my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
2081: '$secondid','$thirdid')";
2082: return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
2083: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
2084: (&mt('all'),10,20,50,100,1000,10000))).
2085: '</label></span> <span class="LC_nobreak">'.
2086: &mt('Filter: [_1]',
2087: &select_form($env{'form.displayfilter'},
2088: 'displayfilter',
2089: {'currentfolder' => 'Current folder/page',
2090: 'containing' => 'Containing phrase',
2091: 'none' => 'None'},$onchange)).' '.
2092: '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
2093: &HTML::Entities::encode($env{'form.containingphrase'}).
2094: '" />'.$additional;
2095: }
2096:
2097: sub display_filter_js {
2098: my $includetext = &mt('Include parameter types');
2099: return <<"ENDJS";
2100:
2101: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
2102: var firstType = 'hidden';
2103: if (setter.options[setter.selectedIndex].value == 'containing') {
2104: firstType = 'text';
2105: }
2106: firstObject = document.getElementById(firstid);
2107: if (typeof(firstObject) == 'object') {
2108: if (firstObject.type != firstType) {
2109: changeInputType(firstObject,firstType);
2110: }
2111: }
2112: if (context == 'parmslog') {
2113: var secondType = 'hidden';
2114: if (firstType == 'text') {
2115: secondType = 'checkbox';
2116: }
2117: secondObject = document.getElementById(secondid);
2118: if (typeof(secondObject) == 'object') {
2119: if (secondObject.type != secondType) {
2120: changeInputType(secondObject,secondType);
2121: }
2122: }
2123: var textItem = document.getElementById(thirdid);
2124: var currtext = textItem.innerHTML;
2125: var newtext;
2126: if (firstType == 'text') {
2127: newtext = '$includetext';
2128: } else {
2129: newtext = ' ';
2130: }
2131: if (currtext != newtext) {
2132: textItem.innerHTML = newtext;
2133: }
2134: }
2135: return;
2136: }
2137:
2138: function changeInputType(oldObject,newType) {
2139: var newObject = document.createElement('input');
2140: newObject.type = newType;
2141: if (oldObject.size) {
2142: newObject.size = oldObject.size;
2143: }
2144: if (oldObject.value) {
2145: newObject.value = oldObject.value;
2146: }
2147: if (oldObject.name) {
2148: newObject.name = oldObject.name;
2149: }
2150: if (oldObject.id) {
2151: newObject.id = oldObject.id;
2152: }
2153: oldObject.parentNode.replaceChild(newObject,oldObject);
2154: return;
2155: }
2156:
2157: ENDJS
2158: }
2159:
2160: sub gradeleveldescription {
2161: my $gradelevel=shift;
2162: my %gradelevels=(0 => 'Not specified',
2163: 1 => 'Grade 1',
2164: 2 => 'Grade 2',
2165: 3 => 'Grade 3',
2166: 4 => 'Grade 4',
2167: 5 => 'Grade 5',
2168: 6 => 'Grade 6',
2169: 7 => 'Grade 7',
2170: 8 => 'Grade 8',
2171: 9 => 'Grade 9',
2172: 10 => 'Grade 10',
2173: 11 => 'Grade 11',
2174: 12 => 'Grade 12',
2175: 13 => 'Grade 13',
2176: 14 => '100 Level',
2177: 15 => '200 Level',
2178: 16 => '300 Level',
2179: 17 => '400 Level',
2180: 18 => 'Graduate Level');
2181: return &mt($gradelevels{$gradelevel});
2182: }
2183:
2184: sub select_level_form {
2185: my ($deflevel,$name)=@_;
2186: unless ($deflevel) { $deflevel=0; }
2187: my $selectform = "<select name=\"$name\" size=\"1\">\n";
2188: for (my $i=0; $i<=18; $i++) {
2189: $selectform.="<option value=\"$i\" ".
2190: ($i==$deflevel ? 'selected="selected" ' : '').
2191: ">".&gradeleveldescription($i)."</option>\n";
2192: }
2193: $selectform.="</select>";
2194: return $selectform;
2195: }
2196:
2197: #-------------------------------------------
2198:
2199: =pod
2200:
2201: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
2202:
2203: Returns a string containing a <select name='$name' size='1'> form to
2204: allow a user to select the domain to preform an operation in.
2205: See loncreateuser.pm for an example invocation and use.
2206:
2207: If the $includeempty flag is set, it also includes an empty choice ("no domain
2208: selected");
2209:
2210: If the $showdomdesc flag is set, the domain name is followed by the domain description.
2211:
2212: 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.
2213:
2214: The optional $incdoms is a reference to an array of domains which will be the only available options.
2215:
2216: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
2217:
2218: =cut
2219:
2220: #-------------------------------------------
2221: sub select_dom_form {
2222: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
2223: if ($onchange) {
2224: $onchange = ' onchange="'.$onchange.'"';
2225: }
2226: my (@domains,%exclude);
2227: if (ref($incdoms) eq 'ARRAY') {
2228: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
2229: } else {
2230: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
2231: }
2232: if ($includeempty) { @domains=('',@domains); }
2233: if (ref($excdoms) eq 'ARRAY') {
2234: map { $exclude{$_} = 1; } @{$excdoms};
2235: }
2236: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
2237: foreach my $dom (@domains) {
2238: next if ($exclude{$dom});
2239: $selectdomain.="<option value=\"$dom\" ".
2240: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
2241: if ($showdomdesc) {
2242: if ($dom ne '') {
2243: my $domdesc = &Apache::lonnet::domain($dom,'description');
2244: if ($domdesc ne '') {
2245: $selectdomain .= ' ('.$domdesc.')';
2246: }
2247: }
2248: }
2249: $selectdomain .= "</option>\n";
2250: }
2251: $selectdomain.="</select>";
2252: return $selectdomain;
2253: }
2254:
2255: #-------------------------------------------
2256:
2257: =pod
2258:
2259: =item * &home_server_form_item($domain,$name,$defaultflag)
2260:
2261: input: 4 arguments (two required, two optional) -
2262: $domain - domain of new user
2263: $name - name of form element
2264: $default - Value of 'default' causes a default item to be first
2265: option, and selected by default.
2266: $hide - Value of 'hide' causes hiding of the name of the server,
2267: if 1 server found, or default, if 0 found.
2268: output: returns 2 items:
2269: (a) form element which contains either:
2270: (i) <select name="$name">
2271: <option value="$hostid1">$hostid $servers{$hostid}</option>
2272: <option value="$hostid2">$hostid $servers{$hostid}</option>
2273: </select>
2274: form item if there are multiple library servers in $domain, or
2275: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2276: if there is only one library server in $domain.
2277:
2278: (b) number of library servers found.
2279:
2280: See loncreateuser.pm for example of use.
2281:
2282: =cut
2283:
2284: #-------------------------------------------
2285: sub home_server_form_item {
2286: my ($domain,$name,$default,$hide) = @_;
2287: my %servers = &Apache::lonnet::get_servers($domain,'library');
2288: my $result;
2289: my $numlib = keys(%servers);
2290: if ($numlib > 1) {
2291: $result .= '<select name="'.$name.'" />'."\n";
2292: if ($default) {
2293: $result .= '<option value="default" selected="selected">'.&mt('default').
2294: '</option>'."\n";
2295: }
2296: foreach my $hostid (sort(keys(%servers))) {
2297: $result.= '<option value="'.$hostid.'">'.
2298: $hostid.' '.$servers{$hostid}."</option>\n";
2299: }
2300: $result .= '</select>'."\n";
2301: } elsif ($numlib == 1) {
2302: my $hostid;
2303: foreach my $item (keys(%servers)) {
2304: $hostid = $item;
2305: }
2306: $result .= '<input type="hidden" name="'.$name.'" value="'.
2307: $hostid.'" />';
2308: if (!$hide) {
2309: $result .= $hostid.' '.$servers{$hostid};
2310: }
2311: $result .= "\n";
2312: } elsif ($default) {
2313: $result .= '<input type="hidden" name="'.$name.
2314: '" value="default" />';
2315: if (!$hide) {
2316: $result .= &mt('default');
2317: }
2318: $result .= "\n";
2319: }
2320: return ($result,$numlib);
2321: }
2322:
2323: =pod
2324:
2325: =back
2326:
2327: =cut
2328:
2329: ###############################################################
2330: ## Decoding User Agent ##
2331: ###############################################################
2332:
2333: =pod
2334:
2335: =head1 Decoding the User Agent
2336:
2337: =over 4
2338:
2339: =item * &decode_user_agent()
2340:
2341: Inputs: $r
2342:
2343: Outputs:
2344:
2345: =over 4
2346:
2347: =item * $httpbrowser
2348:
2349: =item * $clientbrowser
2350:
2351: =item * $clientversion
2352:
2353: =item * $clientmathml
2354:
2355: =item * $clientunicode
2356:
2357: =item * $clientos
2358:
2359: =item * $clientmobile
2360:
2361: =item * $clientinfo
2362:
2363: =back
2364:
2365: =back
2366:
2367: =cut
2368:
2369: ###############################################################
2370: ###############################################################
2371: sub decode_user_agent {
2372: my ($r)=@_;
2373: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
2374: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
2375: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
2376: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
2377: my $clientbrowser='unknown';
2378: my $clientversion='0';
2379: my $clientmathml='';
2380: my $clientunicode='0';
2381: my $clientmobile=0;
2382: for (my $i=0;$i<=$#browsertype;$i++) {
2383: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
2384: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
2385: $clientbrowser=$bname;
2386: $httpbrowser=~/$vreg/i;
2387: $clientversion=$1;
2388: $clientmathml=($clientversion>=$minv);
2389: $clientunicode=($clientversion>=$univ);
2390: }
2391: }
2392: my $clientos='unknown';
2393: my $clientinfo;
2394: if (($httpbrowser=~/linux/i) ||
2395: ($httpbrowser=~/unix/i) ||
2396: ($httpbrowser=~/ux/i) ||
2397: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
2398: if (($httpbrowser=~/vax/i) ||
2399: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
2400: if ($httpbrowser=~/next/i) { $clientos='next'; }
2401: if (($httpbrowser=~/mac/i) ||
2402: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
2403: if ($httpbrowser=~/win/i) { $clientos='win'; }
2404: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
2405: if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
2406: $clientmobile=lc($1);
2407: }
2408: if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
2409: $clientinfo = 'firefox-'.$1;
2410: } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
2411: $clientinfo = 'chromeframe-'.$1;
2412: }
2413: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
2414: $clientunicode,$clientos,$clientmobile,$clientinfo);
2415: }
2416:
2417: ###############################################################
2418: ## Authentication changing form generation subroutines ##
2419: ###############################################################
2420: ##
2421: ## All of the authform_xxxxxxx subroutines take their inputs in a
2422: ## hash, and have reasonable default values.
2423: ##
2424: ## formname = the name given in the <form> tag.
2425: #-------------------------------------------
2426:
2427: =pod
2428:
2429: =head1 Authentication Routines
2430:
2431: =over 4
2432:
2433: =item * &authform_xxxxxx()
2434:
2435: The authform_xxxxxx subroutines provide javascript and html forms which
2436: handle some of the conveniences required for authentication forms.
2437: This is not an optimal method, but it works.
2438:
2439: =over 4
2440:
2441: =item * authform_header
2442:
2443: =item * authform_authorwarning
2444:
2445: =item * authform_nochange
2446:
2447: =item * authform_kerberos
2448:
2449: =item * authform_internal
2450:
2451: =item * authform_filesystem
2452:
2453: =back
2454:
2455: See loncreateuser.pm for invocation and use examples.
2456:
2457: =cut
2458:
2459: #-------------------------------------------
2460: sub authform_header{
2461: my %in = (
2462: formname => 'cu',
2463: kerb_def_dom => '',
2464: @_,
2465: );
2466: $in{'formname'} = 'document.' . $in{'formname'};
2467: my $result='';
2468:
2469: #---------------------------------------------- Code for upper case translation
2470: my $Javascript_toUpperCase;
2471: unless ($in{kerb_def_dom}) {
2472: $Javascript_toUpperCase =<<"END";
2473: switch (choice) {
2474: case 'krb': currentform.elements[choicearg].value =
2475: currentform.elements[choicearg].value.toUpperCase();
2476: break;
2477: default:
2478: }
2479: END
2480: } else {
2481: $Javascript_toUpperCase = "";
2482: }
2483:
2484: my $radioval = "'nochange'";
2485: if (defined($in{'curr_authtype'})) {
2486: if ($in{'curr_authtype'} ne '') {
2487: $radioval = "'".$in{'curr_authtype'}."arg'";
2488: }
2489: }
2490: my $argfield = 'null';
2491: if (defined($in{'mode'})) {
2492: if ($in{'mode'} eq 'modifycourse') {
2493: if (defined($in{'curr_autharg'})) {
2494: if ($in{'curr_autharg'} ne '') {
2495: $argfield = "'$in{'curr_autharg'}'";
2496: }
2497: }
2498: }
2499: }
2500:
2501: $result.=<<"END";
2502: var current = new Object();
2503: current.radiovalue = $radioval;
2504: current.argfield = $argfield;
2505:
2506: function changed_radio(choice,currentform) {
2507: var choicearg = choice + 'arg';
2508: // If a radio button in changed, we need to change the argfield
2509: if (current.radiovalue != choice) {
2510: current.radiovalue = choice;
2511: if (current.argfield != null) {
2512: currentform.elements[current.argfield].value = '';
2513: }
2514: if (choice == 'nochange') {
2515: current.argfield = null;
2516: } else {
2517: current.argfield = choicearg;
2518: switch(choice) {
2519: case 'krb':
2520: currentform.elements[current.argfield].value =
2521: "$in{'kerb_def_dom'}";
2522: break;
2523: default:
2524: break;
2525: }
2526: }
2527: }
2528: return;
2529: }
2530:
2531: function changed_text(choice,currentform) {
2532: var choicearg = choice + 'arg';
2533: if (currentform.elements[choicearg].value !='') {
2534: $Javascript_toUpperCase
2535: // clear old field
2536: if ((current.argfield != choicearg) && (current.argfield != null)) {
2537: currentform.elements[current.argfield].value = '';
2538: }
2539: current.argfield = choicearg;
2540: }
2541: set_auth_radio_buttons(choice,currentform);
2542: return;
2543: }
2544:
2545: function set_auth_radio_buttons(newvalue,currentform) {
2546: var numauthchoices = currentform.login.length;
2547: if (typeof numauthchoices == "undefined") {
2548: return;
2549: }
2550: var i=0;
2551: while (i < numauthchoices) {
2552: if (currentform.login[i].value == newvalue) { break; }
2553: i++;
2554: }
2555: if (i == numauthchoices) {
2556: return;
2557: }
2558: current.radiovalue = newvalue;
2559: currentform.login[i].checked = true;
2560: return;
2561: }
2562: END
2563: return $result;
2564: }
2565:
2566: sub authform_authorwarning {
2567: my $result='';
2568: $result='<i>'.
2569: &mt('As a general rule, only authors or co-authors should be '.
2570: 'filesystem authenticated '.
2571: '(which allows access to the server filesystem).')."</i>\n";
2572: return $result;
2573: }
2574:
2575: sub authform_nochange {
2576: my %in = (
2577: formname => 'document.cu',
2578: kerb_def_dom => 'MSU.EDU',
2579: @_,
2580: );
2581: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2582: my $result;
2583: if (!$authnum) {
2584: $result = &mt('Under your current role you are not permitted to change login settings for this user');
2585: } else {
2586: $result = '<label>'.&mt('[_1] Do not change login data',
2587: '<input type="radio" name="login" value="nochange" '.
2588: 'checked="checked" onclick="'.
2589: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
2590: '</label>';
2591: }
2592: return $result;
2593: }
2594:
2595: sub authform_kerberos {
2596: my %in = (
2597: formname => 'document.cu',
2598: kerb_def_dom => 'MSU.EDU',
2599: kerb_def_auth => 'krb4',
2600: @_,
2601: );
2602: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2603: $autharg,$jscall);
2604: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2605: if ($in{'kerb_def_auth'} eq 'krb5') {
2606: $check5 = ' checked="checked"';
2607: } else {
2608: $check4 = ' checked="checked"';
2609: }
2610: $krbarg = $in{'kerb_def_dom'};
2611: if (defined($in{'curr_authtype'})) {
2612: if ($in{'curr_authtype'} eq 'krb') {
2613: $krbcheck = ' checked="checked"';
2614: if (defined($in{'mode'})) {
2615: if ($in{'mode'} eq 'modifyuser') {
2616: $krbcheck = '';
2617: }
2618: }
2619: if (defined($in{'curr_kerb_ver'})) {
2620: if ($in{'curr_krb_ver'} eq '5') {
2621: $check5 = ' checked="checked"';
2622: $check4 = '';
2623: } else {
2624: $check4 = ' checked="checked"';
2625: $check5 = '';
2626: }
2627: }
2628: if (defined($in{'curr_autharg'})) {
2629: $krbarg = $in{'curr_autharg'};
2630: }
2631: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2632: if (defined($in{'curr_autharg'})) {
2633: $result =
2634: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
2635: $in{'curr_autharg'},$krbver);
2636: } else {
2637: $result =
2638: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
2639: }
2640: return $result;
2641: }
2642: }
2643: } else {
2644: if ($authnum == 1) {
2645: $authtype = '<input type="hidden" name="login" value="krb" />';
2646: }
2647: }
2648: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2649: return;
2650: } elsif ($authtype eq '') {
2651: if (defined($in{'mode'})) {
2652: if ($in{'mode'} eq 'modifycourse') {
2653: if ($authnum == 1) {
2654: $authtype = '<input type="radio" name="login" value="krb" />';
2655: }
2656: }
2657: }
2658: }
2659: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
2660: if ($authtype eq '') {
2661: $authtype = '<input type="radio" name="login" value="krb" '.
2662: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
2663: $krbcheck.' />';
2664: }
2665: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
2666: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
2667: $in{'curr_authtype'} eq 'krb5') ||
2668: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
2669: $in{'curr_authtype'} eq 'krb4')) {
2670: $result .= &mt
2671: ('[_1] Kerberos authenticated with domain [_2] '.
2672: '[_3] Version 4 [_4] Version 5 [_5]',
2673: '<label>'.$authtype,
2674: '</label><input type="text" size="10" name="krbarg" '.
2675: 'value="'.$krbarg.'" '.
2676: 'onchange="'.$jscall.'" />',
2677: '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
2678: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
2679: '</label>');
2680: } elsif ($can_assign{'krb4'}) {
2681: $result .= &mt
2682: ('[_1] Kerberos authenticated with domain [_2] '.
2683: '[_3] Version 4 [_4]',
2684: '<label>'.$authtype,
2685: '</label><input type="text" size="10" name="krbarg" '.
2686: 'value="'.$krbarg.'" '.
2687: 'onchange="'.$jscall.'" />',
2688: '<label><input type="hidden" name="krbver" value="4" />',
2689: '</label>');
2690: } elsif ($can_assign{'krb5'}) {
2691: $result .= &mt
2692: ('[_1] Kerberos authenticated with domain [_2] '.
2693: '[_3] Version 5 [_4]',
2694: '<label>'.$authtype,
2695: '</label><input type="text" size="10" name="krbarg" '.
2696: 'value="'.$krbarg.'" '.
2697: 'onchange="'.$jscall.'" />',
2698: '<label><input type="hidden" name="krbver" value="5" />',
2699: '</label>');
2700: }
2701: return $result;
2702: }
2703:
2704: sub authform_internal {
2705: my %in = (
2706: formname => 'document.cu',
2707: kerb_def_dom => 'MSU.EDU',
2708: @_,
2709: );
2710: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
2711: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2712: if (defined($in{'curr_authtype'})) {
2713: if ($in{'curr_authtype'} eq 'int') {
2714: if ($can_assign{'int'}) {
2715: $intcheck = 'checked="checked" ';
2716: if (defined($in{'mode'})) {
2717: if ($in{'mode'} eq 'modifyuser') {
2718: $intcheck = '';
2719: }
2720: }
2721: if (defined($in{'curr_autharg'})) {
2722: $intarg = $in{'curr_autharg'};
2723: }
2724: } else {
2725: $result = &mt('Currently internally authenticated.');
2726: return $result;
2727: }
2728: }
2729: } else {
2730: if ($authnum == 1) {
2731: $authtype = '<input type="hidden" name="login" value="int" />';
2732: }
2733: }
2734: if (!$can_assign{'int'}) {
2735: return;
2736: } elsif ($authtype eq '') {
2737: if (defined($in{'mode'})) {
2738: if ($in{'mode'} eq 'modifycourse') {
2739: if ($authnum == 1) {
2740: $authtype = '<input type="radio" name="login" value="int" />';
2741: }
2742: }
2743: }
2744: }
2745: $jscall = "javascript:changed_radio('int',$in{'formname'});";
2746: if ($authtype eq '') {
2747: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
2748: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
2749: }
2750: $autharg = '<input type="password" size="10" name="intarg" value="'.
2751: $intarg.'" onchange="'.$jscall.'" />';
2752: $result = &mt
2753: ('[_1] Internally authenticated (with initial password [_2])',
2754: '<label>'.$authtype,'</label>'.$autharg);
2755: $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>';
2756: return $result;
2757: }
2758:
2759: sub authform_local {
2760: my %in = (
2761: formname => 'document.cu',
2762: kerb_def_dom => 'MSU.EDU',
2763: @_,
2764: );
2765: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
2766: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2767: if (defined($in{'curr_authtype'})) {
2768: if ($in{'curr_authtype'} eq 'loc') {
2769: if ($can_assign{'loc'}) {
2770: $loccheck = 'checked="checked" ';
2771: if (defined($in{'mode'})) {
2772: if ($in{'mode'} eq 'modifyuser') {
2773: $loccheck = '';
2774: }
2775: }
2776: if (defined($in{'curr_autharg'})) {
2777: $locarg = $in{'curr_autharg'};
2778: }
2779: } else {
2780: $result = &mt('Currently using local (institutional) authentication.');
2781: return $result;
2782: }
2783: }
2784: } else {
2785: if ($authnum == 1) {
2786: $authtype = '<input type="hidden" name="login" value="loc" />';
2787: }
2788: }
2789: if (!$can_assign{'loc'}) {
2790: return;
2791: } elsif ($authtype eq '') {
2792: if (defined($in{'mode'})) {
2793: if ($in{'mode'} eq 'modifycourse') {
2794: if ($authnum == 1) {
2795: $authtype = '<input type="radio" name="login" value="loc" />';
2796: }
2797: }
2798: }
2799: }
2800: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
2801: if ($authtype eq '') {
2802: $authtype = '<input type="radio" name="login" value="loc" '.
2803: $loccheck.' onchange="'.$jscall.'" onclick="'.
2804: $jscall.'" />';
2805: }
2806: $autharg = '<input type="text" size="10" name="locarg" value="'.
2807: $locarg.'" onchange="'.$jscall.'" />';
2808: $result = &mt('[_1] Local Authentication with argument [_2]',
2809: '<label>'.$authtype,'</label>'.$autharg);
2810: return $result;
2811: }
2812:
2813: sub authform_filesystem {
2814: my %in = (
2815: formname => 'document.cu',
2816: kerb_def_dom => 'MSU.EDU',
2817: @_,
2818: );
2819: my ($fsyscheck,$result,$authtype,$autharg,$jscall);
2820: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2821: if (defined($in{'curr_authtype'})) {
2822: if ($in{'curr_authtype'} eq 'fsys') {
2823: if ($can_assign{'fsys'}) {
2824: $fsyscheck = 'checked="checked" ';
2825: if (defined($in{'mode'})) {
2826: if ($in{'mode'} eq 'modifyuser') {
2827: $fsyscheck = '';
2828: }
2829: }
2830: } else {
2831: $result = &mt('Currently Filesystem Authenticated.');
2832: return $result;
2833: }
2834: }
2835: } else {
2836: if ($authnum == 1) {
2837: $authtype = '<input type="hidden" name="login" value="fsys" />';
2838: }
2839: }
2840: if (!$can_assign{'fsys'}) {
2841: return;
2842: } elsif ($authtype eq '') {
2843: if (defined($in{'mode'})) {
2844: if ($in{'mode'} eq 'modifycourse') {
2845: if ($authnum == 1) {
2846: $authtype = '<input type="radio" name="login" value="fsys" />';
2847: }
2848: }
2849: }
2850: }
2851: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
2852: if ($authtype eq '') {
2853: $authtype = '<input type="radio" name="login" value="fsys" '.
2854: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
2855: $jscall.'" />';
2856: }
2857: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
2858: ' onchange="'.$jscall.'" />';
2859: $result = &mt
2860: ('[_1] Filesystem Authenticated (with initial password [_2])',
2861: '<label><input type="radio" name="login" value="fsys" '.
2862: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
2863: '</label><input type="password" size="10" name="fsysarg" value="" '.
2864: 'onchange="'.$jscall.'" />');
2865: return $result;
2866: }
2867:
2868: sub get_assignable_auth {
2869: my ($dom) = @_;
2870: if ($dom eq '') {
2871: $dom = $env{'request.role.domain'};
2872: }
2873: my %can_assign = (
2874: krb4 => 1,
2875: krb5 => 1,
2876: int => 1,
2877: loc => 1,
2878: );
2879: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
2880: if (ref($domconfig{'usercreation'}) eq 'HASH') {
2881: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
2882: my $authhash = $domconfig{'usercreation'}{'authtypes'};
2883: my $context;
2884: if ($env{'request.role'} =~ /^au/) {
2885: $context = 'author';
2886: } elsif ($env{'request.role'} =~ /^dc/) {
2887: $context = 'domain';
2888: } elsif ($env{'request.course.id'}) {
2889: $context = 'course';
2890: }
2891: if ($context) {
2892: if (ref($authhash->{$context}) eq 'HASH') {
2893: %can_assign = %{$authhash->{$context}};
2894: }
2895: }
2896: }
2897: }
2898: my $authnum = 0;
2899: foreach my $key (keys(%can_assign)) {
2900: if ($can_assign{$key}) {
2901: $authnum ++;
2902: }
2903: }
2904: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
2905: $authnum --;
2906: }
2907: return ($authnum,%can_assign);
2908: }
2909:
2910: ###############################################################
2911: ## Get Kerberos Defaults for Domain ##
2912: ###############################################################
2913: ##
2914: ## Returns default kerberos version and an associated argument
2915: ## as listed in file domain.tab. If not listed, provides
2916: ## appropriate default domain and kerberos version.
2917: ##
2918: #-------------------------------------------
2919:
2920: =pod
2921:
2922: =item * &get_kerberos_defaults()
2923:
2924: get_kerberos_defaults($target_domain) returns the default kerberos
2925: version and domain. If not found, it defaults to version 4 and the
2926: domain of the server.
2927:
2928: =over 4
2929:
2930: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
2931:
2932: =back
2933:
2934: =back
2935:
2936: =cut
2937:
2938: #-------------------------------------------
2939: sub get_kerberos_defaults {
2940: my $domain=shift;
2941: my ($krbdef,$krbdefdom);
2942: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
2943: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
2944: $krbdef = $domdefaults{'auth_def'};
2945: $krbdefdom = $domdefaults{'auth_arg_def'};
2946: } else {
2947: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
2948: my $krbdefdom=$1;
2949: $krbdefdom=~tr/a-z/A-Z/;
2950: $krbdef = "krb4";
2951: }
2952: return ($krbdef,$krbdefdom);
2953: }
2954:
2955:
2956: ###############################################################
2957: ## Thesaurus Functions ##
2958: ###############################################################
2959:
2960: =pod
2961:
2962: =head1 Thesaurus Functions
2963:
2964: =over 4
2965:
2966: =item * &initialize_keywords()
2967:
2968: Initializes the package variable %Keywords if it is empty. Uses the
2969: package variable $thesaurus_db_file.
2970:
2971: =cut
2972:
2973: ###################################################
2974:
2975: sub initialize_keywords {
2976: return 1 if (scalar keys(%Keywords));
2977: # If we are here, %Keywords is empty, so fill it up
2978: # Make sure the file we need exists...
2979: if (! -e $thesaurus_db_file) {
2980: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
2981: " failed because it does not exist");
2982: return 0;
2983: }
2984: # Set up the hash as a database
2985: my %thesaurus_db;
2986: if (! tie(%thesaurus_db,'GDBM_File',
2987: $thesaurus_db_file,&GDBM_READER(),0640)){
2988: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
2989: $thesaurus_db_file);
2990: return 0;
2991: }
2992: # Get the average number of appearances of a word.
2993: my $avecount = $thesaurus_db{'average.count'};
2994: # Put keywords (those that appear > average) into %Keywords
2995: while (my ($word,$data)=each (%thesaurus_db)) {
2996: my ($count,undef) = split /:/,$data;
2997: $Keywords{$word}++ if ($count > $avecount);
2998: }
2999: untie %thesaurus_db;
3000: # Remove special values from %Keywords.
3001: foreach my $value ('total.count','average.count') {
3002: delete($Keywords{$value}) if (exists($Keywords{$value}));
3003: }
3004: return 1;
3005: }
3006:
3007: ###################################################
3008:
3009: =pod
3010:
3011: =item * &keyword($word)
3012:
3013: Returns true if $word is a keyword. A keyword is a word that appears more
3014: than the average number of times in the thesaurus database. Calls
3015: &initialize_keywords
3016:
3017: =cut
3018:
3019: ###################################################
3020:
3021: sub keyword {
3022: return if (!&initialize_keywords());
3023: my $word=lc(shift());
3024: $word=~s/\W//g;
3025: return exists($Keywords{$word});
3026: }
3027:
3028: ###############################################################
3029:
3030: =pod
3031:
3032: =item * &get_related_words()
3033:
3034: Look up a word in the thesaurus. Takes a scalar argument and returns
3035: an array of words. If the keyword is not in the thesaurus, an empty array
3036: will be returned. The order of the words returned is determined by the
3037: database which holds them.
3038:
3039: Uses global $thesaurus_db_file.
3040:
3041:
3042: =cut
3043:
3044: ###############################################################
3045: sub get_related_words {
3046: my $keyword = shift;
3047: my %thesaurus_db;
3048: if (! -e $thesaurus_db_file) {
3049: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
3050: "failed because the file does not exist");
3051: return ();
3052: }
3053: if (! tie(%thesaurus_db,'GDBM_File',
3054: $thesaurus_db_file,&GDBM_READER(),0640)){
3055: return ();
3056: }
3057: my @Words=();
3058: my $count=0;
3059: if (exists($thesaurus_db{$keyword})) {
3060: # The first element is the number of times
3061: # the word appears. We do not need it now.
3062: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
3063: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
3064: my $threshold=$mostfrequentcount/10;
3065: foreach my $possibleword (@RelatedWords) {
3066: my ($word,$wordcount)=split(/\,/,$possibleword);
3067: if ($wordcount>$threshold) {
3068: push(@Words,$word);
3069: $count++;
3070: if ($count>10) { last; }
3071: }
3072: }
3073: }
3074: untie %thesaurus_db;
3075: return @Words;
3076: }
3077: ###############################################################
3078: #
3079: # Spell checking
3080: #
3081:
3082: =pod
3083:
3084: =back
3085:
3086: =head1 Spell checking
3087:
3088: =over 4
3089:
3090: =item * &check_spelling($wordlist $language)
3091:
3092: Takes a string containing words and feeds it to an external
3093: spellcheck program via a pipeline. Returns a string containing
3094: them mis-spelled words.
3095:
3096: Parameters:
3097:
3098: =over 4
3099:
3100: =item - $wordlist
3101:
3102: String that will be fed into the spellcheck program.
3103:
3104: =item - $language
3105:
3106: Language string that specifies the language for which the spell
3107: check will be performed.
3108:
3109: =back
3110:
3111: =back
3112:
3113: Note: This sub assumes that aspell is installed.
3114:
3115:
3116: =cut
3117:
3118:
3119: sub check_spelling {
3120: my ($wordlist, $language) = @_;
3121: my @misspellings;
3122:
3123: # Generate the speller and set the langauge.
3124: # if explicitly selected:
3125:
3126: my $speller = Text::Aspell->new;
3127: if ($language) {
3128: $speller->set_option('lang', $language);
3129: }
3130:
3131: # Turn the word list into an array of words by splittingon whitespace
3132:
3133: my @words = split(/\s+/, $wordlist);
3134:
3135: foreach my $word (@words) {
3136: if(! $speller->check($word)) {
3137: push(@misspellings, $word);
3138: }
3139: }
3140: return join(' ', @misspellings);
3141:
3142: }
3143:
3144: # -------------------------------------------------------------- Plaintext name
3145: =pod
3146:
3147: =head1 User Name Functions
3148:
3149: =over 4
3150:
3151: =item * &plainname($uname,$udom,$first)
3152:
3153: Takes a users logon name and returns it as a string in
3154: "first middle last generation" form
3155: if $first is set to 'lastname' then it returns it as
3156: 'lastname generation, firstname middlename' if their is a lastname
3157:
3158: =cut
3159:
3160:
3161: ###############################################################
3162: sub plainname {
3163: my ($uname,$udom,$first)=@_;
3164: return if (!defined($uname) || !defined($udom));
3165: my %names=&getnames($uname,$udom);
3166: my $name=&Apache::lonnet::format_name($names{'firstname'},
3167: $names{'middlename'},
3168: $names{'lastname'},
3169: $names{'generation'},$first);
3170: $name=~s/^\s+//;
3171: $name=~s/\s+$//;
3172: $name=~s/\s+/ /g;
3173: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
3174: return $name;
3175: }
3176:
3177: # -------------------------------------------------------------------- Nickname
3178: =pod
3179:
3180: =item * &nickname($uname,$udom)
3181:
3182: Gets a users name and returns it as a string as
3183:
3184: ""nickname""
3185:
3186: if the user has a nickname or
3187:
3188: "first middle last generation"
3189:
3190: if the user does not
3191:
3192: =cut
3193:
3194: sub nickname {
3195: my ($uname,$udom)=@_;
3196: return if (!defined($uname) || !defined($udom));
3197: my %names=&getnames($uname,$udom);
3198: my $name=$names{'nickname'};
3199: if ($name) {
3200: $name='"'.$name.'"';
3201: } else {
3202: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
3203: $names{'lastname'}.' '.$names{'generation'};
3204: $name=~s/\s+$//;
3205: $name=~s/\s+/ /g;
3206: }
3207: return $name;
3208: }
3209:
3210: sub getnames {
3211: my ($uname,$udom)=@_;
3212: return if (!defined($uname) || !defined($udom));
3213: if ($udom eq 'public' && $uname eq 'public') {
3214: return ('lastname' => &mt('Public'));
3215: }
3216: my $id=$uname.':'.$udom;
3217: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
3218: if ($cached) {
3219: return %{$names};
3220: } else {
3221: my %loadnames=&Apache::lonnet::get('environment',
3222: ['firstname','middlename','lastname','generation','nickname'],
3223: $udom,$uname);
3224: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
3225: return %loadnames;
3226: }
3227: }
3228:
3229: # -------------------------------------------------------------------- getemails
3230:
3231: =pod
3232:
3233: =item * &getemails($uname,$udom)
3234:
3235: Gets a user's email information and returns it as a hash with keys:
3236: notification, critnotification, permanentemail
3237:
3238: For notification and critnotification, values are comma-separated lists
3239: of e-mail addresses; for permanentemail, value is a single e-mail address.
3240:
3241:
3242: =cut
3243:
3244:
3245: sub getemails {
3246: my ($uname,$udom)=@_;
3247: if ($udom eq 'public' && $uname eq 'public') {
3248: return;
3249: }
3250: if (!$udom) { $udom=$env{'user.domain'}; }
3251: if (!$uname) { $uname=$env{'user.name'}; }
3252: my $id=$uname.':'.$udom;
3253: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
3254: if ($cached) {
3255: return %{$names};
3256: } else {
3257: my %loadnames=&Apache::lonnet::get('environment',
3258: ['notification','critnotification',
3259: 'permanentemail'],
3260: $udom,$uname);
3261: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
3262: return %loadnames;
3263: }
3264: }
3265:
3266: sub flush_email_cache {
3267: my ($uname,$udom)=@_;
3268: if (!$udom) { $udom =$env{'user.domain'}; }
3269: if (!$uname) { $uname=$env{'user.name'}; }
3270: return if ($udom eq 'public' && $uname eq 'public');
3271: my $id=$uname.':'.$udom;
3272: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
3273: }
3274:
3275: # -------------------------------------------------------------------- getlangs
3276:
3277: =pod
3278:
3279: =item * &getlangs($uname,$udom)
3280:
3281: Gets a user's language preference and returns it as a hash with key:
3282: language.
3283:
3284: =cut
3285:
3286:
3287: sub getlangs {
3288: my ($uname,$udom) = @_;
3289: if (!$udom) { $udom =$env{'user.domain'}; }
3290: if (!$uname) { $uname=$env{'user.name'}; }
3291: my $id=$uname.':'.$udom;
3292: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
3293: if ($cached) {
3294: return %{$langs};
3295: } else {
3296: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
3297: $udom,$uname);
3298: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
3299: return %loadlangs;
3300: }
3301: }
3302:
3303: sub flush_langs_cache {
3304: my ($uname,$udom)=@_;
3305: if (!$udom) { $udom =$env{'user.domain'}; }
3306: if (!$uname) { $uname=$env{'user.name'}; }
3307: return if ($udom eq 'public' && $uname eq 'public');
3308: my $id=$uname.':'.$udom;
3309: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
3310: }
3311:
3312: # ------------------------------------------------------------------ Screenname
3313:
3314: =pod
3315:
3316: =item * &screenname($uname,$udom)
3317:
3318: Gets a users screenname and returns it as a string
3319:
3320: =cut
3321:
3322: sub screenname {
3323: my ($uname,$udom)=@_;
3324: if ($uname eq $env{'user.name'} &&
3325: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
3326: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
3327: return $names{'screenname'};
3328: }
3329:
3330:
3331: # ------------------------------------------------------------- Confirm Wrapper
3332: =pod
3333:
3334: =item * &confirmwrapper($message)
3335:
3336: Wrap messages about completion of operation in box
3337:
3338: =cut
3339:
3340: sub confirmwrapper {
3341: my ($message)=@_;
3342: if ($message) {
3343: return "\n".'<div class="LC_confirm_box">'."\n"
3344: .$message."\n"
3345: .'</div>'."\n";
3346: } else {
3347: return $message;
3348: }
3349: }
3350:
3351: # ------------------------------------------------------------- Message Wrapper
3352:
3353: sub messagewrapper {
3354: my ($link,$username,$domain,$subject,$text)=@_;
3355: return
3356: '<a href="/adm/email?compose=individual&'.
3357: 'recname='.$username.'&recdom='.$domain.
3358: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
3359: 'title="'.&mt('Send message').'">'.$link.'</a>';
3360: }
3361:
3362: # --------------------------------------------------------------- Notes Wrapper
3363:
3364: sub noteswrapper {
3365: my ($link,$un,$do)=@_;
3366: return
3367: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
3368: }
3369:
3370: # ------------------------------------------------------------- Aboutme Wrapper
3371:
3372: sub aboutmewrapper {
3373: my ($link,$username,$domain,$target,$class)=@_;
3374: if (!defined($username) && !defined($domain)) {
3375: return;
3376: }
3377: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
3378: ($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
3379: }
3380:
3381: # ------------------------------------------------------------ Syllabus Wrapper
3382:
3383: sub syllabuswrapper {
3384: my ($linktext,$coursedir,$domain)=@_;
3385: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
3386: }
3387:
3388: # -----------------------------------------------------------------------------
3389:
3390: sub track_student_link {
3391: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
3392: my $link ="/adm/trackstudent?";
3393: my $title = 'View recent activity';
3394: if (defined($sname) && $sname !~ /^\s*$/ &&
3395: defined($sdom) && $sdom !~ /^\s*$/) {
3396: $link .= "selected_student=$sname:$sdom";
3397: $title .= ' of this student';
3398: }
3399: if (defined($target) && $target !~ /^\s*$/) {
3400: $target = qq{target="$target"};
3401: } else {
3402: $target = '';
3403: }
3404: if ($start) { $link.='&start='.$start; }
3405: if ($only_body) { $link .= '&only_body=1'; }
3406: $title = &mt($title);
3407: $linktext = &mt($linktext);
3408: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
3409: &help_open_topic('View_recent_activity');
3410: }
3411:
3412: sub slot_reservations_link {
3413: my ($linktext,$sname,$sdom,$target) = @_;
3414: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
3415: my $title = 'View slot reservation history';
3416: if (defined($sname) && $sname !~ /^\s*$/ &&
3417: defined($sdom) && $sdom !~ /^\s*$/) {
3418: $link .= "&uname=$sname&udom=$sdom";
3419: $title .= ' of this student';
3420: }
3421: if (defined($target) && $target !~ /^\s*$/) {
3422: $target = qq{target="$target"};
3423: } else {
3424: $target = '';
3425: }
3426: $title = &mt($title);
3427: $linktext = &mt($linktext);
3428: return qq{<a href="$link" title="$title" $target>$linktext</a>};
3429: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
3430:
3431: }
3432:
3433: # ===================================================== Display a student photo
3434:
3435:
3436: sub student_image_tag {
3437: my ($domain,$user)=@_;
3438: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
3439: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
3440: return '<img src="'.$imgsrc.'" align="right" />';
3441: } else {
3442: return '';
3443: }
3444: }
3445:
3446: =pod
3447:
3448: =back
3449:
3450: =head1 Access .tab File Data
3451:
3452: =over 4
3453:
3454: =item * &languageids()
3455:
3456: returns list of all language ids
3457:
3458: =cut
3459:
3460: sub languageids {
3461: return sort(keys(%language));
3462: }
3463:
3464: =pod
3465:
3466: =item * &languagedescription()
3467:
3468: returns description of a specified language id
3469:
3470: =cut
3471:
3472: sub languagedescription {
3473: my $code=shift;
3474: return ($supported_language{$code}?'* ':'').
3475: $language{$code}.
3476: ($supported_language{$code}?' ('.&mt('interface available').')':'');
3477: }
3478:
3479: =pod
3480:
3481: =item * &plainlanguagedescription
3482:
3483: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
3484: and the language character encoding (e.g. ISO) separated by a ' - ' string.
3485:
3486: =cut
3487:
3488: sub plainlanguagedescription {
3489: my $code=shift;
3490: return $language{$code};
3491: }
3492:
3493: =pod
3494:
3495: =item * &supportedlanguagecode
3496:
3497: Returns the supported language code (e.g. sptutf maps to pt) given a language
3498: code.
3499:
3500: =cut
3501:
3502: sub supportedlanguagecode {
3503: my $code=shift;
3504: return $supported_language{$code};
3505: }
3506:
3507: =pod
3508:
3509: =item * &latexlanguage()
3510:
3511: Given a language key code returns the correspondnig language to use
3512: to select the correct hyphenation on LaTeX printouts. This is undef if there
3513: is no supported hyphenation for the language code.
3514:
3515: =cut
3516:
3517: sub latexlanguage {
3518: my $code = shift;
3519: return $latex_language{$code};
3520: }
3521:
3522: =pod
3523:
3524: =item * &latexhyphenation()
3525:
3526: Same as above but what's supplied is the language as it might be stored
3527: in the metadata.
3528:
3529: =cut
3530:
3531: sub latexhyphenation {
3532: my $key = shift;
3533: return $latex_language_bykey{$key};
3534: }
3535:
3536: =pod
3537:
3538: =item * ©rightids()
3539:
3540: returns list of all copyrights
3541:
3542: =cut
3543:
3544: sub copyrightids {
3545: return sort(keys(%cprtag));
3546: }
3547:
3548: =pod
3549:
3550: =item * ©rightdescription()
3551:
3552: returns description of a specified copyright id
3553:
3554: =cut
3555:
3556: sub copyrightdescription {
3557: return &mt($cprtag{shift(@_)});
3558: }
3559:
3560: =pod
3561:
3562: =item * &source_copyrightids()
3563:
3564: returns list of all source copyrights
3565:
3566: =cut
3567:
3568: sub source_copyrightids {
3569: return sort(keys(%scprtag));
3570: }
3571:
3572: =pod
3573:
3574: =item * &source_copyrightdescription()
3575:
3576: returns description of a specified source copyright id
3577:
3578: =cut
3579:
3580: sub source_copyrightdescription {
3581: return &mt($scprtag{shift(@_)});
3582: }
3583:
3584: =pod
3585:
3586: =item * &filecategories()
3587:
3588: returns list of all file categories
3589:
3590: =cut
3591:
3592: sub filecategories {
3593: return sort(keys(%category_extensions));
3594: }
3595:
3596: =pod
3597:
3598: =item * &filecategorytypes()
3599:
3600: returns list of file types belonging to a given file
3601: category
3602:
3603: =cut
3604:
3605: sub filecategorytypes {
3606: my ($cat) = @_;
3607: return @{$category_extensions{lc($cat)}};
3608: }
3609:
3610: =pod
3611:
3612: =item * &fileembstyle()
3613:
3614: returns embedding style for a specified file type
3615:
3616: =cut
3617:
3618: sub fileembstyle {
3619: return $fe{lc(shift(@_))};
3620: }
3621:
3622: sub filemimetype {
3623: return $fm{lc(shift(@_))};
3624: }
3625:
3626:
3627: sub filecategoryselect {
3628: my ($name,$value)=@_;
3629: return &select_form($value,$name,
3630: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
3631: }
3632:
3633: =pod
3634:
3635: =item * &filedescription()
3636:
3637: returns description for a specified file type
3638:
3639: =cut
3640:
3641: sub filedescription {
3642: my $file_description = $fd{lc(shift())};
3643: $file_description =~ s:([\[\]]):~$1:g;
3644: return &mt($file_description);
3645: }
3646:
3647: =pod
3648:
3649: =item * &filedescriptionex()
3650:
3651: returns description for a specified file type with
3652: extra formatting
3653:
3654: =cut
3655:
3656: sub filedescriptionex {
3657: my $ex=shift;
3658: my $file_description = $fd{lc($ex)};
3659: $file_description =~ s:([\[\]]):~$1:g;
3660: return '.'.$ex.' '.&mt($file_description);
3661: }
3662:
3663: # End of .tab access
3664: =pod
3665:
3666: =back
3667:
3668: =cut
3669:
3670: # ------------------------------------------------------------------ File Types
3671: sub fileextensions {
3672: return sort(keys(%fe));
3673: }
3674:
3675: # ----------------------------------------------------------- Display Languages
3676: # returns a hash with all desired display languages
3677: #
3678:
3679: sub display_languages {
3680: my %languages=();
3681: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
3682: $languages{$lang}=1;
3683: }
3684: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3685: if ($env{'form.displaylanguage'}) {
3686: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3687: $languages{$lang}=1;
3688: }
3689: }
3690: return %languages;
3691: }
3692:
3693: sub languages {
3694: my ($possible_langs) = @_;
3695: my @preferred_langs = &Apache::lonlocal::preferred_languages();
3696: if (!ref($possible_langs)) {
3697: if( wantarray ) {
3698: return @preferred_langs;
3699: } else {
3700: return $preferred_langs[0];
3701: }
3702: }
3703: my %possibilities = map { $_ => 1 } (@$possible_langs);
3704: my @preferred_possibilities;
3705: foreach my $preferred_lang (@preferred_langs) {
3706: if (exists($possibilities{$preferred_lang})) {
3707: push(@preferred_possibilities, $preferred_lang);
3708: }
3709: }
3710: if( wantarray ) {
3711: return @preferred_possibilities;
3712: }
3713: return $preferred_possibilities[0];
3714: }
3715:
3716: sub user_lang {
3717: my ($touname,$toudom,$fromcid) = @_;
3718: my @userlangs;
3719: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
3720: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
3721: $env{'course.'.$fromcid.'.languages'}));
3722: } else {
3723: my %langhash = &getlangs($touname,$toudom);
3724: if ($langhash{'languages'} ne '') {
3725: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
3726: } else {
3727: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
3728: if ($domdefs{'lang_def'} ne '') {
3729: @userlangs = ($domdefs{'lang_def'});
3730: }
3731: }
3732: }
3733: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
3734: my $user_lh = Apache::localize->get_handle(@languages);
3735: return $user_lh;
3736: }
3737:
3738:
3739: ###############################################################
3740: ## Student Answer Attempts ##
3741: ###############################################################
3742:
3743: =pod
3744:
3745: =head1 Alternate Problem Views
3746:
3747: =over 4
3748:
3749: =item * &get_previous_attempt($symb, $username, $domain, $course,
3750: $getattempt, $regexp, $gradesub)
3751:
3752: Return string with previous attempt on problem. Arguments:
3753:
3754: =over 4
3755:
3756: =item * $symb: Problem, including path
3757:
3758: =item * $username: username of the desired student
3759:
3760: =item * $domain: domain of the desired student
3761:
3762: =item * $course: Course ID
3763:
3764: =item * $getattempt: Leave blank for all attempts, otherwise put
3765: something
3766:
3767: =item * $regexp: if string matches this regexp, the string will be
3768: sent to $gradesub
3769:
3770: =item * $gradesub: routine that processes the string if it matches $regexp
3771:
3772: =back
3773:
3774: The output string is a table containing all desired attempts, if any.
3775:
3776: =cut
3777:
3778: sub get_previous_attempt {
3779: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
3780: my $prevattempts='';
3781: no strict 'refs';
3782: if ($symb) {
3783: my (%returnhash)=
3784: &Apache::lonnet::restore($symb,$course,$domain,$username);
3785: if ($returnhash{'version'}) {
3786: my %lasthash=();
3787: my $version;
3788: for ($version=1;$version<=$returnhash{'version'};$version++) {
3789: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
3790: $lasthash{$key}=$returnhash{$version.':'.$key};
3791: }
3792: }
3793: $prevattempts=&start_data_table().&start_data_table_header_row();
3794: $prevattempts.='<th>'.&mt('History').'</th>';
3795: my (%typeparts,%lasthidden);
3796: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
3797: foreach my $key (sort(keys(%lasthash))) {
3798: my ($ign,@parts) = split(/\./,$key);
3799: if ($#parts > 0) {
3800: my $data=$parts[-1];
3801: next if ($data eq 'foilorder');
3802: pop(@parts);
3803: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
3804: if ($data eq 'type') {
3805: unless ($showsurv) {
3806: my $id = join(',',@parts);
3807: $typeparts{$ign.'.'.$id} = $lasthash{$key};
3808: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
3809: $lasthidden{$ign.'.'.$id} = 1;
3810: }
3811: }
3812: }
3813: } else {
3814: if ($#parts == 0) {
3815: $prevattempts.='<th>'.$parts[0].'</th>';
3816: } else {
3817: $prevattempts.='<th>'.$ign.'</th>';
3818: }
3819: }
3820: }
3821: $prevattempts.=&end_data_table_header_row();
3822: if ($getattempt eq '') {
3823: for ($version=1;$version<=$returnhash{'version'};$version++) {
3824: my @hidden;
3825: if (%typeparts) {
3826: foreach my $id (keys(%typeparts)) {
3827: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
3828: push(@hidden,$id);
3829: }
3830: }
3831: }
3832: $prevattempts.=&start_data_table_row().
3833: '<td>'.&mt('Transaction [_1]',$version).'</td>';
3834: if (@hidden) {
3835: foreach my $key (sort(keys(%lasthash))) {
3836: next if ($key =~ /\.foilorder$/);
3837: my $hide;
3838: foreach my $id (@hidden) {
3839: if ($key =~ /^\Q$id\E/) {
3840: $hide = 1;
3841: last;
3842: }
3843: }
3844: if ($hide) {
3845: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
3846: if (($data eq 'award') || ($data eq 'awarddetail')) {
3847: my $value = &format_previous_attempt_value($key,
3848: $returnhash{$version.':'.$key});
3849: $prevattempts.='<td>'.$value.' </td>';
3850: } else {
3851: $prevattempts.='<td> </td>';
3852: }
3853: } else {
3854: if ($key =~ /\./) {
3855: my $value = &format_previous_attempt_value($key,
3856: $returnhash{$version.':'.$key});
3857: $prevattempts.='<td>'.$value.' </td>';
3858: } else {
3859: $prevattempts.='<td> </td>';
3860: }
3861: }
3862: }
3863: } else {
3864: foreach my $key (sort(keys(%lasthash))) {
3865: next if ($key =~ /\.foilorder$/);
3866: my $value = &format_previous_attempt_value($key,
3867: $returnhash{$version.':'.$key});
3868: $prevattempts.='<td>'.$value.' </td>';
3869: }
3870: }
3871: $prevattempts.=&end_data_table_row();
3872: }
3873: }
3874: my @currhidden = keys(%lasthidden);
3875: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
3876: foreach my $key (sort(keys(%lasthash))) {
3877: next if ($key =~ /\.foilorder$/);
3878: if (%typeparts) {
3879: my $hidden;
3880: foreach my $id (@currhidden) {
3881: if ($key =~ /^\Q$id\E/) {
3882: $hidden = 1;
3883: last;
3884: }
3885: }
3886: if ($hidden) {
3887: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
3888: if (($data eq 'award') || ($data eq 'awarddetail')) {
3889: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3890: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3891: $value = &$gradesub($value);
3892: }
3893: $prevattempts.='<td>'.$value.' </td>';
3894: } else {
3895: $prevattempts.='<td> </td>';
3896: }
3897: } else {
3898: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3899: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3900: $value = &$gradesub($value);
3901: }
3902: $prevattempts.='<td>'.$value.' </td>';
3903: }
3904: } else {
3905: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3906: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3907: $value = &$gradesub($value);
3908: }
3909: $prevattempts.='<td>'.$value.' </td>';
3910: }
3911: }
3912: $prevattempts.= &end_data_table_row().&end_data_table();
3913: } else {
3914: $prevattempts=
3915: &start_data_table().&start_data_table_row().
3916: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
3917: &end_data_table_row().&end_data_table();
3918: }
3919: } else {
3920: $prevattempts=
3921: &start_data_table().&start_data_table_row().
3922: '<td>'.&mt('No data.').'</td>'.
3923: &end_data_table_row().&end_data_table();
3924: }
3925: }
3926:
3927: sub format_previous_attempt_value {
3928: my ($key,$value) = @_;
3929: if (($key =~ /timestamp/) || ($key=~/duedate/)) {
3930: $value = &Apache::lonlocal::locallocaltime($value);
3931: } elsif (ref($value) eq 'ARRAY') {
3932: $value = '('.join(', ', @{ $value }).')';
3933: } elsif ($key =~ /answerstring$/) {
3934: my %answers = &Apache::lonnet::str2hash($value);
3935: my @anskeys = sort(keys(%answers));
3936: if (@anskeys == 1) {
3937: my $answer = $answers{$anskeys[0]};
3938: if ($answer =~ m{\0}) {
3939: $answer =~ s{\0}{,}g;
3940: }
3941: my $tag_internal_answer_name = 'INTERNAL';
3942: if ($anskeys[0] eq $tag_internal_answer_name) {
3943: $value = $answer;
3944: } else {
3945: $value = $anskeys[0].'='.$answer;
3946: }
3947: } else {
3948: foreach my $ans (@anskeys) {
3949: my $answer = $answers{$ans};
3950: if ($answer =~ m{\0}) {
3951: $answer =~ s{\0}{,}g;
3952: }
3953: $value .= $ans.'='.$answer.'<br />';;
3954: }
3955: }
3956: } else {
3957: $value = &unescape($value);
3958: }
3959: return $value;
3960: }
3961:
3962:
3963: sub relative_to_absolute {
3964: my ($url,$output)=@_;
3965: my $parser=HTML::TokeParser->new(\$output);
3966: my $token;
3967: my $thisdir=$url;
3968: my @rlinks=();
3969: while ($token=$parser->get_token) {
3970: if ($token->[0] eq 'S') {
3971: if ($token->[1] eq 'a') {
3972: if ($token->[2]->{'href'}) {
3973: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
3974: }
3975: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
3976: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
3977: } elsif ($token->[1] eq 'base') {
3978: $thisdir=$token->[2]->{'href'};
3979: }
3980: }
3981: }
3982: $thisdir=~s-/[^/]*$--;
3983: foreach my $link (@rlinks) {
3984: unless (($link=~/^https?\:\/\//i) ||
3985: ($link=~/^\//) ||
3986: ($link=~/^javascript:/i) ||
3987: ($link=~/^mailto:/i) ||
3988: ($link=~/^\#/)) {
3989: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
3990: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
3991: }
3992: }
3993: # -------------------------------------------------- Deal with Applet codebases
3994: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
3995: return $output;
3996: }
3997:
3998: =pod
3999:
4000: =item * &get_student_view()
4001:
4002: show a snapshot of what student was looking at
4003:
4004: =cut
4005:
4006: sub get_student_view {
4007: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
4008: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4009: my (%form);
4010: my @elements=('symb','courseid','domain','username');
4011: foreach my $element (@elements) {
4012: $form{'grade_'.$element}=eval '$'.$element #'
4013: }
4014: if (defined($moreenv)) {
4015: %form=(%form,%{$moreenv});
4016: }
4017: if (defined($target)) { $form{'grade_target'} = $target; }
4018: $feedurl=&Apache::lonnet::clutter($feedurl);
4019: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
4020: $userview=~s/\<body[^\>]*\>//gi;
4021: $userview=~s/\<\/body\>//gi;
4022: $userview=~s/\<html\>//gi;
4023: $userview=~s/\<\/html\>//gi;
4024: $userview=~s/\<head\>//gi;
4025: $userview=~s/\<\/head\>//gi;
4026: $userview=~s/action\s*\=/would_be_action\=/gi;
4027: $userview=&relative_to_absolute($feedurl,$userview);
4028: if (wantarray) {
4029: return ($userview,$response);
4030: } else {
4031: return $userview;
4032: }
4033: }
4034:
4035: sub get_student_view_with_retries {
4036: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
4037:
4038: my $ok = 0; # True if we got a good response.
4039: my $content;
4040: my $response;
4041:
4042: # Try to get the student_view done. within the retries count:
4043:
4044: do {
4045: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
4046: $ok = $response->is_success;
4047: if (!$ok) {
4048: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
4049: }
4050: $retries--;
4051: } while (!$ok && ($retries > 0));
4052:
4053: if (!$ok) {
4054: $content = ''; # On error return an empty content.
4055: }
4056: if (wantarray) {
4057: return ($content, $response);
4058: } else {
4059: return $content;
4060: }
4061: }
4062:
4063: =pod
4064:
4065: =item * &get_student_answers()
4066:
4067: show a snapshot of how student was answering problem
4068:
4069: =cut
4070:
4071: sub get_student_answers {
4072: my ($symb,$username,$domain,$courseid,%form) = @_;
4073: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4074: my (%moreenv);
4075: my @elements=('symb','courseid','domain','username');
4076: foreach my $element (@elements) {
4077: $moreenv{'grade_'.$element}=eval '$'.$element #'
4078: }
4079: $moreenv{'grade_target'}='answer';
4080: %moreenv=(%form,%moreenv);
4081: $feedurl = &Apache::lonnet::clutter($feedurl);
4082: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
4083: return $userview;
4084: }
4085:
4086: =pod
4087:
4088: =item * &submlink()
4089:
4090: Inputs: $text $uname $udom $symb $target
4091:
4092: Returns: A link to grades.pm such as to see the SUBM view of a student
4093:
4094: =cut
4095:
4096: ###############################################
4097: sub submlink {
4098: my ($text,$uname,$udom,$symb,$target)=@_;
4099: if (!($uname && $udom)) {
4100: (my $cursymb, my $courseid,$udom,$uname)=
4101: &Apache::lonnet::whichuser($symb);
4102: if (!$symb) { $symb=$cursymb; }
4103: }
4104: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4105: $symb=&escape($symb);
4106: if ($target) { $target=" target=\"$target\""; }
4107: return
4108: '<a href="/adm/grades?command=submission'.
4109: '&symb='.$symb.
4110: '&student='.$uname.
4111: '&userdom='.$udom.'"'.
4112: $target.'>'.$text.'</a>';
4113: }
4114: ##############################################
4115:
4116: =pod
4117:
4118: =item * &pgrdlink()
4119:
4120: Inputs: $text $uname $udom $symb $target
4121:
4122: Returns: A link to grades.pm such as to see the PGRD view of a student
4123:
4124: =cut
4125:
4126: ###############################################
4127: sub pgrdlink {
4128: my $link=&submlink(@_);
4129: $link=~s/(&command=submission)/$1&showgrading=yes/;
4130: return $link;
4131: }
4132: ##############################################
4133:
4134: =pod
4135:
4136: =item * &pprmlink()
4137:
4138: Inputs: $text $uname $udom $symb $target
4139:
4140: Returns: A link to parmset.pm such as to see the PPRM view of a
4141: student and a specific resource
4142:
4143: =cut
4144:
4145: ###############################################
4146: sub pprmlink {
4147: my ($text,$uname,$udom,$symb,$target)=@_;
4148: if (!($uname && $udom)) {
4149: (my $cursymb, my $courseid,$udom,$uname)=
4150: &Apache::lonnet::whichuser($symb);
4151: if (!$symb) { $symb=$cursymb; }
4152: }
4153: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4154: $symb=&escape($symb);
4155: if ($target) { $target="target=\"$target\""; }
4156: return '<a href="/adm/parmset?command=set&'.
4157: 'symb='.$symb.'&uname='.$uname.
4158: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
4159: }
4160: ##############################################
4161:
4162: =pod
4163:
4164: =back
4165:
4166: =cut
4167:
4168: ###############################################
4169:
4170:
4171: sub timehash {
4172: my ($thistime) = @_;
4173: my $timezone = &Apache::lonlocal::gettimezone();
4174: my $dt = DateTime->from_epoch(epoch => $thistime)
4175: ->set_time_zone($timezone);
4176: my $wday = $dt->day_of_week();
4177: if ($wday == 7) { $wday = 0; }
4178: return ( 'second' => $dt->second(),
4179: 'minute' => $dt->minute(),
4180: 'hour' => $dt->hour(),
4181: 'day' => $dt->day_of_month(),
4182: 'month' => $dt->month(),
4183: 'year' => $dt->year(),
4184: 'weekday' => $wday,
4185: 'dayyear' => $dt->day_of_year(),
4186: 'dlsav' => $dt->is_dst() );
4187: }
4188:
4189: sub utc_string {
4190: my ($date)=@_;
4191: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
4192: }
4193:
4194: sub maketime {
4195: my %th=@_;
4196: my ($epoch_time,$timezone,$dt);
4197: $timezone = &Apache::lonlocal::gettimezone();
4198: eval {
4199: $dt = DateTime->new( year => $th{'year'},
4200: month => $th{'month'},
4201: day => $th{'day'},
4202: hour => $th{'hour'},
4203: minute => $th{'minute'},
4204: second => $th{'second'},
4205: time_zone => $timezone,
4206: );
4207: };
4208: if (!$@) {
4209: $epoch_time = $dt->epoch;
4210: if ($epoch_time) {
4211: return $epoch_time;
4212: }
4213: }
4214: return POSIX::mktime(
4215: ($th{'seconds'},$th{'minutes'},$th{'hours'},
4216: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
4217: }
4218:
4219: #########################################
4220:
4221: sub findallcourses {
4222: my ($roles,$uname,$udom) = @_;
4223: my %roles;
4224: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
4225: my %courses;
4226: my $now=time;
4227: if (!defined($uname)) {
4228: $uname = $env{'user.name'};
4229: }
4230: if (!defined($udom)) {
4231: $udom = $env{'user.domain'};
4232: }
4233: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
4234: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
4235: if (!%roles) {
4236: %roles = (
4237: cc => 1,
4238: co => 1,
4239: in => 1,
4240: ep => 1,
4241: ta => 1,
4242: cr => 1,
4243: st => 1,
4244: );
4245: }
4246: foreach my $entry (keys(%roleshash)) {
4247: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
4248: if ($trole =~ /^cr/) {
4249: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
4250: } else {
4251: next if (!exists($roles{$trole}));
4252: }
4253: if ($tend) {
4254: next if ($tend < $now);
4255: }
4256: if ($tstart) {
4257: next if ($tstart > $now);
4258: }
4259: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
4260: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
4261: my $value = $trole.'/'.$cdom.'/';
4262: if ($secpart eq '') {
4263: ($cnum,$role) = split(/_/,$cnumpart);
4264: $sec = 'none';
4265: $value .= $cnum.'/';
4266: } else {
4267: $cnum = $cnumpart;
4268: ($sec,$role) = split(/_/,$secpart);
4269: $value .= $cnum.'/'.$sec;
4270: }
4271: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4272: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4273: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4274: }
4275: } else {
4276: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4277: }
4278: }
4279: } else {
4280: foreach my $key (keys(%env)) {
4281: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
4282: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
4283: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
4284: next if ($role eq 'ca' || $role eq 'aa');
4285: next if (%roles && !exists($roles{$role}));
4286: my ($starttime,$endtime)=split(/\./,$env{$key});
4287: my $active=1;
4288: if ($starttime) {
4289: if ($now<$starttime) { $active=0; }
4290: }
4291: if ($endtime) {
4292: if ($now>$endtime) { $active=0; }
4293: }
4294: if ($active) {
4295: my $value = $role.'/'.$cdom.'/'.$cnum.'/';
4296: if ($sec eq '') {
4297: $sec = 'none';
4298: } else {
4299: $value .= $sec;
4300: }
4301: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4302: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4303: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4304: }
4305: } else {
4306: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4307: }
4308: }
4309: }
4310: }
4311: }
4312: return %courses;
4313: }
4314:
4315: ###############################################
4316:
4317: sub blockcheck {
4318: my ($setters,$activity,$uname,$udom,$url) = @_;
4319:
4320: if (!defined($udom)) {
4321: $udom = $env{'user.domain'};
4322: }
4323: if (!defined($uname)) {
4324: $uname = $env{'user.name'};
4325: }
4326:
4327: # If uname and udom are for a course, check for blocks in the course.
4328:
4329: if (&Apache::lonnet::is_course($udom,$uname)) {
4330: my ($startblock,$endblock,$triggerblock) =
4331: &get_blocks($setters,$activity,$udom,$uname,$url);
4332: return ($startblock,$endblock,$triggerblock);
4333: }
4334:
4335: my $startblock = 0;
4336: my $endblock = 0;
4337: my $triggerblock = '';
4338: my %live_courses = &findallcourses(undef,$uname,$udom);
4339:
4340: # If uname is for a user, and activity is course-specific, i.e.,
4341: # boards, chat or groups, check for blocking in current course only.
4342:
4343: if (($activity eq 'boards' || $activity eq 'chat' ||
4344: $activity eq 'groups') && ($env{'request.course.id'})) {
4345: foreach my $key (keys(%live_courses)) {
4346: if ($key ne $env{'request.course.id'}) {
4347: delete($live_courses{$key});
4348: }
4349: }
4350: }
4351:
4352: my $otheruser = 0;
4353: my %own_courses;
4354: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
4355: # Resource belongs to user other than current user.
4356: $otheruser = 1;
4357: # Gather courses for current user
4358: %own_courses =
4359: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
4360: }
4361:
4362: # Gather active course roles - course coordinator, instructor,
4363: # exam proctor, ta, student, or custom role.
4364:
4365: foreach my $course (keys(%live_courses)) {
4366: my ($cdom,$cnum);
4367: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
4368: $cdom = $env{'course.'.$course.'.domain'};
4369: $cnum = $env{'course.'.$course.'.num'};
4370: } else {
4371: ($cdom,$cnum) = split(/_/,$course);
4372: }
4373: my $no_ownblock = 0;
4374: my $no_userblock = 0;
4375: if ($otheruser && $activity ne 'com') {
4376: # Check if current user has 'evb' priv for this
4377: if (defined($own_courses{$course})) {
4378: foreach my $sec (keys(%{$own_courses{$course}})) {
4379: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4380: if ($sec ne 'none') {
4381: $checkrole .= '/'.$sec;
4382: }
4383: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4384: $no_ownblock = 1;
4385: last;
4386: }
4387: }
4388: }
4389: # if they have 'evb' priv and are currently not playing student
4390: next if (($no_ownblock) &&
4391: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
4392: }
4393: foreach my $sec (keys(%{$live_courses{$course}})) {
4394: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4395: if ($sec ne 'none') {
4396: $checkrole .= '/'.$sec;
4397: }
4398: if ($otheruser) {
4399: # Resource belongs to user other than current user.
4400: # Assemble privs for that user, and check for 'evb' priv.
4401: my (%allroles,%userroles);
4402: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
4403: foreach my $entry (@{$live_courses{$course}{$sec}}) {
4404: my ($trole,$tdom,$tnum,$tsec);
4405: if ($entry =~ /^cr/) {
4406: ($trole,$tdom,$tnum,$tsec) =
4407: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
4408: } else {
4409: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
4410: }
4411: my ($spec,$area,$trest);
4412: $area = '/'.$tdom.'/'.$tnum;
4413: $trest = $tnum;
4414: if ($tsec ne '') {
4415: $area .= '/'.$tsec;
4416: $trest .= '/'.$tsec;
4417: }
4418: $spec = $trole.'.'.$area;
4419: if ($trole =~ /^cr/) {
4420: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
4421: $tdom,$spec,$trest,$area);
4422: } else {
4423: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
4424: $tdom,$spec,$trest,$area);
4425: }
4426: }
4427: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
4428: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
4429: if ($1) {
4430: $no_userblock = 1;
4431: last;
4432: }
4433: }
4434: }
4435: } else {
4436: # Resource belongs to current user
4437: # Check for 'evb' priv via lonnet::allowed().
4438: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4439: $no_ownblock = 1;
4440: last;
4441: }
4442: }
4443: }
4444: # if they have the evb priv and are currently not playing student
4445: next if (($no_ownblock) &&
4446: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
4447: next if ($no_userblock);
4448:
4449: # Retrieve blocking times and identity of locker for course
4450: # of specified user, unless user has 'evb' privilege.
4451:
4452: my ($start,$end,$trigger) =
4453: &get_blocks($setters,$activity,$cdom,$cnum,$url);
4454: if (($start != 0) &&
4455: (($startblock == 0) || ($startblock > $start))) {
4456: $startblock = $start;
4457: if ($trigger ne '') {
4458: $triggerblock = $trigger;
4459: }
4460: }
4461: if (($end != 0) &&
4462: (($endblock == 0) || ($endblock < $end))) {
4463: $endblock = $end;
4464: if ($trigger ne '') {
4465: $triggerblock = $trigger;
4466: }
4467: }
4468: }
4469: return ($startblock,$endblock,$triggerblock);
4470: }
4471:
4472: sub get_blocks {
4473: my ($setters,$activity,$cdom,$cnum,$url) = @_;
4474: my $startblock = 0;
4475: my $endblock = 0;
4476: my $triggerblock = '';
4477: my $course = $cdom.'_'.$cnum;
4478: $setters->{$course} = {};
4479: $setters->{$course}{'staff'} = [];
4480: $setters->{$course}{'times'} = [];
4481: $setters->{$course}{'triggers'} = [];
4482: my (@blockers,%triggered);
4483: my $now = time;
4484: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
4485: if ($activity eq 'docs') {
4486: @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
4487: foreach my $block (@blockers) {
4488: if ($block =~ /^firstaccess____(.+)$/) {
4489: my $item = $1;
4490: my $type = 'map';
4491: my $timersymb = $item;
4492: if ($item eq 'course') {
4493: $type = 'course';
4494: } elsif ($item =~ /___\d+___/) {
4495: $type = 'resource';
4496: } else {
4497: $timersymb = &Apache::lonnet::symbread($item);
4498: }
4499: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4500: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4501: $triggered{$block} = {
4502: start => $start,
4503: end => $end,
4504: type => $type,
4505: };
4506: }
4507: }
4508: } else {
4509: foreach my $block (keys(%commblocks)) {
4510: if ($block =~ m/^(\d+)____(\d+)$/) {
4511: my ($start,$end) = ($1,$2);
4512: if ($start <= time && $end >= time) {
4513: if (ref($commblocks{$block}) eq 'HASH') {
4514: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
4515: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
4516: unless(grep(/^\Q$block\E$/,@blockers)) {
4517: push(@blockers,$block);
4518: }
4519: }
4520: }
4521: }
4522: }
4523: } elsif ($block =~ /^firstaccess____(.+)$/) {
4524: my $item = $1;
4525: my $timersymb = $item;
4526: my $type = 'map';
4527: if ($item eq 'course') {
4528: $type = 'course';
4529: } elsif ($item =~ /___\d+___/) {
4530: $type = 'resource';
4531: } else {
4532: $timersymb = &Apache::lonnet::symbread($item);
4533: }
4534: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4535: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4536: if ($start && $end) {
4537: if (($start <= time) && ($end >= time)) {
4538: unless (grep(/^\Q$block\E$/,@blockers)) {
4539: push(@blockers,$block);
4540: $triggered{$block} = {
4541: start => $start,
4542: end => $end,
4543: type => $type,
4544: };
4545: }
4546: }
4547: }
4548: }
4549: }
4550: }
4551: foreach my $blocker (@blockers) {
4552: my ($staff_name,$staff_dom,$title,$blocks) =
4553: &parse_block_record($commblocks{$blocker});
4554: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
4555: my ($start,$end,$triggertype);
4556: if ($blocker =~ m/^(\d+)____(\d+)$/) {
4557: ($start,$end) = ($1,$2);
4558: } elsif (ref($triggered{$blocker}) eq 'HASH') {
4559: $start = $triggered{$blocker}{'start'};
4560: $end = $triggered{$blocker}{'end'};
4561: $triggertype = $triggered{$blocker}{'type'};
4562: }
4563: if ($start) {
4564: push(@{$$setters{$course}{'times'}}, [$start,$end]);
4565: if ($triggertype) {
4566: push(@{$$setters{$course}{'triggers'}},$triggertype);
4567: } else {
4568: push(@{$$setters{$course}{'triggers'}},0);
4569: }
4570: if ( ($startblock == 0) || ($startblock > $start) ) {
4571: $startblock = $start;
4572: if ($triggertype) {
4573: $triggerblock = $blocker;
4574: }
4575: }
4576: if ( ($endblock == 0) || ($endblock < $end) ) {
4577: $endblock = $end;
4578: if ($triggertype) {
4579: $triggerblock = $blocker;
4580: }
4581: }
4582: }
4583: }
4584: return ($startblock,$endblock,$triggerblock);
4585: }
4586:
4587: sub parse_block_record {
4588: my ($record) = @_;
4589: my ($setuname,$setudom,$title,$blocks);
4590: if (ref($record) eq 'HASH') {
4591: ($setuname,$setudom) = split(/:/,$record->{'setter'});
4592: $title = &unescape($record->{'event'});
4593: $blocks = $record->{'blocks'};
4594: } else {
4595: my @data = split(/:/,$record,3);
4596: if (scalar(@data) eq 2) {
4597: $title = $data[1];
4598: ($setuname,$setudom) = split(/@/,$data[0]);
4599: } else {
4600: ($setuname,$setudom,$title) = @data;
4601: }
4602: $blocks = { 'com' => 'on' };
4603: }
4604: return ($setuname,$setudom,$title,$blocks);
4605: }
4606:
4607: sub blocking_status {
4608: my ($activity,$uname,$udom,$url) = @_;
4609: my %setters;
4610:
4611: # check for active blocking
4612: my ($startblock,$endblock,$triggerblock) =
4613: &blockcheck(\%setters,$activity,$uname,$udom,$url);
4614: my $blocked = 0;
4615: if ($startblock && $endblock) {
4616: $blocked = 1;
4617: }
4618:
4619: # caller just wants to know whether a block is active
4620: if (!wantarray) { return $blocked; }
4621:
4622: # build a link to a popup window containing the details
4623: my $querystring = "?activity=$activity";
4624: # $uname and $udom decide whose portfolio the user is trying to look at
4625: if ($activity eq 'port') {
4626: $querystring .= "&udom=$udom" if $udom;
4627: $querystring .= "&uname=$uname" if $uname;
4628: } elsif ($activity eq 'docs') {
4629: $querystring .= '&url='.&HTML::Entities::encode($url,'&"');
4630: }
4631:
4632: my $output .= <<'END_MYBLOCK';
4633: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
4634: var options = "width=" + w + ",height=" + h + ",";
4635: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
4636: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
4637: var newWin = window.open(url, wdwName, options);
4638: newWin.focus();
4639: }
4640: END_MYBLOCK
4641:
4642: $output = Apache::lonhtmlcommon::scripttag($output);
4643:
4644: my $popupUrl = "/adm/blockingstatus/$querystring";
4645: my $text = &mt('Communication Blocked');
4646: if ($activity eq 'docs') {
4647: $text = &mt('Content Access Blocked');
4648: } elsif ($activity eq 'printout') {
4649: $text = &mt('Printing Blocked');
4650: }
4651: $output .= <<"END_BLOCK";
4652: <div class='LC_comblock'>
4653: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4654: title='$text'>
4655: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
4656: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4657: title='$text'>$text</a>
4658: </div>
4659:
4660: END_BLOCK
4661:
4662: return ($blocked, $output);
4663: }
4664:
4665: ###############################################
4666:
4667: sub check_ip_acc {
4668: my ($acc)=@_;
4669: &Apache::lonxml::debug("acc is $acc");
4670: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
4671: return 1;
4672: }
4673: my $allowed=0;
4674: my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
4675:
4676: my $name;
4677: foreach my $pattern (split(',',$acc)) {
4678: $pattern =~ s/^\s*//;
4679: $pattern =~ s/\s*$//;
4680: if ($pattern =~ /\*$/) {
4681: #35.8.*
4682: $pattern=~s/\*//;
4683: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4684: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
4685: #35.8.3.[34-56]
4686: my $low=$2;
4687: my $high=$3;
4688: $pattern=$1;
4689: if ($ip =~ /^\Q$pattern\E/) {
4690: my $last=(split(/\./,$ip))[3];
4691: if ($last <=$high && $last >=$low) { $allowed=1; }
4692: }
4693: } elsif ($pattern =~ /^\*/) {
4694: #*.msu.edu
4695: $pattern=~s/\*//;
4696: if (!defined($name)) {
4697: use Socket;
4698: my $netaddr=inet_aton($ip);
4699: ($name)=gethostbyaddr($netaddr,AF_INET);
4700: }
4701: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4702: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
4703: #127.0.0.1
4704: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4705: } else {
4706: #some.name.com
4707: if (!defined($name)) {
4708: use Socket;
4709: my $netaddr=inet_aton($ip);
4710: ($name)=gethostbyaddr($netaddr,AF_INET);
4711: }
4712: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4713: }
4714: if ($allowed) { last; }
4715: }
4716: return $allowed;
4717: }
4718:
4719: ###############################################
4720:
4721: =pod
4722:
4723: =head1 Domain Template Functions
4724:
4725: =over 4
4726:
4727: =item * &determinedomain()
4728:
4729: Inputs: $domain (usually will be undef)
4730:
4731: Returns: Determines which domain should be used for designs
4732:
4733: =cut
4734:
4735: ###############################################
4736: sub determinedomain {
4737: my $domain=shift;
4738: if (! $domain) {
4739: # Determine domain if we have not been given one
4740: $domain = &Apache::lonnet::default_login_domain();
4741: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
4742: if ($env{'request.role.domain'}) {
4743: $domain=$env{'request.role.domain'};
4744: }
4745: }
4746: return $domain;
4747: }
4748: ###############################################
4749:
4750: sub devalidate_domconfig_cache {
4751: my ($udom)=@_;
4752: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
4753: }
4754:
4755: # ---------------------- Get domain configuration for a domain
4756: sub get_domainconf {
4757: my ($udom) = @_;
4758: my $cachetime=1800;
4759: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
4760: if (defined($cached)) { return %{$result}; }
4761:
4762: my %domconfig = &Apache::lonnet::get_dom('configuration',
4763: ['login','rolecolors','autoenroll'],$udom);
4764: my (%designhash,%legacy);
4765: if (keys(%domconfig) > 0) {
4766: if (ref($domconfig{'login'}) eq 'HASH') {
4767: if (keys(%{$domconfig{'login'}})) {
4768: foreach my $key (keys(%{$domconfig{'login'}})) {
4769: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
4770: if ($key eq 'loginvia') {
4771: if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
4772: foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
4773: if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
4774: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
4775: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
4776: $designhash{$udom.'.login.loginvia'} = $server;
4777: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
4778:
4779: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
4780: } else {
4781: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
4782: }
4783: if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
4784: $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
4785: }
4786: }
4787: }
4788: }
4789: }
4790: } else {
4791: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
4792: $designhash{$udom.'.login.'.$key.'_'.$img} =
4793: $domconfig{'login'}{$key}{$img};
4794: }
4795: }
4796: } else {
4797: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
4798: }
4799: }
4800: } else {
4801: $legacy{'login'} = 1;
4802: }
4803: } else {
4804: $legacy{'login'} = 1;
4805: }
4806: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
4807: if (keys(%{$domconfig{'rolecolors'}})) {
4808: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
4809: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
4810: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
4811: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
4812: }
4813: }
4814: }
4815: } else {
4816: $legacy{'rolecolors'} = 1;
4817: }
4818: } else {
4819: $legacy{'rolecolors'} = 1;
4820: }
4821: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
4822: if ($domconfig{'autoenroll'}{'co-owners'}) {
4823: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
4824: }
4825: }
4826: if (keys(%legacy) > 0) {
4827: my %legacyhash = &get_legacy_domconf($udom);
4828: foreach my $item (keys(%legacyhash)) {
4829: if ($item =~ /^\Q$udom\E\.login/) {
4830: if ($legacy{'login'}) {
4831: $designhash{$item} = $legacyhash{$item};
4832: }
4833: } else {
4834: if ($legacy{'rolecolors'}) {
4835: $designhash{$item} = $legacyhash{$item};
4836: }
4837: }
4838: }
4839: }
4840: } else {
4841: %designhash = &get_legacy_domconf($udom);
4842: }
4843: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
4844: $cachetime);
4845: return %designhash;
4846: }
4847:
4848: sub get_legacy_domconf {
4849: my ($udom) = @_;
4850: my %legacyhash;
4851: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
4852: my $designfile = $designdir.'/'.$udom.'.tab';
4853: if (-e $designfile) {
4854: if ( open (my $fh,"<$designfile") ) {
4855: while (my $line = <$fh>) {
4856: next if ($line =~ /^\#/);
4857: chomp($line);
4858: my ($key,$val)=(split(/\=/,$line));
4859: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
4860: }
4861: close($fh);
4862: }
4863: }
4864: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
4865: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
4866: }
4867: return %legacyhash;
4868: }
4869:
4870: =pod
4871:
4872: =item * &domainlogo()
4873:
4874: Inputs: $domain (usually will be undef)
4875:
4876: Returns: A link to a domain logo, if the domain logo exists.
4877: If the domain logo does not exist, a description of the domain.
4878:
4879: =cut
4880:
4881: ###############################################
4882: sub domainlogo {
4883: my $domain = &determinedomain(shift);
4884: my %designhash = &get_domainconf($domain);
4885: # See if there is a logo
4886: if ($designhash{$domain.'.login.domlogo'} ne '') {
4887: my $imgsrc = $designhash{$domain.'.login.domlogo'};
4888: if ($imgsrc =~ m{^/(adm|res)/}) {
4889: if ($imgsrc =~ m{^/res/}) {
4890: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
4891: &Apache::lonnet::repcopy($local_name);
4892: }
4893: $imgsrc = &lonhttpdurl($imgsrc);
4894: }
4895: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
4896: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
4897: return &Apache::lonnet::domain($domain,'description');
4898: } else {
4899: return '';
4900: }
4901: }
4902: ##############################################
4903:
4904: =pod
4905:
4906: =item * &designparm()
4907:
4908: Inputs: $which parameter; $domain (usually will be undef)
4909:
4910: Returns: value of designparamter $which
4911:
4912: =cut
4913:
4914:
4915: ##############################################
4916: sub designparm {
4917: my ($which,$domain)=@_;
4918: if (exists($env{'environment.color.'.$which})) {
4919: return $env{'environment.color.'.$which};
4920: }
4921: $domain=&determinedomain($domain);
4922: my %domdesign;
4923: unless ($domain eq 'public') {
4924: %domdesign = &get_domainconf($domain);
4925: }
4926: my $output;
4927: if ($domdesign{$domain.'.'.$which} ne '') {
4928: $output = $domdesign{$domain.'.'.$which};
4929: } else {
4930: $output = $defaultdesign{$which};
4931: }
4932: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
4933: ($which =~ /login\.(img|logo|domlogo|login)/)) {
4934: if ($output =~ m{^/(adm|res)/}) {
4935: if ($output =~ m{^/res/}) {
4936: my $local_name = &Apache::lonnet::filelocation('',$output);
4937: &Apache::lonnet::repcopy($local_name);
4938: }
4939: $output = &lonhttpdurl($output);
4940: }
4941: }
4942: return $output;
4943: }
4944:
4945: ##############################################
4946: =pod
4947:
4948: =item * &authorspace()
4949:
4950: Inputs: $url (usually will be undef).
4951:
4952: Returns: Path to Authoring Space containing the resource or
4953: directory being viewed (or for which action is being taken).
4954: If $url is provided, and begins /priv/<domain>/<uname>
4955: the path will be that portion of the $context argument.
4956: Otherwise the path will be for the author space of the current
4957: user when the current role is author, or for that of the
4958: co-author/assistant co-author space when the current role
4959: is co-author or assistant co-author.
4960:
4961: =cut
4962:
4963: sub authorspace {
4964: my ($url) = @_;
4965: if ($url ne '') {
4966: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
4967: return $1;
4968: }
4969: }
4970: my $caname = '';
4971: my $cadom = '';
4972: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
4973: ($cadom,$caname) =
4974: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
4975: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
4976: $caname = $env{'user.name'};
4977: $cadom = $env{'user.domain'};
4978: }
4979: if (($caname ne '') && ($cadom ne '')) {
4980: return "/priv/$cadom/$caname/";
4981: }
4982: return;
4983: }
4984:
4985: ##############################################
4986: =pod
4987:
4988: =item * &head_subbox()
4989:
4990: Inputs: $content (contains HTML code with page functions, etc.)
4991:
4992: Returns: HTML div with $content
4993: To be included in page header
4994:
4995: =cut
4996:
4997: sub head_subbox {
4998: my ($content)=@_;
4999: my $output =
5000: '<div class="LC_head_subbox">'
5001: .$content
5002: .'</div>'
5003: }
5004:
5005: ##############################################
5006: =pod
5007:
5008: =item * &CSTR_pageheader()
5009:
5010: Input: (optional) filename from which breadcrumb trail is built.
5011: In most cases no input as needed, as $env{'request.filename'}
5012: is appropriate for use in building the breadcrumb trail.
5013:
5014: Returns: HTML div with CSTR path and recent box
5015: To be included on Authoring Space pages
5016:
5017: =cut
5018:
5019: sub CSTR_pageheader {
5020: my ($trailfile) = @_;
5021: if ($trailfile eq '') {
5022: $trailfile = $env{'request.filename'};
5023: }
5024:
5025: # this is for resources; directories have customtitle, and crumbs
5026: # and select recent are created in lonpubdir.pm
5027:
5028: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
5029: my ($udom,$uname,$thisdisfn)=
5030: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
5031: my $formaction = "/priv/$udom/$uname/$thisdisfn";
5032: $formaction =~ s{/+}{/}g;
5033:
5034: my $parentpath = '';
5035: my $lastitem = '';
5036: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
5037: $parentpath = $1;
5038: $lastitem = $2;
5039: } else {
5040: $lastitem = $thisdisfn;
5041: }
5042:
5043: my $output =
5044: '<div>'
5045: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
5046: .'<b>'.&mt('Authoring Space:').'</b> '
5047: .'<form name="dirs" method="post" action="'.$formaction
5048: .'" target="_top">' #FIXME lonpubdir: target="_parent"
5049: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
5050:
5051: if ($lastitem) {
5052: $output .=
5053: '<span class="LC_filename">'
5054: .$lastitem
5055: .'</span>';
5056: }
5057: $output .=
5058: '<br />'
5059: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
5060: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
5061: .'</form>'
5062: .&Apache::lonmenu::constspaceform()
5063: .'</div>';
5064:
5065: return $output;
5066: }
5067:
5068: ###############################################
5069: ###############################################
5070:
5071: =pod
5072:
5073: =back
5074:
5075: =head1 HTML Helpers
5076:
5077: =over 4
5078:
5079: =item * &bodytag()
5080:
5081: Returns a uniform header for LON-CAPA web pages.
5082:
5083: Inputs:
5084:
5085: =over 4
5086:
5087: =item * $title, A title to be displayed on the page.
5088:
5089: =item * $function, the current role (can be undef).
5090:
5091: =item * $addentries, extra parameters for the <body> tag.
5092:
5093: =item * $bodyonly, if defined, only return the <body> tag.
5094:
5095: =item * $domain, if defined, force a given domain.
5096:
5097: =item * $forcereg, if page should register as content page (relevant for
5098: text interface only)
5099:
5100: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
5101: navigational links
5102:
5103: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
5104:
5105: =item * $args, optional argument valid values are
5106: no_auto_mt_title -> prevents &mt()ing the title arg
5107: inherit_jsmath -> when creating popup window in a page,
5108: should it have jsmath forced on by the
5109: current page
5110:
5111: =item * $advtoolsref, optional argument, ref to an array containing
5112: inlineremote items to be added in "Functions" menu below
5113: breadcrumbs.
5114:
5115: =back
5116:
5117: Returns: A uniform header for LON-CAPA web pages.
5118: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
5119: If $bodyonly is undef or zero, an html string containing a <body> tag and
5120: other decorations will be returned.
5121:
5122: =cut
5123:
5124: sub bodytag {
5125: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
5126: $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
5127:
5128: my $public;
5129: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
5130: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
5131: $public = 1;
5132: }
5133: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
5134: my $httphost = $args->{'use_absolute'};
5135:
5136: $function = &get_users_function() if (!$function);
5137: my $img = &designparm($function.'.img',$domain);
5138: my $font = &designparm($function.'.font',$domain);
5139: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
5140:
5141: my %design = ( 'style' => 'margin-top: 0',
5142: 'bgcolor' => $pgbg,
5143: 'text' => $font,
5144: 'alink' => &designparm($function.'.alink',$domain),
5145: 'vlink' => &designparm($function.'.vlink',$domain),
5146: 'link' => &designparm($function.'.link',$domain),);
5147: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
5148:
5149: # role and realm
5150: my ($role,$realm) = split(/\./,$env{'request.role'},2);
5151: if ($role eq 'ca') {
5152: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
5153: $realm = &plainname($rname,$rdom);
5154: }
5155: # realm
5156: if ($env{'request.course.id'}) {
5157: if ($env{'request.role'} !~ /^cr/) {
5158: $role = &Apache::lonnet::plaintext($role,&course_type());
5159: }
5160: if ($env{'request.course.sec'}) {
5161: $role .= (' 'x2).'- '.&mt('section:').' '.$env{'request.course.sec'};
5162: }
5163: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
5164: } else {
5165: $role = &Apache::lonnet::plaintext($role);
5166: }
5167:
5168: if (!$realm) { $realm=' '; }
5169:
5170: my $extra_body_attr = &make_attr_string($forcereg,\%design);
5171:
5172: # construct main body tag
5173: my $bodytag = "<body $extra_body_attr>".
5174: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
5175:
5176: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
5177:
5178: if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
5179: return $bodytag;
5180: }
5181:
5182: if ($public) {
5183: undef($role);
5184: }
5185:
5186: my $titleinfo = '<h1>'.$title.'</h1>';
5187: #
5188: # Extra info if you are the DC
5189: my $dc_info = '';
5190: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
5191: $env{'course.'.$env{'request.course.id'}.
5192: '.domain'}.'/'})) {
5193: my $cid = $env{'request.course.id'};
5194: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
5195: $dc_info =~ s/\s+$//;
5196: }
5197:
5198: $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
5199:
5200: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
5201:
5202: # if ($env{'request.state'} eq 'construct') {
5203: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
5204: # }
5205:
5206: $bodytag .= Apache::lonhtmlcommon::scripttag(
5207: Apache::lonmenu::utilityfunctions($httphost), 'start');
5208:
5209: my ($left,$right) = Apache::lonmenu::primary_menu();
5210:
5211: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
5212: if ($dc_info) {
5213: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
5214: }
5215: $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
5216: <em>$realm</em> $dc_info</div>|;
5217: return $bodytag;
5218: }
5219:
5220: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
5221: $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
5222: }
5223:
5224: $bodytag .= $right;
5225:
5226: if ($dc_info) {
5227: $dc_info = &dc_courseid_toggle($dc_info);
5228: }
5229: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
5230:
5231: #don't show menus for public users
5232: if ($args->{'no_secondary_menu'}) {
5233: return $bodytag;
5234: }
5235: if (!$public){
5236: $bodytag .= Apache::lonmenu::secondary_menu($httphost);
5237: $bodytag .= Apache::lonmenu::serverform();
5238: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5239: if ($env{'request.state'} eq 'construct') {
5240: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
5241: $args->{'bread_crumbs'});
5242: } elsif ($forcereg) {
5243: $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
5244: $args->{'group'});
5245: } else {
5246: $bodytag .=
5247: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
5248: $forcereg,$args->{'group'},
5249: $args->{'bread_crumbs'},
5250: $advtoolsref);
5251: }
5252: }else{
5253: # this is to seperate menu from content when there's no secondary
5254: # menu. Especially needed for public accessible ressources.
5255: $bodytag .= '<hr style="clear:both" />';
5256: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5257: }
5258:
5259: return $bodytag;
5260: }
5261:
5262: sub dc_courseid_toggle {
5263: my ($dc_info) = @_;
5264: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
5265: '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
5266: &mt('(More ...)').'</a></span>'.
5267: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
5268: }
5269:
5270: sub make_attr_string {
5271: my ($register,$attr_ref) = @_;
5272:
5273: if ($attr_ref && !ref($attr_ref)) {
5274: die("addentries Must be a hash ref ".
5275: join(':',caller(1))." ".
5276: join(':',caller(0))." ");
5277: }
5278:
5279: if ($register) {
5280: my ($on_load,$on_unload);
5281: foreach my $key (keys(%{$attr_ref})) {
5282: if (lc($key) eq 'onload') {
5283: $on_load.=$attr_ref->{$key}.';';
5284: delete($attr_ref->{$key});
5285:
5286: } elsif (lc($key) eq 'onunload') {
5287: $on_unload.=$attr_ref->{$key}.';';
5288: delete($attr_ref->{$key});
5289: }
5290: }
5291: $attr_ref->{'onload'} = $on_load;
5292: $attr_ref->{'onunload'}= $on_unload;
5293: }
5294:
5295: my $attr_string;
5296: foreach my $attr (sort(keys(%$attr_ref))) {
5297: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
5298: }
5299: return $attr_string;
5300: }
5301:
5302:
5303: ###############################################
5304: ###############################################
5305:
5306: =pod
5307:
5308: =item * &endbodytag()
5309:
5310: Returns a uniform footer for LON-CAPA web pages.
5311:
5312: Inputs: 1 - optional reference to an args hash
5313: If in the hash, key for noredirectlink has a value which evaluates to true,
5314: a 'Continue' link is not displayed if the page contains an
5315: internal redirect in the <head></head> section,
5316: i.e., $env{'internal.head.redirect'} exists
5317:
5318: =cut
5319:
5320: sub endbodytag {
5321: my ($args) = @_;
5322: my $endbodytag;
5323: unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
5324: $endbodytag='</body>';
5325: }
5326: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
5327: if ( exists( $env{'internal.head.redirect'} ) ) {
5328: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
5329: $endbodytag=
5330: "<br /><a href=\"$env{'internal.head.redirect'}\">".
5331: &mt('Continue').'</a>'.
5332: $endbodytag;
5333: }
5334: }
5335: return $endbodytag;
5336: }
5337:
5338: =pod
5339:
5340: =item * &standard_css()
5341:
5342: Returns a style sheet
5343:
5344: Inputs: (all optional)
5345: domain -> force to color decorate a page for a specific
5346: domain
5347: function -> force usage of a specific rolish color scheme
5348: bgcolor -> override the default page bgcolor
5349:
5350: =cut
5351:
5352: sub standard_css {
5353: my ($function,$domain,$bgcolor) = @_;
5354: $function = &get_users_function() if (!$function);
5355: my $img = &designparm($function.'.img', $domain);
5356: my $tabbg = &designparm($function.'.tabbg', $domain);
5357: my $font = &designparm($function.'.font', $domain);
5358: my $fontmenu = &designparm($function.'.fontmenu', $domain);
5359: #second colour for later usage
5360: my $sidebg = &designparm($function.'.sidebg',$domain);
5361: my $pgbg_or_bgcolor =
5362: $bgcolor ||
5363: &designparm($function.'.pgbg', $domain);
5364: my $pgbg = &designparm($function.'.pgbg', $domain);
5365: my $alink = &designparm($function.'.alink', $domain);
5366: my $vlink = &designparm($function.'.vlink', $domain);
5367: my $link = &designparm($function.'.link', $domain);
5368:
5369: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
5370: my $mono = 'monospace';
5371: my $data_table_head = $sidebg;
5372: my $data_table_light = '#FAFAFA';
5373: my $data_table_dark = '#E0E0E0';
5374: my $data_table_darker = '#CCCCCC';
5375: my $data_table_highlight = '#FFFF00';
5376: my $mail_new = '#FFBB77';
5377: my $mail_new_hover = '#DD9955';
5378: my $mail_read = '#BBBB77';
5379: my $mail_read_hover = '#999944';
5380: my $mail_replied = '#AAAA88';
5381: my $mail_replied_hover = '#888855';
5382: my $mail_other = '#99BBBB';
5383: my $mail_other_hover = '#669999';
5384: my $table_header = '#DDDDDD';
5385: my $feedback_link_bg = '#BBBBBB';
5386: my $lg_border_color = '#C8C8C8';
5387: my $button_hover = '#BF2317';
5388:
5389: my $border = ($env{'browser.type'} eq 'explorer' ||
5390: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
5391: : '0 3px 0 4px';
5392:
5393:
5394: return <<END;
5395:
5396: /* needed for iframe to allow 100% height in FF */
5397: body, html {
5398: margin: 0;
5399: padding: 0 0.5%;
5400: height: 99%; /* to avoid scrollbars */
5401: }
5402:
5403: body {
5404: font-family: $sans;
5405: line-height:130%;
5406: font-size:0.83em;
5407: color:$font;
5408: }
5409:
5410: a:focus,
5411: a:focus img {
5412: color: red;
5413: }
5414:
5415: form, .inline {
5416: display: inline;
5417: }
5418:
5419: .LC_right {
5420: text-align:right;
5421: }
5422:
5423: .LC_middle {
5424: vertical-align:middle;
5425: }
5426:
5427: .LC_floatleft {
5428: float: left;
5429: }
5430:
5431: .LC_floatright {
5432: float: right;
5433: }
5434:
5435: .LC_400Box {
5436: width:400px;
5437: }
5438:
5439: .LC_iframecontainer {
5440: width: 98%;
5441: margin: 0;
5442: position: fixed;
5443: top: 8.5em;
5444: bottom: 0;
5445: }
5446:
5447: .LC_iframecontainer iframe{
5448: border: none;
5449: width: 100%;
5450: height: 100%;
5451: }
5452:
5453: .LC_filename {
5454: font-family: $mono;
5455: white-space:pre;
5456: font-size: 120%;
5457: }
5458:
5459: .LC_fileicon {
5460: border: none;
5461: height: 1.3em;
5462: vertical-align: text-bottom;
5463: margin-right: 0.3em;
5464: text-decoration:none;
5465: }
5466:
5467: .LC_setting {
5468: text-decoration:underline;
5469: }
5470:
5471: .LC_error {
5472: color: red;
5473: }
5474:
5475: .LC_warning {
5476: color: darkorange;
5477: }
5478:
5479: .LC_diff_removed {
5480: color: red;
5481: }
5482:
5483: .LC_info,
5484: .LC_success,
5485: .LC_diff_added {
5486: color: green;
5487: }
5488:
5489: div.LC_confirm_box {
5490: background-color: #FAFAFA;
5491: border: 1px solid $lg_border_color;
5492: margin-right: 0;
5493: padding: 5px;
5494: }
5495:
5496: div.LC_confirm_box .LC_error img,
5497: div.LC_confirm_box .LC_success img {
5498: vertical-align: middle;
5499: }
5500:
5501: .LC_icon {
5502: border: none;
5503: vertical-align: middle;
5504: }
5505:
5506: .LC_docs_spacer {
5507: width: 25px;
5508: height: 1px;
5509: border: none;
5510: }
5511:
5512: .LC_internal_info {
5513: color: #999999;
5514: }
5515:
5516: .LC_discussion {
5517: background: $data_table_dark;
5518: border: 1px solid black;
5519: margin: 2px;
5520: }
5521:
5522: .LC_disc_action_left {
5523: background: $sidebg;
5524: text-align: left;
5525: padding: 4px;
5526: margin: 2px;
5527: }
5528:
5529: .LC_disc_action_right {
5530: background: $sidebg;
5531: text-align: right;
5532: padding: 4px;
5533: margin: 2px;
5534: }
5535:
5536: .LC_disc_new_item {
5537: background: white;
5538: border: 2px solid red;
5539: margin: 4px;
5540: padding: 4px;
5541: }
5542:
5543: .LC_disc_old_item {
5544: background: white;
5545: margin: 4px;
5546: padding: 4px;
5547: }
5548:
5549: table.LC_pastsubmission {
5550: border: 1px solid black;
5551: margin: 2px;
5552: }
5553:
5554: table#LC_menubuttons {
5555: width: 100%;
5556: background: $pgbg;
5557: border: 2px;
5558: border-collapse: separate;
5559: padding: 0;
5560: }
5561:
5562: table#LC_title_bar a {
5563: color: $fontmenu;
5564: }
5565:
5566: table#LC_title_bar {
5567: clear: both;
5568: display: none;
5569: }
5570:
5571: table#LC_title_bar,
5572: table.LC_breadcrumbs, /* obsolete? */
5573: table#LC_title_bar.LC_with_remote {
5574: width: 100%;
5575: border-color: $pgbg;
5576: border-style: solid;
5577: border-width: $border;
5578: background: $pgbg;
5579: color: $fontmenu;
5580: border-collapse: collapse;
5581: padding: 0;
5582: margin: 0;
5583: }
5584:
5585: ul.LC_breadcrumb_tools_outerlist {
5586: margin: 0;
5587: padding: 0;
5588: position: relative;
5589: list-style: none;
5590: }
5591: ul.LC_breadcrumb_tools_outerlist li {
5592: display: inline;
5593: }
5594:
5595: .LC_breadcrumb_tools_navigation {
5596: padding: 0;
5597: margin: 0;
5598: float: left;
5599: }
5600: .LC_breadcrumb_tools_tools {
5601: padding: 0;
5602: margin: 0;
5603: float: right;
5604: }
5605:
5606: table#LC_title_bar td {
5607: background: $tabbg;
5608: }
5609:
5610: table#LC_menubuttons img {
5611: border: none;
5612: }
5613:
5614: .LC_breadcrumbs_component {
5615: float: right;
5616: margin: 0 1em;
5617: }
5618: .LC_breadcrumbs_component img {
5619: vertical-align: middle;
5620: }
5621:
5622: td.LC_table_cell_checkbox {
5623: text-align: center;
5624: }
5625:
5626: .LC_fontsize_small {
5627: font-size: 70%;
5628: }
5629:
5630: #LC_breadcrumbs {
5631: clear:both;
5632: background: $sidebg;
5633: border-bottom: 1px solid $lg_border_color;
5634: line-height: 2.5em;
5635: overflow: hidden;
5636: margin: 0;
5637: padding: 0;
5638: text-align: left;
5639: }
5640:
5641: .LC_head_subbox, .LC_actionbox {
5642: clear:both;
5643: background: #F8F8F8; /* $sidebg; */
5644: border: 1px solid $sidebg;
5645: margin: 0 0 10px 0;
5646: padding: 3px;
5647: text-align: left;
5648: }
5649:
5650: .LC_fontsize_medium {
5651: font-size: 85%;
5652: }
5653:
5654: .LC_fontsize_large {
5655: font-size: 120%;
5656: }
5657:
5658: .LC_menubuttons_inline_text {
5659: color: $font;
5660: font-size: 90%;
5661: padding-left:3px;
5662: }
5663:
5664: .LC_menubuttons_inline_text img{
5665: vertical-align: middle;
5666: }
5667:
5668: li.LC_menubuttons_inline_text img {
5669: cursor:pointer;
5670: text-decoration: none;
5671: }
5672:
5673: .LC_menubuttons_link {
5674: text-decoration: none;
5675: }
5676:
5677: .LC_menubuttons_category {
5678: color: $font;
5679: background: $pgbg;
5680: font-size: larger;
5681: font-weight: bold;
5682: }
5683:
5684: td.LC_menubuttons_text {
5685: color: $font;
5686: }
5687:
5688: .LC_current_location {
5689: background: $tabbg;
5690: }
5691:
5692: table.LC_data_table {
5693: border: 1px solid #000000;
5694: border-collapse: separate;
5695: border-spacing: 1px;
5696: background: $pgbg;
5697: }
5698:
5699: .LC_data_table_dense {
5700: font-size: small;
5701: }
5702:
5703: table.LC_nested_outer {
5704: border: 1px solid #000000;
5705: border-collapse: collapse;
5706: border-spacing: 0;
5707: width: 100%;
5708: }
5709:
5710: table.LC_innerpickbox,
5711: table.LC_nested {
5712: border: none;
5713: border-collapse: collapse;
5714: border-spacing: 0;
5715: width: 100%;
5716: }
5717:
5718: table.LC_data_table tr th,
5719: table.LC_calendar tr th,
5720: table.LC_prior_tries tr th,
5721: table.LC_innerpickbox tr th {
5722: font-weight: bold;
5723: background-color: $data_table_head;
5724: color:$fontmenu;
5725: font-size:90%;
5726: }
5727:
5728: table.LC_innerpickbox tr th,
5729: table.LC_innerpickbox tr td {
5730: vertical-align: top;
5731: }
5732:
5733: table.LC_data_table tr.LC_info_row > td {
5734: background-color: #CCCCCC;
5735: font-weight: bold;
5736: text-align: left;
5737: }
5738:
5739: table.LC_data_table tr.LC_odd_row > td {
5740: background-color: $data_table_light;
5741: padding: 2px;
5742: vertical-align: top;
5743: }
5744:
5745: table.LC_pick_box tr > td.LC_odd_row {
5746: background-color: $data_table_light;
5747: vertical-align: top;
5748: }
5749:
5750: table.LC_data_table tr.LC_even_row > td {
5751: background-color: $data_table_dark;
5752: padding: 2px;
5753: vertical-align: top;
5754: }
5755:
5756: table.LC_pick_box tr > td.LC_even_row {
5757: background-color: $data_table_dark;
5758: vertical-align: top;
5759: }
5760:
5761: table.LC_data_table tr.LC_data_table_highlight td {
5762: background-color: $data_table_darker;
5763: }
5764:
5765: table.LC_data_table tr td.LC_leftcol_header {
5766: background-color: $data_table_head;
5767: font-weight: bold;
5768: }
5769:
5770: table.LC_data_table tr.LC_empty_row td,
5771: table.LC_nested tr.LC_empty_row td {
5772: font-weight: bold;
5773: font-style: italic;
5774: text-align: center;
5775: padding: 8px;
5776: }
5777:
5778: table.LC_data_table tr.LC_empty_row td,
5779: table.LC_data_table tr.LC_footer_row td {
5780: background-color: $sidebg;
5781: }
5782:
5783: table.LC_nested tr.LC_empty_row td {
5784: background-color: #FFFFFF;
5785: }
5786:
5787: table.LC_caption {
5788: }
5789:
5790: table.LC_nested tr.LC_empty_row td {
5791: padding: 4ex
5792: }
5793:
5794: table.LC_nested_outer tr th {
5795: font-weight: bold;
5796: color:$fontmenu;
5797: background-color: $data_table_head;
5798: font-size: small;
5799: border-bottom: 1px solid #000000;
5800: }
5801:
5802: table.LC_nested_outer tr td.LC_subheader {
5803: background-color: $data_table_head;
5804: font-weight: bold;
5805: font-size: small;
5806: border-bottom: 1px solid #000000;
5807: text-align: right;
5808: }
5809:
5810: table.LC_nested tr.LC_info_row td {
5811: background-color: #CCCCCC;
5812: font-weight: bold;
5813: font-size: small;
5814: text-align: center;
5815: }
5816:
5817: table.LC_nested tr.LC_info_row td.LC_left_item,
5818: table.LC_nested_outer tr th.LC_left_item {
5819: text-align: left;
5820: }
5821:
5822: table.LC_nested td {
5823: background-color: #FFFFFF;
5824: font-size: small;
5825: }
5826:
5827: table.LC_nested_outer tr th.LC_right_item,
5828: table.LC_nested tr.LC_info_row td.LC_right_item,
5829: table.LC_nested tr.LC_odd_row td.LC_right_item,
5830: table.LC_nested tr td.LC_right_item {
5831: text-align: right;
5832: }
5833:
5834: table.LC_nested tr.LC_odd_row td {
5835: background-color: #EEEEEE;
5836: }
5837:
5838: table.LC_createuser {
5839: }
5840:
5841: table.LC_createuser tr.LC_section_row td {
5842: font-size: small;
5843: }
5844:
5845: table.LC_createuser tr.LC_info_row td {
5846: background-color: #CCCCCC;
5847: font-weight: bold;
5848: text-align: center;
5849: }
5850:
5851: table.LC_calendar {
5852: border: 1px solid #000000;
5853: border-collapse: collapse;
5854: width: 98%;
5855: }
5856:
5857: table.LC_calendar_pickdate {
5858: font-size: xx-small;
5859: }
5860:
5861: table.LC_calendar tr td {
5862: border: 1px solid #000000;
5863: vertical-align: top;
5864: width: 14%;
5865: }
5866:
5867: table.LC_calendar tr td.LC_calendar_day_empty {
5868: background-color: $data_table_dark;
5869: }
5870:
5871: table.LC_calendar tr td.LC_calendar_day_current {
5872: background-color: $data_table_highlight;
5873: }
5874:
5875: table.LC_data_table tr td.LC_mail_new {
5876: background-color: $mail_new;
5877: }
5878:
5879: table.LC_data_table tr.LC_mail_new:hover {
5880: background-color: $mail_new_hover;
5881: }
5882:
5883: table.LC_data_table tr td.LC_mail_read {
5884: background-color: $mail_read;
5885: }
5886:
5887: /*
5888: table.LC_data_table tr.LC_mail_read:hover {
5889: background-color: $mail_read_hover;
5890: }
5891: */
5892:
5893: table.LC_data_table tr td.LC_mail_replied {
5894: background-color: $mail_replied;
5895: }
5896:
5897: /*
5898: table.LC_data_table tr.LC_mail_replied:hover {
5899: background-color: $mail_replied_hover;
5900: }
5901: */
5902:
5903: table.LC_data_table tr td.LC_mail_other {
5904: background-color: $mail_other;
5905: }
5906:
5907: /*
5908: table.LC_data_table tr.LC_mail_other:hover {
5909: background-color: $mail_other_hover;
5910: }
5911: */
5912:
5913: table.LC_data_table tr > td.LC_browser_file,
5914: table.LC_data_table tr > td.LC_browser_file_published {
5915: background: #AAEE77;
5916: }
5917:
5918: table.LC_data_table tr > td.LC_browser_file_locked,
5919: table.LC_data_table tr > td.LC_browser_file_unpublished {
5920: background: #FFAA99;
5921: }
5922:
5923: table.LC_data_table tr > td.LC_browser_file_obsolete {
5924: background: #888888;
5925: }
5926:
5927: table.LC_data_table tr > td.LC_browser_file_modified,
5928: table.LC_data_table tr > td.LC_browser_file_metamodified {
5929: background: #F8F866;
5930: }
5931:
5932: table.LC_data_table tr.LC_browser_folder > td {
5933: background: #E0E8FF;
5934: }
5935:
5936: table.LC_data_table tr > td.LC_roles_is {
5937: /* background: #77FF77; */
5938: }
5939:
5940: table.LC_data_table tr > td.LC_roles_future {
5941: border-right: 8px solid #FFFF77;
5942: }
5943:
5944: table.LC_data_table tr > td.LC_roles_will {
5945: border-right: 8px solid #FFAA77;
5946: }
5947:
5948: table.LC_data_table tr > td.LC_roles_expired {
5949: border-right: 8px solid #FF7777;
5950: }
5951:
5952: table.LC_data_table tr > td.LC_roles_will_not {
5953: border-right: 8px solid #AAFF77;
5954: }
5955:
5956: table.LC_data_table tr > td.LC_roles_selected {
5957: border-right: 8px solid #11CC55;
5958: }
5959:
5960: span.LC_current_location {
5961: font-size:larger;
5962: background: $pgbg;
5963: }
5964:
5965: span.LC_current_nav_location {
5966: font-weight:bold;
5967: background: $sidebg;
5968: }
5969:
5970: span.LC_parm_menu_item {
5971: font-size: larger;
5972: }
5973:
5974: span.LC_parm_scope_all {
5975: color: red;
5976: }
5977:
5978: span.LC_parm_scope_folder {
5979: color: green;
5980: }
5981:
5982: span.LC_parm_scope_resource {
5983: color: orange;
5984: }
5985:
5986: span.LC_parm_part {
5987: color: blue;
5988: }
5989:
5990: span.LC_parm_folder,
5991: span.LC_parm_symb {
5992: font-size: x-small;
5993: font-family: $mono;
5994: color: #AAAAAA;
5995: }
5996:
5997: ul.LC_parm_parmlist li {
5998: display: inline-block;
5999: padding: 0.3em 0.8em;
6000: vertical-align: top;
6001: width: 150px;
6002: border-top:1px solid $lg_border_color;
6003: }
6004:
6005: td.LC_parm_overview_level_menu,
6006: td.LC_parm_overview_map_menu,
6007: td.LC_parm_overview_parm_selectors,
6008: td.LC_parm_overview_restrictions {
6009: border: 1px solid black;
6010: border-collapse: collapse;
6011: }
6012:
6013: table.LC_parm_overview_restrictions td {
6014: border-width: 1px 4px 1px 4px;
6015: border-style: solid;
6016: border-color: $pgbg;
6017: text-align: center;
6018: }
6019:
6020: table.LC_parm_overview_restrictions th {
6021: background: $tabbg;
6022: border-width: 1px 4px 1px 4px;
6023: border-style: solid;
6024: border-color: $pgbg;
6025: }
6026:
6027: table#LC_helpmenu {
6028: border: none;
6029: height: 55px;
6030: border-spacing: 0;
6031: }
6032:
6033: table#LC_helpmenu fieldset legend {
6034: font-size: larger;
6035: }
6036:
6037: table#LC_helpmenu_links {
6038: width: 100%;
6039: border: 1px solid black;
6040: background: $pgbg;
6041: padding: 0;
6042: border-spacing: 1px;
6043: }
6044:
6045: table#LC_helpmenu_links tr td {
6046: padding: 1px;
6047: background: $tabbg;
6048: text-align: center;
6049: font-weight: bold;
6050: }
6051:
6052: table#LC_helpmenu_links a:link,
6053: table#LC_helpmenu_links a:visited,
6054: table#LC_helpmenu_links a:active {
6055: text-decoration: none;
6056: color: $font;
6057: }
6058:
6059: table#LC_helpmenu_links a:hover {
6060: text-decoration: underline;
6061: color: $vlink;
6062: }
6063:
6064: .LC_chrt_popup_exists {
6065: border: 1px solid #339933;
6066: margin: -1px;
6067: }
6068:
6069: .LC_chrt_popup_up {
6070: border: 1px solid yellow;
6071: margin: -1px;
6072: }
6073:
6074: .LC_chrt_popup {
6075: border: 1px solid #8888FF;
6076: background: #CCCCFF;
6077: }
6078:
6079: table.LC_pick_box {
6080: border-collapse: separate;
6081: background: white;
6082: border: 1px solid black;
6083: border-spacing: 1px;
6084: }
6085:
6086: table.LC_pick_box td.LC_pick_box_title {
6087: background: $sidebg;
6088: font-weight: bold;
6089: text-align: left;
6090: vertical-align: top;
6091: width: 184px;
6092: padding: 8px;
6093: }
6094:
6095: table.LC_pick_box td.LC_pick_box_value {
6096: text-align: left;
6097: padding: 8px;
6098: }
6099:
6100: table.LC_pick_box td.LC_pick_box_select {
6101: text-align: left;
6102: padding: 8px;
6103: }
6104:
6105: table.LC_pick_box td.LC_pick_box_separator {
6106: padding: 0;
6107: height: 1px;
6108: background: black;
6109: }
6110:
6111: table.LC_pick_box td.LC_pick_box_submit {
6112: text-align: right;
6113: }
6114:
6115: table.LC_pick_box td.LC_evenrow_value {
6116: text-align: left;
6117: padding: 8px;
6118: background-color: $data_table_light;
6119: }
6120:
6121: table.LC_pick_box td.LC_oddrow_value {
6122: text-align: left;
6123: padding: 8px;
6124: background-color: $data_table_light;
6125: }
6126:
6127: span.LC_helpform_receipt_cat {
6128: font-weight: bold;
6129: }
6130:
6131: table.LC_group_priv_box {
6132: background: white;
6133: border: 1px solid black;
6134: border-spacing: 1px;
6135: }
6136:
6137: table.LC_group_priv_box td.LC_pick_box_title {
6138: background: $tabbg;
6139: font-weight: bold;
6140: text-align: right;
6141: width: 184px;
6142: }
6143:
6144: table.LC_group_priv_box td.LC_groups_fixed {
6145: background: $data_table_light;
6146: text-align: center;
6147: }
6148:
6149: table.LC_group_priv_box td.LC_groups_optional {
6150: background: $data_table_dark;
6151: text-align: center;
6152: }
6153:
6154: table.LC_group_priv_box td.LC_groups_functionality {
6155: background: $data_table_darker;
6156: text-align: center;
6157: font-weight: bold;
6158: }
6159:
6160: table.LC_group_priv td {
6161: text-align: left;
6162: padding: 0;
6163: }
6164:
6165: .LC_navbuttons {
6166: margin: 2ex 0ex 2ex 0ex;
6167: }
6168:
6169: .LC_topic_bar {
6170: font-weight: bold;
6171: background: $tabbg;
6172: margin: 1em 0em 1em 2em;
6173: padding: 3px;
6174: font-size: 1.2em;
6175: }
6176:
6177: .LC_topic_bar span {
6178: left: 0.5em;
6179: position: absolute;
6180: vertical-align: middle;
6181: font-size: 1.2em;
6182: }
6183:
6184: table.LC_course_group_status {
6185: margin: 20px;
6186: }
6187:
6188: table.LC_status_selector td {
6189: vertical-align: top;
6190: text-align: center;
6191: padding: 4px;
6192: }
6193:
6194: div.LC_feedback_link {
6195: clear: both;
6196: background: $sidebg;
6197: width: 100%;
6198: padding-bottom: 10px;
6199: border: 1px $tabbg solid;
6200: height: 22px;
6201: line-height: 22px;
6202: padding-top: 5px;
6203: }
6204:
6205: div.LC_feedback_link img {
6206: height: 22px;
6207: vertical-align:middle;
6208: }
6209:
6210: div.LC_feedback_link a {
6211: text-decoration: none;
6212: }
6213:
6214: div.LC_comblock {
6215: display:inline;
6216: color:$font;
6217: font-size:90%;
6218: }
6219:
6220: div.LC_feedback_link div.LC_comblock {
6221: padding-left:5px;
6222: }
6223:
6224: div.LC_feedback_link div.LC_comblock a {
6225: color:$font;
6226: }
6227:
6228: span.LC_feedback_link {
6229: /* background: $feedback_link_bg; */
6230: font-size: larger;
6231: }
6232:
6233: span.LC_message_link {
6234: /* background: $feedback_link_bg; */
6235: font-size: larger;
6236: position: absolute;
6237: right: 1em;
6238: }
6239:
6240: table.LC_prior_tries {
6241: border: 1px solid #000000;
6242: border-collapse: separate;
6243: border-spacing: 1px;
6244: }
6245:
6246: table.LC_prior_tries td {
6247: padding: 2px;
6248: }
6249:
6250: .LC_answer_correct {
6251: background: lightgreen;
6252: color: darkgreen;
6253: padding: 6px;
6254: }
6255:
6256: .LC_answer_charged_try {
6257: background: #FFAAAA;
6258: color: darkred;
6259: padding: 6px;
6260: }
6261:
6262: .LC_answer_not_charged_try,
6263: .LC_answer_no_grade,
6264: .LC_answer_late {
6265: background: lightyellow;
6266: color: black;
6267: padding: 6px;
6268: }
6269:
6270: .LC_answer_previous {
6271: background: lightblue;
6272: color: darkblue;
6273: padding: 6px;
6274: }
6275:
6276: .LC_answer_no_message {
6277: background: #FFFFFF;
6278: color: black;
6279: padding: 6px;
6280: }
6281:
6282: .LC_answer_unknown {
6283: background: orange;
6284: color: black;
6285: padding: 6px;
6286: }
6287:
6288: span.LC_prior_numerical,
6289: span.LC_prior_string,
6290: span.LC_prior_custom,
6291: span.LC_prior_reaction,
6292: span.LC_prior_math {
6293: font-family: $mono;
6294: white-space: pre;
6295: }
6296:
6297: span.LC_prior_string {
6298: font-family: $mono;
6299: white-space: pre;
6300: }
6301:
6302: table.LC_prior_option {
6303: width: 100%;
6304: border-collapse: collapse;
6305: }
6306:
6307: table.LC_prior_rank,
6308: table.LC_prior_match {
6309: border-collapse: collapse;
6310: }
6311:
6312: table.LC_prior_option tr td,
6313: table.LC_prior_rank tr td,
6314: table.LC_prior_match tr td {
6315: border: 1px solid #000000;
6316: }
6317:
6318: .LC_nobreak {
6319: white-space: nowrap;
6320: }
6321:
6322: span.LC_cusr_emph {
6323: font-style: italic;
6324: }
6325:
6326: span.LC_cusr_subheading {
6327: font-weight: normal;
6328: font-size: 85%;
6329: }
6330:
6331: div.LC_docs_entry_move {
6332: border: 1px solid #BBBBBB;
6333: background: #DDDDDD;
6334: width: 22px;
6335: padding: 1px;
6336: margin: 0;
6337: }
6338:
6339: table.LC_data_table tr > td.LC_docs_entry_commands,
6340: table.LC_data_table tr > td.LC_docs_entry_parameter {
6341: font-size: x-small;
6342: }
6343:
6344: .LC_docs_entry_parameter {
6345: white-space: nowrap;
6346: }
6347:
6348: .LC_docs_copy {
6349: color: #000099;
6350: }
6351:
6352: .LC_docs_cut {
6353: color: #550044;
6354: }
6355:
6356: .LC_docs_rename {
6357: color: #009900;
6358: }
6359:
6360: .LC_docs_remove {
6361: color: #990000;
6362: }
6363:
6364: .LC_docs_reinit_warn,
6365: .LC_docs_ext_edit {
6366: font-size: x-small;
6367: }
6368:
6369: table.LC_docs_adddocs td,
6370: table.LC_docs_adddocs th {
6371: border: 1px solid #BBBBBB;
6372: padding: 4px;
6373: background: #DDDDDD;
6374: }
6375:
6376: table.LC_sty_begin {
6377: background: #BBFFBB;
6378: }
6379:
6380: table.LC_sty_end {
6381: background: #FFBBBB;
6382: }
6383:
6384: table.LC_double_column {
6385: border-width: 0;
6386: border-collapse: collapse;
6387: width: 100%;
6388: padding: 2px;
6389: }
6390:
6391: table.LC_double_column tr td.LC_left_col {
6392: top: 2px;
6393: left: 2px;
6394: width: 47%;
6395: vertical-align: top;
6396: }
6397:
6398: table.LC_double_column tr td.LC_right_col {
6399: top: 2px;
6400: right: 2px;
6401: width: 47%;
6402: vertical-align: top;
6403: }
6404:
6405: div.LC_left_float {
6406: float: left;
6407: padding-right: 5%;
6408: padding-bottom: 4px;
6409: }
6410:
6411: div.LC_clear_float_header {
6412: padding-bottom: 2px;
6413: }
6414:
6415: div.LC_clear_float_footer {
6416: padding-top: 10px;
6417: clear: both;
6418: }
6419:
6420: div.LC_grade_show_user {
6421: /* border-left: 5px solid $sidebg; */
6422: border-top: 5px solid #000000;
6423: margin: 50px 0 0 0;
6424: padding: 15px 0 5px 10px;
6425: }
6426:
6427: div.LC_grade_show_user_odd_row {
6428: /* border-left: 5px solid #000000; */
6429: }
6430:
6431: div.LC_grade_show_user div.LC_Box {
6432: margin-right: 50px;
6433: }
6434:
6435: div.LC_grade_submissions,
6436: div.LC_grade_message_center,
6437: div.LC_grade_info_links {
6438: margin: 5px;
6439: width: 99%;
6440: background: #FFFFFF;
6441: }
6442:
6443: div.LC_grade_submissions_header,
6444: div.LC_grade_message_center_header {
6445: font-weight: bold;
6446: font-size: large;
6447: }
6448:
6449: div.LC_grade_submissions_body,
6450: div.LC_grade_message_center_body {
6451: border: 1px solid black;
6452: width: 99%;
6453: background: #FFFFFF;
6454: }
6455:
6456: table.LC_scantron_action {
6457: width: 100%;
6458: }
6459:
6460: table.LC_scantron_action tr th {
6461: font-weight:bold;
6462: font-style:normal;
6463: }
6464:
6465: .LC_edit_problem_header,
6466: div.LC_edit_problem_footer {
6467: font-weight: normal;
6468: font-size: medium;
6469: margin: 2px;
6470: background-color: $sidebg;
6471: }
6472:
6473: div.LC_edit_problem_header,
6474: div.LC_edit_problem_header div,
6475: div.LC_edit_problem_footer,
6476: div.LC_edit_problem_footer div,
6477: div.LC_edit_problem_editxml_header,
6478: div.LC_edit_problem_editxml_header div {
6479: margin-top: 5px;
6480: }
6481:
6482: div.LC_edit_problem_header_title {
6483: font-weight: bold;
6484: font-size: larger;
6485: background: $tabbg;
6486: padding: 3px;
6487: margin: 0 0 5px 0;
6488: }
6489:
6490: table.LC_edit_problem_header_title {
6491: width: 100%;
6492: background: $tabbg;
6493: }
6494:
6495: div.LC_edit_problem_discards {
6496: float: left;
6497: padding-bottom: 5px;
6498: }
6499:
6500: div.LC_edit_problem_saves {
6501: float: right;
6502: padding-bottom: 5px;
6503: }
6504:
6505: .LC_edit_opt {
6506: padding-left: 1em;
6507: white-space: nowrap;
6508: }
6509:
6510: .LC_edit_problem_latexhelper{
6511: text-align: right;
6512: }
6513:
6514: #LC_edit_problem_colorful div{
6515: margin-left: 40px;
6516: }
6517:
6518: img.stift {
6519: border-width: 0;
6520: vertical-align: middle;
6521: }
6522:
6523: table td.LC_mainmenu_col_fieldset {
6524: vertical-align: top;
6525: }
6526:
6527: div.LC_createcourse {
6528: margin: 10px 10px 10px 10px;
6529: }
6530:
6531: .LC_dccid {
6532: float: right;
6533: margin: 0.2em 0 0 0;
6534: padding: 0;
6535: font-size: 90%;
6536: display:none;
6537: }
6538:
6539: ol.LC_primary_menu a:hover,
6540: ol#LC_MenuBreadcrumbs a:hover,
6541: ol#LC_PathBreadcrumbs a:hover,
6542: ul#LC_secondary_menu a:hover,
6543: .LC_FormSectionClearButton input:hover
6544: ul.LC_TabContent li:hover a {
6545: color:$button_hover;
6546: text-decoration:none;
6547: }
6548:
6549: h1 {
6550: padding: 0;
6551: line-height:130%;
6552: }
6553:
6554: h2,
6555: h3,
6556: h4,
6557: h5,
6558: h6 {
6559: margin: 5px 0 5px 0;
6560: padding: 0;
6561: line-height:130%;
6562: }
6563:
6564: .LC_hcell {
6565: padding:3px 15px 3px 15px;
6566: margin: 0;
6567: background-color:$tabbg;
6568: color:$fontmenu;
6569: border-bottom:solid 1px $lg_border_color;
6570: }
6571:
6572: .LC_Box > .LC_hcell {
6573: margin: 0 -10px 10px -10px;
6574: }
6575:
6576: .LC_noBorder {
6577: border: 0;
6578: }
6579:
6580: .LC_FormSectionClearButton input {
6581: background-color:transparent;
6582: border: none;
6583: cursor:pointer;
6584: text-decoration:underline;
6585: }
6586:
6587: .LC_help_open_topic {
6588: color: #FFFFFF;
6589: background-color: #EEEEFF;
6590: margin: 1px;
6591: padding: 4px;
6592: border: 1px solid #000033;
6593: white-space: nowrap;
6594: /* vertical-align: middle; */
6595: }
6596:
6597: dl,
6598: ul,
6599: div,
6600: fieldset {
6601: margin: 10px 10px 10px 0;
6602: /* overflow: hidden; */
6603: }
6604:
6605: fieldset > legend {
6606: font-weight: bold;
6607: padding: 0 5px 0 5px;
6608: }
6609:
6610: #LC_nav_bar {
6611: float: left;
6612: background-color: $pgbg_or_bgcolor;
6613: margin: 0 0 2px 0;
6614: }
6615:
6616: #LC_realm {
6617: margin: 0.2em 0 0 0;
6618: padding: 0;
6619: font-weight: bold;
6620: text-align: center;
6621: background-color: $pgbg_or_bgcolor;
6622: }
6623:
6624: #LC_nav_bar em {
6625: font-weight: bold;
6626: font-style: normal;
6627: }
6628:
6629: ol.LC_primary_menu {
6630: margin: 0;
6631: padding: 0;
6632: background-color: $pgbg_or_bgcolor;
6633: }
6634:
6635: ol#LC_PathBreadcrumbs {
6636: margin: 0;
6637: }
6638:
6639: ol.LC_primary_menu li {
6640: color: RGB(80, 80, 80);
6641: vertical-align: middle;
6642: text-align: left;
6643: list-style: none;
6644: float: left;
6645: }
6646:
6647: ol.LC_primary_menu li a {
6648: display: block;
6649: margin: 0;
6650: padding: 0 5px 0 10px;
6651: text-decoration: none;
6652: }
6653:
6654: ol.LC_primary_menu li ul {
6655: display: none;
6656: width: 10em;
6657: background-color: $data_table_light;
6658: }
6659:
6660: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
6661: display: block;
6662: position: absolute;
6663: margin: 0;
6664: padding: 0;
6665: z-index: 2;
6666: }
6667:
6668: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
6669: font-size: 90%;
6670: vertical-align: top;
6671: float: none;
6672: border-left: 1px solid black;
6673: border-right: 1px solid black;
6674: }
6675:
6676: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
6677: background-color:$data_table_light;
6678: }
6679:
6680: ol.LC_primary_menu li li a:hover {
6681: color:$button_hover;
6682: background-color:$data_table_dark;
6683: }
6684:
6685: ol.LC_primary_menu li img {
6686: vertical-align: bottom;
6687: height: 1.1em;
6688: margin: 0.2em 0 0 0;
6689: }
6690:
6691: ol.LC_primary_menu a {
6692: color: RGB(80, 80, 80);
6693: text-decoration: none;
6694: }
6695:
6696: ol.LC_primary_menu a.LC_new_message {
6697: font-weight:bold;
6698: color: darkred;
6699: }
6700:
6701: ol.LC_docs_parameters {
6702: margin-left: 0;
6703: padding: 0;
6704: list-style: none;
6705: }
6706:
6707: ol.LC_docs_parameters li {
6708: margin: 0;
6709: padding-right: 20px;
6710: display: inline;
6711: }
6712:
6713: ol.LC_docs_parameters li:before {
6714: content: "\\002022 \\0020";
6715: }
6716:
6717: li.LC_docs_parameters_title {
6718: font-weight: bold;
6719: }
6720:
6721: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
6722: content: "";
6723: }
6724:
6725: ul#LC_secondary_menu {
6726: clear: right;
6727: color: $fontmenu;
6728: background: $tabbg;
6729: list-style: none;
6730: padding: 0;
6731: margin: 0;
6732: width: 100%;
6733: text-align: left;
6734: float: left;
6735: }
6736:
6737: ul#LC_secondary_menu li {
6738: font-weight: bold;
6739: line-height: 1.8em;
6740: border-right: 1px solid black;
6741: float: left;
6742: }
6743:
6744: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
6745: background-color: $data_table_light;
6746: }
6747:
6748: ul#LC_secondary_menu li a {
6749: padding: 0 0.8em;
6750: }
6751:
6752: ul#LC_secondary_menu li ul {
6753: display: none;
6754: }
6755:
6756: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
6757: display: block;
6758: position: absolute;
6759: margin: 0;
6760: padding: 0;
6761: list-style:none;
6762: float: none;
6763: background-color: $data_table_light;
6764: z-index: 2;
6765: margin-left: -1px;
6766: }
6767:
6768: ul#LC_secondary_menu li ul li {
6769: font-size: 90%;
6770: vertical-align: top;
6771: border-left: 1px solid black;
6772: border-right: 1px solid black;
6773: background-color: $data_table_light;
6774: list-style:none;
6775: float: none;
6776: }
6777:
6778: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
6779: background-color: $data_table_dark;
6780: }
6781:
6782: ul.LC_TabContent {
6783: display:block;
6784: background: $sidebg;
6785: border-bottom: solid 1px $lg_border_color;
6786: list-style:none;
6787: margin: -1px -10px 0 -10px;
6788: padding: 0;
6789: }
6790:
6791: ul.LC_TabContent li,
6792: ul.LC_TabContentBigger li {
6793: float:left;
6794: }
6795:
6796: ul#LC_secondary_menu li a {
6797: color: $fontmenu;
6798: text-decoration: none;
6799: }
6800:
6801: ul.LC_TabContent {
6802: min-height:20px;
6803: }
6804:
6805: ul.LC_TabContent li {
6806: vertical-align:middle;
6807: padding: 0 16px 0 10px;
6808: background-color:$tabbg;
6809: border-bottom:solid 1px $lg_border_color;
6810: border-left: solid 1px $font;
6811: }
6812:
6813: ul.LC_TabContent .right {
6814: float:right;
6815: }
6816:
6817: ul.LC_TabContent li a,
6818: ul.LC_TabContent li {
6819: color:rgb(47,47,47);
6820: text-decoration:none;
6821: font-size:95%;
6822: font-weight:bold;
6823: min-height:20px;
6824: }
6825:
6826: ul.LC_TabContent li a:hover,
6827: ul.LC_TabContent li a:focus {
6828: color: $button_hover;
6829: background:none;
6830: outline:none;
6831: }
6832:
6833: ul.LC_TabContent li:hover {
6834: color: $button_hover;
6835: cursor:pointer;
6836: }
6837:
6838: ul.LC_TabContent li.active {
6839: color: $font;
6840: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
6841: border-bottom:solid 1px #FFFFFF;
6842: cursor: default;
6843: }
6844:
6845: ul.LC_TabContent li.active a {
6846: color:$font;
6847: background:#FFFFFF;
6848: outline: none;
6849: }
6850:
6851: ul.LC_TabContent li.goback {
6852: float: left;
6853: border-left: none;
6854: }
6855:
6856: #maincoursedoc {
6857: clear:both;
6858: }
6859:
6860: ul.LC_TabContentBigger {
6861: display:block;
6862: list-style:none;
6863: padding: 0;
6864: }
6865:
6866: ul.LC_TabContentBigger li {
6867: vertical-align:bottom;
6868: height: 30px;
6869: font-size:110%;
6870: font-weight:bold;
6871: color: #737373;
6872: }
6873:
6874: ul.LC_TabContentBigger li.active {
6875: position: relative;
6876: top: 1px;
6877: }
6878:
6879: ul.LC_TabContentBigger li a {
6880: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
6881: height: 30px;
6882: line-height: 30px;
6883: text-align: center;
6884: display: block;
6885: text-decoration: none;
6886: outline: none;
6887: }
6888:
6889: ul.LC_TabContentBigger li.active a {
6890: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
6891: color:$font;
6892: }
6893:
6894: ul.LC_TabContentBigger li b {
6895: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
6896: display: block;
6897: float: left;
6898: padding: 0 30px;
6899: border-bottom: 1px solid $lg_border_color;
6900: }
6901:
6902: ul.LC_TabContentBigger li:hover b {
6903: color:$button_hover;
6904: }
6905:
6906: ul.LC_TabContentBigger li.active b {
6907: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
6908: color:$font;
6909: border: 0;
6910: }
6911:
6912:
6913: ul.LC_CourseBreadcrumbs {
6914: background: $sidebg;
6915: height: 2em;
6916: padding-left: 10px;
6917: margin: 0;
6918: list-style-position: inside;
6919: }
6920:
6921: ol#LC_MenuBreadcrumbs,
6922: ol#LC_PathBreadcrumbs {
6923: padding-left: 10px;
6924: margin: 0;
6925: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
6926: }
6927:
6928: ol#LC_MenuBreadcrumbs li,
6929: ol#LC_PathBreadcrumbs li,
6930: ul.LC_CourseBreadcrumbs li {
6931: display: inline;
6932: white-space: normal;
6933: }
6934:
6935: ol#LC_MenuBreadcrumbs li a,
6936: ul.LC_CourseBreadcrumbs li a {
6937: text-decoration: none;
6938: font-size:90%;
6939: }
6940:
6941: ol#LC_MenuBreadcrumbs h1 {
6942: display: inline;
6943: font-size: 90%;
6944: line-height: 2.5em;
6945: margin: 0;
6946: padding: 0;
6947: }
6948:
6949: ol#LC_PathBreadcrumbs li a {
6950: text-decoration:none;
6951: font-size:100%;
6952: font-weight:bold;
6953: }
6954:
6955: .LC_Box {
6956: border: solid 1px $lg_border_color;
6957: padding: 0 10px 10px 10px;
6958: }
6959:
6960: .LC_DocsBox {
6961: border: solid 1px $lg_border_color;
6962: padding: 0 0 10px 10px;
6963: }
6964:
6965: .LC_AboutMe_Image {
6966: float:left;
6967: margin-right:10px;
6968: }
6969:
6970: .LC_Clear_AboutMe_Image {
6971: clear:left;
6972: }
6973:
6974: dl.LC_ListStyleClean dt {
6975: padding-right: 5px;
6976: display: table-header-group;
6977: }
6978:
6979: dl.LC_ListStyleClean dd {
6980: display: table-row;
6981: }
6982:
6983: .LC_ListStyleClean,
6984: .LC_ListStyleSimple,
6985: .LC_ListStyleNormal,
6986: .LC_ListStyleSpecial {
6987: /* display:block; */
6988: list-style-position: inside;
6989: list-style-type: none;
6990: overflow: hidden;
6991: padding: 0;
6992: }
6993:
6994: .LC_ListStyleSimple li,
6995: .LC_ListStyleSimple dd,
6996: .LC_ListStyleNormal li,
6997: .LC_ListStyleNormal dd,
6998: .LC_ListStyleSpecial li,
6999: .LC_ListStyleSpecial dd {
7000: margin: 0;
7001: padding: 5px 5px 5px 10px;
7002: clear: both;
7003: }
7004:
7005: .LC_ListStyleClean li,
7006: .LC_ListStyleClean dd {
7007: padding-top: 0;
7008: padding-bottom: 0;
7009: }
7010:
7011: .LC_ListStyleSimple dd,
7012: .LC_ListStyleSimple li {
7013: border-bottom: solid 1px $lg_border_color;
7014: }
7015:
7016: .LC_ListStyleSpecial li,
7017: .LC_ListStyleSpecial dd {
7018: list-style-type: none;
7019: background-color: RGB(220, 220, 220);
7020: margin-bottom: 4px;
7021: }
7022:
7023: table.LC_SimpleTable {
7024: margin:5px;
7025: border:solid 1px $lg_border_color;
7026: }
7027:
7028: table.LC_SimpleTable tr {
7029: padding: 0;
7030: border:solid 1px $lg_border_color;
7031: }
7032:
7033: table.LC_SimpleTable thead {
7034: background:rgb(220,220,220);
7035: }
7036:
7037: div.LC_columnSection {
7038: display: block;
7039: clear: both;
7040: overflow: hidden;
7041: margin: 0;
7042: }
7043:
7044: div.LC_columnSection>* {
7045: float: left;
7046: margin: 10px 20px 10px 0;
7047: overflow:hidden;
7048: }
7049:
7050: table em {
7051: font-weight: bold;
7052: font-style: normal;
7053: }
7054:
7055: table.LC_tableBrowseRes,
7056: table.LC_tableOfContent {
7057: border:none;
7058: border-spacing: 1px;
7059: padding: 3px;
7060: background-color: #FFFFFF;
7061: font-size: 90%;
7062: }
7063:
7064: table.LC_tableOfContent {
7065: border-collapse: collapse;
7066: }
7067:
7068: table.LC_tableBrowseRes a,
7069: table.LC_tableOfContent a {
7070: background-color: transparent;
7071: text-decoration: none;
7072: }
7073:
7074: table.LC_tableOfContent img {
7075: border: none;
7076: height: 1.3em;
7077: vertical-align: text-bottom;
7078: margin-right: 0.3em;
7079: }
7080:
7081: a#LC_content_toolbar_firsthomework {
7082: background-image:url(/res/adm/pages/open-first-problem.gif);
7083: }
7084:
7085: a#LC_content_toolbar_everything {
7086: background-image:url(/res/adm/pages/show-all.gif);
7087: }
7088:
7089: a#LC_content_toolbar_uncompleted {
7090: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
7091: }
7092:
7093: #LC_content_toolbar_clearbubbles {
7094: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
7095: }
7096:
7097: a#LC_content_toolbar_changefolder {
7098: background : url(/res/adm/pages/close-all-folders.gif) top center ;
7099: }
7100:
7101: a#LC_content_toolbar_changefolder_toggled {
7102: background-image:url(/res/adm/pages/open-all-folders.gif);
7103: }
7104:
7105: a#LC_content_toolbar_edittoplevel {
7106: background-image:url(/res/adm/pages/edittoplevel.gif);
7107: }
7108:
7109: ul#LC_toolbar li a:hover {
7110: background-position: bottom center;
7111: }
7112:
7113: ul#LC_toolbar {
7114: padding: 0;
7115: margin: 2px;
7116: list-style:none;
7117: position:relative;
7118: background-color:white;
7119: overflow: auto;
7120: }
7121:
7122: ul#LC_toolbar li {
7123: border:1px solid white;
7124: padding: 0;
7125: margin: 0;
7126: float: left;
7127: display:inline;
7128: vertical-align:middle;
7129: white-space: nowrap;
7130: }
7131:
7132:
7133: a.LC_toolbarItem {
7134: display:block;
7135: padding: 0;
7136: margin: 0;
7137: height: 32px;
7138: width: 32px;
7139: color:white;
7140: border: none;
7141: background-repeat:no-repeat;
7142: background-color:transparent;
7143: }
7144:
7145: ul.LC_funclist {
7146: margin: 0;
7147: padding: 0.5em 1em 0.5em 0;
7148: }
7149:
7150: ul.LC_funclist > li:first-child {
7151: font-weight:bold;
7152: margin-left:0.8em;
7153: }
7154:
7155: ul.LC_funclist + ul.LC_funclist {
7156: /*
7157: left border as a seperator if we have more than
7158: one list
7159: */
7160: border-left: 1px solid $sidebg;
7161: /*
7162: this hides the left border behind the border of the
7163: outer box if element is wrapped to the next 'line'
7164: */
7165: margin-left: -1px;
7166: }
7167:
7168: ul.LC_funclist li {
7169: display: inline;
7170: white-space: nowrap;
7171: margin: 0 0 0 25px;
7172: line-height: 150%;
7173: }
7174:
7175: .LC_hidden {
7176: display: none;
7177: }
7178:
7179: .LCmodal-overlay {
7180: position:fixed;
7181: top:0;
7182: right:0;
7183: bottom:0;
7184: left:0;
7185: height:100%;
7186: width:100%;
7187: margin:0;
7188: padding:0;
7189: background:#999;
7190: opacity:.75;
7191: filter: alpha(opacity=75);
7192: -moz-opacity: 0.75;
7193: z-index:101;
7194: }
7195:
7196: * html .LCmodal-overlay {
7197: position: absolute;
7198: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
7199: }
7200:
7201: .LCmodal-window {
7202: position:fixed;
7203: top:50%;
7204: left:50%;
7205: margin:0;
7206: padding:0;
7207: z-index:102;
7208: }
7209:
7210: * html .LCmodal-window {
7211: position:absolute;
7212: }
7213:
7214: .LCclose-window {
7215: position:absolute;
7216: width:32px;
7217: height:32px;
7218: right:8px;
7219: top:8px;
7220: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
7221: text-indent:-99999px;
7222: overflow:hidden;
7223: cursor:pointer;
7224: }
7225:
7226: /*
7227: styles used by TTH when "Default set of options to pass to tth/m
7228: when converting TeX" in course settings has been set
7229:
7230: option passed: -t
7231:
7232: */
7233:
7234: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
7235: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
7236: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
7237: td div.norm {line-height:normal;}
7238:
7239: /*
7240: option passed -y3
7241: */
7242:
7243: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
7244: span.overacc2 {position: relative; left: .8em; top: -1.2ex;}
7245: span.overacc1 {position: relative; left: .6em; top: -1.2ex;}
7246:
7247: END
7248: }
7249:
7250: =pod
7251:
7252: =item * &headtag()
7253:
7254: Returns a uniform footer for LON-CAPA web pages.
7255:
7256: Inputs: $title - optional title for the head
7257: $head_extra - optional extra HTML to put inside the <head>
7258: $args - optional arguments
7259: force_register - if is true call registerurl so the remote is
7260: informed
7261: redirect -> array ref of
7262: 1- seconds before redirect occurs
7263: 2- url to redirect to
7264: 3- whether the side effect should occur
7265: (side effect of setting
7266: $env{'internal.head.redirect'} to the url
7267: redirected too)
7268: domain -> force to color decorate a page for a specific
7269: domain
7270: function -> force usage of a specific rolish color scheme
7271: bgcolor -> override the default page bgcolor
7272: no_auto_mt_title
7273: -> prevent &mt()ing the title arg
7274:
7275: =cut
7276:
7277: sub headtag {
7278: my ($title,$head_extra,$args) = @_;
7279:
7280: my $function = $args->{'function'} || &get_users_function();
7281: my $domain = $args->{'domain'} || &determinedomain();
7282: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
7283: my $httphost = $args->{'use_absolute'};
7284: my $url = join(':',$env{'user.name'},$env{'user.domain'},
7285: $Apache::lonnet::perlvar{'lonVersion'},
7286: #time(),
7287: $env{'environment.color.timestamp'},
7288: $function,$domain,$bgcolor);
7289:
7290: $url = '/adm/css/'.&escape($url).'.css';
7291:
7292: my $result =
7293: '<head>'.
7294: &font_settings($args);
7295:
7296: my $inhibitprint = &print_suppression();
7297:
7298: if (!$args->{'frameset'}) {
7299: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
7300: }
7301: if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
7302: $result .= Apache::lonxml::display_title();
7303: }
7304: if (!$args->{'no_nav_bar'}
7305: && !$args->{'only_body'}
7306: && !$args->{'frameset'}) {
7307: $result .= &help_menu_js($httphost);
7308: $result.=&modal_window();
7309: $result.=&togglebox_script();
7310: $result.=&wishlist_window();
7311: $result.=&LCprogressbarUpdate_script();
7312: } else {
7313: if ($args->{'add_modal'}) {
7314: $result.=&modal_window();
7315: }
7316: if ($args->{'add_wishlist'}) {
7317: $result.=&wishlist_window();
7318: }
7319: if ($args->{'add_togglebox'}) {
7320: $result.=&togglebox_script();
7321: }
7322: if ($args->{'add_progressbar'}) {
7323: $result.=&LCprogressbarUpdate_script();
7324: }
7325: }
7326: if (ref($args->{'redirect'})) {
7327: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
7328: $url = &Apache::lonenc::check_encrypt($url);
7329: if (!$inhibit_continue) {
7330: $env{'internal.head.redirect'} = $url;
7331: }
7332: $result.=<<ADDMETA
7333: <meta http-equiv="pragma" content="no-cache" />
7334: <meta http-equiv="Refresh" content="$time; url=$url" />
7335: ADDMETA
7336: }
7337: if (!defined($title)) {
7338: $title = 'The LearningOnline Network with CAPA';
7339: }
7340: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
7341: $result .= '<title> LON-CAPA '.$title.'</title>'
7342: .'<link rel="stylesheet" type="text/css" href="'.$url.'"';
7343: if (!$args->{'frameset'}) {
7344: $result .= ' /';
7345: }
7346: $result .= '>'
7347: .$inhibitprint
7348: .$head_extra;
7349: if ($env{'browser.mobile'}) {
7350: $result .= '
7351: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
7352: <meta name="apple-mobile-web-app-capable" content="yes" />';
7353: }
7354: return $result.'</head>';
7355: }
7356:
7357: =pod
7358:
7359: =item * &font_settings()
7360:
7361: Returns neccessary <meta> to set the proper encoding
7362:
7363: Inputs: optional reference to HASH -- $args passed to &headtag()
7364:
7365: =cut
7366:
7367: sub font_settings {
7368: my ($args) = @_;
7369: my $headerstring='';
7370: if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
7371: ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
7372: $headerstring.=
7373: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
7374: if (!$args->{'frameset'}) {
7375: $headerstring.= ' /';
7376: }
7377: $headerstring .= '>'."\n";
7378: }
7379: return $headerstring;
7380: }
7381:
7382: =pod
7383:
7384: =item * &print_suppression()
7385:
7386: In course context returns css which causes the body to be blank when media="print",
7387: if printout generation is unavailable for the current resource.
7388:
7389: This could be because:
7390:
7391: (a) printstartdate is in the future
7392:
7393: (b) printenddate is in the past
7394:
7395: (c) there is an active exam block with "printout"
7396: functionality blocked
7397:
7398: Users with pav, pfo or evb privileges are exempt.
7399:
7400: Inputs: none
7401:
7402: =cut
7403:
7404:
7405: sub print_suppression {
7406: my $noprint;
7407: if ($env{'request.course.id'}) {
7408: my $scope = $env{'request.course.id'};
7409: if ((&Apache::lonnet::allowed('pav',$scope)) ||
7410: (&Apache::lonnet::allowed('pfo',$scope))) {
7411: return;
7412: }
7413: if ($env{'request.course.sec'} ne '') {
7414: $scope .= "/$env{'request.course.sec'}";
7415: if ((&Apache::lonnet::allowed('pav',$scope)) ||
7416: (&Apache::lonnet::allowed('pfo',$scope))) {
7417: return;
7418: }
7419: }
7420: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7421: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7422: my $blocked = &blocking_status('printout',$cnum,$cdom);
7423: if ($blocked) {
7424: my $checkrole = "cm./$cdom/$cnum";
7425: if ($env{'request.course.sec'} ne '') {
7426: $checkrole .= "/$env{'request.course.sec'}";
7427: }
7428: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
7429: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
7430: $noprint = 1;
7431: }
7432: }
7433: unless ($noprint) {
7434: my $symb = &Apache::lonnet::symbread();
7435: if ($symb ne '') {
7436: my $navmap = Apache::lonnavmaps::navmap->new();
7437: if (ref($navmap)) {
7438: my $res = $navmap->getBySymb($symb);
7439: if (ref($res)) {
7440: if (!$res->resprintable()) {
7441: $noprint = 1;
7442: }
7443: }
7444: }
7445: }
7446: }
7447: if ($noprint) {
7448: return <<"ENDSTYLE";
7449: <style type="text/css" media="print">
7450: body { display:none }
7451: </style>
7452: ENDSTYLE
7453: }
7454: }
7455: return;
7456: }
7457:
7458: =pod
7459:
7460: =item * &xml_begin()
7461:
7462: Returns the needed doctype and <html>
7463:
7464: Inputs: none
7465:
7466: =cut
7467:
7468: sub xml_begin {
7469: my ($is_frameset) = @_;
7470: my $output='';
7471:
7472: if ($env{'browser.mathml'}) {
7473: $output='<?xml version="1.0"?>'
7474: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
7475: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
7476:
7477: # .'<!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">] >'
7478: .'<!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">'
7479: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
7480: .'xmlns="http://www.w3.org/1999/xhtml">';
7481: } elsif ($is_frameset) {
7482: $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
7483: '<html>'."\n";
7484: } else {
7485: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
7486: '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
7487: }
7488: return $output;
7489: }
7490:
7491: =pod
7492:
7493: =item * &start_page()
7494:
7495: Returns a complete <html> .. <body> section for LON-CAPA web pages.
7496:
7497: Inputs:
7498:
7499: =over 4
7500:
7501: $title - optional title for the page
7502:
7503: $head_extra - optional extra HTML to incude inside the <head>
7504:
7505: $args - additional optional args supported are:
7506:
7507: =over 8
7508:
7509: only_body -> is true will set &bodytag() onlybodytag
7510: arg on
7511: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
7512: add_entries -> additional attributes to add to the <body>
7513: domain -> force to color decorate a page for a
7514: specific domain
7515: function -> force usage of a specific rolish color
7516: scheme
7517: redirect -> see &headtag()
7518: bgcolor -> override the default page bg color
7519: js_ready -> return a string ready for being used in
7520: a javascript writeln
7521: html_encode -> return a string ready for being used in
7522: a html attribute
7523: force_register -> if is true will turn on the &bodytag()
7524: $forcereg arg
7525: frameset -> if true will start with a <frameset>
7526: rather than <body>
7527: skip_phases -> hash ref of
7528: head -> skip the <html><head> generation
7529: body -> skip all <body> generation
7530: no_auto_mt_title -> prevent &mt()ing the title arg
7531: inherit_jsmath -> when creating popup window in a page,
7532: should it have jsmath forced on by the
7533: current page
7534: bread_crumbs -> Array containing breadcrumbs
7535: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
7536: group -> includes the current group, if page is for a
7537: specific group
7538:
7539: =back
7540:
7541: =back
7542:
7543: =cut
7544:
7545: sub start_page {
7546: my ($title,$head_extra,$args) = @_;
7547: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
7548:
7549: $env{'internal.start_page'}++;
7550: my ($result,@advtools);
7551:
7552: if (! exists($args->{'skip_phases'}{'head'}) ) {
7553: $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
7554: }
7555:
7556: if (! exists($args->{'skip_phases'}{'body'}) ) {
7557: if ($args->{'frameset'}) {
7558: my $attr_string = &make_attr_string($args->{'force_register'},
7559: $args->{'add_entries'});
7560: $result .= "\n<frameset $attr_string>\n";
7561: } else {
7562: $result .=
7563: &bodytag($title,
7564: $args->{'function'}, $args->{'add_entries'},
7565: $args->{'only_body'}, $args->{'domain'},
7566: $args->{'force_register'}, $args->{'no_nav_bar'},
7567: $args->{'bgcolor'}, $args,
7568: \@advtools);
7569: }
7570: }
7571:
7572: if ($args->{'js_ready'}) {
7573: $result = &js_ready($result);
7574: }
7575: if ($args->{'html_encode'}) {
7576: $result = &html_encode($result);
7577: }
7578:
7579: # Preparation for new and consistent functionlist at top of screen
7580: # if ($args->{'functionlist'}) {
7581: # $result .= &build_functionlist();
7582: #}
7583:
7584: # Don't add anything more if only_body wanted or in const space
7585: return $result if $args->{'only_body'}
7586: || $env{'request.state'} eq 'construct';
7587:
7588: #Breadcrumbs
7589: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
7590: &Apache::lonhtmlcommon::clear_breadcrumbs();
7591: #if any br links exists, add them to the breadcrumbs
7592: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
7593: foreach my $crumb (@{$args->{'bread_crumbs'}}){
7594: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
7595: }
7596: }
7597: # if @advtools array contains items add then to the breadcrumbs
7598: if (@advtools > 0) {
7599: &Apache::lonmenu::advtools_crumbs(@advtools);
7600: }
7601:
7602: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
7603: if(exists($args->{'bread_crumbs_component'})){
7604: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
7605: }else{
7606: $result .= &Apache::lonhtmlcommon::breadcrumbs();
7607: }
7608: }
7609: return $result;
7610: }
7611:
7612: sub end_page {
7613: my ($args) = @_;
7614: $env{'internal.end_page'}++;
7615: my $result;
7616: if ($args->{'discussion'}) {
7617: my ($target,$parser);
7618: if (ref($args->{'discussion'})) {
7619: ($target,$parser) =($args->{'discussion'}{'target'},
7620: $args->{'discussion'}{'parser'});
7621: }
7622: $result .= &Apache::lonxml::xmlend($target,$parser);
7623: }
7624: if ($args->{'frameset'}) {
7625: $result .= '</frameset>';
7626: } else {
7627: $result .= &endbodytag($args);
7628: }
7629: unless ($args->{'notbody'}) {
7630: $result .= "\n</html>";
7631: }
7632:
7633: if ($args->{'js_ready'}) {
7634: $result = &js_ready($result);
7635: }
7636:
7637: if ($args->{'html_encode'}) {
7638: $result = &html_encode($result);
7639: }
7640:
7641: return $result;
7642: }
7643:
7644: sub wishlist_window {
7645: return(<<'ENDWISHLIST');
7646: <script type="text/javascript">
7647: // <![CDATA[
7648: // <!-- BEGIN LON-CAPA Internal
7649: function set_wishlistlink(title, path) {
7650: if (!title) {
7651: title = document.title;
7652: title = title.replace(/^LON-CAPA /,'');
7653: }
7654: if (!path) {
7655: path = location.pathname;
7656: }
7657: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
7658: 'wishlistNewLink','width=560,height=350,scrollbars=0');
7659: }
7660: // END LON-CAPA Internal -->
7661: // ]]>
7662: </script>
7663: ENDWISHLIST
7664: }
7665:
7666: sub modal_window {
7667: return(<<'ENDMODAL');
7668: <script type="text/javascript">
7669: // <![CDATA[
7670: // <!-- BEGIN LON-CAPA Internal
7671: var modalWindow = {
7672: parent:"body",
7673: windowId:null,
7674: content:null,
7675: width:null,
7676: height:null,
7677: close:function()
7678: {
7679: $(".LCmodal-window").remove();
7680: $(".LCmodal-overlay").remove();
7681: },
7682: open:function()
7683: {
7684: var modal = "";
7685: modal += "<div class=\"LCmodal-overlay\"></div>";
7686: 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;\">";
7687: modal += this.content;
7688: modal += "</div>";
7689:
7690: $(this.parent).append(modal);
7691:
7692: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
7693: $(".LCclose-window").click(function(){modalWindow.close();});
7694: $(".LCmodal-overlay").click(function(){modalWindow.close();});
7695: }
7696: };
7697: var openMyModal = function(source,width,height,scrolling,transparency,style)
7698: {
7699: modalWindow.windowId = "myModal";
7700: modalWindow.width = width;
7701: modalWindow.height = height;
7702: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
7703: modalWindow.open();
7704: };
7705: // END LON-CAPA Internal -->
7706: // ]]>
7707: </script>
7708: ENDMODAL
7709: }
7710:
7711: sub modal_link {
7712: my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
7713: unless ($width) { $width=480; }
7714: unless ($height) { $height=400; }
7715: unless ($scrolling) { $scrolling='yes'; }
7716: unless ($transparency) { $transparency='true'; }
7717:
7718: my $target_attr;
7719: if (defined($target)) {
7720: $target_attr = 'target="'.$target.'"';
7721: }
7722: return <<"ENDLINK";
7723: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
7724: $linktext</a>
7725: ENDLINK
7726: }
7727:
7728: sub modal_adhoc_script {
7729: my ($funcname,$width,$height,$content)=@_;
7730: return (<<ENDADHOC);
7731: <script type="text/javascript">
7732: // <![CDATA[
7733: var $funcname = function()
7734: {
7735: modalWindow.windowId = "myModal";
7736: modalWindow.width = $width;
7737: modalWindow.height = $height;
7738: modalWindow.content = '$content';
7739: modalWindow.open();
7740: };
7741: // ]]>
7742: </script>
7743: ENDADHOC
7744: }
7745:
7746: sub modal_adhoc_inner {
7747: my ($funcname,$width,$height,$content)=@_;
7748: my $innerwidth=$width-20;
7749: $content=&js_ready(
7750: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
7751: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
7752: $content.
7753: &end_scrollbox().
7754: &end_page()
7755: );
7756: return &modal_adhoc_script($funcname,$width,$height,$content);
7757: }
7758:
7759: sub modal_adhoc_window {
7760: my ($funcname,$width,$height,$content,$linktext)=@_;
7761: return &modal_adhoc_inner($funcname,$width,$height,$content).
7762: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
7763: }
7764:
7765: sub modal_adhoc_launch {
7766: my ($funcname,$width,$height,$content)=@_;
7767: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
7768: <script type="text/javascript">
7769: // <![CDATA[
7770: $funcname();
7771: // ]]>
7772: </script>
7773: ENDLAUNCH
7774: }
7775:
7776: sub modal_adhoc_close {
7777: return (<<ENDCLOSE);
7778: <script type="text/javascript">
7779: // <![CDATA[
7780: modalWindow.close();
7781: // ]]>
7782: </script>
7783: ENDCLOSE
7784: }
7785:
7786: sub togglebox_script {
7787: return(<<ENDTOGGLE);
7788: <script type="text/javascript">
7789: // <![CDATA[
7790: function LCtoggleDisplay(id,hidetext,showtext) {
7791: link = document.getElementById(id + "link").childNodes[0];
7792: with (document.getElementById(id).style) {
7793: if (display == "none" ) {
7794: display = "inline";
7795: link.nodeValue = hidetext;
7796: } else {
7797: display = "none";
7798: link.nodeValue = showtext;
7799: }
7800: }
7801: }
7802: // ]]>
7803: </script>
7804: ENDTOGGLE
7805: }
7806:
7807: sub start_togglebox {
7808: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
7809: unless ($heading) { $heading=''; } else { $heading.=' '; }
7810: unless ($showtext) { $showtext=&mt('show'); }
7811: unless ($hidetext) { $hidetext=&mt('hide'); }
7812: unless ($headerbg) { $headerbg='#FFFFFF'; }
7813: return &start_data_table().
7814: &start_data_table_header_row().
7815: '<td bgcolor="'.$headerbg.'">'.$heading.
7816: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
7817: $showtext.'\')">'.$showtext.'</a>]</td>'.
7818: &end_data_table_header_row().
7819: '<tr id="'.$id.'" style="display:none""><td>';
7820: }
7821:
7822: sub end_togglebox {
7823: return '</td></tr>'.&end_data_table();
7824: }
7825:
7826: sub LCprogressbar_script {
7827: my ($id)=@_;
7828: return(<<ENDPROGRESS);
7829: <script type="text/javascript">
7830: // <![CDATA[
7831: \$('#progressbar$id').progressbar({
7832: value: 0,
7833: change: function(event, ui) {
7834: var newVal = \$(this).progressbar('option', 'value');
7835: \$('.pblabel', this).text(LCprogressTxt);
7836: }
7837: });
7838: // ]]>
7839: </script>
7840: ENDPROGRESS
7841: }
7842:
7843: sub LCprogressbarUpdate_script {
7844: return(<<ENDPROGRESSUPDATE);
7845: <style type="text/css">
7846: .ui-progressbar { position:relative; }
7847: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
7848: </style>
7849: <script type="text/javascript">
7850: // <![CDATA[
7851: var LCprogressTxt='---';
7852:
7853: function LCupdateProgress(percent,progresstext,id) {
7854: LCprogressTxt=progresstext;
7855: \$('#progressbar'+id).progressbar('value',percent);
7856: }
7857: // ]]>
7858: </script>
7859: ENDPROGRESSUPDATE
7860: }
7861:
7862: my $LClastpercent;
7863: my $LCidcnt;
7864: my $LCcurrentid;
7865:
7866: sub LCprogressbar {
7867: my ($r)=(@_);
7868: $LClastpercent=0;
7869: $LCidcnt++;
7870: $LCcurrentid=$$.'_'.$LCidcnt;
7871: my $starting=&mt('Starting');
7872: my $content=(<<ENDPROGBAR);
7873: <div id="progressbar$LCcurrentid">
7874: <span class="pblabel">$starting</span>
7875: </div>
7876: ENDPROGBAR
7877: &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
7878: }
7879:
7880: sub LCprogressbarUpdate {
7881: my ($r,$val,$text)=@_;
7882: unless ($val) {
7883: if ($LClastpercent) {
7884: $val=$LClastpercent;
7885: } else {
7886: $val=0;
7887: }
7888: }
7889: if ($val<0) { $val=0; }
7890: if ($val>100) { $val=0; }
7891: $LClastpercent=$val;
7892: unless ($text) { $text=$val.'%'; }
7893: $text=&js_ready($text);
7894: &r_print($r,<<ENDUPDATE);
7895: <script type="text/javascript">
7896: // <![CDATA[
7897: LCupdateProgress($val,'$text','$LCcurrentid');
7898: // ]]>
7899: </script>
7900: ENDUPDATE
7901: }
7902:
7903: sub LCprogressbarClose {
7904: my ($r)=@_;
7905: $LClastpercent=0;
7906: &r_print($r,<<ENDCLOSE);
7907: <script type="text/javascript">
7908: // <![CDATA[
7909: \$("#progressbar$LCcurrentid").hide('slow');
7910: // ]]>
7911: </script>
7912: ENDCLOSE
7913: }
7914:
7915: sub r_print {
7916: my ($r,$to_print)=@_;
7917: if ($r) {
7918: $r->print($to_print);
7919: $r->rflush();
7920: } else {
7921: print($to_print);
7922: }
7923: }
7924:
7925: sub html_encode {
7926: my ($result) = @_;
7927:
7928: $result = &HTML::Entities::encode($result,'<>&"');
7929:
7930: return $result;
7931: }
7932:
7933: sub js_ready {
7934: my ($result) = @_;
7935:
7936: $result =~ s/[\n\r]/ /xmsg;
7937: $result =~ s/\\/\\\\/xmsg;
7938: $result =~ s/'/\\'/xmsg;
7939: $result =~ s{</}{<\\/}xmsg;
7940:
7941: return $result;
7942: }
7943:
7944: sub validate_page {
7945: if ( exists($env{'internal.start_page'})
7946: && $env{'internal.start_page'} > 1) {
7947: &Apache::lonnet::logthis('start_page called multiple times '.
7948: $env{'internal.start_page'}.' '.
7949: $ENV{'request.filename'});
7950: }
7951: if ( exists($env{'internal.end_page'})
7952: && $env{'internal.end_page'} > 1) {
7953: &Apache::lonnet::logthis('end_page called multiple times '.
7954: $env{'internal.end_page'}.' '.
7955: $env{'request.filename'});
7956: }
7957: if ( exists($env{'internal.start_page'})
7958: && ! exists($env{'internal.end_page'})) {
7959: &Apache::lonnet::logthis('start_page called without end_page '.
7960: $env{'request.filename'});
7961: }
7962: if ( ! exists($env{'internal.start_page'})
7963: && exists($env{'internal.end_page'})) {
7964: &Apache::lonnet::logthis('end_page called without start_page'.
7965: $env{'request.filename'});
7966: }
7967: }
7968:
7969:
7970: sub start_scrollbox {
7971: my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
7972: unless ($outerwidth) { $outerwidth='520px'; }
7973: unless ($width) { $width='500px'; }
7974: unless ($height) { $height='200px'; }
7975: my ($table_id,$div_id,$tdcol);
7976: if ($id ne '') {
7977: $table_id = ' id="table_'.$id.'"';
7978: $div_id = ' id="div_'.$id.'"';
7979: }
7980: if ($bgcolor ne '') {
7981: $tdcol = "background-color: $bgcolor;";
7982: }
7983: my $nicescroll_js;
7984: if ($env{'browser.mobile'}) {
7985: $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
7986: }
7987: return <<"END";
7988: $nicescroll_js
7989:
7990: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
7991: <div style="overflow:auto; width:$width; height:$height;"$div_id>
7992: END
7993: }
7994:
7995: sub end_scrollbox {
7996: return '</div></td></tr></table>';
7997: }
7998:
7999: sub nicescroll_javascript {
8000: my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
8001: my %options;
8002: if (ref($cursor) eq 'HASH') {
8003: %options = %{$cursor};
8004: }
8005: unless ($options{'railalign'} =~ /^left|right$/) {
8006: $options{'railalign'} = 'left';
8007: }
8008: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
8009: my $function = &get_users_function();
8010: $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
8011: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
8012: $options{'cursorcolor'} = '#00F';
8013: }
8014: }
8015: if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
8016: unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
8017: $options{'cursoropacity'}='1.0';
8018: }
8019: } else {
8020: $options{'cursoropacity'}='1.0';
8021: }
8022: if ($options{'cursorfixedheight'} eq 'none') {
8023: delete($options{'cursorfixedheight'});
8024: } else {
8025: unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
8026: }
8027: unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
8028: delete($options{'railoffset'});
8029: }
8030: my @niceoptions;
8031: while (my($key,$value) = each(%options)) {
8032: if ($value =~ /^\{.+\}$/) {
8033: push(@niceoptions,$key.':'.$value);
8034: } else {
8035: push(@niceoptions,$key.':"'.$value.'"');
8036: }
8037: }
8038: my $nicescroll_js = '
8039: $(document).ready(
8040: function() {
8041: $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
8042: }
8043: );
8044: ';
8045: if ($framecheck) {
8046: $nicescroll_js .= '
8047: function expand_div(caller) {
8048: if (top === self) {
8049: document.getElementById("'.$id.'").style.width = "auto";
8050: document.getElementById("'.$id.'").style.height = "auto";
8051: } else {
8052: try {
8053: if (parent.frames) {
8054: if (parent.frames.length > 1) {
8055: var framesrc = parent.frames[1].location.href;
8056: var currsrc = framesrc.replace(/\#.*$/,"");
8057: if ((caller == "search") || (currsrc == "'.$location.'")) {
8058: document.getElementById("'.$id.'").style.width = "auto";
8059: document.getElementById("'.$id.'").style.height = "auto";
8060: }
8061: }
8062: }
8063: } catch (e) {
8064: return;
8065: }
8066: }
8067: return;
8068: }
8069: ';
8070: }
8071: if ($needjsready) {
8072: $nicescroll_js = '
8073: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
8074: } else {
8075: $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
8076: }
8077: return $nicescroll_js;
8078: }
8079:
8080: sub simple_error_page {
8081: my ($r,$title,$msg,$args) = @_;
8082: if (ref($args) eq 'HASH') {
8083: if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
8084: } else {
8085: $msg = &mt($msg);
8086: }
8087:
8088: my $page =
8089: &Apache::loncommon::start_page($title).
8090: '<p class="LC_error">'.$msg.'</p>'.
8091: &Apache::loncommon::end_page();
8092: if (ref($r)) {
8093: $r->print($page);
8094: return;
8095: }
8096: return $page;
8097: }
8098:
8099: {
8100: my @row_count;
8101:
8102: sub start_data_table_count {
8103: unshift(@row_count, 0);
8104: return;
8105: }
8106:
8107: sub end_data_table_count {
8108: shift(@row_count);
8109: return;
8110: }
8111:
8112: sub start_data_table {
8113: my ($add_class,$id) = @_;
8114: my $css_class = (join(' ','LC_data_table',$add_class));
8115: my $table_id;
8116: if (defined($id)) {
8117: $table_id = ' id="'.$id.'"';
8118: }
8119: &start_data_table_count();
8120: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
8121: }
8122:
8123: sub end_data_table {
8124: &end_data_table_count();
8125: return '</table>'."\n";;
8126: }
8127:
8128: sub start_data_table_row {
8129: my ($add_class, $id) = @_;
8130: $row_count[0]++;
8131: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
8132: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
8133: $id = (' id="'.$id.'"') unless ($id eq '');
8134: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
8135: }
8136:
8137: sub continue_data_table_row {
8138: my ($add_class, $id) = @_;
8139: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
8140: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
8141: $id = (' id="'.$id.'"') unless ($id eq '');
8142: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
8143: }
8144:
8145: sub end_data_table_row {
8146: return '</tr>'."\n";;
8147: }
8148:
8149: sub start_data_table_empty_row {
8150: # $row_count[0]++;
8151: return '<tr class="LC_empty_row" >'."\n";;
8152: }
8153:
8154: sub end_data_table_empty_row {
8155: return '</tr>'."\n";;
8156: }
8157:
8158: sub start_data_table_header_row {
8159: return '<tr class="LC_header_row">'."\n";;
8160: }
8161:
8162: sub end_data_table_header_row {
8163: return '</tr>'."\n";;
8164: }
8165:
8166: sub data_table_caption {
8167: my $caption = shift;
8168: return "<caption class=\"LC_caption\">$caption</caption>";
8169: }
8170: }
8171:
8172: =pod
8173:
8174: =item * &inhibit_menu_check($arg)
8175:
8176: Checks for a inhibitmenu state and generates output to preserve it
8177:
8178: Inputs: $arg - can be any of
8179: - undef - in which case the return value is a string
8180: to add into arguments list of a uri
8181: - 'input' - in which case the return value is a HTML
8182: <form> <input> field of type hidden to
8183: preserve the value
8184: - a url - in which case the return value is the url with
8185: the neccesary cgi args added to preserve the
8186: inhibitmenu state
8187: - a ref to a url - no return value, but the string is
8188: updated to include the neccessary cgi
8189: args to preserve the inhibitmenu state
8190:
8191: =cut
8192:
8193: sub inhibit_menu_check {
8194: my ($arg) = @_;
8195: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
8196: if ($arg eq 'input') {
8197: if ($env{'form.inhibitmenu'}) {
8198: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
8199: } else {
8200: return
8201: }
8202: }
8203: if ($env{'form.inhibitmenu'}) {
8204: if (ref($arg)) {
8205: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
8206: } elsif ($arg eq '') {
8207: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
8208: } else {
8209: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
8210: }
8211: }
8212: if (!ref($arg)) {
8213: return $arg;
8214: }
8215: }
8216:
8217: ###############################################
8218:
8219: =pod
8220:
8221: =back
8222:
8223: =head1 User Information Routines
8224:
8225: =over 4
8226:
8227: =item * &get_users_function()
8228:
8229: Used by &bodytag to determine the current users primary role.
8230: Returns either 'student','coordinator','admin', or 'author'.
8231:
8232: =cut
8233:
8234: ###############################################
8235: sub get_users_function {
8236: my $function = 'norole';
8237: if ($env{'request.role'}=~/^(st)/) {
8238: $function='student';
8239: }
8240: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
8241: $function='coordinator';
8242: }
8243: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
8244: $function='admin';
8245: }
8246: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
8247: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
8248: $function='author';
8249: }
8250: return $function;
8251: }
8252:
8253: ###############################################
8254:
8255: =pod
8256:
8257: =item * &show_course()
8258:
8259: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
8260: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
8261:
8262: Inputs:
8263: None
8264:
8265: Outputs:
8266: Scalar: 1 if 'Course' to be used, 0 otherwise.
8267:
8268: =cut
8269:
8270: ###############################################
8271: sub show_course {
8272: my $course = !$env{'user.adv'};
8273: if (!$env{'user.adv'}) {
8274: foreach my $env (keys(%env)) {
8275: next if ($env !~ m/^user\.priv\./);
8276: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
8277: $course = 0;
8278: last;
8279: }
8280: }
8281: }
8282: return $course;
8283: }
8284:
8285: ###############################################
8286:
8287: =pod
8288:
8289: =item * &check_user_status()
8290:
8291: Determines current status of supplied role for a
8292: specific user. Roles can be active, previous or future.
8293:
8294: Inputs:
8295: user's domain, user's username, course's domain,
8296: course's number, optional section ID.
8297:
8298: Outputs:
8299: role status: active, previous or future.
8300:
8301: =cut
8302:
8303: sub check_user_status {
8304: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
8305: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
8306: my @uroles = keys %userinfo;
8307: my $srchstr;
8308: my $active_chk = 'none';
8309: my $now = time;
8310: if (@uroles > 0) {
8311: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
8312: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
8313: } else {
8314: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
8315: }
8316: if (grep/^\Q$srchstr\E$/,@uroles) {
8317: my $role_end = 0;
8318: my $role_start = 0;
8319: $active_chk = 'active';
8320: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
8321: $role_end = $1;
8322: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
8323: $role_start = $1;
8324: }
8325: }
8326: if ($role_start > 0) {
8327: if ($now < $role_start) {
8328: $active_chk = 'future';
8329: }
8330: }
8331: if ($role_end > 0) {
8332: if ($now > $role_end) {
8333: $active_chk = 'previous';
8334: }
8335: }
8336: }
8337: }
8338: return $active_chk;
8339: }
8340:
8341: ###############################################
8342:
8343: =pod
8344:
8345: =item * &get_sections()
8346:
8347: Determines all the sections for a course including
8348: sections with students and sections containing other roles.
8349: Incoming parameters:
8350:
8351: 1. domain
8352: 2. course number
8353: 3. reference to array containing roles for which sections should
8354: be gathered (optional).
8355: 4. reference to array containing status types for which sections
8356: should be gathered (optional).
8357:
8358: If the third argument is undefined, sections are gathered for any role.
8359: If the fourth argument is undefined, sections are gathered for any status.
8360: Permissible values are 'active' or 'future' or 'previous'.
8361:
8362: Returns section hash (keys are section IDs, values are
8363: number of users in each section), subject to the
8364: optional roles filter, optional status filter
8365:
8366: =cut
8367:
8368: ###############################################
8369: sub get_sections {
8370: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
8371: if (!defined($cdom) || !defined($cnum)) {
8372: my $cid = $env{'request.course.id'};
8373:
8374: return if (!defined($cid));
8375:
8376: $cdom = $env{'course.'.$cid.'.domain'};
8377: $cnum = $env{'course.'.$cid.'.num'};
8378: }
8379:
8380: my %sectioncount;
8381: my $now = time;
8382:
8383: my $check_students = 1;
8384: my $only_students = 0;
8385: if (ref($possible_roles) eq 'ARRAY') {
8386: if (grep(/^st$/,@{$possible_roles})) {
8387: if (@{$possible_roles} == 1) {
8388: $only_students = 1;
8389: }
8390: } else {
8391: $check_students = 0;
8392: }
8393: }
8394:
8395: if ($check_students) {
8396: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
8397: my $sec_index = &Apache::loncoursedata::CL_SECTION();
8398: my $status_index = &Apache::loncoursedata::CL_STATUS();
8399: my $start_index = &Apache::loncoursedata::CL_START();
8400: my $end_index = &Apache::loncoursedata::CL_END();
8401: my $status;
8402: while (my ($student,$data) = each(%$classlist)) {
8403: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
8404: $data->[$status_index],
8405: $data->[$start_index],
8406: $data->[$end_index]);
8407: if ($stu_status eq 'Active') {
8408: $status = 'active';
8409: } elsif ($end < $now) {
8410: $status = 'previous';
8411: } elsif ($start > $now) {
8412: $status = 'future';
8413: }
8414: if ($section ne '-1' && $section !~ /^\s*$/) {
8415: if ((!defined($possible_status)) || (($status ne '') &&
8416: (grep/^\Q$status\E$/,@{$possible_status}))) {
8417: $sectioncount{$section}++;
8418: }
8419: }
8420: }
8421: }
8422: if ($only_students) {
8423: return %sectioncount;
8424: }
8425: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
8426: foreach my $user (sort(keys(%courseroles))) {
8427: if ($user !~ /^(\w{2})/) { next; }
8428: my ($role) = ($user =~ /^(\w{2})/);
8429: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
8430: my ($section,$status);
8431: if ($role eq 'cr' &&
8432: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
8433: $section=$1;
8434: }
8435: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
8436: if (!defined($section) || $section eq '-1') { next; }
8437: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
8438: if ($end == -1 && $start == -1) {
8439: next; #deleted role
8440: }
8441: if (!defined($possible_status)) {
8442: $sectioncount{$section}++;
8443: } else {
8444: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
8445: $status = 'active';
8446: } elsif ($end < $now) {
8447: $status = 'future';
8448: } elsif ($start > $now) {
8449: $status = 'previous';
8450: }
8451: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
8452: $sectioncount{$section}++;
8453: }
8454: }
8455: }
8456: return %sectioncount;
8457: }
8458:
8459: ###############################################
8460:
8461: =pod
8462:
8463: =item * &get_course_users()
8464:
8465: Retrieves usernames:domains for users in the specified course
8466: with specific role(s), and access status.
8467:
8468: Incoming parameters:
8469: 1. course domain
8470: 2. course number
8471: 3. access status: users must have - either active,
8472: previous, future, or all.
8473: 4. reference to array of permissible roles
8474: 5. reference to array of section restrictions (optional)
8475: 6. reference to results object (hash of hashes).
8476: 7. reference to optional userdata hash
8477: 8. reference to optional statushash
8478: 9. flag if privileged users (except those set to unhide in
8479: course settings) should be excluded
8480: Keys of top level results hash are roles.
8481: Keys of inner hashes are username:domain, with
8482: values set to access type.
8483: Optional userdata hash returns an array with arguments in the
8484: same order as loncoursedata::get_classlist() for student data.
8485:
8486: Optional statushash returns
8487:
8488: Entries for end, start, section and status are blank because
8489: of the possibility of multiple values for non-student roles.
8490:
8491: =cut
8492:
8493: ###############################################
8494:
8495: sub get_course_users {
8496: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
8497: my %idx = ();
8498: my %seclists;
8499:
8500: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
8501: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
8502: $idx{end} = &Apache::loncoursedata::CL_END();
8503: $idx{start} = &Apache::loncoursedata::CL_START();
8504: $idx{id} = &Apache::loncoursedata::CL_ID();
8505: $idx{section} = &Apache::loncoursedata::CL_SECTION();
8506: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
8507: $idx{status} = &Apache::loncoursedata::CL_STATUS();
8508:
8509: if (grep(/^st$/,@{$roles})) {
8510: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
8511: my $now = time;
8512: foreach my $student (keys(%{$classlist})) {
8513: my $match = 0;
8514: my $secmatch = 0;
8515: my $section = $$classlist{$student}[$idx{section}];
8516: my $status = $$classlist{$student}[$idx{status}];
8517: if ($section eq '') {
8518: $section = 'none';
8519: }
8520: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
8521: if (grep(/^all$/,@{$sections})) {
8522: $secmatch = 1;
8523: } elsif ($$classlist{$student}[$idx{section}] eq '') {
8524: if (grep(/^none$/,@{$sections})) {
8525: $secmatch = 1;
8526: }
8527: } else {
8528: if (grep(/^\Q$section\E$/,@{$sections})) {
8529: $secmatch = 1;
8530: }
8531: }
8532: if (!$secmatch) {
8533: next;
8534: }
8535: }
8536: if (defined($$types{'active'})) {
8537: if ($$classlist{$student}[$idx{status}] eq 'Active') {
8538: push(@{$$users{st}{$student}},'active');
8539: $match = 1;
8540: }
8541: }
8542: if (defined($$types{'previous'})) {
8543: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
8544: push(@{$$users{st}{$student}},'previous');
8545: $match = 1;
8546: }
8547: }
8548: if (defined($$types{'future'})) {
8549: if ($$classlist{$student}[$idx{status}] eq 'Future') {
8550: push(@{$$users{st}{$student}},'future');
8551: $match = 1;
8552: }
8553: }
8554: if ($match) {
8555: push(@{$seclists{$student}},$section);
8556: if (ref($userdata) eq 'HASH') {
8557: $$userdata{$student} = $$classlist{$student};
8558: }
8559: if (ref($statushash) eq 'HASH') {
8560: $statushash->{$student}{'st'}{$section} = $status;
8561: }
8562: }
8563: }
8564: }
8565: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
8566: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
8567: my $now = time;
8568: my %displaystatus = ( previous => 'Expired',
8569: active => 'Active',
8570: future => 'Future',
8571: );
8572: my (%nothide,@possdoms);
8573: if ($hidepriv) {
8574: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
8575: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
8576: if ($user !~ /:/) {
8577: $nothide{join(':',split(/[\@]/,$user))}=1;
8578: } else {
8579: $nothide{$user} = 1;
8580: }
8581: }
8582: my @possdoms = ($cdom);
8583: if ($coursehash{'checkforpriv'}) {
8584: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
8585: }
8586: }
8587: foreach my $person (sort(keys(%coursepersonnel))) {
8588: my $match = 0;
8589: my $secmatch = 0;
8590: my $status;
8591: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
8592: $user =~ s/:$//;
8593: my ($end,$start) = split(/:/,$coursepersonnel{$person});
8594: if ($end == -1 || $start == -1) {
8595: next;
8596: }
8597: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
8598: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
8599: my ($uname,$udom) = split(/:/,$user);
8600: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
8601: if (grep(/^all$/,@{$sections})) {
8602: $secmatch = 1;
8603: } elsif ($usec eq '') {
8604: if (grep(/^none$/,@{$sections})) {
8605: $secmatch = 1;
8606: }
8607: } else {
8608: if (grep(/^\Q$usec\E$/,@{$sections})) {
8609: $secmatch = 1;
8610: }
8611: }
8612: if (!$secmatch) {
8613: next;
8614: }
8615: }
8616: if ($usec eq '') {
8617: $usec = 'none';
8618: }
8619: if ($uname ne '' && $udom ne '') {
8620: if ($hidepriv) {
8621: if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
8622: (!$nothide{$uname.':'.$udom})) {
8623: next;
8624: }
8625: }
8626: if ($end > 0 && $end < $now) {
8627: $status = 'previous';
8628: } elsif ($start > $now) {
8629: $status = 'future';
8630: } else {
8631: $status = 'active';
8632: }
8633: foreach my $type (keys(%{$types})) {
8634: if ($status eq $type) {
8635: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
8636: push(@{$$users{$role}{$user}},$type);
8637: }
8638: $match = 1;
8639: }
8640: }
8641: if (($match) && (ref($userdata) eq 'HASH')) {
8642: if (!exists($$userdata{$uname.':'.$udom})) {
8643: &get_user_info($udom,$uname,\%idx,$userdata);
8644: }
8645: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
8646: push(@{$seclists{$uname.':'.$udom}},$usec);
8647: }
8648: if (ref($statushash) eq 'HASH') {
8649: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
8650: }
8651: }
8652: }
8653: }
8654: }
8655: if (grep(/^ow$/,@{$roles})) {
8656: if ((defined($cdom)) && (defined($cnum))) {
8657: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
8658: if ( defined($csettings{'internal.courseowner'}) ) {
8659: my $owner = $csettings{'internal.courseowner'};
8660: next if ($owner eq '');
8661: my ($ownername,$ownerdom);
8662: if ($owner =~ /^([^:]+):([^:]+)$/) {
8663: $ownername = $1;
8664: $ownerdom = $2;
8665: } else {
8666: $ownername = $owner;
8667: $ownerdom = $cdom;
8668: $owner = $ownername.':'.$ownerdom;
8669: }
8670: @{$$users{'ow'}{$owner}} = 'any';
8671: if (defined($userdata) &&
8672: !exists($$userdata{$owner})) {
8673: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
8674: if (!grep(/^none$/,@{$seclists{$owner}})) {
8675: push(@{$seclists{$owner}},'none');
8676: }
8677: if (ref($statushash) eq 'HASH') {
8678: $statushash->{$owner}{'ow'}{'none'} = 'Any';
8679: }
8680: }
8681: }
8682: }
8683: }
8684: foreach my $user (keys(%seclists)) {
8685: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
8686: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
8687: }
8688: }
8689: return;
8690: }
8691:
8692: sub get_user_info {
8693: my ($udom,$uname,$idx,$userdata) = @_;
8694: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
8695: &plainname($uname,$udom,'lastname');
8696: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
8697: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
8698: my %idhash = &Apache::lonnet::idrget($udom,($uname));
8699: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
8700: return;
8701: }
8702:
8703: ###############################################
8704:
8705: =pod
8706:
8707: =item * &get_user_quota()
8708:
8709: Retrieves quota assigned for storage of user files.
8710: Default is to report quota for portfolio files.
8711:
8712: Incoming parameters:
8713: 1. user's username
8714: 2. user's domain
8715: 3. quota name - portfolio, author, or course
8716: (if no quota name provided, defaults to portfolio).
8717: 4. crstype - official, unofficial, textbook or community, if quota name is
8718: course
8719:
8720: Returns:
8721: 1. Disk quota (in MB) assigned to student.
8722: 2. (Optional) Type of setting: custom or default
8723: (individually assigned or default for user's
8724: institutional status).
8725: 3. (Optional) - User's institutional status (e.g., faculty, staff
8726: or student - types as defined in localenroll::inst_usertypes
8727: for user's domain, which determines default quota for user.
8728: 4. (Optional) - Default quota which would apply to the user.
8729:
8730: If a value has been stored in the user's environment,
8731: it will return that, otherwise it returns the maximal default
8732: defined for the user's institutional status(es) in the domain.
8733:
8734: =cut
8735:
8736: ###############################################
8737:
8738:
8739: sub get_user_quota {
8740: my ($uname,$udom,$quotaname,$crstype) = @_;
8741: my ($quota,$quotatype,$settingstatus,$defquota);
8742: if (!defined($udom)) {
8743: $udom = $env{'user.domain'};
8744: }
8745: if (!defined($uname)) {
8746: $uname = $env{'user.name'};
8747: }
8748: if (($udom eq '' || $uname eq '') ||
8749: ($udom eq 'public') && ($uname eq 'public')) {
8750: $quota = 0;
8751: $quotatype = 'default';
8752: $defquota = 0;
8753: } else {
8754: my $inststatus;
8755: if ($quotaname eq 'course') {
8756: if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
8757: ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
8758: $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
8759: } else {
8760: my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
8761: $quota = $cenv{'internal.uploadquota'};
8762: }
8763: } else {
8764: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
8765: if ($quotaname eq 'author') {
8766: $quota = $env{'environment.authorquota'};
8767: } else {
8768: $quota = $env{'environment.portfolioquota'};
8769: }
8770: $inststatus = $env{'environment.inststatus'};
8771: } else {
8772: my %userenv =
8773: &Apache::lonnet::get('environment',['portfolioquota',
8774: 'authorquota','inststatus'],$udom,$uname);
8775: my ($tmp) = keys(%userenv);
8776: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8777: if ($quotaname eq 'author') {
8778: $quota = $userenv{'authorquota'};
8779: } else {
8780: $quota = $userenv{'portfolioquota'};
8781: }
8782: $inststatus = $userenv{'inststatus'};
8783: } else {
8784: undef(%userenv);
8785: }
8786: }
8787: }
8788: if ($quota eq '' || wantarray) {
8789: if ($quotaname eq 'course') {
8790: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
8791: if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
8792: ($crstype eq 'community') || ($crstype eq 'textbook')) {
8793: $defquota = $domdefs{$crstype.'quota'};
8794: }
8795: if ($defquota eq '') {
8796: $defquota = 500;
8797: }
8798: } else {
8799: ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
8800: }
8801: if ($quota eq '') {
8802: $quota = $defquota;
8803: $quotatype = 'default';
8804: } else {
8805: $quotatype = 'custom';
8806: }
8807: }
8808: }
8809: if (wantarray) {
8810: return ($quota,$quotatype,$settingstatus,$defquota);
8811: } else {
8812: return $quota;
8813: }
8814: }
8815:
8816: ###############################################
8817:
8818: =pod
8819:
8820: =item * &default_quota()
8821:
8822: Retrieves default quota assigned for storage of user portfolio files,
8823: given an (optional) user's institutional status.
8824:
8825: Incoming parameters:
8826:
8827: 1. domain
8828: 2. (Optional) institutional status(es). This is a : separated list of
8829: status types (e.g., faculty, staff, student etc.)
8830: which apply to the user for whom the default is being retrieved.
8831: If the institutional status string in undefined, the domain
8832: default quota will be returned.
8833: 3. quota name - portfolio, author, or course
8834: (if no quota name provided, defaults to portfolio).
8835:
8836: Returns:
8837:
8838: 1. Default disk quota (in MB) for user portfolios in the domain.
8839: 2. (Optional) institutional type which determined the value of the
8840: default quota.
8841:
8842: If a value has been stored in the domain's configuration db,
8843: it will return that, otherwise it returns 20 (for backwards
8844: compatibility with domains which have not set up a configuration
8845: db file; the original statically defined portfolio quota was 20 MB).
8846:
8847: If the user's status includes multiple types (e.g., staff and student),
8848: the largest default quota which applies to the user determines the
8849: default quota returned.
8850:
8851: =cut
8852:
8853: ###############################################
8854:
8855:
8856: sub default_quota {
8857: my ($udom,$inststatus,$quotaname) = @_;
8858: my ($defquota,$settingstatus);
8859: my %quotahash = &Apache::lonnet::get_dom('configuration',
8860: ['quotas'],$udom);
8861: my $key = 'defaultquota';
8862: if ($quotaname eq 'author') {
8863: $key = 'authorquota';
8864: }
8865: if (ref($quotahash{'quotas'}) eq 'HASH') {
8866: if ($inststatus ne '') {
8867: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
8868: foreach my $item (@statuses) {
8869: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
8870: if ($quotahash{'quotas'}{$key}{$item} ne '') {
8871: if ($defquota eq '') {
8872: $defquota = $quotahash{'quotas'}{$key}{$item};
8873: $settingstatus = $item;
8874: } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
8875: $defquota = $quotahash{'quotas'}{$key}{$item};
8876: $settingstatus = $item;
8877: }
8878: }
8879: } elsif ($key eq 'defaultquota') {
8880: if ($quotahash{'quotas'}{$item} ne '') {
8881: if ($defquota eq '') {
8882: $defquota = $quotahash{'quotas'}{$item};
8883: $settingstatus = $item;
8884: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
8885: $defquota = $quotahash{'quotas'}{$item};
8886: $settingstatus = $item;
8887: }
8888: }
8889: }
8890: }
8891: }
8892: if ($defquota eq '') {
8893: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
8894: $defquota = $quotahash{'quotas'}{$key}{'default'};
8895: } elsif ($key eq 'defaultquota') {
8896: $defquota = $quotahash{'quotas'}{'default'};
8897: }
8898: $settingstatus = 'default';
8899: if ($defquota eq '') {
8900: if ($quotaname eq 'author') {
8901: $defquota = 500;
8902: }
8903: }
8904: }
8905: } else {
8906: $settingstatus = 'default';
8907: if ($quotaname eq 'author') {
8908: $defquota = 500;
8909: } else {
8910: $defquota = 20;
8911: }
8912: }
8913: if (wantarray) {
8914: return ($defquota,$settingstatus);
8915: } else {
8916: return $defquota;
8917: }
8918: }
8919:
8920: ###############################################
8921:
8922: =pod
8923:
8924: =item * &excess_filesize_warning()
8925:
8926: Returns warning message if upload of file to authoring space, or copying
8927: of existing file within authoring space will cause quota for the authoring
8928: space to be exceeded.
8929:
8930: Same, if upload of a file directly to a course/community via Course Editor
8931: will cause quota for uploaded content for the course to be exceeded.
8932:
8933: Inputs: 7
8934: 1. username or coursenum
8935: 2. domain
8936: 3. context ('author' or 'course')
8937: 4. filename of file for which action is being requested
8938: 5. filesize (kB) of file
8939: 6. action being taken: copy or upload.
8940: 7. quotatype (in course context -- official, unofficial, community or textbook).
8941:
8942: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
8943: otherwise return null.
8944:
8945: =back
8946:
8947: =cut
8948:
8949: sub excess_filesize_warning {
8950: my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
8951: my $current_disk_usage = 0;
8952: my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
8953: if ($context eq 'author') {
8954: my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
8955: $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
8956: } else {
8957: foreach my $subdir ('docs','supplemental') {
8958: $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
8959: }
8960: }
8961: $disk_quota = int($disk_quota * 1000);
8962: if (($current_disk_usage + $filesize) > $disk_quota) {
8963: return '<p><span class="LC_warning">'.
8964: &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
8965: '<span class="LC_filename">'.$filename.'</span>',$filesize).'</span>'.
8966: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
8967: $disk_quota,$current_disk_usage).
8968: '</p>';
8969: }
8970: return;
8971: }
8972:
8973: ###############################################
8974:
8975:
8976:
8977:
8978: sub get_secgrprole_info {
8979: my ($cdom,$cnum,$needroles,$type) = @_;
8980: my %sections_count = &get_sections($cdom,$cnum);
8981: my @sections = (sort {$a <=> $b} keys(%sections_count));
8982: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
8983: my @groups = sort(keys(%curr_groups));
8984: my $allroles = [];
8985: my $rolehash;
8986: my $accesshash = {
8987: active => 'Currently has access',
8988: future => 'Will have future access',
8989: previous => 'Previously had access',
8990: };
8991: if ($needroles) {
8992: $rolehash = {'all' => 'all'};
8993: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
8994: if (&Apache::lonnet::error(%user_roles)) {
8995: undef(%user_roles);
8996: }
8997: foreach my $item (keys(%user_roles)) {
8998: my ($role)=split(/\:/,$item,2);
8999: if ($role eq 'cr') { next; }
9000: if ($role =~ /^cr/) {
9001: $$rolehash{$role} = (split('/',$role))[3];
9002: } else {
9003: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
9004: }
9005: }
9006: foreach my $key (sort(keys(%{$rolehash}))) {
9007: push(@{$allroles},$key);
9008: }
9009: push (@{$allroles},'st');
9010: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
9011: }
9012: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
9013: }
9014:
9015: sub user_picker {
9016: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
9017: my $currdom = $dom;
9018: my %curr_selected = (
9019: srchin => 'dom',
9020: srchby => 'lastname',
9021: );
9022: my $srchterm;
9023: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
9024: if ($srch->{'srchby'} ne '') {
9025: $curr_selected{'srchby'} = $srch->{'srchby'};
9026: }
9027: if ($srch->{'srchin'} ne '') {
9028: $curr_selected{'srchin'} = $srch->{'srchin'};
9029: }
9030: if ($srch->{'srchtype'} ne '') {
9031: $curr_selected{'srchtype'} = $srch->{'srchtype'};
9032: }
9033: if ($srch->{'srchdomain'} ne '') {
9034: $currdom = $srch->{'srchdomain'};
9035: }
9036: $srchterm = $srch->{'srchterm'};
9037: }
9038: my %lt=&Apache::lonlocal::texthash(
9039: 'usr' => 'Search criteria',
9040: 'doma' => 'Domain/institution to search',
9041: 'uname' => 'username',
9042: 'lastname' => 'last name',
9043: 'lastfirst' => 'last name, first name',
9044: 'crs' => 'in this course',
9045: 'dom' => 'in selected LON-CAPA domain',
9046: 'alc' => 'all LON-CAPA',
9047: 'instd' => 'in institutional directory for selected domain',
9048: 'exact' => 'is',
9049: 'contains' => 'contains',
9050: 'begins' => 'begins with',
9051: 'youm' => "You must include some text to search for.",
9052: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
9053: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
9054: 'yomc' => "You must choose a domain when using an institutional directory search.",
9055: 'ymcd' => "You must choose a domain when using a domain search.",
9056: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
9057: 'whse' => "When searching by last,first you must include at least one character in the first name.",
9058: 'thfo' => "The following need to be corrected before the search can be run:",
9059: );
9060: my $domform = &select_dom_form($currdom,'srchdomain',1,1);
9061: my $srchinsel = ' <select name="srchin">';
9062:
9063: my @srchins = ('crs','dom','alc','instd');
9064:
9065: foreach my $option (@srchins) {
9066: # FIXME 'alc' option unavailable until
9067: # loncreateuser::print_user_query_page()
9068: # has been completed.
9069: next if ($option eq 'alc');
9070: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
9071: next if ($option eq 'crs' && !$env{'request.course.id'});
9072: if ($curr_selected{'srchin'} eq $option) {
9073: $srchinsel .= '
9074: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
9075: } else {
9076: $srchinsel .= '
9077: <option value="'.$option.'">'.$lt{$option}.'</option>';
9078: }
9079: }
9080: $srchinsel .= "\n </select>\n";
9081:
9082: my $srchbysel = ' <select name="srchby">';
9083: foreach my $option ('lastname','lastfirst','uname') {
9084: if ($curr_selected{'srchby'} eq $option) {
9085: $srchbysel .= '
9086: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
9087: } else {
9088: $srchbysel .= '
9089: <option value="'.$option.'">'.$lt{$option}.'</option>';
9090: }
9091: }
9092: $srchbysel .= "\n </select>\n";
9093:
9094: my $srchtypesel = ' <select name="srchtype">';
9095: foreach my $option ('begins','contains','exact') {
9096: if ($curr_selected{'srchtype'} eq $option) {
9097: $srchtypesel .= '
9098: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
9099: } else {
9100: $srchtypesel .= '
9101: <option value="'.$option.'">'.$lt{$option}.'</option>';
9102: }
9103: }
9104: $srchtypesel .= "\n </select>\n";
9105:
9106: my ($newuserscript,$new_user_create);
9107: my $context_dom = $env{'request.role.domain'};
9108: if ($context eq 'requestcrs') {
9109: if ($env{'form.coursedom'} ne '') {
9110: $context_dom = $env{'form.coursedom'};
9111: }
9112: }
9113: if ($forcenewuser) {
9114: if (ref($srch) eq 'HASH') {
9115: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
9116: if ($cancreate) {
9117: $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>';
9118: } else {
9119: my $helplink = 'javascript:helpMenu('."'display'".')';
9120: my %usertypetext = (
9121: official => 'institutional',
9122: unofficial => 'non-institutional',
9123: );
9124: $new_user_create = '<p class="LC_warning">'
9125: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
9126: .' '
9127: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
9128: ,'<a href="'.$helplink.'">','</a>')
9129: .'</p><br />';
9130: }
9131: }
9132: }
9133:
9134: $newuserscript = <<"ENDSCRIPT";
9135:
9136: function setSearch(createnew,callingForm) {
9137: if (createnew == 1) {
9138: for (var i=0; i<callingForm.srchby.length; i++) {
9139: if (callingForm.srchby.options[i].value == 'uname') {
9140: callingForm.srchby.selectedIndex = i;
9141: }
9142: }
9143: for (var i=0; i<callingForm.srchin.length; i++) {
9144: if ( callingForm.srchin.options[i].value == 'dom') {
9145: callingForm.srchin.selectedIndex = i;
9146: }
9147: }
9148: for (var i=0; i<callingForm.srchtype.length; i++) {
9149: if (callingForm.srchtype.options[i].value == 'exact') {
9150: callingForm.srchtype.selectedIndex = i;
9151: }
9152: }
9153: for (var i=0; i<callingForm.srchdomain.length; i++) {
9154: if (callingForm.srchdomain.options[i].value == '$context_dom') {
9155: callingForm.srchdomain.selectedIndex = i;
9156: }
9157: }
9158: }
9159: }
9160: ENDSCRIPT
9161:
9162: }
9163:
9164: my $output = <<"END_BLOCK";
9165: <script type="text/javascript">
9166: // <![CDATA[
9167: function validateEntry(callingForm) {
9168:
9169: var checkok = 1;
9170: var srchin;
9171: for (var i=0; i<callingForm.srchin.length; i++) {
9172: if ( callingForm.srchin[i].checked ) {
9173: srchin = callingForm.srchin[i].value;
9174: }
9175: }
9176:
9177: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
9178: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
9179: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
9180: var srchterm = callingForm.srchterm.value;
9181: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
9182: var msg = "";
9183:
9184: if (srchterm == "") {
9185: checkok = 0;
9186: msg += "$lt{'youm'}\\n";
9187: }
9188:
9189: if (srchtype== 'begins') {
9190: if (srchterm.length < 2) {
9191: checkok = 0;
9192: msg += "$lt{'thte'}\\n";
9193: }
9194: }
9195:
9196: if (srchtype== 'contains') {
9197: if (srchterm.length < 3) {
9198: checkok = 0;
9199: msg += "$lt{'thet'}\\n";
9200: }
9201: }
9202: if (srchin == 'instd') {
9203: if (srchdomain == '') {
9204: checkok = 0;
9205: msg += "$lt{'yomc'}\\n";
9206: }
9207: }
9208: if (srchin == 'dom') {
9209: if (srchdomain == '') {
9210: checkok = 0;
9211: msg += "$lt{'ymcd'}\\n";
9212: }
9213: }
9214: if (srchby == 'lastfirst') {
9215: if (srchterm.indexOf(",") == -1) {
9216: checkok = 0;
9217: msg += "$lt{'whus'}\\n";
9218: }
9219: if (srchterm.indexOf(",") == srchterm.length -1) {
9220: checkok = 0;
9221: msg += "$lt{'whse'}\\n";
9222: }
9223: }
9224: if (checkok == 0) {
9225: alert("$lt{'thfo'}\\n"+msg);
9226: return;
9227: }
9228: if (checkok == 1) {
9229: callingForm.submit();
9230: }
9231: }
9232:
9233: $newuserscript
9234:
9235: // ]]>
9236: </script>
9237:
9238: $new_user_create
9239:
9240: END_BLOCK
9241:
9242: $output .= &Apache::lonhtmlcommon::start_pick_box().
9243: &Apache::lonhtmlcommon::row_title($lt{'doma'}).
9244: $domform.
9245: &Apache::lonhtmlcommon::row_closure().
9246: &Apache::lonhtmlcommon::row_title($lt{'usr'}).
9247: $srchbysel.
9248: $srchtypesel.
9249: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
9250: $srchinsel.
9251: &Apache::lonhtmlcommon::row_closure(1).
9252: &Apache::lonhtmlcommon::end_pick_box().
9253: '<br />';
9254: return $output;
9255: }
9256:
9257: sub user_rule_check {
9258: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
9259: my $response;
9260: if (ref($usershash) eq 'HASH') {
9261: foreach my $user (keys(%{$usershash})) {
9262: my ($uname,$udom) = split(/:/,$user);
9263: next if ($udom eq '' || $uname eq '');
9264: my ($id,$newuser);
9265: if (ref($usershash->{$user}) eq 'HASH') {
9266: $newuser = $usershash->{$user}->{'newuser'};
9267: $id = $usershash->{$user}->{'id'};
9268: }
9269: my $inst_response;
9270: if (ref($checks) eq 'HASH') {
9271: if (defined($checks->{'username'})) {
9272: ($inst_response,%{$inst_results->{$user}}) =
9273: &Apache::lonnet::get_instuser($udom,$uname);
9274: } elsif (defined($checks->{'id'})) {
9275: ($inst_response,%{$inst_results->{$user}}) =
9276: &Apache::lonnet::get_instuser($udom,undef,$id);
9277: }
9278: } else {
9279: ($inst_response,%{$inst_results->{$user}}) =
9280: &Apache::lonnet::get_instuser($udom,$uname);
9281: return;
9282: }
9283: if (!$got_rules->{$udom}) {
9284: my %domconfig = &Apache::lonnet::get_dom('configuration',
9285: ['usercreation'],$udom);
9286: if (ref($domconfig{'usercreation'}) eq 'HASH') {
9287: foreach my $item ('username','id') {
9288: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
9289: $$curr_rules{$udom}{$item} =
9290: $domconfig{'usercreation'}{$item.'_rule'};
9291: }
9292: }
9293: }
9294: $got_rules->{$udom} = 1;
9295: }
9296: foreach my $item (keys(%{$checks})) {
9297: if (ref($$curr_rules{$udom}) eq 'HASH') {
9298: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
9299: if (@{$$curr_rules{$udom}{$item}} > 0) {
9300: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
9301: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
9302: if ($rule_check{$rule}) {
9303: $$rulematch{$user}{$item} = $rule;
9304: if ($inst_response eq 'ok') {
9305: if (ref($inst_results) eq 'HASH') {
9306: if (ref($inst_results->{$user}) eq 'HASH') {
9307: if (keys(%{$inst_results->{$user}}) == 0) {
9308: $$alerts{$item}{$udom}{$uname} = 1;
9309: }
9310: }
9311: }
9312: }
9313: last;
9314: }
9315: }
9316: }
9317: }
9318: }
9319: }
9320: }
9321: }
9322: return;
9323: }
9324:
9325: sub user_rule_formats {
9326: my ($domain,$domdesc,$curr_rules,$check) = @_;
9327: my %text = (
9328: 'username' => 'Usernames',
9329: 'id' => 'IDs',
9330: );
9331: my $output;
9332: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
9333: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
9334: if (@{$ruleorder} > 0) {
9335: $output = '<br />'.
9336: &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
9337: '<span class="LC_cusr_emph">','</span>',$domdesc).
9338: ' <ul>';
9339: foreach my $rule (@{$ruleorder}) {
9340: if (ref($curr_rules) eq 'ARRAY') {
9341: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
9342: if (ref($rules->{$rule}) eq 'HASH') {
9343: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
9344: $rules->{$rule}{'desc'}.'</li>';
9345: }
9346: }
9347: }
9348: }
9349: $output .= '</ul>';
9350: }
9351: }
9352: return $output;
9353: }
9354:
9355: sub instrule_disallow_msg {
9356: my ($checkitem,$domdesc,$count,$mode) = @_;
9357: my $response;
9358: my %text = (
9359: item => 'username',
9360: items => 'usernames',
9361: match => 'matches',
9362: do => 'does',
9363: action => 'a username',
9364: one => 'one',
9365: );
9366: if ($count > 1) {
9367: $text{'item'} = 'usernames';
9368: $text{'match'} ='match';
9369: $text{'do'} = 'do';
9370: $text{'action'} = 'usernames',
9371: $text{'one'} = 'ones';
9372: }
9373: if ($checkitem eq 'id') {
9374: $text{'items'} = 'IDs';
9375: $text{'item'} = 'ID';
9376: $text{'action'} = 'an ID';
9377: if ($count > 1) {
9378: $text{'item'} = 'IDs';
9379: $text{'action'} = 'IDs';
9380: }
9381: }
9382: $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 />';
9383: if ($mode eq 'upload') {
9384: if ($checkitem eq 'username') {
9385: $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'}.");
9386: } elsif ($checkitem eq 'id') {
9387: $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.");
9388: }
9389: } elsif ($mode eq 'selfcreate') {
9390: if ($checkitem eq 'id') {
9391: $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.");
9392: }
9393: } else {
9394: if ($checkitem eq 'username') {
9395: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
9396: } elsif ($checkitem eq 'id') {
9397: $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.");
9398: }
9399: }
9400: return $response;
9401: }
9402:
9403: sub personal_data_fieldtitles {
9404: my %fieldtitles = &Apache::lonlocal::texthash (
9405: id => 'Student/Employee ID',
9406: permanentemail => 'E-mail address',
9407: lastname => 'Last Name',
9408: firstname => 'First Name',
9409: middlename => 'Middle Name',
9410: generation => 'Generation',
9411: gen => 'Generation',
9412: inststatus => 'Affiliation',
9413: );
9414: return %fieldtitles;
9415: }
9416:
9417: sub sorted_inst_types {
9418: my ($dom) = @_;
9419: my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
9420: my $othertitle = &mt('All users');
9421: if ($env{'request.course.id'}) {
9422: $othertitle = &mt('Any users');
9423: }
9424: my @types;
9425: if (ref($order) eq 'ARRAY') {
9426: @types = @{$order};
9427: }
9428: if (@types == 0) {
9429: if (ref($usertypes) eq 'HASH') {
9430: @types = sort(keys(%{$usertypes}));
9431: }
9432: }
9433: if (keys(%{$usertypes}) > 0) {
9434: $othertitle = &mt('Other users');
9435: }
9436: return ($othertitle,$usertypes,\@types);
9437: }
9438:
9439: sub get_institutional_codes {
9440: my ($settings,$allcourses,$LC_code) = @_;
9441: # Get complete list of course sections to update
9442: my @currsections = ();
9443: my @currxlists = ();
9444: my $coursecode = $$settings{'internal.coursecode'};
9445:
9446: if ($$settings{'internal.sectionnums'} ne '') {
9447: @currsections = split(/,/,$$settings{'internal.sectionnums'});
9448: }
9449:
9450: if ($$settings{'internal.crosslistings'} ne '') {
9451: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
9452: }
9453:
9454: if (@currxlists > 0) {
9455: foreach (@currxlists) {
9456: if (m/^([^:]+):(\w*)$/) {
9457: unless (grep/^$1$/,@{$allcourses}) {
9458: push @{$allcourses},$1;
9459: $$LC_code{$1} = $2;
9460: }
9461: }
9462: }
9463: }
9464:
9465: if (@currsections > 0) {
9466: foreach (@currsections) {
9467: if (m/^(\w+):(\w*)$/) {
9468: my $sec = $coursecode.$1;
9469: my $lc_sec = $2;
9470: unless (grep/^$sec$/,@{$allcourses}) {
9471: push @{$allcourses},$sec;
9472: $$LC_code{$sec} = $lc_sec;
9473: }
9474: }
9475: }
9476: }
9477: return;
9478: }
9479:
9480: sub get_standard_codeitems {
9481: return ('Year','Semester','Department','Number','Section');
9482: }
9483:
9484: =pod
9485:
9486: =head1 Slot Helpers
9487:
9488: =over 4
9489:
9490: =item * sorted_slots()
9491:
9492: Sorts an array of slot names in order of an optional sort key,
9493: default sort is by slot start time (earliest first).
9494:
9495: Inputs:
9496:
9497: =over 4
9498:
9499: slotsarr - Reference to array of unsorted slot names.
9500:
9501: slots - Reference to hash of hash, where outer hash keys are slot names.
9502:
9503: sortkey - Name of key in inner hash to be sorted on (e.g., starttime).
9504:
9505: =back
9506:
9507: Returns:
9508:
9509: =over 4
9510:
9511: sorted - An array of slot names sorted by a specified sort key
9512: (default sort key is start time of the slot).
9513:
9514: =back
9515:
9516: =cut
9517:
9518:
9519: sub sorted_slots {
9520: my ($slotsarr,$slots,$sortkey) = @_;
9521: if ($sortkey eq '') {
9522: $sortkey = 'starttime';
9523: }
9524: my @sorted;
9525: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
9526: @sorted =
9527: sort {
9528: if (ref($slots->{$a}) && ref($slots->{$b})) {
9529: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
9530: }
9531: if (ref($slots->{$a})) { return -1;}
9532: if (ref($slots->{$b})) { return 1;}
9533: return 0;
9534: } @{$slotsarr};
9535: }
9536: return @sorted;
9537: }
9538:
9539: =pod
9540:
9541: =item * get_future_slots()
9542:
9543: Inputs:
9544:
9545: =over 4
9546:
9547: cnum - course number
9548:
9549: cdom - course domain
9550:
9551: now - current UNIX time
9552:
9553: symb - optional symb
9554:
9555: =back
9556:
9557: Returns:
9558:
9559: =over 4
9560:
9561: sorted_reservable - ref to array of student_schedulable slots currently
9562: reservable, ordered by end date of reservation period.
9563:
9564: reservable_now - ref to hash of student_schedulable slots currently
9565: reservable.
9566:
9567: Keys in inner hash are:
9568: (a) symb: either blank or symb to which slot use is restricted.
9569: (b) endreserve: end date of reservation period.
9570:
9571: sorted_future - ref to array of student_schedulable slots reservable in
9572: the future, ordered by start date of reservation period.
9573:
9574: future_reservable - ref to hash of student_schedulable slots reservable
9575: in the future.
9576:
9577: Keys in inner hash are:
9578: (a) symb: either blank or symb to which slot use is restricted.
9579: (b) startreserve: start date of reservation period.
9580:
9581: =back
9582:
9583: =cut
9584:
9585: sub get_future_slots {
9586: my ($cnum,$cdom,$now,$symb) = @_;
9587: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
9588: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
9589: foreach my $slot (keys(%slots)) {
9590: next unless($slots{$slot}->{'type'} eq 'schedulable_student');
9591: if ($symb) {
9592: next if (($slots{$slot}->{'symb'} ne '') &&
9593: ($slots{$slot}->{'symb'} ne $symb));
9594: }
9595: if (($slots{$slot}->{'starttime'} > $now) &&
9596: ($slots{$slot}->{'endtime'} > $now)) {
9597: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
9598: my $userallowed = 0;
9599: if ($slots{$slot}->{'allowedsections'}) {
9600: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
9601: if (!defined($env{'request.role.sec'})
9602: && grep(/^No section assigned$/,@allowed_sec)) {
9603: $userallowed=1;
9604: } else {
9605: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
9606: $userallowed=1;
9607: }
9608: }
9609: unless ($userallowed) {
9610: if (defined($env{'request.course.groups'})) {
9611: my @groups = split(/:/,$env{'request.course.groups'});
9612: foreach my $group (@groups) {
9613: if (grep(/^\Q$group\E$/,@allowed_sec)) {
9614: $userallowed=1;
9615: last;
9616: }
9617: }
9618: }
9619: }
9620: }
9621: if ($slots{$slot}->{'allowedusers'}) {
9622: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
9623: my $user = $env{'user.name'}.':'.$env{'user.domain'};
9624: if (grep(/^\Q$user\E$/,@allowed_users)) {
9625: $userallowed = 1;
9626: }
9627: }
9628: next unless($userallowed);
9629: }
9630: my $startreserve = $slots{$slot}->{'startreserve'};
9631: my $endreserve = $slots{$slot}->{'endreserve'};
9632: my $symb = $slots{$slot}->{'symb'};
9633: if (($startreserve < $now) &&
9634: (!$endreserve || $endreserve > $now)) {
9635: my $lastres = $endreserve;
9636: if (!$lastres) {
9637: $lastres = $slots{$slot}->{'starttime'};
9638: }
9639: $reservable_now{$slot} = {
9640: symb => $symb,
9641: endreserve => $lastres
9642: };
9643: } elsif (($startreserve > $now) &&
9644: (!$endreserve || $endreserve > $startreserve)) {
9645: $future_reservable{$slot} = {
9646: symb => $symb,
9647: startreserve => $startreserve
9648: };
9649: }
9650: }
9651: }
9652: my @unsorted_reservable = keys(%reservable_now);
9653: if (@unsorted_reservable > 0) {
9654: @sorted_reservable =
9655: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
9656: }
9657: my @unsorted_future = keys(%future_reservable);
9658: if (@unsorted_future > 0) {
9659: @sorted_future =
9660: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
9661: }
9662: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
9663: }
9664:
9665: =pod
9666:
9667: =back
9668:
9669: =head1 HTTP Helpers
9670:
9671: =over 4
9672:
9673: =item * &get_unprocessed_cgi($query,$possible_names)
9674:
9675: Modify the %env hash to contain unprocessed CGI form parameters held in
9676: $query. The parameters listed in $possible_names (an array reference),
9677: will be set in $env{'form.name'} if they do not already exist.
9678:
9679: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
9680: $possible_names is an ref to an array of form element names. As an example:
9681: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
9682: will result in $env{'form.uname'} and $env{'form.udom'} being set.
9683:
9684: =cut
9685:
9686: sub get_unprocessed_cgi {
9687: my ($query,$possible_names)= @_;
9688: # $Apache::lonxml::debug=1;
9689: foreach my $pair (split(/&/,$query)) {
9690: my ($name, $value) = split(/=/,$pair);
9691: $name = &unescape($name);
9692: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
9693: $value =~ tr/+/ /;
9694: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
9695: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
9696: }
9697: }
9698: }
9699:
9700: =pod
9701:
9702: =item * &cacheheader()
9703:
9704: returns cache-controlling header code
9705:
9706: =cut
9707:
9708: sub cacheheader {
9709: unless ($env{'request.method'} eq 'GET') { return ''; }
9710: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
9711: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
9712: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
9713: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
9714: return $output;
9715: }
9716:
9717: =pod
9718:
9719: =item * &no_cache($r)
9720:
9721: specifies header code to not have cache
9722:
9723: =cut
9724:
9725: sub no_cache {
9726: my ($r) = @_;
9727: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
9728: $env{'request.method'} ne 'GET') { return ''; }
9729: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
9730: $r->no_cache(1);
9731: $r->header_out("Expires" => $date);
9732: $r->header_out("Pragma" => "no-cache");
9733: }
9734:
9735: sub content_type {
9736: my ($r,$type,$charset) = @_;
9737: if ($r) {
9738: # Note that printout.pl calls this with undef for $r.
9739: &no_cache($r);
9740: }
9741: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
9742: unless ($charset) {
9743: $charset=&Apache::lonlocal::current_encoding;
9744: }
9745: if ($charset) { $type.='; charset='.$charset; }
9746: if ($r) {
9747: $r->content_type($type);
9748: } else {
9749: print("Content-type: $type\n\n");
9750: }
9751: }
9752:
9753: =pod
9754:
9755: =item * &add_to_env($name,$value)
9756:
9757: adds $name to the %env hash with value
9758: $value, if $name already exists, the entry is converted to an array
9759: reference and $value is added to the array.
9760:
9761: =cut
9762:
9763: sub add_to_env {
9764: my ($name,$value)=@_;
9765: if (defined($env{$name})) {
9766: if (ref($env{$name})) {
9767: #already have multiple values
9768: push(@{ $env{$name} },$value);
9769: } else {
9770: #first time seeing multiple values, convert hash entry to an arrayref
9771: my $first=$env{$name};
9772: undef($env{$name});
9773: push(@{ $env{$name} },$first,$value);
9774: }
9775: } else {
9776: $env{$name}=$value;
9777: }
9778: }
9779:
9780: =pod
9781:
9782: =item * &get_env_multiple($name)
9783:
9784: gets $name from the %env hash, it seemlessly handles the cases where multiple
9785: values may be defined and end up as an array ref.
9786:
9787: returns an array of values
9788:
9789: =cut
9790:
9791: sub get_env_multiple {
9792: my ($name) = @_;
9793: my @values;
9794: if (defined($env{$name})) {
9795: # exists is it an array
9796: if (ref($env{$name})) {
9797: @values=@{ $env{$name} };
9798: } else {
9799: $values[0]=$env{$name};
9800: }
9801: }
9802: return(@values);
9803: }
9804:
9805: sub ask_for_embedded_content {
9806: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
9807: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
9808: %currsubfile,%unused,$rem);
9809: my $counter = 0;
9810: my $numnew = 0;
9811: my $numremref = 0;
9812: my $numinvalid = 0;
9813: my $numpathchg = 0;
9814: my $numexisting = 0;
9815: my $numunused = 0;
9816: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
9817: $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
9818: my $heading = &mt('Upload embedded files');
9819: my $buttontext = &mt('Upload');
9820:
9821: if ($env{'request.course.id'}) {
9822: if ($actionurl eq '/adm/dependencies') {
9823: $navmap = Apache::lonnavmaps::navmap->new();
9824: }
9825: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9826: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9827: }
9828: if (($actionurl eq '/adm/portfolio') ||
9829: ($actionurl eq '/adm/coursegrp_portfolio')) {
9830: my $current_path='/';
9831: if ($env{'form.currentpath'}) {
9832: $current_path = $env{'form.currentpath'};
9833: }
9834: if ($actionurl eq '/adm/coursegrp_portfolio') {
9835: $udom = $cdom;
9836: $uname = $cnum;
9837: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
9838: } else {
9839: $udom = $env{'user.domain'};
9840: $uname = $env{'user.name'};
9841: $url = '/userfiles/portfolio';
9842: }
9843: $toplevel = $url.'/';
9844: $url .= $current_path;
9845: $getpropath = 1;
9846: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
9847: ($actionurl eq '/adm/imsimport')) {
9848: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
9849: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
9850: $toplevel = $url;
9851: if ($rest ne '') {
9852: $url .= $rest;
9853: }
9854: } elsif ($actionurl eq '/adm/coursedocs') {
9855: if (ref($args) eq 'HASH') {
9856: $url = $args->{'docs_url'};
9857: $toplevel = $url;
9858: if ($args->{'context'} eq 'paste') {
9859: ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
9860: ($path) =
9861: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
9862: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
9863: $fileloc =~ s{^/}{};
9864: }
9865: }
9866: } elsif ($actionurl eq '/adm/dependencies') {
9867: if ($env{'request.course.id'} ne '') {
9868: if (ref($args) eq 'HASH') {
9869: $url = $args->{'docs_url'};
9870: $title = $args->{'docs_title'};
9871: $toplevel = $url;
9872: unless ($toplevel =~ m{^/}) {
9873: $toplevel = "/$url";
9874: }
9875: ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
9876: if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
9877: $path = $1;
9878: } else {
9879: ($path) =
9880: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
9881: }
9882: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
9883: $fileloc =~ s{^/}{};
9884: ($filename) = ($fileloc =~ m{.+/([^/]+)$});
9885: $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
9886: }
9887: }
9888: } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
9889: $udom = $cdom;
9890: $uname = $cnum;
9891: $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
9892: $toplevel = $url;
9893: $path = $url;
9894: $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
9895: $fileloc =~ s{^/}{};
9896: }
9897: foreach my $file (keys(%{$allfiles})) {
9898: my $embed_file;
9899: if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
9900: $embed_file = $1;
9901: } else {
9902: $embed_file = $file;
9903: }
9904: my ($absolutepath,$cleaned_file);
9905: if ($embed_file =~ m{^\w+://}) {
9906: $cleaned_file = $embed_file;
9907: $newfiles{$cleaned_file} = 1;
9908: $mapping{$cleaned_file} = $embed_file;
9909: } else {
9910: $cleaned_file = &clean_path($embed_file);
9911: if ($embed_file =~ m{^/}) {
9912: $absolutepath = $embed_file;
9913: }
9914: if ($cleaned_file =~ m{/}) {
9915: my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
9916: $path = &check_for_traversal($path,$url,$toplevel);
9917: my $item = $fname;
9918: if ($path ne '') {
9919: $item = $path.'/'.$fname;
9920: $subdependencies{$path}{$fname} = 1;
9921: } else {
9922: $dependencies{$item} = 1;
9923: }
9924: if ($absolutepath) {
9925: $mapping{$item} = $absolutepath;
9926: } else {
9927: $mapping{$item} = $embed_file;
9928: }
9929: } else {
9930: $dependencies{$embed_file} = 1;
9931: if ($absolutepath) {
9932: $mapping{$cleaned_file} = $absolutepath;
9933: } else {
9934: $mapping{$cleaned_file} = $embed_file;
9935: }
9936: }
9937: }
9938: }
9939: my $dirptr = 16384;
9940: foreach my $path (keys(%subdependencies)) {
9941: $currsubfile{$path} = {};
9942: if (($actionurl eq '/adm/portfolio') ||
9943: ($actionurl eq '/adm/coursegrp_portfolio')) {
9944: my ($sublistref,$listerror) =
9945: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
9946: if (ref($sublistref) eq 'ARRAY') {
9947: foreach my $line (@{$sublistref}) {
9948: my ($file_name,$rest) = split(/\&/,$line,2);
9949: $currsubfile{$path}{$file_name} = 1;
9950: }
9951: }
9952: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
9953: if (opendir(my $dir,$url.'/'.$path)) {
9954: my @subdir_list = grep(!/^\./,readdir($dir));
9955: map {$currsubfile{$path}{$_} = 1;} @subdir_list;
9956: }
9957: } elsif (($actionurl eq '/adm/dependencies') ||
9958: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
9959: ($args->{'context'} eq 'paste')) ||
9960: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
9961: if ($env{'request.course.id'} ne '') {
9962: my $dir;
9963: if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
9964: $dir = $fileloc;
9965: } else {
9966: ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
9967: }
9968: if ($dir ne '') {
9969: my ($sublistref,$listerror) =
9970: &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
9971: if (ref($sublistref) eq 'ARRAY') {
9972: foreach my $line (@{$sublistref}) {
9973: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
9974: undef,$mtime)=split(/\&/,$line,12);
9975: unless (($testdir&$dirptr) ||
9976: ($file_name =~ /^\.\.?$/)) {
9977: $currsubfile{$path}{$file_name} = [$size,$mtime];
9978: }
9979: }
9980: }
9981: }
9982: }
9983: }
9984: foreach my $file (keys(%{$subdependencies{$path}})) {
9985: if (exists($currsubfile{$path}{$file})) {
9986: my $item = $path.'/'.$file;
9987: unless ($mapping{$item} eq $item) {
9988: $pathchanges{$item} = 1;
9989: }
9990: $existing{$item} = 1;
9991: $numexisting ++;
9992: } else {
9993: $newfiles{$path.'/'.$file} = 1;
9994: }
9995: }
9996: if ($actionurl eq '/adm/dependencies') {
9997: foreach my $path (keys(%currsubfile)) {
9998: if (ref($currsubfile{$path}) eq 'HASH') {
9999: foreach my $file (keys(%{$currsubfile{$path}})) {
10000: unless ($subdependencies{$path}{$file}) {
10001: next if (($rem ne '') &&
10002: (($env{"httpref.$rem"."$path/$file"} ne '') ||
10003: (ref($navmap) &&
10004: (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10005: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10006: ($navmap->getResourceByUrl($rem."$path/$1")))))));
10007: $unused{$path.'/'.$file} = 1;
10008: }
10009: }
10010: }
10011: }
10012: }
10013: }
10014: my %currfile;
10015: if (($actionurl eq '/adm/portfolio') ||
10016: ($actionurl eq '/adm/coursegrp_portfolio')) {
10017: my ($dirlistref,$listerror) =
10018: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10019: if (ref($dirlistref) eq 'ARRAY') {
10020: foreach my $line (@{$dirlistref}) {
10021: my ($file_name,$rest) = split(/\&/,$line,2);
10022: $currfile{$file_name} = 1;
10023: }
10024: }
10025: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10026: if (opendir(my $dir,$url)) {
10027: my @dir_list = grep(!/^\./,readdir($dir));
10028: map {$currfile{$_} = 1;} @dir_list;
10029: }
10030: } elsif (($actionurl eq '/adm/dependencies') ||
10031: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10032: ($args->{'context'} eq 'paste')) ||
10033: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10034: if ($env{'request.course.id'} ne '') {
10035: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10036: if ($dir ne '') {
10037: my ($dirlistref,$listerror) =
10038: &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10039: if (ref($dirlistref) eq 'ARRAY') {
10040: foreach my $line (@{$dirlistref}) {
10041: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10042: $size,undef,$mtime)=split(/\&/,$line,12);
10043: unless (($testdir&$dirptr) ||
10044: ($file_name =~ /^\.\.?$/)) {
10045: $currfile{$file_name} = [$size,$mtime];
10046: }
10047: }
10048: }
10049: }
10050: }
10051: }
10052: foreach my $file (keys(%dependencies)) {
10053: if (exists($currfile{$file})) {
10054: unless ($mapping{$file} eq $file) {
10055: $pathchanges{$file} = 1;
10056: }
10057: $existing{$file} = 1;
10058: $numexisting ++;
10059: } else {
10060: $newfiles{$file} = 1;
10061: }
10062: }
10063: foreach my $file (keys(%currfile)) {
10064: unless (($file eq $filename) ||
10065: ($file eq $filename.'.bak') ||
10066: ($dependencies{$file})) {
10067: if ($actionurl eq '/adm/dependencies') {
10068: unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10069: next if (($rem ne '') &&
10070: (($env{"httpref.$rem".$file} ne '') ||
10071: (ref($navmap) &&
10072: (($navmap->getResourceByUrl($rem.$file) ne '') ||
10073: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10074: ($navmap->getResourceByUrl($rem.$1)))))));
10075: }
10076: }
10077: $unused{$file} = 1;
10078: }
10079: }
10080: if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10081: ($args->{'context'} eq 'paste')) {
10082: $counter = scalar(keys(%existing));
10083: $numpathchg = scalar(keys(%pathchanges));
10084: return ($output,$counter,$numpathchg,\%existing);
10085: } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
10086: (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10087: $counter = scalar(keys(%existing));
10088: $numpathchg = scalar(keys(%pathchanges));
10089: return ($output,$counter,$numpathchg,\%existing,\%mapping);
10090: }
10091: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10092: if ($actionurl eq '/adm/dependencies') {
10093: next if ($embed_file =~ m{^\w+://});
10094: }
10095: $upload_output .= &start_data_table_row().
10096: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
10097: '<span class="LC_filename">'.$embed_file.'</span>';
10098: unless ($mapping{$embed_file} eq $embed_file) {
10099: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10100: &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10101: }
10102: $upload_output .= '</td>';
10103: if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) {
10104: $upload_output.='<td align="right">'.
10105: '<span class="LC_info LC_fontsize_medium">'.
10106: &mt("URL points to web address").'</span>';
10107: $numremref++;
10108: } elsif ($args->{'error_on_invalid_names'}
10109: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10110: $upload_output.='<td align="right"><span class="LC_warning">'.
10111: &mt('Invalid characters').'</span>';
10112: $numinvalid++;
10113: } else {
10114: $upload_output .= '<td>'.
10115: &embedded_file_element('upload_embedded',$counter,
10116: $embed_file,\%mapping,
10117: $allfiles,$codebase,'upload');
10118: $counter ++;
10119: $numnew ++;
10120: }
10121: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10122: }
10123: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10124: if ($actionurl eq '/adm/dependencies') {
10125: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10126: $modify_output .= &start_data_table_row().
10127: '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10128: '<img src="'.&icon($embed_file).'" border="0" />'.
10129: ' <span class="LC_filename">'.$embed_file.'</span></a></td>'.
10130: '<td>'.$size.'</td>'.
10131: '<td>'.$mtime.'</td>'.
10132: '<td><label><input type="checkbox" name="mod_upload_dep" '.
10133: 'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10134: $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10135: '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10136: &embedded_file_element('upload_embedded',$counter,
10137: $embed_file,\%mapping,
10138: $allfiles,$codebase,'modify').
10139: '</div></td>'.
10140: &end_data_table_row()."\n";
10141: $counter ++;
10142: } else {
10143: $upload_output .= &start_data_table_row().
10144: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
10145: '<span class="LC_filename">'.$embed_file.'</span></td>'.
10146: '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10147: &Apache::loncommon::end_data_table_row()."\n";
10148: }
10149: }
10150: my $delidx = $counter;
10151: foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10152: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10153: $delete_output .= &start_data_table_row().
10154: '<td><img src="'.&icon($oldfile).'" />'.
10155: ' <span class="LC_filename">'.$oldfile.'</span></td>'.
10156: '<td>'.$size.'</td>'.
10157: '<td>'.$mtime.'</td>'.
10158: '<td><label><input type="checkbox" name="del_upload_dep" '.
10159: ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10160: &embedded_file_element('upload_embedded',$delidx,
10161: $oldfile,\%mapping,$allfiles,
10162: $codebase,'delete').'</td>'.
10163: &end_data_table_row()."\n";
10164: $numunused ++;
10165: $delidx ++;
10166: }
10167: if ($upload_output) {
10168: $upload_output = &start_data_table().
10169: $upload_output.
10170: &end_data_table()."\n";
10171: }
10172: if ($modify_output) {
10173: $modify_output = &start_data_table().
10174: &start_data_table_header_row().
10175: '<th>'.&mt('File').'</th>'.
10176: '<th>'.&mt('Size (KB)').'</th>'.
10177: '<th>'.&mt('Modified').'</th>'.
10178: '<th>'.&mt('Upload replacement?').'</th>'.
10179: &end_data_table_header_row().
10180: $modify_output.
10181: &end_data_table()."\n";
10182: }
10183: if ($delete_output) {
10184: $delete_output = &start_data_table().
10185: &start_data_table_header_row().
10186: '<th>'.&mt('File').'</th>'.
10187: '<th>'.&mt('Size (KB)').'</th>'.
10188: '<th>'.&mt('Modified').'</th>'.
10189: '<th>'.&mt('Delete?').'</th>'.
10190: &end_data_table_header_row().
10191: $delete_output.
10192: &end_data_table()."\n";
10193: }
10194: my $applies = 0;
10195: if ($numremref) {
10196: $applies ++;
10197: }
10198: if ($numinvalid) {
10199: $applies ++;
10200: }
10201: if ($numexisting) {
10202: $applies ++;
10203: }
10204: if ($counter || $numunused) {
10205: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10206: ' method="post" enctype="multipart/form-data">'."\n".
10207: $state.'<h3>'.$heading.'</h3>';
10208: if ($actionurl eq '/adm/dependencies') {
10209: if ($numnew) {
10210: $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10211: '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10212: $upload_output.'<br />'."\n";
10213: }
10214: if ($numexisting) {
10215: $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10216: '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10217: $modify_output.'<br />'."\n";
10218: $buttontext = &mt('Save changes');
10219: }
10220: if ($numunused) {
10221: $output .= '<h4>'.&mt('Unused files').'</h4>'.
10222: '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
10223: $delete_output.'<br />'."\n";
10224: $buttontext = &mt('Save changes');
10225: }
10226: } else {
10227: $output .= $upload_output.'<br />'."\n";
10228: }
10229: $output .= '<input type ="hidden" name="number_embedded_items" value="'.
10230: $counter.'" />'."\n";
10231: if ($actionurl eq '/adm/dependencies') {
10232: $output .= '<input type ="hidden" name="number_newemb_items" value="'.
10233: $numnew.'" />'."\n";
10234: } elsif ($actionurl eq '') {
10235: $output .= '<input type="hidden" name="phase" value="three" />';
10236: }
10237: } elsif ($applies) {
10238: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
10239: if ($applies > 1) {
10240: $output .=
10241: &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
10242: if ($numremref) {
10243: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
10244: }
10245: if ($numinvalid) {
10246: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
10247: }
10248: if ($numexisting) {
10249: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
10250: }
10251: $output .= '</ul><br />';
10252: } elsif ($numremref) {
10253: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
10254: } elsif ($numinvalid) {
10255: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
10256: } elsif ($numexisting) {
10257: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
10258: }
10259: $output .= $upload_output.'<br />';
10260: }
10261: my ($pathchange_output,$chgcount);
10262: $chgcount = $counter;
10263: if (keys(%pathchanges) > 0) {
10264: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
10265: if ($counter) {
10266: $output .= &embedded_file_element('pathchange',$chgcount,
10267: $embed_file,\%mapping,
10268: $allfiles,$codebase,'change');
10269: } else {
10270: $pathchange_output .=
10271: &start_data_table_row().
10272: '<td><input type ="checkbox" name="namechange" value="'.
10273: $chgcount.'" checked="checked" /></td>'.
10274: '<td>'.$mapping{$embed_file}.'</td>'.
10275: '<td>'.$embed_file.
10276: &embedded_file_element('pathchange',$numpathchg,$embed_file,
10277: \%mapping,$allfiles,$codebase,'change').
10278: '</td>'.&end_data_table_row();
10279: }
10280: $numpathchg ++;
10281: $chgcount ++;
10282: }
10283: }
10284: if (($counter) || ($numunused)) {
10285: if ($numpathchg) {
10286: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
10287: $numpathchg.'" />'."\n";
10288: }
10289: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10290: ($actionurl eq '/adm/imsimport')) {
10291: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
10292: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
10293: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
10294: } elsif ($actionurl eq '/adm/dependencies') {
10295: $output .= '<input type="hidden" name="action" value="process_changes" />';
10296: }
10297: $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
10298: } elsif ($numpathchg) {
10299: my %pathchange = ();
10300: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
10301: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10302: $output .= '<p>'.&mt('or').'</p>';
10303: }
10304: }
10305: return ($output,$counter,$numpathchg);
10306: }
10307:
10308: =pod
10309:
10310: =item * clean_path($name)
10311:
10312: Performs clean-up of directories, subdirectories and filename in an
10313: embedded object, referenced in an HTML file which is being uploaded
10314: to a course or portfolio, where
10315: "Upload embedded images/multimedia files if HTML file" checkbox was
10316: checked.
10317:
10318: Clean-up is similar to replacements in lonnet::clean_filename()
10319: except each / between sub-directory and next level is preserved.
10320:
10321: =cut
10322:
10323: sub clean_path {
10324: my ($embed_file) = @_;
10325: $embed_file =~s{^/+}{};
10326: my @contents;
10327: if ($embed_file =~ m{/}) {
10328: @contents = split(/\//,$embed_file);
10329: } else {
10330: @contents = ($embed_file);
10331: }
10332: my $lastidx = scalar(@contents)-1;
10333: for (my $i=0; $i<=$lastidx; $i++) {
10334: $contents[$i]=~s{\\}{/}g;
10335: $contents[$i]=~s/\s+/\_/g;
10336: $contents[$i]=~s{[^/\w\.\-]}{}g;
10337: if ($i == $lastidx) {
10338: $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
10339: }
10340: }
10341: if ($lastidx > 0) {
10342: return join('/',@contents);
10343: } else {
10344: return $contents[0];
10345: }
10346: }
10347:
10348: sub embedded_file_element {
10349: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
10350: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
10351: (ref($codebase) eq 'HASH'));
10352: my $output;
10353: if (($context eq 'upload_embedded') && ($type ne 'delete')) {
10354: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
10355: }
10356: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
10357: &escape($embed_file).'" />';
10358: unless (($context eq 'upload_embedded') &&
10359: ($mapping->{$embed_file} eq $embed_file)) {
10360: $output .='
10361: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
10362: }
10363: my $attrib;
10364: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
10365: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
10366: }
10367: $output .=
10368: "\n\t\t".
10369: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
10370: $attrib.'" />';
10371: if (exists($codebase->{$mapping->{$embed_file}})) {
10372: $output .=
10373: "\n\t\t".
10374: '<input name="codebase_'.$num.'" type="hidden" value="'.
10375: &escape($codebase->{$mapping->{$embed_file}}).'" />';
10376: }
10377: return $output;
10378: }
10379:
10380: sub get_dependency_details {
10381: my ($currfile,$currsubfile,$embed_file) = @_;
10382: my ($size,$mtime,$showsize,$showmtime);
10383: if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
10384: if ($embed_file =~ m{/}) {
10385: my ($path,$fname) = split(/\//,$embed_file);
10386: if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
10387: ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
10388: }
10389: } else {
10390: if (ref($currfile->{$embed_file}) eq 'ARRAY') {
10391: ($size,$mtime) = @{$currfile->{$embed_file}};
10392: }
10393: }
10394: $showsize = $size/1024.0;
10395: $showsize = sprintf("%.1f",$showsize);
10396: if ($mtime > 0) {
10397: $showmtime = &Apache::lonlocal::locallocaltime($mtime);
10398: }
10399: }
10400: return ($showsize,$showmtime);
10401: }
10402:
10403: sub ask_embedded_js {
10404: return <<"END";
10405: <script type="text/javascript"">
10406: // <![CDATA[
10407: function toggleBrowse(counter) {
10408: var chkboxid = document.getElementById('mod_upload_dep_'+counter);
10409: var fileid = document.getElementById('embedded_item_'+counter);
10410: var uploaddivid = document.getElementById('moduploaddep_'+counter);
10411: if (chkboxid.checked == true) {
10412: uploaddivid.style.display='block';
10413: } else {
10414: uploaddivid.style.display='none';
10415: fileid.value = '';
10416: }
10417: }
10418: // ]]>
10419: </script>
10420:
10421: END
10422: }
10423:
10424: sub upload_embedded {
10425: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
10426: $current_disk_usage,$hiddenstate,$actionurl) = @_;
10427: my (%pathchange,$output,$modifyform,$footer,$returnflag);
10428: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
10429: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
10430: my $orig_uploaded_filename =
10431: $env{'form.embedded_item_'.$i.'.filename'};
10432: foreach my $type ('orig','ref','attrib','codebase') {
10433: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
10434: $env{'form.embedded_'.$type.'_'.$i} =
10435: &unescape($env{'form.embedded_'.$type.'_'.$i});
10436: }
10437: }
10438: my ($path,$fname) =
10439: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
10440: # no path, whole string is fname
10441: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
10442: $fname = &Apache::lonnet::clean_filename($fname);
10443: # See if there is anything left
10444: next if ($fname eq '');
10445:
10446: # Check if file already exists as a file or directory.
10447: my ($state,$msg);
10448: if ($context eq 'portfolio') {
10449: my $port_path = $dirpath;
10450: if ($group ne '') {
10451: $port_path = "groups/$group/$port_path";
10452: }
10453: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
10454: $fname,$group,'embedded_item_'.$i,
10455: $dir_root,$port_path,$disk_quota,
10456: $current_disk_usage,$uname,$udom);
10457: if ($state eq 'will_exceed_quota'
10458: || $state eq 'file_locked') {
10459: $output .= $msg;
10460: next;
10461: }
10462: } elsif (($context eq 'author') || ($context eq 'testbank')) {
10463: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
10464: if ($state eq 'exists') {
10465: $output .= $msg;
10466: next;
10467: }
10468: }
10469: # Check if extension is valid
10470: if (($fname =~ /\.(\w+)$/) &&
10471: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10472: $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
10473: .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
10474: next;
10475: } elsif (($fname =~ /\.(\w+)$/) &&
10476: (!defined(&Apache::loncommon::fileembstyle($1)))) {
10477: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10478: next;
10479: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10480: $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10481: next;
10482: }
10483: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10484: my $subdir = $path;
10485: $subdir =~ s{/+$}{};
10486: if ($context eq 'portfolio') {
10487: my $result;
10488: if ($state eq 'existingfile') {
10489: $result=
10490: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10491: $dirpath.$env{'form.currentpath'}.$subdir);
10492: } else {
10493: $result=
10494: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10495: $dirpath.
10496: $env{'form.currentpath'}.$subdir);
10497: if ($result !~ m|^/uploaded/|) {
10498: $output .= '<span class="LC_error">'
10499: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10500: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10501: .'</span><br />';
10502: next;
10503: } else {
10504: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10505: $path.$fname.'</span>').'<br />';
10506: }
10507: }
10508: } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
10509: my $extendedsubdir = $dirpath.'/'.$subdir;
10510: $extendedsubdir =~ s{/+$}{};
10511: my $result =
10512: &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
10513: if ($result !~ m|^/uploaded/|) {
10514: $output .= '<span class="LC_error">'
10515: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10516: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10517: .'</span><br />';
10518: next;
10519: } else {
10520: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10521: $path.$fname.'</span>').'<br />';
10522: if ($context eq 'syllabus') {
10523: &Apache::lonnet::make_public_indefinitely($result);
10524: }
10525: }
10526: } else {
10527: # Save the file
10528: my $target = $env{'form.embedded_item_'.$i};
10529: my $fullpath = $dir_root.$dirpath.'/'.$path;
10530: my $dest = $fullpath.$fname;
10531: my $url = $url_root.$dirpath.'/'.$path.$fname;
10532: my @parts=split(/\//,"$dirpath/$path");
10533: my $count;
10534: my $filepath = $dir_root;
10535: foreach my $subdir (@parts) {
10536: $filepath .= "/$subdir";
10537: if (!-e $filepath) {
10538: mkdir($filepath,0770);
10539: }
10540: }
10541: my $fh;
10542: if (!open($fh,'>'.$dest)) {
10543: &Apache::lonnet::logthis('Failed to create '.$dest);
10544: $output .= '<span class="LC_error">'.
10545: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10546: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10547: '</span><br />';
10548: } else {
10549: if (!print $fh $env{'form.embedded_item_'.$i}) {
10550: &Apache::lonnet::logthis('Failed to write to '.$dest);
10551: $output .= '<span class="LC_error">'.
10552: &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10553: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10554: '</span><br />';
10555: } else {
10556: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10557: $url.'</span>').'<br />';
10558: unless ($context eq 'testbank') {
10559: $footer .= &mt('View embedded file: [_1]',
10560: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10561: }
10562: }
10563: close($fh);
10564: }
10565: }
10566: if ($env{'form.embedded_ref_'.$i}) {
10567: $pathchange{$i} = 1;
10568: }
10569: }
10570: if ($output) {
10571: $output = '<p>'.$output.'</p>';
10572: }
10573: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10574: $returnflag = 'ok';
10575: my $numpathchgs = scalar(keys(%pathchange));
10576: if ($numpathchgs > 0) {
10577: if ($context eq 'portfolio') {
10578: $output .= '<p>'.&mt('or').'</p>';
10579: } elsif ($context eq 'testbank') {
10580: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10581: '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10582: $returnflag = 'modify_orightml';
10583: }
10584: }
10585: return ($output.$footer,$returnflag,$numpathchgs);
10586: }
10587:
10588: sub modify_html_form {
10589: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10590: my $end = 0;
10591: my $modifyform;
10592: if ($context eq 'upload_embedded') {
10593: return unless (ref($pathchange) eq 'HASH');
10594: if ($env{'form.number_embedded_items'}) {
10595: $end += $env{'form.number_embedded_items'};
10596: }
10597: if ($env{'form.number_pathchange_items'}) {
10598: $end += $env{'form.number_pathchange_items'};
10599: }
10600: if ($end) {
10601: for (my $i=0; $i<$end; $i++) {
10602: if ($i < $env{'form.number_embedded_items'}) {
10603: next unless($pathchange->{$i});
10604: }
10605: $modifyform .=
10606: &start_data_table_row().
10607: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10608: 'checked="checked" /></td>'.
10609: '<td>'.$env{'form.embedded_ref_'.$i}.
10610: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10611: &escape($env{'form.embedded_ref_'.$i}).'" />'.
10612: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10613: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10614: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10615: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10616: '<td>'.$env{'form.embedded_orig_'.$i}.
10617: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10618: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10619: &end_data_table_row();
10620: }
10621: }
10622: } else {
10623: $modifyform = $pathchgtable;
10624: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10625: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10626: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10627: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10628: }
10629: }
10630: if ($modifyform) {
10631: if ($actionurl eq '/adm/dependencies') {
10632: $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10633: }
10634: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10635: '<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".
10636: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10637: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10638: '</ol></p>'."\n".'<p>'.
10639: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10640: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10641: &start_data_table()."\n".
10642: &start_data_table_header_row().
10643: '<th>'.&mt('Change?').'</th>'.
10644: '<th>'.&mt('Current reference').'</th>'.
10645: '<th>'.&mt('Required reference').'</th>'.
10646: &end_data_table_header_row()."\n".
10647: $modifyform.
10648: &end_data_table().'<br />'."\n".$hiddenstate.
10649: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10650: '</form>'."\n";
10651: }
10652: return;
10653: }
10654:
10655: sub modify_html_refs {
10656: my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
10657: my $container;
10658: if ($context eq 'portfolio') {
10659: $container = $env{'form.container'};
10660: } elsif ($context eq 'coursedoc') {
10661: $container = $env{'form.primaryurl'};
10662: } elsif ($context eq 'manage_dependencies') {
10663: (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10664: $container = "/$container";
10665: } elsif ($context eq 'syllabus') {
10666: $container = $url;
10667: } else {
10668: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10669: }
10670: my (%allfiles,%codebase,$output,$content);
10671: my @changes = &get_env_multiple('form.namechange');
10672: unless ((@changes > 0) || ($context eq 'syllabus')) {
10673: if (wantarray) {
10674: return ('',0,0);
10675: } else {
10676: return;
10677: }
10678: }
10679: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
10680: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10681: unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10682: if (wantarray) {
10683: return ('',0,0);
10684: } else {
10685: return;
10686: }
10687: }
10688: $content = &Apache::lonnet::getfile($container);
10689: if ($content eq '-1') {
10690: if (wantarray) {
10691: return ('',0,0);
10692: } else {
10693: return;
10694: }
10695: }
10696: } else {
10697: unless ($container =~ /^\Q$dir_root\E/) {
10698: if (wantarray) {
10699: return ('',0,0);
10700: } else {
10701: return;
10702: }
10703: }
10704: if (open(my $fh,"<$container")) {
10705: $content = join('', <$fh>);
10706: close($fh);
10707: } else {
10708: if (wantarray) {
10709: return ('',0,0);
10710: } else {
10711: return;
10712: }
10713: }
10714: }
10715: my ($count,$codebasecount) = (0,0);
10716: my $mm = new File::MMagic;
10717: my $mime_type = $mm->checktype_contents($content);
10718: if ($mime_type eq 'text/html') {
10719: my $parse_result =
10720: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
10721: \%codebase,\$content);
10722: if ($parse_result eq 'ok') {
10723: foreach my $i (@changes) {
10724: my $orig = &unescape($env{'form.embedded_orig_'.$i});
10725: my $ref = &unescape($env{'form.embedded_ref_'.$i});
10726: if ($allfiles{$ref}) {
10727: my $newname = $orig;
10728: my ($attrib_regexp,$codebase);
10729: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
10730: if ($attrib_regexp =~ /:/) {
10731: $attrib_regexp =~ s/\:/|/g;
10732: }
10733: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10734: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10735: $count += $numchg;
10736: $allfiles{$newname} = $allfiles{$ref};
10737: delete($allfiles{$ref});
10738: }
10739: if ($env{'form.embedded_codebase_'.$i} ne '') {
10740: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
10741: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
10742: $codebasecount ++;
10743: }
10744: }
10745: }
10746: my $skiprewrites;
10747: if ($count || $codebasecount) {
10748: my $saveresult;
10749: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
10750: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10751: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10752: if ($url eq $container) {
10753: my ($fname) = ($container =~ m{/([^/]+)$});
10754: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10755: $count,'<span class="LC_filename">'.
10756: $fname.'</span>').'</p>';
10757: } else {
10758: $output = '<p class="LC_error">'.
10759: &mt('Error: update failed for: [_1].',
10760: '<span class="LC_filename">'.
10761: $container.'</span>').'</p>';
10762: }
10763: if ($context eq 'syllabus') {
10764: unless ($saveresult eq 'ok') {
10765: $skiprewrites = 1;
10766: }
10767: }
10768: } else {
10769: if (open(my $fh,">$container")) {
10770: print $fh $content;
10771: close($fh);
10772: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10773: $count,'<span class="LC_filename">'.
10774: $container.'</span>').'</p>';
10775: } else {
10776: $output = '<p class="LC_error">'.
10777: &mt('Error: could not update [_1].',
10778: '<span class="LC_filename">'.
10779: $container.'</span>').'</p>';
10780: }
10781: }
10782: }
10783: if (($context eq 'syllabus') && (!$skiprewrites)) {
10784: my ($actionurl,$state);
10785: $actionurl = "/public/$udom/$uname/syllabus";
10786: my ($ignore,$num,$numpathchanges,$existing,$mapping) =
10787: &ask_for_embedded_content($actionurl,$state,\%allfiles,
10788: \%codebase,
10789: {'context' => 'rewrites',
10790: 'ignore_remote_references' => 1,});
10791: if (ref($mapping) eq 'HASH') {
10792: my $rewrites = 0;
10793: foreach my $key (keys(%{$mapping})) {
10794: next if ($key =~ m{^https?://});
10795: my $ref = $mapping->{$key};
10796: my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
10797: my $attrib;
10798: if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
10799: $attrib = join('|',@{$allfiles{$mapping->{$key}}});
10800: }
10801: if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10802: my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10803: $rewrites += $numchg;
10804: }
10805: }
10806: if ($rewrites) {
10807: my $saveresult;
10808: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10809: if ($url eq $container) {
10810: my ($fname) = ($container =~ m{/([^/]+)$});
10811: $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
10812: $count,'<span class="LC_filename">'.
10813: $fname.'</span>').'</p>';
10814: } else {
10815: $output .= '<p class="LC_error">'.
10816: &mt('Error: could not update links in [_1].',
10817: '<span class="LC_filename">'.
10818: $container.'</span>').'</p>';
10819:
10820: }
10821: }
10822: }
10823: }
10824: } else {
10825: &logthis('Failed to parse '.$container.
10826: ' to modify references: '.$parse_result);
10827: }
10828: }
10829: if (wantarray) {
10830: return ($output,$count,$codebasecount);
10831: } else {
10832: return $output;
10833: }
10834: }
10835:
10836: sub check_for_existing {
10837: my ($path,$fname,$element) = @_;
10838: my ($state,$msg);
10839: if (-d $path.'/'.$fname) {
10840: $state = 'exists';
10841: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10842: } elsif (-e $path.'/'.$fname) {
10843: $state = 'exists';
10844: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10845: }
10846: if ($state eq 'exists') {
10847: $msg = '<span class="LC_error">'.$msg.'</span><br />';
10848: }
10849: return ($state,$msg);
10850: }
10851:
10852: sub check_for_upload {
10853: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
10854: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
10855: my $filesize = length($env{'form.'.$element});
10856: if (!$filesize) {
10857: my $msg = '<span class="LC_error">'.
10858: &mt('Unable to upload [_1]. (size = [_2] bytes)',
10859: '<span class="LC_filename">'.$fname.'</span>',
10860: $filesize).'<br />'.
10861: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
10862: '</span>';
10863: return ('zero_bytes',$msg);
10864: }
10865: $filesize = $filesize/1000; #express in k (1024?)
10866: my $getpropath = 1;
10867: my ($dirlistref,$listerror) =
10868: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
10869: my $found_file = 0;
10870: my $locked_file = 0;
10871: my @lockers;
10872: my $navmap;
10873: if ($env{'request.course.id'}) {
10874: $navmap = Apache::lonnavmaps::navmap->new();
10875: }
10876: if (ref($dirlistref) eq 'ARRAY') {
10877: foreach my $line (@{$dirlistref}) {
10878: my ($file_name,$rest)=split(/\&/,$line,2);
10879: if ($file_name eq $fname){
10880: $file_name = $path.$file_name;
10881: if ($group ne '') {
10882: $file_name = $group.$file_name;
10883: }
10884: $found_file = 1;
10885: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
10886: foreach my $lock (@lockers) {
10887: if (ref($lock) eq 'ARRAY') {
10888: my ($symb,$crsid) = @{$lock};
10889: if ($crsid eq $env{'request.course.id'}) {
10890: if (ref($navmap)) {
10891: my $res = $navmap->getBySymb($symb);
10892: foreach my $part (@{$res->parts()}) {
10893: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
10894: unless (($slot_status == $res->RESERVED) ||
10895: ($slot_status == $res->RESERVED_LOCATION)) {
10896: $locked_file = 1;
10897: }
10898: }
10899: } else {
10900: $locked_file = 1;
10901: }
10902: } else {
10903: $locked_file = 1;
10904: }
10905: }
10906: }
10907: } else {
10908: my @info = split(/\&/,$rest);
10909: my $currsize = $info[6]/1000;
10910: if ($currsize < $filesize) {
10911: my $extra = $filesize - $currsize;
10912: if (($current_disk_usage + $extra) > $disk_quota) {
10913: my $msg = '<span class="LC_error">'.
10914: &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.',
10915: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
10916: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10917: $disk_quota,$current_disk_usage);
10918: return ('will_exceed_quota',$msg);
10919: }
10920: }
10921: }
10922: }
10923: }
10924: }
10925: if (($current_disk_usage + $filesize) > $disk_quota){
10926: my $msg = '<span class="LC_error">'.
10927: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
10928: '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
10929: return ('will_exceed_quota',$msg);
10930: } elsif ($found_file) {
10931: if ($locked_file) {
10932: my $msg = '<span class="LC_error">';
10933: $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>');
10934: $msg .= '</span><br />';
10935: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
10936: return ('file_locked',$msg);
10937: } else {
10938: my $msg = '<span class="LC_error">';
10939: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
10940: $msg .= '</span>';
10941: return ('existingfile',$msg);
10942: }
10943: }
10944: }
10945:
10946: sub check_for_traversal {
10947: my ($path,$url,$toplevel) = @_;
10948: my @parts=split(/\//,$path);
10949: my $cleanpath;
10950: my $fullpath = $url;
10951: for (my $i=0;$i<@parts;$i++) {
10952: next if ($parts[$i] eq '.');
10953: if ($parts[$i] eq '..') {
10954: $fullpath =~ s{([^/]+/)$}{};
10955: } else {
10956: $fullpath .= $parts[$i].'/';
10957: }
10958: }
10959: if ($fullpath =~ /^\Q$url\E(.*)$/) {
10960: $cleanpath = $1;
10961: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
10962: my $curr_toprel = $1;
10963: my @parts = split(/\//,$curr_toprel);
10964: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
10965: my @urlparts = split(/\//,$url_toprel);
10966: my $doubledots;
10967: my $startdiff = -1;
10968: for (my $i=0; $i<@urlparts; $i++) {
10969: if ($startdiff == -1) {
10970: unless ($urlparts[$i] eq $parts[$i]) {
10971: $startdiff = $i;
10972: $doubledots .= '../';
10973: }
10974: } else {
10975: $doubledots .= '../';
10976: }
10977: }
10978: if ($startdiff > -1) {
10979: $cleanpath = $doubledots;
10980: for (my $i=$startdiff; $i<@parts; $i++) {
10981: $cleanpath .= $parts[$i].'/';
10982: }
10983: }
10984: }
10985: $cleanpath =~ s{(/)$}{};
10986: return $cleanpath;
10987: }
10988:
10989: sub is_archive_file {
10990: my ($mimetype) = @_;
10991: if (($mimetype eq 'application/octet-stream') ||
10992: ($mimetype eq 'application/x-stuffit') ||
10993: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
10994: return 1;
10995: }
10996: return;
10997: }
10998:
10999: sub decompress_form {
11000: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11001: my %lt = &Apache::lonlocal::texthash (
11002: this => 'This file is an archive file.',
11003: camt => 'This file is a Camtasia archive file.',
11004: itsc => 'Its contents are as follows:',
11005: youm => 'You may wish to extract its contents.',
11006: extr => 'Extract contents',
11007: auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11008: proa => 'Process automatically?',
11009: yes => 'Yes',
11010: no => 'No',
11011: fold => 'Title for folder containing movie',
11012: movi => 'Title for page containing embedded movie',
11013: );
11014: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11015: my ($is_camtasia,$topdir,%toplevel,@paths);
11016: my $info = &list_archive_contents($fileloc,\@paths);
11017: if (@paths) {
11018: foreach my $path (@paths) {
11019: $path =~ s{^/}{};
11020: if ($path =~ m{^([^/]+)/$}) {
11021: $topdir = $1;
11022: }
11023: if ($path =~ m{^([^/]+)/}) {
11024: $toplevel{$1} = $path;
11025: } else {
11026: $toplevel{$path} = $path;
11027: }
11028: }
11029: }
11030: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11031: my @camtasia6 = ("$topdir/","$topdir/index.html",
11032: "$topdir/media/",
11033: "$topdir/media/$topdir.mp4",
11034: "$topdir/media/FirstFrame.png",
11035: "$topdir/media/player.swf",
11036: "$topdir/media/swfobject.js",
11037: "$topdir/media/expressInstall.swf");
11038: my @camtasia8 = ("$topdir/","$topdir/$topdir.html",
11039: "$topdir/$topdir.mp4",
11040: "$topdir/$topdir\_config.xml",
11041: "$topdir/$topdir\_controller.swf",
11042: "$topdir/$topdir\_embed.css",
11043: "$topdir/$topdir\_First_Frame.png",
11044: "$topdir/$topdir\_player.html",
11045: "$topdir/$topdir\_Thumbnails.png",
11046: "$topdir/playerProductInstall.swf",
11047: "$topdir/scripts/",
11048: "$topdir/scripts/config_xml.js",
11049: "$topdir/scripts/handlebars.js",
11050: "$topdir/scripts/jquery-1.7.1.min.js",
11051: "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11052: "$topdir/scripts/modernizr.js",
11053: "$topdir/scripts/player-min.js",
11054: "$topdir/scripts/swfobject.js",
11055: "$topdir/skins/",
11056: "$topdir/skins/configuration_express.xml",
11057: "$topdir/skins/express_show/",
11058: "$topdir/skins/express_show/player-min.css",
11059: "$topdir/skins/express_show/spritesheet.png");
11060: my @diffs = &compare_arrays(\@paths,\@camtasia6);
11061: if (@diffs == 0) {
11062: $is_camtasia = 6;
11063: } else {
11064: @diffs = &compare_arrays(\@paths,\@camtasia8);
11065: if (@diffs == 0) {
11066: $is_camtasia = 8;
11067: }
11068: }
11069: }
11070: my $output;
11071: if ($is_camtasia) {
11072: $output = <<"ENDCAM";
11073: <script type="text/javascript" language="Javascript">
11074: // <![CDATA[
11075:
11076: function camtasiaToggle() {
11077: for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11078: if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11079: if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11080:
11081: document.getElementById('camtasia_titles').style.display='block';
11082: } else {
11083: document.getElementById('camtasia_titles').style.display='none';
11084: }
11085: }
11086: }
11087: return;
11088: }
11089:
11090: // ]]>
11091: </script>
11092: <p>$lt{'camt'}</p>
11093: ENDCAM
11094: } else {
11095: $output = '<p>'.$lt{'this'};
11096: if ($info eq '') {
11097: $output .= ' '.$lt{'youm'}.'</p>'."\n";
11098: } else {
11099: $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11100: '<div><pre>'.$info.'</pre></div>';
11101: }
11102: }
11103: $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11104: my $duplicates;
11105: my $num = 0;
11106: if (ref($dirlist) eq 'ARRAY') {
11107: foreach my $item (@{$dirlist}) {
11108: if (ref($item) eq 'ARRAY') {
11109: if (exists($toplevel{$item->[0]})) {
11110: $duplicates .=
11111: &start_data_table_row().
11112: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11113: 'value="0" checked="checked" />'.&mt('No').'</label>'.
11114: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '.
11115: 'value="1" />'.&mt('Yes').'</label>'.
11116: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11117: '<td>'.$item->[0].'</td>';
11118: if ($item->[2]) {
11119: $duplicates .= '<td>'.&mt('Directory').'</td>';
11120: } else {
11121: $duplicates .= '<td>'.&mt('File').'</td>';
11122: }
11123: $duplicates .= '<td>'.$item->[3].'</td>'.
11124: '<td>'.
11125: &Apache::lonlocal::locallocaltime($item->[4]).
11126: '</td>'.
11127: &end_data_table_row();
11128: $num ++;
11129: }
11130: }
11131: }
11132: }
11133: my $itemcount;
11134: if (@paths > 0) {
11135: $itemcount = scalar(@paths);
11136: } else {
11137: $itemcount = 1;
11138: }
11139: if ($is_camtasia) {
11140: $output .= $lt{'auto'}.'<br />'.
11141: '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11142: '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11143: $lt{'yes'}.'</label> <label>'.
11144: '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11145: $lt{'no'}.'</label></span><br />'.
11146: '<div id="camtasia_titles" style="display:block">'.
11147: &Apache::lonhtmlcommon::start_pick_box().
11148: &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11149: '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11150: &Apache::lonhtmlcommon::row_closure().
11151: &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11152: '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11153: &Apache::lonhtmlcommon::row_closure(1).
11154: &Apache::lonhtmlcommon::end_pick_box().
11155: '</div>';
11156: }
11157: $output .=
11158: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11159: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11160: "\n";
11161: if ($duplicates ne '') {
11162: $output .= '<p><span class="LC_warning">'.
11163: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.
11164: &start_data_table().
11165: &start_data_table_header_row().
11166: '<th>'.&mt('Overwrite?').'</th>'.
11167: '<th>'.&mt('Name').'</th>'.
11168: '<th>'.&mt('Type').'</th>'.
11169: '<th>'.&mt('Size').'</th>'.
11170: '<th>'.&mt('Last modified').'</th>'.
11171: &end_data_table_header_row().
11172: $duplicates.
11173: &end_data_table().
11174: '</p>';
11175: }
11176: $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11177: if (ref($hiddenelements) eq 'HASH') {
11178: foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11179: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11180: }
11181: }
11182: $output .= <<"END";
11183: <br />
11184: <input type="submit" name="decompress" value="$lt{'extr'}" />
11185: </form>
11186: $noextract
11187: END
11188: return $output;
11189: }
11190:
11191: sub decompression_utility {
11192: my ($program) = @_;
11193: my @utilities = ('tar','gunzip','bunzip2','unzip');
11194: my $location;
11195: if (grep(/^\Q$program\E$/,@utilities)) {
11196: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
11197: '/usr/sbin/') {
11198: if (-x $dir.$program) {
11199: $location = $dir.$program;
11200: last;
11201: }
11202: }
11203: }
11204: return $location;
11205: }
11206:
11207: sub list_archive_contents {
11208: my ($file,$pathsref) = @_;
11209: my (@cmd,$output);
11210: my $needsregexp;
11211: if ($file =~ /\.zip$/) {
11212: @cmd = (&decompression_utility('unzip'),"-l");
11213: $needsregexp = 1;
11214: } elsif (($file =~ m/\.tar\.gz$/) ||
11215: ($file =~ /\.tgz$/)) {
11216: @cmd = (&decompression_utility('tar'),"-ztf");
11217: } elsif ($file =~ /\.tar\.bz2$/) {
11218: @cmd = (&decompression_utility('tar'),"-jtf");
11219: } elsif ($file =~ m|\.tar$|) {
11220: @cmd = (&decompression_utility('tar'),"-tf");
11221: }
11222: if (@cmd) {
11223: undef($!);
11224: undef($@);
11225: if (open(my $fh,"-|", @cmd, $file)) {
11226: while (my $line = <$fh>) {
11227: $output .= $line;
11228: chomp($line);
11229: my $item;
11230: if ($needsregexp) {
11231: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/);
11232: } else {
11233: $item = $line;
11234: }
11235: if ($item ne '') {
11236: unless (grep(/^\Q$item\E$/,@{$pathsref})) {
11237: push(@{$pathsref},$item);
11238: }
11239: }
11240: }
11241: close($fh);
11242: }
11243: }
11244: return $output;
11245: }
11246:
11247: sub decompress_uploaded_file {
11248: my ($file,$dir) = @_;
11249: &Apache::lonnet::appenv({'cgi.file' => $file});
11250: &Apache::lonnet::appenv({'cgi.dir' => $dir});
11251: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
11252: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
11253: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
11254: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
11255: my $decompressed = $env{'cgi.decompressed'};
11256: &Apache::lonnet::delenv('cgi.file');
11257: &Apache::lonnet::delenv('cgi.dir');
11258: &Apache::lonnet::delenv('cgi.decompressed');
11259: return ($decompressed,$result);
11260: }
11261:
11262: sub process_decompression {
11263: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
11264: my ($dir,$error,$warning,$output);
11265: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
11266: $error = &mt('Filename not a supported archive file type.').
11267: '<br />'.&mt('Filename should end with one of: [_1].',
11268: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
11269: } else {
11270: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11271: if ($docuhome eq 'no_host') {
11272: $error = &mt('Could not determine home server for course.');
11273: } else {
11274: my @ids=&Apache::lonnet::current_machine_ids();
11275: my $currdir = "$dir_root/$destination";
11276: if (grep(/^\Q$docuhome\E$/,@ids)) {
11277: $dir = &LONCAPA::propath($docudom,$docuname).
11278: "$dir_root/$destination";
11279: } else {
11280: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
11281: "$dir_root/$docudom/$docuname/$destination";
11282: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
11283: $error = &mt('Archive file not found.');
11284: }
11285: }
11286: my (@to_overwrite,@to_skip);
11287: if ($env{'form.archive_overwrite_total'} > 0) {
11288: my $total = $env{'form.archive_overwrite_total'};
11289: for (my $i=0; $i<$total; $i++) {
11290: if ($env{'form.archive_overwrite_'.$i} == 1) {
11291: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
11292: } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
11293: push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
11294: }
11295: }
11296: }
11297: my $numskip = scalar(@to_skip);
11298: if (($numskip > 0) &&
11299: ($numskip == $env{'form.archive_itemcount'})) {
11300: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');
11301: } elsif ($dir eq '') {
11302: $error = &mt('Directory containing archive file unavailable.');
11303: } elsif (!$error) {
11304: my ($decompressed,$display);
11305: if ($numskip > 0) {
11306: my $tempdir = time.'_'.$$.int(rand(10000));
11307: mkdir("$dir/$tempdir",0755);
11308: system("mv $dir/$file $dir/$tempdir/$file");
11309: ($decompressed,$display) =
11310: &decompress_uploaded_file($file,"$dir/$tempdir");
11311: foreach my $item (@to_skip) {
11312: if (($item ne '') && ($item !~ /\.\./)) {
11313: if (-f "$dir/$tempdir/$item") {
11314: unlink("$dir/$tempdir/$item");
11315: } elsif (-d "$dir/$tempdir/$item") {
11316: system("rm -rf $dir/$tempdir/$item");
11317: }
11318: }
11319: }
11320: system("mv $dir/$tempdir/* $dir");
11321: rmdir("$dir/$tempdir");
11322: } else {
11323: ($decompressed,$display) =
11324: &decompress_uploaded_file($file,$dir);
11325: }
11326: if ($decompressed eq 'ok') {
11327: $output = '<p class="LC_info">'.
11328: &mt('Files extracted successfully from archive.').
11329: '</p>'."\n";
11330: my ($warning,$result,@contents);
11331: my ($newdirlistref,$newlisterror) =
11332: &Apache::lonnet::dirlist($currdir,$docudom,
11333: $docuname,1);
11334: my (%is_dir,%changes,@newitems);
11335: my $dirptr = 16384;
11336: if (ref($newdirlistref) eq 'ARRAY') {
11337: foreach my $dir_line (@{$newdirlistref}) {
11338: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11339: unless (($item =~ /^\.+$/) || ($item eq $file) ||
11340: ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
11341: push(@newitems,$item);
11342: if ($dirptr&$testdir) {
11343: $is_dir{$item} = 1;
11344: }
11345: $changes{$item} = 1;
11346: }
11347: }
11348: }
11349: if (keys(%changes) > 0) {
11350: foreach my $item (sort(@newitems)) {
11351: if ($changes{$item}) {
11352: push(@contents,$item);
11353: }
11354: }
11355: }
11356: if (@contents > 0) {
11357: my $wantform;
11358: unless ($env{'form.autoextract_camtasia'}) {
11359: $wantform = 1;
11360: }
11361: my (%children,%parent,%dirorder,%titles);
11362: my ($count,$datatable) = &get_extracted($docudom,$docuname,
11363: $currdir,\%is_dir,
11364: \%children,\%parent,
11365: \@contents,\%dirorder,
11366: \%titles,$wantform);
11367: if ($datatable ne '') {
11368: $output .= &archive_options_form('decompressed',$datatable,
11369: $count,$hiddenelem);
11370: my $startcount = 6;
11371: $output .= &archive_javascript($startcount,$count,
11372: \%titles,\%children);
11373: }
11374: if ($env{'form.autoextract_camtasia'}) {
11375: my $version = $env{'form.autoextract_camtasia'};
11376: my %displayed;
11377: my $total = 1;
11378: $env{'form.archive_directory'} = [];
11379: foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
11380: my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
11381: $path =~ s{/$}{};
11382: my $item;
11383: if ($path ne '') {
11384: $item = "$path/$titles{$i}";
11385: } else {
11386: $item = $titles{$i};
11387: }
11388: $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
11389: if ($item eq $contents[0]) {
11390: push(@{$env{'form.archive_directory'}},$i);
11391: $env{'form.archive_'.$i} = 'display';
11392: $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
11393: $displayed{'folder'} = $i;
11394: } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
11395: (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
11396: $env{'form.archive_'.$i} = 'display';
11397: $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
11398: $displayed{'web'} = $i;
11399: } else {
11400: if ((($item eq "$contents[0]/media") && ($version == 6)) ||
11401: ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
11402: ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
11403: push(@{$env{'form.archive_directory'}},$i);
11404: }
11405: $env{'form.archive_'.$i} = 'dependency';
11406: }
11407: $total ++;
11408: }
11409: for (my $i=1; $i<$total; $i++) {
11410: next if ($i == $displayed{'web'});
11411: next if ($i == $displayed{'folder'});
11412: $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
11413: }
11414: $env{'form.phase'} = 'decompress_cleanup';
11415: $env{'form.archivedelete'} = 1;
11416: $env{'form.archive_count'} = $total-1;
11417: $output .=
11418: &process_extracted_files('coursedocs',$docudom,
11419: $docuname,$destination,
11420: $dir_root,$hiddenelem);
11421: }
11422: } else {
11423: $warning = &mt('No new items extracted from archive file.');
11424: }
11425: } else {
11426: $output = $display;
11427: $error = &mt('An error occurred during extraction from the archive file.');
11428: }
11429: }
11430: }
11431: }
11432: if ($error) {
11433: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11434: $error.'</p>'."\n";
11435: }
11436: if ($warning) {
11437: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11438: }
11439: return $output;
11440: }
11441:
11442: sub get_extracted {
11443: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
11444: $titles,$wantform) = @_;
11445: my $count = 0;
11446: my $depth = 0;
11447: my $datatable;
11448: my @hierarchy;
11449: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
11450: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
11451: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
11452: foreach my $item (@{$contents}) {
11453: $count ++;
11454: @{$dirorder->{$count}} = @hierarchy;
11455: $titles->{$count} = $item;
11456: &archive_hierarchy($depth,$count,$parent,$children);
11457: if ($wantform) {
11458: $datatable .= &archive_row($is_dir->{$item},$item,
11459: $currdir,$depth,$count);
11460: }
11461: if ($is_dir->{$item}) {
11462: $depth ++;
11463: push(@hierarchy,$count);
11464: $parent->{$depth} = $count;
11465: $datatable .=
11466: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
11467: \$depth,\$count,\@hierarchy,$dirorder,
11468: $children,$parent,$titles,$wantform);
11469: $depth --;
11470: pop(@hierarchy);
11471: }
11472: }
11473: return ($count,$datatable);
11474: }
11475:
11476: sub recurse_extracted_archive {
11477: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
11478: $children,$parent,$titles,$wantform) = @_;
11479: my $result='';
11480: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
11481: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
11482: (ref($dirorder) eq 'HASH')) {
11483: return $result;
11484: }
11485: my $dirptr = 16384;
11486: my ($newdirlistref,$newlisterror) =
11487: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
11488: if (ref($newdirlistref) eq 'ARRAY') {
11489: foreach my $dir_line (@{$newdirlistref}) {
11490: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11491: unless ($item =~ /^\.+$/) {
11492: $$count ++;
11493: @{$dirorder->{$$count}} = @{$hierarchy};
11494: $titles->{$$count} = $item;
11495: &archive_hierarchy($$depth,$$count,$parent,$children);
11496:
11497: my $is_dir;
11498: if ($dirptr&$testdir) {
11499: $is_dir = 1;
11500: }
11501: if ($wantform) {
11502: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
11503: }
11504: if ($is_dir) {
11505: $$depth ++;
11506: push(@{$hierarchy},$$count);
11507: $parent->{$$depth} = $$count;
11508: $result .=
11509: &recurse_extracted_archive("$currdir/$item",$docudom,
11510: $docuname,$depth,$count,
11511: $hierarchy,$dirorder,$children,
11512: $parent,$titles,$wantform);
11513: $$depth --;
11514: pop(@{$hierarchy});
11515: }
11516: }
11517: }
11518: }
11519: return $result;
11520: }
11521:
11522: sub archive_hierarchy {
11523: my ($depth,$count,$parent,$children) =@_;
11524: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
11525: if (exists($parent->{$depth})) {
11526: $children->{$parent->{$depth}} .= $count.':';
11527: }
11528: }
11529: return;
11530: }
11531:
11532: sub archive_row {
11533: my ($is_dir,$item,$currdir,$depth,$count) = @_;
11534: my ($name) = ($item =~ m{([^/]+)$});
11535: my %choices = &Apache::lonlocal::texthash (
11536: 'display' => 'Add as file',
11537: 'dependency' => 'Include as dependency',
11538: 'discard' => 'Discard',
11539: );
11540: if ($is_dir) {
11541: $choices{'display'} = &mt('Add as folder');
11542: }
11543: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
11544: my $offset = 0;
11545: foreach my $action ('display','dependency','discard') {
11546: $offset ++;
11547: if ($action ne 'display') {
11548: $offset ++;
11549: }
11550: $output .= '<td><span class="LC_nobreak">'.
11551: '<label><input type="radio" name="archive_'.$count.
11552: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
11553: my $text = $choices{$action};
11554: if ($is_dir) {
11555: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
11556: if ($action eq 'display') {
11557: $text = &mt('Add as folder');
11558: }
11559: } else {
11560: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
11561:
11562: }
11563: $output .= ' /> '.$choices{$action}.'</label></span>';
11564: if ($action eq 'dependency') {
11565: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
11566: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '.
11567: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
11568: '<option value=""></option>'."\n".
11569: '</select>'."\n".
11570: '</div>';
11571: } elsif ($action eq 'display') {
11572: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11573: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11574: '</div>';
11575: }
11576: $output .= '</td>';
11577: }
11578: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11579: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2);
11580: for (my $i=0; $i<$depth; $i++) {
11581: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11582: }
11583: if ($is_dir) {
11584: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n".
11585: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11586: } else {
11587: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11588: }
11589: $output .= ' '.$name.'</td>'."\n".
11590: &end_data_table_row();
11591: return $output;
11592: }
11593:
11594: sub archive_options_form {
11595: my ($form,$display,$count,$hiddenelem) = @_;
11596: my %lt = &Apache::lonlocal::texthash(
11597: perm => 'Permanently remove archive file?',
11598: hows => 'How should each extracted item be incorporated in the course?',
11599: cont => 'Content actions for all',
11600: addf => 'Add as folder/file',
11601: incd => 'Include as dependency for a displayed file',
11602: disc => 'Discard',
11603: no => 'No',
11604: yes => 'Yes',
11605: save => 'Save',
11606: );
11607: my $output = <<"END";
11608: <form name="$form" method="post" action="">
11609: <p><span class="LC_nobreak">$lt{'perm'}
11610: <label>
11611: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11612: </label>
11613:
11614: <label>
11615: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11616: </span>
11617: </p>
11618: <input type="hidden" name="phase" value="decompress_cleanup" />
11619: <br />$lt{'hows'}
11620: <div class="LC_columnSection">
11621: <fieldset>
11622: <legend>$lt{'cont'}</legend>
11623: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" />
11624: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11625: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11626: </fieldset>
11627: </div>
11628: END
11629: return $output.
11630: &start_data_table()."\n".
11631: $display."\n".
11632: &end_data_table()."\n".
11633: '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11634: $hiddenelem.
11635: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11636: '</form>';
11637: }
11638:
11639: sub archive_javascript {
11640: my ($startcount,$numitems,$titles,$children) = @_;
11641: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11642: my $maintitle = $env{'form.comment'};
11643: my $scripttag = <<START;
11644: <script type="text/javascript">
11645: // <![CDATA[
11646:
11647: function checkAll(form,prefix) {
11648: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$");
11649: for (var i=0; i < form.elements.length; i++) {
11650: var id = form.elements[i].id;
11651: if ((id != '') && (id != undefined)) {
11652: if (idstr.test(id)) {
11653: if (form.elements[i].type == 'radio') {
11654: form.elements[i].checked = true;
11655: var nostart = i-$startcount;
11656: var offset = nostart%7;
11657: var count = (nostart-offset)/7;
11658: dependencyCheck(form,count,offset);
11659: }
11660: }
11661: }
11662: }
11663: }
11664:
11665: function propagateCheck(form,count) {
11666: if (count > 0) {
11667: var startelement = $startcount + ((count-1) * 7);
11668: for (var j=1; j<6; j++) {
11669: if ((j != 2) && (j != 4)) {
11670: var item = startelement + j;
11671: if (form.elements[item].type == 'radio') {
11672: if (form.elements[item].checked) {
11673: containerCheck(form,count,j);
11674: break;
11675: }
11676: }
11677: }
11678: }
11679: }
11680: }
11681:
11682: numitems = $numitems
11683: var titles = new Array(numitems);
11684: var parents = new Array(numitems);
11685: for (var i=0; i<numitems; i++) {
11686: parents[i] = new Array;
11687: }
11688: var maintitle = '$maintitle';
11689:
11690: START
11691:
11692: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
11693: my @contents = split(/:/,$children->{$container});
11694: for (my $i=0; $i<@contents; $i ++) {
11695: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
11696: }
11697: }
11698:
11699: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
11700: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
11701: }
11702:
11703: $scripttag .= <<END;
11704:
11705: function containerCheck(form,count,offset) {
11706: if (count > 0) {
11707: dependencyCheck(form,count,offset);
11708: var item = (offset+$startcount)+7*(count-1);
11709: form.elements[item].checked = true;
11710: if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
11711: if (parents[count].length > 0) {
11712: for (var j=0; j<parents[count].length; j++) {
11713: containerCheck(form,parents[count][j],offset);
11714: }
11715: }
11716: }
11717: }
11718: }
11719:
11720: function dependencyCheck(form,count,offset) {
11721: if (count > 0) {
11722: var chosen = (offset+$startcount)+7*(count-1);
11723: var depitem = $startcount + ((count-1) * 7) + 4;
11724: var currtype = form.elements[depitem].type;
11725: if (form.elements[chosen].value == 'dependency') {
11726: document.getElementById('arc_depon_'+count).style.display='block';
11727: form.elements[depitem].options.length = 0;
11728: form.elements[depitem].options[0] = new Option('Select','',true,true);
11729: for (var i=1; i<=numitems; i++) {
11730: if (i == count) {
11731: continue;
11732: }
11733: var startelement = $startcount + (i-1) * 7;
11734: for (var j=1; j<6; j++) {
11735: if ((j != 2) && (j!= 4)) {
11736: var item = startelement + j;
11737: if (form.elements[item].type == 'radio') {
11738: if (form.elements[item].checked) {
11739: if (form.elements[item].value == 'display') {
11740: var n = form.elements[depitem].options.length;
11741: form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
11742: }
11743: }
11744: }
11745: }
11746: }
11747: }
11748: } else {
11749: document.getElementById('arc_depon_'+count).style.display='none';
11750: form.elements[depitem].options.length = 0;
11751: form.elements[depitem].options[0] = new Option('Select','',true,true);
11752: }
11753: titleCheck(form,count,offset);
11754: }
11755: }
11756:
11757: function propagateSelect(form,count,offset) {
11758: if (count > 0) {
11759: var item = (1+offset+$startcount)+7*(count-1);
11760: var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
11761: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11762: if (parents[count].length > 0) {
11763: for (var j=0; j<parents[count].length; j++) {
11764: containerSelect(form,parents[count][j],offset,picked);
11765: }
11766: }
11767: }
11768: }
11769: }
11770:
11771: function containerSelect(form,count,offset,picked) {
11772: if (count > 0) {
11773: var item = (offset+$startcount)+7*(count-1);
11774: if (form.elements[item].type == 'radio') {
11775: if (form.elements[item].value == 'dependency') {
11776: if (form.elements[item+1].type == 'select-one') {
11777: for (var i=0; i<form.elements[item+1].options.length; i++) {
11778: if (form.elements[item+1].options[i].value == picked) {
11779: form.elements[item+1].selectedIndex = i;
11780: break;
11781: }
11782: }
11783: }
11784: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11785: if (parents[count].length > 0) {
11786: for (var j=0; j<parents[count].length; j++) {
11787: containerSelect(form,parents[count][j],offset,picked);
11788: }
11789: }
11790: }
11791: }
11792: }
11793: }
11794: }
11795:
11796: function titleCheck(form,count,offset) {
11797: if (count > 0) {
11798: var chosen = (offset+$startcount)+7*(count-1);
11799: var depitem = $startcount + ((count-1) * 7) + 2;
11800: var currtype = form.elements[depitem].type;
11801: if (form.elements[chosen].value == 'display') {
11802: document.getElementById('arc_title_'+count).style.display='block';
11803: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
11804: document.getElementById('archive_title_'+count).value=maintitle;
11805: }
11806: } else {
11807: document.getElementById('arc_title_'+count).style.display='none';
11808: if (currtype == 'text') {
11809: document.getElementById('archive_title_'+count).value='';
11810: }
11811: }
11812: }
11813: return;
11814: }
11815:
11816: // ]]>
11817: </script>
11818: END
11819: return $scripttag;
11820: }
11821:
11822: sub process_extracted_files {
11823: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
11824: my $numitems = $env{'form.archive_count'};
11825: return unless ($numitems);
11826: my @ids=&Apache::lonnet::current_machine_ids();
11827: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
11828: %folders,%containers,%mapinner,%prompttofetch);
11829: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11830: if (grep(/^\Q$docuhome\E$/,@ids)) {
11831: $prefix = &LONCAPA::propath($docudom,$docuname);
11832: $pathtocheck = "$dir_root/$destination";
11833: $dir = $dir_root;
11834: $ishome = 1;
11835: } else {
11836: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
11837: $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
11838: $dir = "$dir_root/$docudom/$docuname";
11839: }
11840: my $currdir = "$dir_root/$destination";
11841: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
11842: if ($env{'form.folderpath'}) {
11843: my @items = split('&',$env{'form.folderpath'});
11844: $folders{'0'} = $items[-2];
11845: if ($env{'form.folderpath'} =~ /\:1$/) {
11846: $containers{'0'}='page';
11847: } else {
11848: $containers{'0'}='sequence';
11849: }
11850: }
11851: my @archdirs = &get_env_multiple('form.archive_directory');
11852: if ($numitems) {
11853: for (my $i=1; $i<=$numitems; $i++) {
11854: my $path = $env{'form.archive_content_'.$i};
11855: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
11856: my $item = $1;
11857: $toplevelitems{$item} = $i;
11858: if (grep(/^\Q$i\E$/,@archdirs)) {
11859: $is_dir{$item} = 1;
11860: }
11861: }
11862: }
11863: }
11864: my ($output,%children,%parent,%titles,%dirorder,$result);
11865: if (keys(%toplevelitems) > 0) {
11866: my @contents = sort(keys(%toplevelitems));
11867: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
11868: \%parent,\@contents,\%dirorder,\%titles);
11869: }
11870: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
11871: if ($numitems) {
11872: for (my $i=1; $i<=$numitems; $i++) {
11873: next if ($env{'form.archive_'.$i} eq 'dependency');
11874: my $path = $env{'form.archive_content_'.$i};
11875: if ($path =~ /^\Q$pathtocheck\E/) {
11876: if ($env{'form.archive_'.$i} eq 'discard') {
11877: if ($prefix ne '' && $path ne '') {
11878: if (-e $prefix.$path) {
11879: if ((@archdirs > 0) &&
11880: (grep(/^\Q$i\E$/,@archdirs))) {
11881: $todeletedir{$prefix.$path} = 1;
11882: } else {
11883: $todelete{$prefix.$path} = 1;
11884: }
11885: }
11886: }
11887: } elsif ($env{'form.archive_'.$i} eq 'display') {
11888: my ($docstitle,$title,$url,$outer);
11889: ($title) = ($path =~ m{/([^/]+)$});
11890: $docstitle = $env{'form.archive_title_'.$i};
11891: if ($docstitle eq '') {
11892: $docstitle = $title;
11893: }
11894: $outer = 0;
11895: if (ref($dirorder{$i}) eq 'ARRAY') {
11896: if (@{$dirorder{$i}} > 0) {
11897: foreach my $item (reverse(@{$dirorder{$i}})) {
11898: if ($env{'form.archive_'.$item} eq 'display') {
11899: $outer = $item;
11900: last;
11901: }
11902: }
11903: }
11904: }
11905: my ($errtext,$fatal) =
11906: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
11907: '/'.$folders{$outer}.'.'.
11908: $containers{$outer});
11909: next if ($fatal);
11910: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
11911: if ($context eq 'coursedocs') {
11912: $mapinner{$i} = time;
11913: $folders{$i} = 'default_'.$mapinner{$i};
11914: $containers{$i} = 'sequence';
11915: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11916: $folders{$i}.'.'.$containers{$i};
11917: my $newidx = &LONCAPA::map::getresidx();
11918: $LONCAPA::map::resources[$newidx]=
11919: $docstitle.':'.$url.':false:normal:res';
11920: push(@LONCAPA::map::order,$newidx);
11921: my ($outtext,$errtext) =
11922: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11923: $docuname.'/'.$folders{$outer}.
11924: '.'.$containers{$outer},1,1);
11925: $newseqid{$i} = $newidx;
11926: unless ($errtext) {
11927: $result .= '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
11928: }
11929: }
11930: } else {
11931: if ($context eq 'coursedocs') {
11932: my $newidx=&LONCAPA::map::getresidx();
11933: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11934: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
11935: $title;
11936: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
11937: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
11938: }
11939: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11940: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
11941: }
11942: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11943: system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
11944: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
11945: unless ($ishome) {
11946: my $fetch = "$newdest{$i}/$title";
11947: $fetch =~ s/^\Q$prefix$dir\E//;
11948: $prompttofetch{$fetch} = 1;
11949: }
11950: }
11951: $LONCAPA::map::resources[$newidx]=
11952: $docstitle.':'.$url.':false:normal:res';
11953: push(@LONCAPA::map::order, $newidx);
11954: my ($outtext,$errtext)=
11955: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11956: $docuname.'/'.$folders{$outer}.
11957: '.'.$containers{$outer},1,1);
11958: unless ($errtext) {
11959: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
11960: $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
11961: }
11962: }
11963: }
11964: }
11965: }
11966: } else {
11967: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
11968: }
11969: }
11970: for (my $i=1; $i<=$numitems; $i++) {
11971: next unless ($env{'form.archive_'.$i} eq 'dependency');
11972: my $path = $env{'form.archive_content_'.$i};
11973: if ($path =~ /^\Q$pathtocheck\E/) {
11974: my ($title) = ($path =~ m{/([^/]+)$});
11975: $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
11976: if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
11977: if (ref($dirorder{$i}) eq 'ARRAY') {
11978: my ($itemidx,$fullpath,$relpath);
11979: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
11980: my $container = $dirorder{$referrer{$i}}->[-1];
11981: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
11982: if ($dirorder{$i}->[$j] eq $container) {
11983: $itemidx = $j;
11984: }
11985: }
11986: }
11987: if ($itemidx eq '') {
11988: $itemidx = 0;
11989: }
11990: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
11991: if ($mapinner{$referrer{$i}}) {
11992: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
11993: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11994: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11995: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11996: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11997: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11998: if (!-e $fullpath) {
11999: mkdir($fullpath,0755);
12000: }
12001: }
12002: } else {
12003: last;
12004: }
12005: }
12006: }
12007: } elsif ($newdest{$referrer{$i}}) {
12008: $fullpath = $newdest{$referrer{$i}};
12009: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12010: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12011: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12012: last;
12013: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12014: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12015: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12016: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12017: if (!-e $fullpath) {
12018: mkdir($fullpath,0755);
12019: }
12020: }
12021: } else {
12022: last;
12023: }
12024: }
12025: }
12026: if ($fullpath ne '') {
12027: if (-e "$prefix$path") {
12028: system("mv $prefix$path $fullpath/$title");
12029: }
12030: if (-e "$fullpath/$title") {
12031: my $showpath;
12032: if ($relpath ne '') {
12033: $showpath = "$relpath/$title";
12034: } else {
12035: $showpath = "/$title";
12036: }
12037: $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
12038: }
12039: unless ($ishome) {
12040: my $fetch = "$fullpath/$title";
12041: $fetch =~ s/^\Q$prefix$dir\E//;
12042: $prompttofetch{$fetch} = 1;
12043: }
12044: }
12045: }
12046: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12047: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12048: $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
12049: }
12050: } else {
12051: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
12052: }
12053: }
12054: if (keys(%todelete)) {
12055: foreach my $key (keys(%todelete)) {
12056: unlink($key);
12057: }
12058: }
12059: if (keys(%todeletedir)) {
12060: foreach my $key (keys(%todeletedir)) {
12061: rmdir($key);
12062: }
12063: }
12064: foreach my $dir (sort(keys(%is_dir))) {
12065: if (($pathtocheck ne '') && ($dir ne '')) {
12066: &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12067: }
12068: }
12069: if ($result ne '') {
12070: $output .= '<ul>'."\n".
12071: $result."\n".
12072: '</ul>';
12073: }
12074: unless ($ishome) {
12075: my $replicationfail;
12076: foreach my $item (keys(%prompttofetch)) {
12077: my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12078: unless ($fetchresult eq 'ok') {
12079: $replicationfail .= '<li>'.$item.'</li>'."\n";
12080: }
12081: }
12082: if ($replicationfail) {
12083: $output .= '<p class="LC_error">'.
12084: &mt('Course home server failed to retrieve:').'<ul>'.
12085: $replicationfail.
12086: '</ul></p>';
12087: }
12088: }
12089: } else {
12090: $warning = &mt('No items found in archive.');
12091: }
12092: if ($error) {
12093: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12094: $error.'</p>'."\n";
12095: }
12096: if ($warning) {
12097: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12098: }
12099: return $output;
12100: }
12101:
12102: sub cleanup_empty_dirs {
12103: my ($path) = @_;
12104: if (($path ne '') && (-d $path)) {
12105: if (opendir(my $dirh,$path)) {
12106: my @dircontents = grep(!/^\./,readdir($dirh));
12107: my $numitems = 0;
12108: foreach my $item (@dircontents) {
12109: if (-d "$path/$item") {
12110: &cleanup_empty_dirs("$path/$item");
12111: if (-e "$path/$item") {
12112: $numitems ++;
12113: }
12114: } else {
12115: $numitems ++;
12116: }
12117: }
12118: if ($numitems == 0) {
12119: rmdir($path);
12120: }
12121: closedir($dirh);
12122: }
12123: }
12124: return;
12125: }
12126:
12127: =pod
12128:
12129: =item * &get_folder_hierarchy()
12130:
12131: Provides hierarchy of names of folders/sub-folders containing the current
12132: item,
12133:
12134: Inputs: 3
12135: - $navmap - navmaps object
12136:
12137: - $map - url for map (either the trigger itself, or map containing
12138: the resource, which is the trigger).
12139:
12140: - $showitem - 1 => show title for map itself; 0 => do not show.
12141:
12142: Outputs: 1 @pathitems - array of folder/subfolder names.
12143:
12144: =cut
12145:
12146: sub get_folder_hierarchy {
12147: my ($navmap,$map,$showitem) = @_;
12148: my @pathitems;
12149: if (ref($navmap)) {
12150: my $mapres = $navmap->getResourceByUrl($map);
12151: if (ref($mapres)) {
12152: my $pcslist = $mapres->map_hierarchy();
12153: if ($pcslist ne '') {
12154: my @pcs = split(/,/,$pcslist);
12155: foreach my $pc (@pcs) {
12156: if ($pc == 1) {
12157: push(@pathitems,&mt('Main Content'));
12158: } else {
12159: my $res = $navmap->getByMapPc($pc);
12160: if (ref($res)) {
12161: my $title = $res->compTitle();
12162: $title =~ s/\W+/_/g;
12163: if ($title ne '') {
12164: push(@pathitems,$title);
12165: }
12166: }
12167: }
12168: }
12169: }
12170: if ($showitem) {
12171: if ($mapres->{ID} eq '0.0') {
12172: push(@pathitems,&mt('Main Content'));
12173: } else {
12174: my $maptitle = $mapres->compTitle();
12175: $maptitle =~ s/\W+/_/g;
12176: if ($maptitle ne '') {
12177: push(@pathitems,$maptitle);
12178: }
12179: }
12180: }
12181: }
12182: }
12183: return @pathitems;
12184: }
12185:
12186: =pod
12187:
12188: =item * &get_turnedin_filepath()
12189:
12190: Determines path in a user's portfolio file for storage of files uploaded
12191: to a specific essayresponse or dropbox item.
12192:
12193: Inputs: 3 required + 1 optional.
12194: $symb is symb for resource, $uname and $udom are for current user (required).
12195: $caller is optional (can be "submission", if routine is called when storing
12196: an upoaded file when "Submit Answer" button was pressed).
12197:
12198: Returns array containing $path and $multiresp.
12199: $path is path in portfolio. $multiresp is 1 if this resource contains more
12200: than one file upload item. Callers of routine should append partid as a
12201: subdirectory to $path in cases where $multiresp is 1.
12202:
12203: Called by: homework/essayresponse.pm and homework/structuretags.pm
12204:
12205: =cut
12206:
12207: sub get_turnedin_filepath {
12208: my ($symb,$uname,$udom,$caller) = @_;
12209: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
12210: my $turnindir;
12211: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
12212: $turnindir = $userhash{'turnindir'};
12213: my ($path,$multiresp);
12214: if ($turnindir eq '') {
12215: if ($caller eq 'submission') {
12216: $turnindir = &mt('turned in');
12217: $turnindir =~ s/\W+/_/g;
12218: my %newhash = (
12219: 'turnindir' => $turnindir,
12220: );
12221: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
12222: }
12223: }
12224: if ($turnindir ne '') {
12225: $path = '/'.$turnindir.'/';
12226: my ($multipart,$turnin,@pathitems);
12227: my $navmap = Apache::lonnavmaps::navmap->new();
12228: if (defined($navmap)) {
12229: my $mapres = $navmap->getResourceByUrl($map);
12230: if (ref($mapres)) {
12231: my $pcslist = $mapres->map_hierarchy();
12232: if ($pcslist ne '') {
12233: foreach my $pc (split(/,/,$pcslist)) {
12234: my $res = $navmap->getByMapPc($pc);
12235: if (ref($res)) {
12236: my $title = $res->compTitle();
12237: $title =~ s/\W+/_/g;
12238: if ($title ne '') {
12239: if (($pc > 1) && (length($title) > 12)) {
12240: $title = substr($title,0,12);
12241: }
12242: push(@pathitems,$title);
12243: }
12244: }
12245: }
12246: }
12247: my $maptitle = $mapres->compTitle();
12248: $maptitle =~ s/\W+/_/g;
12249: if ($maptitle ne '') {
12250: if (length($maptitle) > 12) {
12251: $maptitle = substr($maptitle,0,12);
12252: }
12253: push(@pathitems,$maptitle);
12254: }
12255: unless ($env{'request.state'} eq 'construct') {
12256: my $res = $navmap->getBySymb($symb);
12257: if (ref($res)) {
12258: my $partlist = $res->parts();
12259: my $totaluploads = 0;
12260: if (ref($partlist) eq 'ARRAY') {
12261: foreach my $part (@{$partlist}) {
12262: my @types = $res->responseType($part);
12263: my @ids = $res->responseIds($part);
12264: for (my $i=0; $i < scalar(@ids); $i++) {
12265: if ($types[$i] eq 'essay') {
12266: my $partid = $part.'_'.$ids[$i];
12267: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
12268: $totaluploads ++;
12269: }
12270: }
12271: }
12272: }
12273: if ($totaluploads > 1) {
12274: $multiresp = 1;
12275: }
12276: }
12277: }
12278: }
12279: } else {
12280: return;
12281: }
12282: } else {
12283: return;
12284: }
12285: my $restitle=&Apache::lonnet::gettitle($symb);
12286: $restitle =~ s/\W+/_/g;
12287: if ($restitle eq '') {
12288: $restitle = ($resurl =~ m{/[^/]+$});
12289: if ($restitle eq '') {
12290: $restitle = time;
12291: }
12292: }
12293: if (length($restitle) > 12) {
12294: $restitle = substr($restitle,0,12);
12295: }
12296: push(@pathitems,$restitle);
12297: $path .= join('/',@pathitems);
12298: }
12299: return ($path,$multiresp);
12300: }
12301:
12302: =pod
12303:
12304: =back
12305:
12306: =head1 CSV Upload/Handling functions
12307:
12308: =over 4
12309:
12310: =item * &upfile_store($r)
12311:
12312: Store uploaded file, $r should be the HTTP Request object,
12313: needs $env{'form.upfile'}
12314: returns $datatoken to be put into hidden field
12315:
12316: =cut
12317:
12318: sub upfile_store {
12319: my $r=shift;
12320: $env{'form.upfile'}=~s/\r/\n/gs;
12321: $env{'form.upfile'}=~s/\f/\n/gs;
12322: $env{'form.upfile'}=~s/\n+/\n/gs;
12323: $env{'form.upfile'}=~s/\n+$//gs;
12324:
12325: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
12326: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
12327: {
12328: my $datafile = $r->dir_config('lonDaemons').
12329: '/tmp/'.$datatoken.'.tmp';
12330: if ( open(my $fh,">$datafile") ) {
12331: print $fh $env{'form.upfile'};
12332: close($fh);
12333: }
12334: }
12335: return $datatoken;
12336: }
12337:
12338: =pod
12339:
12340: =item * &load_tmp_file($r)
12341:
12342: Load uploaded file from tmp, $r should be the HTTP Request object,
12343: needs $env{'form.datatoken'},
12344: sets $env{'form.upfile'} to the contents of the file
12345:
12346: =cut
12347:
12348: sub load_tmp_file {
12349: my $r=shift;
12350: my @studentdata=();
12351: {
12352: my $studentfile = $r->dir_config('lonDaemons').
12353: '/tmp/'.$env{'form.datatoken'}.'.tmp';
12354: if ( open(my $fh,"<$studentfile") ) {
12355: @studentdata=<$fh>;
12356: close($fh);
12357: }
12358: }
12359: $env{'form.upfile'}=join('',@studentdata);
12360: }
12361:
12362: =pod
12363:
12364: =item * &upfile_record_sep()
12365:
12366: Separate uploaded file into records
12367: returns array of records,
12368: needs $env{'form.upfile'} and $env{'form.upfiletype'}
12369:
12370: =cut
12371:
12372: sub upfile_record_sep {
12373: if ($env{'form.upfiletype'} eq 'xml') {
12374: } else {
12375: my @records;
12376: foreach my $line (split(/\n/,$env{'form.upfile'})) {
12377: if ($line=~/^\s*$/) { next; }
12378: push(@records,$line);
12379: }
12380: return @records;
12381: }
12382: }
12383:
12384: =pod
12385:
12386: =item * &record_sep($record)
12387:
12388: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
12389:
12390: =cut
12391:
12392: sub takeleft {
12393: my $index=shift;
12394: return substr('0000'.$index,-4,4);
12395: }
12396:
12397: sub record_sep {
12398: my $record=shift;
12399: my %components=();
12400: if ($env{'form.upfiletype'} eq 'xml') {
12401: } elsif ($env{'form.upfiletype'} eq 'space') {
12402: my $i=0;
12403: foreach my $field (split(/\s+/,$record)) {
12404: $field=~s/^(\"|\')//;
12405: $field=~s/(\"|\')$//;
12406: $components{&takeleft($i)}=$field;
12407: $i++;
12408: }
12409: } elsif ($env{'form.upfiletype'} eq 'tab') {
12410: my $i=0;
12411: foreach my $field (split(/\t/,$record)) {
12412: $field=~s/^(\"|\')//;
12413: $field=~s/(\"|\')$//;
12414: $components{&takeleft($i)}=$field;
12415: $i++;
12416: }
12417: } else {
12418: my $separator=',';
12419: if ($env{'form.upfiletype'} eq 'semisv') {
12420: $separator=';';
12421: }
12422: my $i=0;
12423: # the character we are looking for to indicate the end of a quote or a record
12424: my $looking_for=$separator;
12425: # do not add the characters to the fields
12426: my $ignore=0;
12427: # we just encountered a separator (or the beginning of the record)
12428: my $just_found_separator=1;
12429: # store the field we are working on here
12430: my $field='';
12431: # work our way through all characters in record
12432: foreach my $character ($record=~/(.)/g) {
12433: if ($character eq $looking_for) {
12434: if ($character ne $separator) {
12435: # Found the end of a quote, again looking for separator
12436: $looking_for=$separator;
12437: $ignore=1;
12438: } else {
12439: # Found a separator, store away what we got
12440: $components{&takeleft($i)}=$field;
12441: $i++;
12442: $just_found_separator=1;
12443: $ignore=0;
12444: $field='';
12445: }
12446: next;
12447: }
12448: # single or double quotation marks after a separator indicate beginning of a quote
12449: # we are now looking for the end of the quote and need to ignore separators
12450: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
12451: $looking_for=$character;
12452: next;
12453: }
12454: # ignore would be true after we reached the end of a quote
12455: if ($ignore) { next; }
12456: if (($just_found_separator) && ($character=~/\s/)) { next; }
12457: $field.=$character;
12458: $just_found_separator=0;
12459: }
12460: # catch the very last entry, since we never encountered the separator
12461: $components{&takeleft($i)}=$field;
12462: }
12463: return %components;
12464: }
12465:
12466: ######################################################
12467: ######################################################
12468:
12469: =pod
12470:
12471: =item * &upfile_select_html()
12472:
12473: Return HTML code to select a file from the users machine and specify
12474: the file type.
12475:
12476: =cut
12477:
12478: ######################################################
12479: ######################################################
12480: sub upfile_select_html {
12481: my %Types = (
12482: csv => &mt('CSV (comma separated values, spreadsheet)'),
12483: semisv => &mt('Semicolon separated values'),
12484: space => &mt('Space separated'),
12485: tab => &mt('Tabulator separated'),
12486: # xml => &mt('HTML/XML'),
12487: );
12488: my $Str = '<input type="file" name="upfile" size="50" />'.
12489: '<br />'.&mt('Type').': <select name="upfiletype">';
12490: foreach my $type (sort(keys(%Types))) {
12491: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
12492: }
12493: $Str .= "</select>\n";
12494: return $Str;
12495: }
12496:
12497: sub get_samples {
12498: my ($records,$toget) = @_;
12499: my @samples=({});
12500: my $got=0;
12501: foreach my $rec (@$records) {
12502: my %temp = &record_sep($rec);
12503: if (! grep(/\S/, values(%temp))) { next; }
12504: if (%temp) {
12505: $samples[$got]=\%temp;
12506: $got++;
12507: if ($got == $toget) { last; }
12508: }
12509: }
12510: return \@samples;
12511: }
12512:
12513: ######################################################
12514: ######################################################
12515:
12516: =pod
12517:
12518: =item * &csv_print_samples($r,$records)
12519:
12520: Prints a table of sample values from each column uploaded $r is an
12521: Apache Request ref, $records is an arrayref from
12522: &Apache::loncommon::upfile_record_sep
12523:
12524: =cut
12525:
12526: ######################################################
12527: ######################################################
12528: sub csv_print_samples {
12529: my ($r,$records) = @_;
12530: my $samples = &get_samples($records,5);
12531:
12532: $r->print(&mt('Samples').'<br />'.&start_data_table().
12533: &start_data_table_header_row());
12534: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12535: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
12536: $r->print(&end_data_table_header_row());
12537: foreach my $hash (@$samples) {
12538: $r->print(&start_data_table_row());
12539: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12540: $r->print('<td>');
12541: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
12542: $r->print('</td>');
12543: }
12544: $r->print(&end_data_table_row());
12545: }
12546: $r->print(&end_data_table().'<br />'."\n");
12547: }
12548:
12549: ######################################################
12550: ######################################################
12551:
12552: =pod
12553:
12554: =item * &csv_print_select_table($r,$records,$d)
12555:
12556: Prints a table to create associations between values and table columns.
12557:
12558: $r is an Apache Request ref,
12559: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12560: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
12561:
12562: =cut
12563:
12564: ######################################################
12565: ######################################################
12566: sub csv_print_select_table {
12567: my ($r,$records,$d) = @_;
12568: my $i=0;
12569: my $samples = &get_samples($records,1);
12570: $r->print(&mt('Associate columns with student attributes.')."\n".
12571: &start_data_table().&start_data_table_header_row().
12572: '<th>'.&mt('Attribute').'</th>'.
12573: '<th>'.&mt('Column').'</th>'.
12574: &end_data_table_header_row()."\n");
12575: foreach my $array_ref (@$d) {
12576: my ($value,$display,$defaultcol)=@{ $array_ref };
12577: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
12578:
12579: $r->print('<td><select name="f'.$i.'"'.
12580: ' onchange="javascript:flip(this.form,'.$i.');">');
12581: $r->print('<option value="none"></option>');
12582: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12583: $r->print('<option value="'.$sample.'"'.
12584: ($sample eq $defaultcol ? ' selected="selected" ' : '').
12585: '>'.&mt('Column [_1]',($sample+1)).'</option>');
12586: }
12587: $r->print('</select></td>'.&end_data_table_row()."\n");
12588: $i++;
12589: }
12590: $r->print(&end_data_table());
12591: $i--;
12592: return $i;
12593: }
12594:
12595: ######################################################
12596: ######################################################
12597:
12598: =pod
12599:
12600: =item * &csv_samples_select_table($r,$records,$d)
12601:
12602: Prints a table of sample values from the upload and can make associate samples to internal names.
12603:
12604: $r is an Apache Request ref,
12605: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12606: $d is an array of 2 element arrays (internal name, displayed name)
12607:
12608: =cut
12609:
12610: ######################################################
12611: ######################################################
12612: sub csv_samples_select_table {
12613: my ($r,$records,$d) = @_;
12614: my $i=0;
12615: #
12616: my $max_samples = 5;
12617: my $samples = &get_samples($records,$max_samples);
12618: $r->print(&start_data_table().
12619: &start_data_table_header_row().'<th>'.
12620: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12621: &end_data_table_header_row());
12622:
12623: foreach my $key (sort(keys(%{ $samples->[0] }))) {
12624: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12625: ' onchange="javascript:flip(this.form,'.$i.');">');
12626: foreach my $option (@$d) {
12627: my ($value,$display,$defaultcol)=@{ $option };
12628: $r->print('<option value="'.$value.'"'.
12629: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12630: $display.'</option>');
12631: }
12632: $r->print('</select></td><td>');
12633: foreach my $line (0..($max_samples-1)) {
12634: if (defined($samples->[$line]{$key})) {
12635: $r->print($samples->[$line]{$key}."<br />\n");
12636: }
12637: }
12638: $r->print('</td>'.&end_data_table_row());
12639: $i++;
12640: }
12641: $r->print(&end_data_table());
12642: $i--;
12643: return($i);
12644: }
12645:
12646: ######################################################
12647: ######################################################
12648:
12649: =pod
12650:
12651: =item * &clean_excel_name($name)
12652:
12653: Returns a replacement for $name which does not contain any illegal characters.
12654:
12655: =cut
12656:
12657: ######################################################
12658: ######################################################
12659: sub clean_excel_name {
12660: my ($name) = @_;
12661: $name =~ s/[:\*\?\/\\]//g;
12662: if (length($name) > 31) {
12663: $name = substr($name,0,31);
12664: }
12665: return $name;
12666: }
12667:
12668: =pod
12669:
12670: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
12671:
12672: Returns either 1 or undef
12673:
12674: 1 if the part is to be hidden, undef if it is to be shown
12675:
12676: Arguments are:
12677:
12678: $id the id of the part to be checked
12679: $symb, optional the symb of the resource to check
12680: $udom, optional the domain of the user to check for
12681: $uname, optional the username of the user to check for
12682:
12683: =cut
12684:
12685: sub check_if_partid_hidden {
12686: my ($id,$symb,$udom,$uname) = @_;
12687: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
12688: $symb,$udom,$uname);
12689: my $truth=1;
12690: #if the string starts with !, then the list is the list to show not hide
12691: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
12692: my @hiddenlist=split(/,/,$hiddenparts);
12693: foreach my $checkid (@hiddenlist) {
12694: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
12695: }
12696: return !$truth;
12697: }
12698:
12699:
12700: ############################################################
12701: ############################################################
12702:
12703: =pod
12704:
12705: =back
12706:
12707: =head1 cgi-bin script and graphing routines
12708:
12709: =over 4
12710:
12711: =item * &get_cgi_id()
12712:
12713: Inputs: none
12714:
12715: Returns an id which can be used to pass environment variables
12716: to various cgi-bin scripts. These environment variables will
12717: be removed from the users environment after a given time by
12718: the routine &Apache::lonnet::transfer_profile_to_env.
12719:
12720: =cut
12721:
12722: ############################################################
12723: ############################################################
12724: my $uniq=0;
12725: sub get_cgi_id {
12726: $uniq=($uniq+1)%100000;
12727: return (time.'_'.$$.'_'.$uniq);
12728: }
12729:
12730: ############################################################
12731: ############################################################
12732:
12733: =pod
12734:
12735: =item * &DrawBarGraph()
12736:
12737: Facilitates the plotting of data in a (stacked) bar graph.
12738: Puts plot definition data into the users environment in order for
12739: graph.png to plot it. Returns an <img> tag for the plot.
12740: The bars on the plot are labeled '1','2',...,'n'.
12741:
12742: Inputs:
12743:
12744: =over 4
12745:
12746: =item $Title: string, the title of the plot
12747:
12748: =item $xlabel: string, text describing the X-axis of the plot
12749:
12750: =item $ylabel: string, text describing the Y-axis of the plot
12751:
12752: =item $Max: scalar, the maximum Y value to use in the plot
12753: If $Max is < any data point, the graph will not be rendered.
12754:
12755: =item $colors: array ref holding the colors to be used for the data sets when
12756: they are plotted. If undefined, default values will be used.
12757:
12758: =item $labels: array ref holding the labels to use on the x-axis for the bars.
12759:
12760: =item @Values: An array of array references. Each array reference holds data
12761: to be plotted in a stacked bar chart.
12762:
12763: =item If the final element of @Values is a hash reference the key/value
12764: pairs will be added to the graph definition.
12765:
12766: =back
12767:
12768: Returns:
12769:
12770: An <img> tag which references graph.png and the appropriate identifying
12771: information for the plot.
12772:
12773: =cut
12774:
12775: ############################################################
12776: ############################################################
12777: sub DrawBarGraph {
12778: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
12779: #
12780: if (! defined($colors)) {
12781: $colors = ['#33ff00',
12782: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
12783: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
12784: ];
12785: }
12786: my $extra_settings = {};
12787: if (ref($Values[-1]) eq 'HASH') {
12788: $extra_settings = pop(@Values);
12789: }
12790: #
12791: my $identifier = &get_cgi_id();
12792: my $id = 'cgi.'.$identifier;
12793: if (! @Values || ref($Values[0]) ne 'ARRAY') {
12794: return '';
12795: }
12796: #
12797: my @Labels;
12798: if (defined($labels)) {
12799: @Labels = @$labels;
12800: } else {
12801: for (my $i=0;$i<@{$Values[0]};$i++) {
12802: push (@Labels,$i+1);
12803: }
12804: }
12805: #
12806: my $NumBars = scalar(@{$Values[0]});
12807: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
12808: my %ValuesHash;
12809: my $NumSets=1;
12810: foreach my $array (@Values) {
12811: next if (! ref($array));
12812: $ValuesHash{$id.'.data.'.$NumSets++} =
12813: join(',',@$array);
12814: }
12815: #
12816: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
12817: if ($NumBars < 3) {
12818: $width = 120+$NumBars*32;
12819: $xskip = 1;
12820: $bar_width = 30;
12821: } elsif ($NumBars < 5) {
12822: $width = 120+$NumBars*20;
12823: $xskip = 1;
12824: $bar_width = 20;
12825: } elsif ($NumBars < 10) {
12826: $width = 120+$NumBars*15;
12827: $xskip = 1;
12828: $bar_width = 15;
12829: } elsif ($NumBars <= 25) {
12830: $width = 120+$NumBars*11;
12831: $xskip = 5;
12832: $bar_width = 8;
12833: } elsif ($NumBars <= 50) {
12834: $width = 120+$NumBars*8;
12835: $xskip = 5;
12836: $bar_width = 4;
12837: } else {
12838: $width = 120+$NumBars*8;
12839: $xskip = 5;
12840: $bar_width = 4;
12841: }
12842: #
12843: $Max = 1 if ($Max < 1);
12844: if ( int($Max) < $Max ) {
12845: $Max++;
12846: $Max = int($Max);
12847: }
12848: $Title = '' if (! defined($Title));
12849: $xlabel = '' if (! defined($xlabel));
12850: $ylabel = '' if (! defined($ylabel));
12851: $ValuesHash{$id.'.title'} = &escape($Title);
12852: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
12853: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
12854: $ValuesHash{$id.'.y_max_value'} = $Max;
12855: $ValuesHash{$id.'.NumBars'} = $NumBars;
12856: $ValuesHash{$id.'.NumSets'} = $NumSets;
12857: $ValuesHash{$id.'.PlotType'} = 'bar';
12858: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
12859: $ValuesHash{$id.'.height'} = $height;
12860: $ValuesHash{$id.'.width'} = $width;
12861: $ValuesHash{$id.'.xskip'} = $xskip;
12862: $ValuesHash{$id.'.bar_width'} = $bar_width;
12863: $ValuesHash{$id.'.labels'} = join(',',@Labels);
12864: #
12865: # Deal with other parameters
12866: while (my ($key,$value) = each(%$extra_settings)) {
12867: $ValuesHash{$id.'.'.$key} = $value;
12868: }
12869: #
12870: &Apache::lonnet::appenv(\%ValuesHash);
12871: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12872: }
12873:
12874: ############################################################
12875: ############################################################
12876:
12877: =pod
12878:
12879: =item * &DrawXYGraph()
12880:
12881: Facilitates the plotting of data in an XY graph.
12882: Puts plot definition data into the users environment in order for
12883: graph.png to plot it. Returns an <img> tag for the plot.
12884:
12885: Inputs:
12886:
12887: =over 4
12888:
12889: =item $Title: string, the title of the plot
12890:
12891: =item $xlabel: string, text describing the X-axis of the plot
12892:
12893: =item $ylabel: string, text describing the Y-axis of the plot
12894:
12895: =item $Max: scalar, the maximum Y value to use in the plot
12896: If $Max is < any data point, the graph will not be rendered.
12897:
12898: =item $colors: Array ref containing the hex color codes for the data to be
12899: plotted in. If undefined, default values will be used.
12900:
12901: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12902:
12903: =item $Ydata: Array ref containing Array refs.
12904: Each of the contained arrays will be plotted as a separate curve.
12905:
12906: =item %Values: hash indicating or overriding any default values which are
12907: passed to graph.png.
12908: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12909:
12910: =back
12911:
12912: Returns:
12913:
12914: An <img> tag which references graph.png and the appropriate identifying
12915: information for the plot.
12916:
12917: =cut
12918:
12919: ############################################################
12920: ############################################################
12921: sub DrawXYGraph {
12922: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
12923: #
12924: # Create the identifier for the graph
12925: my $identifier = &get_cgi_id();
12926: my $id = 'cgi.'.$identifier;
12927: #
12928: $Title = '' if (! defined($Title));
12929: $xlabel = '' if (! defined($xlabel));
12930: $ylabel = '' if (! defined($ylabel));
12931: my %ValuesHash =
12932: (
12933: $id.'.title' => &escape($Title),
12934: $id.'.xlabel' => &escape($xlabel),
12935: $id.'.ylabel' => &escape($ylabel),
12936: $id.'.y_max_value'=> $Max,
12937: $id.'.labels' => join(',',@$Xlabels),
12938: $id.'.PlotType' => 'XY',
12939: );
12940: #
12941: if (defined($colors) && ref($colors) eq 'ARRAY') {
12942: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
12943: }
12944: #
12945: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
12946: return '';
12947: }
12948: my $NumSets=1;
12949: foreach my $array (@{$Ydata}){
12950: next if (! ref($array));
12951: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12952: }
12953: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
12954: #
12955: # Deal with other parameters
12956: while (my ($key,$value) = each(%Values)) {
12957: $ValuesHash{$id.'.'.$key} = $value;
12958: }
12959: #
12960: &Apache::lonnet::appenv(\%ValuesHash);
12961: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12962: }
12963:
12964: ############################################################
12965: ############################################################
12966:
12967: =pod
12968:
12969: =item * &DrawXYYGraph()
12970:
12971: Facilitates the plotting of data in an XY graph with two Y axes.
12972: Puts plot definition data into the users environment in order for
12973: graph.png to plot it. Returns an <img> tag for the plot.
12974:
12975: Inputs:
12976:
12977: =over 4
12978:
12979: =item $Title: string, the title of the plot
12980:
12981: =item $xlabel: string, text describing the X-axis of the plot
12982:
12983: =item $ylabel: string, text describing the Y-axis of the plot
12984:
12985: =item $colors: Array ref containing the hex color codes for the data to be
12986: plotted in. If undefined, default values will be used.
12987:
12988: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12989:
12990: =item $Ydata1: The first data set
12991:
12992: =item $Min1: The minimum value of the left Y-axis
12993:
12994: =item $Max1: The maximum value of the left Y-axis
12995:
12996: =item $Ydata2: The second data set
12997:
12998: =item $Min2: The minimum value of the right Y-axis
12999:
13000: =item $Max2: The maximum value of the left Y-axis
13001:
13002: =item %Values: hash indicating or overriding any default values which are
13003: passed to graph.png.
13004: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13005:
13006: =back
13007:
13008: Returns:
13009:
13010: An <img> tag which references graph.png and the appropriate identifying
13011: information for the plot.
13012:
13013: =cut
13014:
13015: ############################################################
13016: ############################################################
13017: sub DrawXYYGraph {
13018: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13019: $Ydata2,$Min2,$Max2,%Values)=@_;
13020: #
13021: # Create the identifier for the graph
13022: my $identifier = &get_cgi_id();
13023: my $id = 'cgi.'.$identifier;
13024: #
13025: $Title = '' if (! defined($Title));
13026: $xlabel = '' if (! defined($xlabel));
13027: $ylabel = '' if (! defined($ylabel));
13028: my %ValuesHash =
13029: (
13030: $id.'.title' => &escape($Title),
13031: $id.'.xlabel' => &escape($xlabel),
13032: $id.'.ylabel' => &escape($ylabel),
13033: $id.'.labels' => join(',',@$Xlabels),
13034: $id.'.PlotType' => 'XY',
13035: $id.'.NumSets' => 2,
13036: $id.'.two_axes' => 1,
13037: $id.'.y1_max_value' => $Max1,
13038: $id.'.y1_min_value' => $Min1,
13039: $id.'.y2_max_value' => $Max2,
13040: $id.'.y2_min_value' => $Min2,
13041: );
13042: #
13043: if (defined($colors) && ref($colors) eq 'ARRAY') {
13044: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
13045: }
13046: #
13047: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13048: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13049: return '';
13050: }
13051: my $NumSets=1;
13052: foreach my $array ($Ydata1,$Ydata2){
13053: next if (! ref($array));
13054: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13055: }
13056: #
13057: # Deal with other parameters
13058: while (my ($key,$value) = each(%Values)) {
13059: $ValuesHash{$id.'.'.$key} = $value;
13060: }
13061: #
13062: &Apache::lonnet::appenv(\%ValuesHash);
13063: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13064: }
13065:
13066: ############################################################
13067: ############################################################
13068:
13069: =pod
13070:
13071: =back
13072:
13073: =head1 Statistics helper routines?
13074:
13075: Bad place for them but what the hell.
13076:
13077: =over 4
13078:
13079: =item * &chartlink()
13080:
13081: Returns a link to the chart for a specific student.
13082:
13083: Inputs:
13084:
13085: =over 4
13086:
13087: =item $linktext: The text of the link
13088:
13089: =item $sname: The students username
13090:
13091: =item $sdomain: The students domain
13092:
13093: =back
13094:
13095: =back
13096:
13097: =cut
13098:
13099: ############################################################
13100: ############################################################
13101: sub chartlink {
13102: my ($linktext, $sname, $sdomain) = @_;
13103: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13104: '&SelectedStudent='.&escape($sname.':'.$sdomain).
13105: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
13106: '">'.$linktext.'</a>';
13107: }
13108:
13109: #######################################################
13110: #######################################################
13111:
13112: =pod
13113:
13114: =head1 Course Environment Routines
13115:
13116: =over 4
13117:
13118: =item * &restore_course_settings()
13119:
13120: =item * &store_course_settings()
13121:
13122: Restores/Store indicated form parameters from the course environment.
13123: Will not overwrite existing values of the form parameters.
13124:
13125: Inputs:
13126: a scalar describing the data (e.g. 'chart', 'problem_analysis')
13127:
13128: a hash ref describing the data to be stored. For example:
13129:
13130: %Save_Parameters = ('Status' => 'scalar',
13131: 'chartoutputmode' => 'scalar',
13132: 'chartoutputdata' => 'scalar',
13133: 'Section' => 'array',
13134: 'Group' => 'array',
13135: 'StudentData' => 'array',
13136: 'Maps' => 'array');
13137:
13138: Returns: both routines return nothing
13139:
13140: =back
13141:
13142: =cut
13143:
13144: #######################################################
13145: #######################################################
13146: sub store_course_settings {
13147: return &store_settings($env{'request.course.id'},@_);
13148: }
13149:
13150: sub store_settings {
13151: # save to the environment
13152: # appenv the same items, just to be safe
13153: my $udom = $env{'user.domain'};
13154: my $uname = $env{'user.name'};
13155: my ($context,$prefix,$Settings) = @_;
13156: my %SaveHash;
13157: my %AppHash;
13158: while (my ($setting,$type) = each(%$Settings)) {
13159: my $basename = join('.','internal',$context,$prefix,$setting);
13160: my $envname = 'environment.'.$basename;
13161: if (exists($env{'form.'.$setting})) {
13162: # Save this value away
13163: if ($type eq 'scalar' &&
13164: (! exists($env{$envname}) ||
13165: $env{$envname} ne $env{'form.'.$setting})) {
13166: $SaveHash{$basename} = $env{'form.'.$setting};
13167: $AppHash{$envname} = $env{'form.'.$setting};
13168: } elsif ($type eq 'array') {
13169: my $stored_form;
13170: if (ref($env{'form.'.$setting})) {
13171: $stored_form = join(',',
13172: map {
13173: &escape($_);
13174: } sort(@{$env{'form.'.$setting}}));
13175: } else {
13176: $stored_form =
13177: &escape($env{'form.'.$setting});
13178: }
13179: # Determine if the array contents are the same.
13180: if ($stored_form ne $env{$envname}) {
13181: $SaveHash{$basename} = $stored_form;
13182: $AppHash{$envname} = $stored_form;
13183: }
13184: }
13185: }
13186: }
13187: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
13188: $udom,$uname);
13189: if ($put_result !~ /^(ok|delayed)/) {
13190: &Apache::lonnet::logthis('unable to save form parameters, '.
13191: 'got error:'.$put_result);
13192: }
13193: # Make sure these settings stick around in this session, too
13194: &Apache::lonnet::appenv(\%AppHash);
13195: return;
13196: }
13197:
13198: sub restore_course_settings {
13199: return &restore_settings($env{'request.course.id'},@_);
13200: }
13201:
13202: sub restore_settings {
13203: my ($context,$prefix,$Settings) = @_;
13204: while (my ($setting,$type) = each(%$Settings)) {
13205: next if (exists($env{'form.'.$setting}));
13206: my $envname = 'environment.internal.'.$context.'.'.$prefix.
13207: '.'.$setting;
13208: if (exists($env{$envname})) {
13209: if ($type eq 'scalar') {
13210: $env{'form.'.$setting} = $env{$envname};
13211: } elsif ($type eq 'array') {
13212: $env{'form.'.$setting} = [
13213: map {
13214: &unescape($_);
13215: } split(',',$env{$envname})
13216: ];
13217: }
13218: }
13219: }
13220: }
13221:
13222: #######################################################
13223: #######################################################
13224:
13225: =pod
13226:
13227: =head1 Domain E-mail Routines
13228:
13229: =over 4
13230:
13231: =item * &build_recipient_list()
13232:
13233: Build recipient lists for following types of e-mail:
13234: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
13235: (d) Help requests, (e) Course requests needing approval, (f) loncapa
13236: module change checking, student/employee ID conflict checks, as
13237: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
13238: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
13239:
13240: Inputs:
13241: defmail (scalar - email address of default recipient),
13242: mailing type (scalar: errormail, packagesmail, helpdeskmail,
13243: requestsmail, updatesmail, or idconflictsmail).
13244:
13245: defdom (domain for which to retrieve configuration settings),
13246:
13247: origmail (scalar - email address of recipient from loncapa.conf,
13248: i.e., predates configuration by DC via domainprefs.pm
13249:
13250: Returns: comma separated list of addresses to which to send e-mail.
13251:
13252: =back
13253:
13254: =cut
13255:
13256: ############################################################
13257: ############################################################
13258: sub build_recipient_list {
13259: my ($defmail,$mailing,$defdom,$origmail) = @_;
13260: my @recipients;
13261: my $otheremails;
13262: my %domconfig =
13263: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
13264: if (ref($domconfig{'contacts'}) eq 'HASH') {
13265: if (exists($domconfig{'contacts'}{$mailing})) {
13266: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
13267: my @contacts = ('adminemail','supportemail');
13268: foreach my $item (@contacts) {
13269: if ($domconfig{'contacts'}{$mailing}{$item}) {
13270: my $addr = $domconfig{'contacts'}{$item};
13271: if (!grep(/^\Q$addr\E$/,@recipients)) {
13272: push(@recipients,$addr);
13273: }
13274: }
13275: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
13276: }
13277: }
13278: } elsif ($origmail ne '') {
13279: push(@recipients,$origmail);
13280: }
13281: } elsif ($origmail ne '') {
13282: push(@recipients,$origmail);
13283: }
13284: if (defined($defmail)) {
13285: if ($defmail ne '') {
13286: push(@recipients,$defmail);
13287: }
13288: }
13289: if ($otheremails) {
13290: my @others;
13291: if ($otheremails =~ /,/) {
13292: @others = split(/,/,$otheremails);
13293: } else {
13294: push(@others,$otheremails);
13295: }
13296: foreach my $addr (@others) {
13297: if (!grep(/^\Q$addr\E$/,@recipients)) {
13298: push(@recipients,$addr);
13299: }
13300: }
13301: }
13302: my $recipientlist = join(',',@recipients);
13303: return $recipientlist;
13304: }
13305:
13306: ############################################################
13307: ############################################################
13308:
13309: =pod
13310:
13311: =head1 Course Catalog Routines
13312:
13313: =over 4
13314:
13315: =item * &gather_categories()
13316:
13317: Converts category definitions - keys of categories hash stored in
13318: coursecategories in configuration.db on the primary library server in a
13319: domain - to an array. Also generates javascript and idx hash used to
13320: generate Domain Coordinator interface for editing Course Categories.
13321:
13322: Inputs:
13323:
13324: categories (reference to hash of category definitions).
13325:
13326: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13327: categories and subcategories).
13328:
13329: idx (reference to hash of counters used in Domain Coordinator interface for
13330: editing Course Categories).
13331:
13332: jsarray (reference to array of categories used to create Javascript arrays for
13333: Domain Coordinator interface for editing Course Categories).
13334:
13335: Returns: nothing
13336:
13337: Side effects: populates cats, idx and jsarray.
13338:
13339: =cut
13340:
13341: sub gather_categories {
13342: my ($categories,$cats,$idx,$jsarray) = @_;
13343: my %counters;
13344: my $num = 0;
13345: foreach my $item (keys(%{$categories})) {
13346: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
13347: if ($container eq '' && $depth == 0) {
13348: $cats->[$depth][$categories->{$item}] = $cat;
13349: } else {
13350: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
13351: }
13352: my ($escitem,$tail) = split(/:/,$item,2);
13353: if ($counters{$tail} eq '') {
13354: $counters{$tail} = $num;
13355: $num ++;
13356: }
13357: if (ref($idx) eq 'HASH') {
13358: $idx->{$item} = $counters{$tail};
13359: }
13360: if (ref($jsarray) eq 'ARRAY') {
13361: push(@{$jsarray->[$counters{$tail}]},$item);
13362: }
13363: }
13364: return;
13365: }
13366:
13367: =pod
13368:
13369: =item * &extract_categories()
13370:
13371: Used to generate breadcrumb trails for course categories.
13372:
13373: Inputs:
13374:
13375: categories (reference to hash of category definitions).
13376:
13377: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13378: categories and subcategories).
13379:
13380: trails (reference to array of breacrumb trails for each category).
13381:
13382: allitems (reference to hash - key is category key
13383: (format: escaped(name):escaped(parent category):depth in hierarchy).
13384:
13385: idx (reference to hash of counters used in Domain Coordinator interface for
13386: editing Course Categories).
13387:
13388: jsarray (reference to array of categories used to create Javascript arrays for
13389: Domain Coordinator interface for editing Course Categories).
13390:
13391: subcats (reference to hash of arrays containing all subcategories within each
13392: category, -recursive)
13393:
13394: Returns: nothing
13395:
13396: Side effects: populates trails and allitems hash references.
13397:
13398: =cut
13399:
13400: sub extract_categories {
13401: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
13402: if (ref($categories) eq 'HASH') {
13403: &gather_categories($categories,$cats,$idx,$jsarray);
13404: if (ref($cats->[0]) eq 'ARRAY') {
13405: for (my $i=0; $i<@{$cats->[0]}; $i++) {
13406: my $name = $cats->[0][$i];
13407: my $item = &escape($name).'::0';
13408: my $trailstr;
13409: if ($name eq 'instcode') {
13410: $trailstr = &mt('Official courses (with institutional codes)');
13411: } elsif ($name eq 'communities') {
13412: $trailstr = &mt('Communities');
13413: } else {
13414: $trailstr = $name;
13415: }
13416: if ($allitems->{$item} eq '') {
13417: push(@{$trails},$trailstr);
13418: $allitems->{$item} = scalar(@{$trails})-1;
13419: }
13420: my @parents = ($name);
13421: if (ref($cats->[1]{$name}) eq 'ARRAY') {
13422: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
13423: my $category = $cats->[1]{$name}[$j];
13424: if (ref($subcats) eq 'HASH') {
13425: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
13426: }
13427: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
13428: }
13429: } else {
13430: if (ref($subcats) eq 'HASH') {
13431: $subcats->{$item} = [];
13432: }
13433: }
13434: }
13435: }
13436: }
13437: return;
13438: }
13439:
13440: =pod
13441:
13442: =item * &recurse_categories()
13443:
13444: Recursively used to generate breadcrumb trails for course categories.
13445:
13446: Inputs:
13447:
13448: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13449: categories and subcategories).
13450:
13451: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
13452:
13453: category (current course category, for which breadcrumb trail is being generated).
13454:
13455: trails (reference to array of breadcrumb trails for each category).
13456:
13457: allitems (reference to hash - key is category key
13458: (format: escaped(name):escaped(parent category):depth in hierarchy).
13459:
13460: parents (array containing containers directories for current category,
13461: back to top level).
13462:
13463: Returns: nothing
13464:
13465: Side effects: populates trails and allitems hash references
13466:
13467: =cut
13468:
13469: sub recurse_categories {
13470: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
13471: my $shallower = $depth - 1;
13472: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
13473: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
13474: my $name = $cats->[$depth]{$category}[$k];
13475: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13476: my $trailstr = join(' -> ',(@{$parents},$category));
13477: if ($allitems->{$item} eq '') {
13478: push(@{$trails},$trailstr);
13479: $allitems->{$item} = scalar(@{$trails})-1;
13480: }
13481: my $deeper = $depth+1;
13482: push(@{$parents},$category);
13483: if (ref($subcats) eq 'HASH') {
13484: my $subcat = &escape($name).':'.$category.':'.$depth;
13485: for (my $j=@{$parents}; $j>=0; $j--) {
13486: my $higher;
13487: if ($j > 0) {
13488: $higher = &escape($parents->[$j]).':'.
13489: &escape($parents->[$j-1]).':'.$j;
13490: } else {
13491: $higher = &escape($parents->[$j]).'::'.$j;
13492: }
13493: push(@{$subcats->{$higher}},$subcat);
13494: }
13495: }
13496: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
13497: $subcats);
13498: pop(@{$parents});
13499: }
13500: } else {
13501: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13502: my $trailstr = join(' -> ',(@{$parents},$category));
13503: if ($allitems->{$item} eq '') {
13504: push(@{$trails},$trailstr);
13505: $allitems->{$item} = scalar(@{$trails})-1;
13506: }
13507: }
13508: return;
13509: }
13510:
13511: =pod
13512:
13513: =item * &assign_categories_table()
13514:
13515: Create a datatable for display of hierarchical categories in a domain,
13516: with checkboxes to allow a course to be categorized.
13517:
13518: Inputs:
13519:
13520: cathash - reference to hash of categories defined for the domain (from
13521: configuration.db)
13522:
13523: currcat - scalar with an & separated list of categories assigned to a course.
13524:
13525: type - scalar contains course type (Course or Community).
13526:
13527: Returns: $output (markup to be displayed)
13528:
13529: =cut
13530:
13531: sub assign_categories_table {
13532: my ($cathash,$currcat,$type) = @_;
13533: my $output;
13534: if (ref($cathash) eq 'HASH') {
13535: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
13536: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
13537: $maxdepth = scalar(@cats);
13538: if (@cats > 0) {
13539: my $itemcount = 0;
13540: if (ref($cats[0]) eq 'ARRAY') {
13541: my @currcategories;
13542: if ($currcat ne '') {
13543: @currcategories = split('&',$currcat);
13544: }
13545: my $table;
13546: for (my $i=0; $i<@{$cats[0]}; $i++) {
13547: my $parent = $cats[0][$i];
13548: next if ($parent eq 'instcode');
13549: if ($type eq 'Community') {
13550: next unless ($parent eq 'communities');
13551: } else {
13552: next if ($parent eq 'communities');
13553: }
13554: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13555: my $item = &escape($parent).'::0';
13556: my $checked = '';
13557: if (@currcategories > 0) {
13558: if (grep(/^\Q$item\E$/,@currcategories)) {
13559: $checked = ' checked="checked"';
13560: }
13561: }
13562: my $parent_title = $parent;
13563: if ($parent eq 'communities') {
13564: $parent_title = &mt('Communities');
13565: }
13566: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
13567: '<input type="checkbox" name="usecategory" value="'.
13568: $item.'"'.$checked.' />'.$parent_title.'</span>'.
13569: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
13570: my $depth = 1;
13571: push(@path,$parent);
13572: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
13573: pop(@path);
13574: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
13575: $itemcount ++;
13576: }
13577: if ($itemcount) {
13578: $output = &Apache::loncommon::start_data_table().
13579: $table.
13580: &Apache::loncommon::end_data_table();
13581: }
13582: }
13583: }
13584: }
13585: return $output;
13586: }
13587:
13588: =pod
13589:
13590: =item * &assign_category_rows()
13591:
13592: Create a datatable row for display of nested categories in a domain,
13593: with checkboxes to allow a course to be categorized,called recursively.
13594:
13595: Inputs:
13596:
13597: itemcount - track row number for alternating colors
13598:
13599: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13600: categories and subcategories.
13601:
13602: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13603:
13604: parent - parent of current category item
13605:
13606: path - Array containing all categories back up through the hierarchy from the
13607: current category to the top level.
13608:
13609: currcategories - reference to array of current categories assigned to the course
13610:
13611: Returns: $output (markup to be displayed).
13612:
13613: =cut
13614:
13615: sub assign_category_rows {
13616: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13617: my ($text,$name,$item,$chgstr);
13618: if (ref($cats) eq 'ARRAY') {
13619: my $maxdepth = scalar(@{$cats});
13620: if (ref($cats->[$depth]) eq 'HASH') {
13621: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13622: my $numchildren = @{$cats->[$depth]{$parent}};
13623: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13624: $text .= '<td><table class="LC_data_table">';
13625: for (my $j=0; $j<$numchildren; $j++) {
13626: $name = $cats->[$depth]{$parent}[$j];
13627: $item = &escape($name).':'.&escape($parent).':'.$depth;
13628: my $deeper = $depth+1;
13629: my $checked = '';
13630: if (ref($currcategories) eq 'ARRAY') {
13631: if (@{$currcategories} > 0) {
13632: if (grep(/^\Q$item\E$/,@{$currcategories})) {
13633: $checked = ' checked="checked"';
13634: }
13635: }
13636: }
13637: $text .= '<tr><td><span class="LC_nobreak"><label>'.
13638: '<input type="checkbox" name="usecategory" value="'.
13639: $item.'"'.$checked.' />'.$name.'</label></span>'.
13640: '<input type="hidden" name="catname" value="'.$name.'" />'.
13641: '</td><td>';
13642: if (ref($path) eq 'ARRAY') {
13643: push(@{$path},$name);
13644: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13645: pop(@{$path});
13646: }
13647: $text .= '</td></tr>';
13648: }
13649: $text .= '</table></td>';
13650: }
13651: }
13652: }
13653: return $text;
13654: }
13655:
13656: ############################################################
13657: ############################################################
13658:
13659:
13660: sub commit_customrole {
13661: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
13662: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
13663: ($start?', '.&mt('starting').' '.localtime($start):'').
13664: ($end?', ending '.localtime($end):'').': <b>'.
13665: &Apache::lonnet::assigncustomrole(
13666: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
13667: '</b><br />';
13668: return $output;
13669: }
13670:
13671: sub commit_standardrole {
13672: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
13673: my ($output,$logmsg,$linefeed);
13674: if ($context eq 'auto') {
13675: $linefeed = "\n";
13676: } else {
13677: $linefeed = "<br />\n";
13678: }
13679: if ($three eq 'st') {
13680: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
13681: $one,$two,$sec,$context,$credits);
13682: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
13683: ($result eq 'unknown_course') || ($result eq 'refused')) {
13684: $output = $logmsg.' '.&mt('Error: ').$result."\n";
13685: } else {
13686: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
13687: ($start?', '.&mt('starting').' '.localtime($start):'').
13688: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13689: if ($context eq 'auto') {
13690: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
13691: } else {
13692: $output .= '<b>'.$result.'</b>'.$linefeed.
13693: &mt('Add to classlist').': <b>ok</b>';
13694: }
13695: $output .= $linefeed;
13696: }
13697: } else {
13698: $output = &mt('Assigning').' '.$three.' in '.$url.
13699: ($start?', '.&mt('starting').' '.localtime($start):'').
13700: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13701: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
13702: if ($context eq 'auto') {
13703: $output .= $result.$linefeed;
13704: } else {
13705: $output .= '<b>'.$result.'</b>'.$linefeed;
13706: }
13707: }
13708: return $output;
13709: }
13710:
13711: sub commit_studentrole {
13712: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
13713: $credits) = @_;
13714: my ($result,$linefeed,$oldsecurl,$newsecurl);
13715: if ($context eq 'auto') {
13716: $linefeed = "\n";
13717: } else {
13718: $linefeed = '<br />'."\n";
13719: }
13720: if (defined($one) && defined($two)) {
13721: my $cid=$one.'_'.$two;
13722: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
13723: my $secchange = 0;
13724: my $expire_role_result;
13725: my $modify_section_result;
13726: if ($oldsec ne '-1') {
13727: if ($oldsec ne $sec) {
13728: $secchange = 1;
13729: my $now = time;
13730: my $uurl='/'.$cid;
13731: $uurl=~s/\_/\//g;
13732: if ($oldsec) {
13733: $uurl.='/'.$oldsec;
13734: }
13735: $oldsecurl = $uurl;
13736: $expire_role_result =
13737: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
13738: if ($env{'request.course.sec'} ne '') {
13739: if ($expire_role_result eq 'refused') {
13740: my @roles = ('st');
13741: my @statuses = ('previous');
13742: my @roledoms = ($one);
13743: my $withsec = 1;
13744: my %roleshash =
13745: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
13746: \@statuses,\@roles,\@roledoms,$withsec);
13747: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
13748: my ($oldstart,$oldend) =
13749: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
13750: if ($oldend > 0 && $oldend <= $now) {
13751: $expire_role_result = 'ok';
13752: }
13753: }
13754: }
13755: }
13756: $result = $expire_role_result;
13757: }
13758: }
13759: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
13760: $modify_section_result =
13761: &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
13762: undef,undef,undef,$sec,
13763: $end,$start,'','',$cid,
13764: '',$context,$credits);
13765: if ($modify_section_result =~ /^ok/) {
13766: if ($secchange == 1) {
13767: if ($sec eq '') {
13768: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
13769: } else {
13770: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
13771: }
13772: } elsif ($oldsec eq '-1') {
13773: if ($sec eq '') {
13774: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
13775: } else {
13776: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13777: }
13778: } else {
13779: if ($sec eq '') {
13780: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
13781: } else {
13782: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13783: }
13784: }
13785: } else {
13786: if ($secchange) {
13787: $$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;
13788: } else {
13789: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
13790: }
13791: }
13792: $result = $modify_section_result;
13793: } elsif ($secchange == 1) {
13794: if ($oldsec eq '') {
13795: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
13796: } else {
13797: $$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;
13798: }
13799: if ($expire_role_result eq 'refused') {
13800: my $newsecurl = '/'.$cid;
13801: $newsecurl =~ s/\_/\//g;
13802: if ($sec ne '') {
13803: $newsecurl.='/'.$sec;
13804: }
13805: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
13806: if ($sec eq '') {
13807: $$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;
13808: } else {
13809: $$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;
13810: }
13811: }
13812: }
13813: }
13814: } else {
13815: $$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;
13816: $result = "error: incomplete course id\n";
13817: }
13818: return $result;
13819: }
13820:
13821: sub show_role_extent {
13822: my ($scope,$context,$role) = @_;
13823: $scope =~ s{^/}{};
13824: my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
13825: push(@courseroles,'co');
13826: my @authorroles = &Apache::lonuserutils::roles_by_context('author');
13827: if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
13828: $scope =~ s{/}{_};
13829: return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
13830: } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
13831: my ($audom,$auname) = split(/\//,$scope);
13832: return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
13833: &Apache::loncommon::plainname($auname,$audom).'</span>');
13834: } else {
13835: $scope =~ s{/$}{};
13836: return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
13837: &Apache::lonnet::domain($scope,'description').'</span>');
13838: }
13839: }
13840:
13841: ############################################################
13842: ############################################################
13843:
13844: sub check_clone {
13845: my ($args,$linefeed) = @_;
13846: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
13847: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
13848: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
13849: my $clonemsg;
13850: my $can_clone = 0;
13851: my $lctype = lc($args->{'crstype'});
13852: if ($lctype ne 'community') {
13853: $lctype = 'course';
13854: }
13855: if ($clonehome eq 'no_host') {
13856: if ($args->{'crstype'} eq 'Community') {
13857: $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'});
13858: } else {
13859: $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'});
13860: }
13861: } else {
13862: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
13863: if ($args->{'crstype'} eq 'Community') {
13864: if ($clonedesc{'type'} ne 'Community') {
13865: $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'});
13866: return ($can_clone, $clonemsg, $cloneid, $clonehome);
13867: }
13868: }
13869: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
13870: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
13871: $can_clone = 1;
13872: } else {
13873: my %clonehash = &Apache::lonnet::get('environment',['cloners'],
13874: $args->{'clonedomain'},$args->{'clonecourse'});
13875: my @cloners = split(/,/,$clonehash{'cloners'});
13876: if (grep(/^\*$/,@cloners)) {
13877: $can_clone = 1;
13878: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
13879: $can_clone = 1;
13880: } else {
13881: my $ccrole = 'cc';
13882: if ($args->{'crstype'} eq 'Community') {
13883: $ccrole = 'co';
13884: }
13885: my %roleshash =
13886: &Apache::lonnet::get_my_roles($args->{'ccuname'},
13887: $args->{'ccdomain'},
13888: 'userroles',['active'],[$ccrole],
13889: [$args->{'clonedomain'}]);
13890: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
13891: $can_clone = 1;
13892: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
13893: $can_clone = 1;
13894: } else {
13895: if ($args->{'crstype'} eq 'Community') {
13896: $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'});
13897: } else {
13898: $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'});
13899: }
13900: }
13901: }
13902: }
13903: }
13904: return ($can_clone, $clonemsg, $cloneid, $clonehome);
13905: }
13906:
13907: sub construct_course {
13908: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
13909: my $outcome;
13910: my $linefeed = '<br />'."\n";
13911: if ($context eq 'auto') {
13912: $linefeed = "\n";
13913: }
13914:
13915: #
13916: # Are we cloning?
13917: #
13918: my ($can_clone, $clonemsg, $cloneid, $clonehome);
13919: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
13920: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
13921: if ($context ne 'auto') {
13922: if ($clonemsg ne '') {
13923: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
13924: }
13925: }
13926: $outcome .= $clonemsg.$linefeed;
13927:
13928: if (!$can_clone) {
13929: return (0,$outcome);
13930: }
13931: }
13932:
13933: #
13934: # Open course
13935: #
13936: my $crstype = lc($args->{'crstype'});
13937: my %cenv=();
13938: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
13939: $args->{'cdescr'},
13940: $args->{'curl'},
13941: $args->{'course_home'},
13942: $args->{'nonstandard'},
13943: $args->{'crscode'},
13944: $args->{'ccuname'}.':'.
13945: $args->{'ccdomain'},
13946: $args->{'crstype'},
13947: $cnum,$context,$category);
13948:
13949: # Note: The testing routines depend on this being output; see
13950: # Utils::Course. This needs to at least be output as a comment
13951: # if anyone ever decides to not show this, and Utils::Course::new
13952: # will need to be suitably modified.
13953: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
13954: if ($$courseid =~ /^error:/) {
13955: return (0,$outcome);
13956: }
13957:
13958: #
13959: # Check if created correctly
13960: #
13961: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
13962: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
13963: if ($crsuhome eq 'no_host') {
13964: $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
13965: return (0,$outcome);
13966: }
13967: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
13968:
13969: #
13970: # Do the cloning
13971: #
13972: if ($can_clone && $cloneid) {
13973: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
13974: if ($context ne 'auto') {
13975: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
13976: }
13977: $outcome .= $clonemsg.$linefeed;
13978: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
13979: # Copy all files
13980: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
13981: # Restore URL
13982: $cenv{'url'}=$oldcenv{'url'};
13983: # Restore title
13984: $cenv{'description'}=$oldcenv{'description'};
13985: # Restore creation date, creator and creation context.
13986: $cenv{'internal.created'}=$oldcenv{'internal.created'};
13987: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
13988: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
13989: # Mark as cloned
13990: $cenv{'clonedfrom'}=$cloneid;
13991: # Need to clone grading mode
13992: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
13993: $cenv{'grading'}=$newenv{'grading'};
13994: # Do not clone these environment entries
13995: &Apache::lonnet::del('environment',
13996: ['default_enrollment_start_date',
13997: 'default_enrollment_end_date',
13998: 'question.email',
13999: 'policy.email',
14000: 'comment.email',
14001: 'pch.users.denied',
14002: 'plc.users.denied',
14003: 'hidefromcat',
14004: 'checkforpriv',
14005: 'categories',
14006: 'internal.uniquecode'],
14007: $$crsudom,$$crsunum);
14008: }
14009:
14010: #
14011: # Set environment (will override cloned, if existing)
14012: #
14013: my @sections = ();
14014: my @xlists = ();
14015: if ($args->{'crstype'}) {
14016: $cenv{'type'}=$args->{'crstype'};
14017: }
14018: if ($args->{'crsid'}) {
14019: $cenv{'courseid'}=$args->{'crsid'};
14020: }
14021: if ($args->{'crscode'}) {
14022: $cenv{'internal.coursecode'}=$args->{'crscode'};
14023: }
14024: if ($args->{'crsquota'} ne '') {
14025: $cenv{'internal.coursequota'}=$args->{'crsquota'};
14026: } else {
14027: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
14028: }
14029: if ($args->{'ccuname'}) {
14030: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
14031: ':'.$args->{'ccdomain'};
14032: } else {
14033: $cenv{'internal.courseowner'} = $args->{'curruser'};
14034: }
14035: if ($args->{'defaultcredits'}) {
14036: $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
14037: }
14038: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
14039: if ($args->{'crssections'}) {
14040: $cenv{'internal.sectionnums'} = '';
14041: if ($args->{'crssections'} =~ m/,/) {
14042: @sections = split/,/,$args->{'crssections'};
14043: } else {
14044: $sections[0] = $args->{'crssections'};
14045: }
14046: if (@sections > 0) {
14047: foreach my $item (@sections) {
14048: my ($sec,$gp) = split/:/,$item;
14049: my $class = $args->{'crscode'}.$sec;
14050: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
14051: $cenv{'internal.sectionnums'} .= $item.',';
14052: unless ($addcheck eq 'ok') {
14053: push @badclasses, $class;
14054: }
14055: }
14056: $cenv{'internal.sectionnums'} =~ s/,$//;
14057: }
14058: }
14059: # do not hide course coordinator from staff listing,
14060: # even if privileged
14061: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14062: # add course coordinator's domain to domains to check for privileged users
14063: # if different to course domain
14064: if ($$crsudom ne $args->{'ccdomain'}) {
14065: $cenv{'checkforpriv'} = $args->{'ccdomain'};
14066: }
14067: # add crosslistings
14068: if ($args->{'crsxlist'}) {
14069: $cenv{'internal.crosslistings'}='';
14070: if ($args->{'crsxlist'} =~ m/,/) {
14071: @xlists = split/,/,$args->{'crsxlist'};
14072: } else {
14073: $xlists[0] = $args->{'crsxlist'};
14074: }
14075: if (@xlists > 0) {
14076: foreach my $item (@xlists) {
14077: my ($xl,$gp) = split/:/,$item;
14078: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
14079: $cenv{'internal.crosslistings'} .= $item.',';
14080: unless ($addcheck eq 'ok') {
14081: push @badclasses, $xl;
14082: }
14083: }
14084: $cenv{'internal.crosslistings'} =~ s/,$//;
14085: }
14086: }
14087: if ($args->{'autoadds'}) {
14088: $cenv{'internal.autoadds'}=$args->{'autoadds'};
14089: }
14090: if ($args->{'autodrops'}) {
14091: $cenv{'internal.autodrops'}=$args->{'autodrops'};
14092: }
14093: # check for notification of enrollment changes
14094: my @notified = ();
14095: if ($args->{'notify_owner'}) {
14096: if ($args->{'ccuname'} ne '') {
14097: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
14098: }
14099: }
14100: if ($args->{'notify_dc'}) {
14101: if ($uname ne '') {
14102: push(@notified,$uname.':'.$udom);
14103: }
14104: }
14105: if (@notified > 0) {
14106: my $notifylist;
14107: if (@notified > 1) {
14108: $notifylist = join(',',@notified);
14109: } else {
14110: $notifylist = $notified[0];
14111: }
14112: $cenv{'internal.notifylist'} = $notifylist;
14113: }
14114: if (@badclasses > 0) {
14115: my %lt=&Apache::lonlocal::texthash(
14116: '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',
14117: 'dnhr' => 'does not have rights to access enrollment in these classes',
14118: 'adby' => 'as determined by the policies of your institution on access to official classlists'
14119: );
14120: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
14121: ' ('.$lt{'adby'}.')';
14122: if ($context eq 'auto') {
14123: $outcome .= $badclass_msg.$linefeed;
14124: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
14125: foreach my $item (@badclasses) {
14126: if ($context eq 'auto') {
14127: $outcome .= " - $item\n";
14128: } else {
14129: $outcome .= "<li>$item</li>\n";
14130: }
14131: }
14132: if ($context eq 'auto') {
14133: $outcome .= $linefeed;
14134: } else {
14135: $outcome .= "</ul><br /><br /></div>\n";
14136: }
14137: }
14138: }
14139: if ($args->{'no_end_date'}) {
14140: $args->{'endaccess'} = 0;
14141: }
14142: $cenv{'internal.autostart'}=$args->{'enrollstart'};
14143: $cenv{'internal.autoend'}=$args->{'enrollend'};
14144: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
14145: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
14146: if ($args->{'showphotos'}) {
14147: $cenv{'internal.showphotos'}=$args->{'showphotos'};
14148: }
14149: $cenv{'internal.authtype'} = $args->{'authtype'};
14150: $cenv{'internal.autharg'} = $args->{'autharg'};
14151: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
14152: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
14153: 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');
14154: if ($context eq 'auto') {
14155: $outcome .= $krb_msg;
14156: } else {
14157: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
14158: }
14159: $outcome .= $linefeed;
14160: }
14161: }
14162: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
14163: if ($args->{'setpolicy'}) {
14164: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14165: }
14166: if ($args->{'setcontent'}) {
14167: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14168: }
14169: }
14170: if ($args->{'reshome'}) {
14171: $cenv{'reshome'}=$args->{'reshome'}.'/';
14172: $cenv{'reshome'}=~s/\/+$/\//;
14173: }
14174: #
14175: # course has keyed access
14176: #
14177: if ($args->{'setkeys'}) {
14178: $cenv{'keyaccess'}='yes';
14179: }
14180: # if specified, key authority is not course, but user
14181: # only active if keyaccess is yes
14182: if ($args->{'keyauth'}) {
14183: my ($user,$domain) = split(':',$args->{'keyauth'});
14184: $user = &LONCAPA::clean_username($user);
14185: $domain = &LONCAPA::clean_username($domain);
14186: if ($user ne '' && $domain ne '') {
14187: $cenv{'keyauth'}=$user.':'.$domain;
14188: }
14189: }
14190:
14191: #
14192: # generate and store uniquecode (available to course requester), if course should have one.
14193: #
14194: if ($args->{'uniquecode'}) {
14195: my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
14196: if ($code) {
14197: $cenv{'internal.uniquecode'} = $code;
14198: my %crsinfo =
14199: &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
14200: if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
14201: $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
14202: my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
14203: }
14204: if (ref($coderef)) {
14205: $$coderef = $code;
14206: }
14207: }
14208: }
14209:
14210: if ($args->{'disresdis'}) {
14211: $cenv{'pch.roles.denied'}='st';
14212: }
14213: if ($args->{'disablechat'}) {
14214: $cenv{'plc.roles.denied'}='st';
14215: }
14216:
14217: # Record we've not yet viewed the Course Initialization Helper for this
14218: # course
14219: $cenv{'course.helper.not.run'} = 1;
14220: #
14221: # Use new Randomseed
14222: #
14223: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
14224: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
14225: #
14226: # The encryption code and receipt prefix for this course
14227: #
14228: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
14229: $cenv{'internal.encpref'}=100+int(9*rand(99));
14230: #
14231: # By default, use standard grading
14232: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
14233:
14234: $outcome .= $linefeed.&mt('Setting environment').': '.
14235: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
14236: #
14237: # Open all assignments
14238: #
14239: if ($args->{'openall'}) {
14240: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
14241: my %storecontent = ($storeunder => time,
14242: $storeunder.'.type' => 'date_start');
14243:
14244: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
14245: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
14246: }
14247: #
14248: # Set first page
14249: #
14250: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
14251: || ($cloneid)) {
14252: use LONCAPA::map;
14253: $outcome .= &mt('Setting first resource').': ';
14254:
14255: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
14256: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
14257:
14258: $outcome .= ($fatal?$errtext:'read ok').' - ';
14259: my $title; my $url;
14260: if ($args->{'firstres'} eq 'syl') {
14261: $title=&mt('Syllabus');
14262: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
14263: } else {
14264: $title=&mt('Table of Contents');
14265: $url='/adm/navmaps';
14266: }
14267:
14268: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
14269: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
14270:
14271: if ($errtext) { $fatal=2; }
14272: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
14273: }
14274:
14275: return (1,$outcome);
14276: }
14277:
14278: sub make_unique_code {
14279: my ($cdom,$cnum) = @_;
14280: # get lock on uniquecodes db
14281: my $lockhash = {
14282: $cnum."\0".'uniquecodes' => $env{'user.name'}.
14283: ':'.$env{'user.domain'},
14284: };
14285: my $tries = 0;
14286: my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14287: my ($code,$error);
14288:
14289: while (($gotlock ne 'ok') && ($tries<3)) {
14290: $tries ++;
14291: sleep 1;
14292: $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14293: }
14294: if ($gotlock eq 'ok') {
14295: my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
14296: my $gotcode;
14297: my $attempts = 0;
14298: while ((!$gotcode) && ($attempts < 100)) {
14299: $code = &generate_code();
14300: if (!exists($currcodes{$code})) {
14301: $gotcode = 1;
14302: unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
14303: $error = 'nostore';
14304: }
14305: }
14306: $attempts ++;
14307: }
14308: my @del_lock = ($cnum."\0".'uniquecodes');
14309: my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
14310: } else {
14311: $error = 'nolock';
14312: }
14313: return ($code,$error);
14314: }
14315:
14316: sub generate_code {
14317: my $code;
14318: my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
14319: for (my $i=0; $i<6; $i++) {
14320: my $lettnum = int (rand 2);
14321: my $item = '';
14322: if ($lettnum) {
14323: $item = $letts[int( rand(18) )];
14324: } else {
14325: $item = 1+int( rand(8) );
14326: }
14327: $code .= $item;
14328: }
14329: return $code;
14330: }
14331:
14332: ############################################################
14333: ############################################################
14334:
14335: #SD
14336: # only Community and Course, or anything else?
14337: sub course_type {
14338: my ($cid) = @_;
14339: if (!defined($cid)) {
14340: $cid = $env{'request.course.id'};
14341: }
14342: if (defined($env{'course.'.$cid.'.type'})) {
14343: return $env{'course.'.$cid.'.type'};
14344: } else {
14345: return 'Course';
14346: }
14347: }
14348:
14349: sub group_term {
14350: my $crstype = &course_type();
14351: my %names = (
14352: 'Course' => 'group',
14353: 'Community' => 'group',
14354: );
14355: return $names{$crstype};
14356: }
14357:
14358: sub course_types {
14359: my @types = ('official','unofficial','community','textbook');
14360: my %typename = (
14361: official => 'Official course',
14362: unofficial => 'Unofficial course',
14363: community => 'Community',
14364: textbook => 'Textbook course',
14365: );
14366: return (\@types,\%typename);
14367: }
14368:
14369: sub icon {
14370: my ($file)=@_;
14371: my $curfext = lc((split(/\./,$file))[-1]);
14372: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
14373: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
14374: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
14375: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
14376: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14377: $curfext.".gif") {
14378: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14379: $curfext.".gif";
14380: }
14381: }
14382: return &lonhttpdurl($iconname);
14383: }
14384:
14385: sub lonhttpdurl {
14386: #
14387: # Had been used for "small fry" static images on separate port 8080.
14388: # Modify here if lightweight http functionality desired again.
14389: # Currently eliminated due to increasing firewall issues.
14390: #
14391: my ($url)=@_;
14392: return $url;
14393: }
14394:
14395: sub connection_aborted {
14396: my ($r)=@_;
14397: $r->print(" ");$r->rflush();
14398: my $c = $r->connection;
14399: return $c->aborted();
14400: }
14401:
14402: # Escapes strings that may have embedded 's that will be put into
14403: # strings as 'strings'.
14404: sub escape_single {
14405: my ($input) = @_;
14406: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
14407: $input =~ s/\'/\\\'/g; # Esacpe the 's....
14408: return $input;
14409: }
14410:
14411: # Same as escape_single, but escape's "'s This
14412: # can be used for "strings"
14413: sub escape_double {
14414: my ($input) = @_;
14415: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
14416: $input =~ s/\"/\\\"/g; # Esacpe the "s....
14417: return $input;
14418: }
14419:
14420: # Escapes the last element of a full URL.
14421: sub escape_url {
14422: my ($url) = @_;
14423: my @urlslices = split(/\//, $url,-1);
14424: my $lastitem = &escape(pop(@urlslices));
14425: return join('/',@urlslices).'/'.$lastitem;
14426: }
14427:
14428: sub compare_arrays {
14429: my ($arrayref1,$arrayref2) = @_;
14430: my (@difference,%count);
14431: @difference = ();
14432: %count = ();
14433: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
14434: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
14435: foreach my $element (keys(%count)) {
14436: if ($count{$element} == 1) {
14437: push(@difference,$element);
14438: }
14439: }
14440: }
14441: return @difference;
14442: }
14443:
14444: # -------------------------------------------------------- Initialize user login
14445: sub init_user_environment {
14446: my ($r, $username, $domain, $authhost, $form, $args) = @_;
14447: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
14448:
14449: my $public=($username eq 'public' && $domain eq 'public');
14450:
14451: # See if old ID present, if so, remove
14452:
14453: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
14454: my $now=time;
14455:
14456: if ($public) {
14457: my $max_public=100;
14458: my $oldest;
14459: my $oldest_time=0;
14460: for(my $next=1;$next<=$max_public;$next++) {
14461: if (-e $lonids."/publicuser_$next.id") {
14462: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
14463: if ($mtime<$oldest_time || !$oldest_time) {
14464: $oldest_time=$mtime;
14465: $oldest=$next;
14466: }
14467: } else {
14468: $cookie="publicuser_$next";
14469: last;
14470: }
14471: }
14472: if (!$cookie) { $cookie="publicuser_$oldest"; }
14473: } else {
14474: # if this isn't a robot, kill any existing non-robot sessions
14475: if (!$args->{'robot'}) {
14476: opendir(DIR,$lonids);
14477: while ($filename=readdir(DIR)) {
14478: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
14479: unlink($lonids.'/'.$filename);
14480: }
14481: }
14482: closedir(DIR);
14483: }
14484: # Give them a new cookie
14485: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
14486: : $now.$$.int(rand(10000)));
14487: $cookie="$username\_$id\_$domain\_$authhost";
14488:
14489: # Initialize roles
14490:
14491: ($userroles,$firstaccenv,$timerintenv) =
14492: &Apache::lonnet::rolesinit($domain,$username,$authhost);
14493: }
14494: # ------------------------------------ Check browser type and MathML capability
14495:
14496: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
14497: $clientunicode,$clientos,$clientmobile,$clientinfo) = &decode_user_agent($r);
14498:
14499: # ------------------------------------------------------------- Get environment
14500:
14501: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
14502: my ($tmp) = keys(%userenv);
14503: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14504: } else {
14505: undef(%userenv);
14506: }
14507: if (($userenv{'interface'}) && (!$form->{'interface'})) {
14508: $form->{'interface'}=$userenv{'interface'};
14509: }
14510: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
14511:
14512: # --------------- Do not trust query string to be put directly into environment
14513: foreach my $option ('interface','localpath','localres') {
14514: $form->{$option}=~s/[\n\r\=]//gs;
14515: }
14516: # --------------------------------------------------------- Write first profile
14517:
14518: {
14519: my %initial_env =
14520: ("user.name" => $username,
14521: "user.domain" => $domain,
14522: "user.home" => $authhost,
14523: "browser.type" => $clientbrowser,
14524: "browser.version" => $clientversion,
14525: "browser.mathml" => $clientmathml,
14526: "browser.unicode" => $clientunicode,
14527: "browser.os" => $clientos,
14528: "browser.mobile" => $clientmobile,
14529: "browser.info" => $clientinfo,
14530: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
14531: "request.course.fn" => '',
14532: "request.course.uri" => '',
14533: "request.course.sec" => '',
14534: "request.role" => 'cm',
14535: "request.role.adv" => $env{'user.adv'},
14536: "request.host" => $ENV{'REMOTE_ADDR'},);
14537:
14538: if ($form->{'localpath'}) {
14539: $initial_env{"browser.localpath"} = $form->{'localpath'};
14540: $initial_env{"browser.localres"} = $form->{'localres'};
14541: }
14542:
14543: if ($form->{'interface'}) {
14544: $form->{'interface'}=~s/\W//gs;
14545: $initial_env{"browser.interface"} = $form->{'interface'};
14546: $env{'browser.interface'}=$form->{'interface'};
14547: }
14548:
14549: if ($form->{'iptoken'}) {
14550: my $lonhost = $r->dir_config('lonHostID');
14551: $initial_env{"user.noloadbalance"} = $lonhost;
14552: $env{'user.noloadbalance'} = $lonhost;
14553: }
14554:
14555: my %is_adv = ( is_adv => $env{'user.adv'} );
14556: my %domdef;
14557: unless ($domain eq 'public') {
14558: %domdef = &Apache::lonnet::get_domain_defaults($domain);
14559: }
14560:
14561: foreach my $tool ('aboutme','blog','webdav','portfolio') {
14562: $userenv{'availabletools.'.$tool} =
14563: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
14564: undef,\%userenv,\%domdef,\%is_adv);
14565: }
14566:
14567: foreach my $crstype ('official','unofficial','community','textbook') {
14568: $userenv{'canrequest.'.$crstype} =
14569: &Apache::lonnet::usertools_access($username,$domain,$crstype,
14570: 'reload','requestcourses',
14571: \%userenv,\%domdef,\%is_adv);
14572: }
14573:
14574: $userenv{'canrequest.author'} =
14575: &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
14576: 'reload','requestauthor',
14577: \%userenv,\%domdef,\%is_adv);
14578: my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
14579: $domain,$username);
14580: my $reqstatus = $reqauthor{'author_status'};
14581: if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
14582: if (ref($reqauthor{'author'}) eq 'HASH') {
14583: $userenv{'requestauthorqueued'} = $reqstatus.':'.
14584: $reqauthor{'author'}{'timestamp'};
14585: }
14586: }
14587:
14588: $env{'user.environment'} = "$lonids/$cookie.id";
14589:
14590: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
14591: &GDBM_WRCREAT(),0640)) {
14592: &_add_to_env(\%disk_env,\%initial_env);
14593: &_add_to_env(\%disk_env,\%userenv,'environment.');
14594: &_add_to_env(\%disk_env,$userroles);
14595: if (ref($firstaccenv) eq 'HASH') {
14596: &_add_to_env(\%disk_env,$firstaccenv);
14597: }
14598: if (ref($timerintenv) eq 'HASH') {
14599: &_add_to_env(\%disk_env,$timerintenv);
14600: }
14601: if (ref($args->{'extra_env'})) {
14602: &_add_to_env(\%disk_env,$args->{'extra_env'});
14603: }
14604: untie(%disk_env);
14605: } else {
14606: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
14607: 'Could not create environment storage in lonauth: '.$!.'</span>');
14608: return 'error: '.$!;
14609: }
14610: }
14611: $env{'request.role'}='cm';
14612: $env{'request.role.adv'}=$env{'user.adv'};
14613: $env{'browser.type'}=$clientbrowser;
14614:
14615: return $cookie;
14616:
14617: }
14618:
14619: sub _add_to_env {
14620: my ($idf,$env_data,$prefix) = @_;
14621: if (ref($env_data) eq 'HASH') {
14622: while (my ($key,$value) = each(%$env_data)) {
14623: $idf->{$prefix.$key} = $value;
14624: $env{$prefix.$key} = $value;
14625: }
14626: }
14627: }
14628:
14629: # --- Get the symbolic name of a problem and the url
14630: sub get_symb {
14631: my ($request,$silent) = @_;
14632: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
14633: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
14634: if ($symb eq '') {
14635: if (!$silent) {
14636: if (ref($request)) {
14637: $request->print("Unable to handle ambiguous references:$url:.");
14638: }
14639: return ();
14640: }
14641: }
14642: &Apache::lonenc::check_decrypt(\$symb);
14643: return ($symb);
14644: }
14645:
14646: # --------------------------------------------------------------Get annotation
14647:
14648: sub get_annotation {
14649: my ($symb,$enc) = @_;
14650:
14651: my $key = $symb;
14652: if (!$enc) {
14653: $key =
14654: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
14655: }
14656: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
14657: return $annotation{$key};
14658: }
14659:
14660: sub clean_symb {
14661: my ($symb,$delete_enc) = @_;
14662:
14663: &Apache::lonenc::check_decrypt(\$symb);
14664: my $enc = $env{'request.enc'};
14665: if ($delete_enc) {
14666: delete($env{'request.enc'});
14667: }
14668:
14669: return ($symb,$enc);
14670: }
14671:
14672: sub build_release_hashes {
14673: my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
14674: return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
14675: (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
14676: (ref($randomizetry) eq 'HASH'));
14677: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14678: my ($item,$name,$value) = split(/:/,$key);
14679: if ($item eq 'parameter') {
14680: if (ref($checkparms->{$name}) eq 'ARRAY') {
14681: unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
14682: push(@{$checkparms->{$name}},$value);
14683: }
14684: } else {
14685: push(@{$checkparms->{$name}},$value);
14686: }
14687: } elsif ($item eq 'resourcetag') {
14688: if ($name eq 'responsetype') {
14689: $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
14690: }
14691: } elsif ($item eq 'course') {
14692: if ($name eq 'crstype') {
14693: $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
14694: }
14695: }
14696: }
14697: ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
14698: ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
14699: return;
14700: }
14701:
14702: sub update_content_constraints {
14703: my ($cdom,$cnum,$chome,$cid) = @_;
14704: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
14705: my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
14706: my %checkresponsetypes;
14707: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14708: my ($item,$name,$value) = split(/:/,$key);
14709: if ($item eq 'resourcetag') {
14710: if ($name eq 'responsetype') {
14711: $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
14712: }
14713: }
14714: }
14715: my $navmap = Apache::lonnavmaps::navmap->new();
14716: if (defined($navmap)) {
14717: my %allresponses;
14718: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
14719: my %responses = $res->responseTypes();
14720: foreach my $key (keys(%responses)) {
14721: next unless(exists($checkresponsetypes{$key}));
14722: $allresponses{$key} += $responses{$key};
14723: }
14724: }
14725: foreach my $key (keys(%allresponses)) {
14726: my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
14727: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
14728: ($reqdmajor,$reqdminor) = ($major,$minor);
14729: }
14730: }
14731: undef($navmap);
14732: }
14733: unless (($reqdmajor eq '') && ($reqdminor eq '')) {
14734: &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
14735: }
14736: return;
14737: }
14738:
14739: sub allmaps_incourse {
14740: my ($cdom,$cnum,$chome,$cid) = @_;
14741: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
14742: $cid = $env{'request.course.id'};
14743: $cdom = $env{'course.'.$cid.'.domain'};
14744: $cnum = $env{'course.'.$cid.'.num'};
14745: $chome = $env{'course.'.$cid.'.home'};
14746: }
14747: my %allmaps = ();
14748: my $lastchange =
14749: &Apache::lonnet::get_coursechange($cdom,$cnum);
14750: if ($lastchange > $env{'request.course.tied'}) {
14751: my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
14752: unless ($ferr) {
14753: &update_content_constraints($cdom,$cnum,$chome,$cid);
14754: }
14755: }
14756: my $navmap = Apache::lonnavmaps::navmap->new();
14757: if (defined($navmap)) {
14758: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
14759: $allmaps{$res->src()} = 1;
14760: }
14761: }
14762: return \%allmaps;
14763: }
14764:
14765: sub parse_supplemental_title {
14766: my ($title) = @_;
14767:
14768: my ($foldertitle,$renametitle);
14769: if ($title =~ /&&&/) {
14770: $title = &HTML::Entites::decode($title);
14771: }
14772: if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
14773: $renametitle=$4;
14774: my ($time,$uname,$udom) = ($1,$2,$3);
14775: $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
14776: my $name = &plainname($uname,$udom);
14777: $name = &HTML::Entities::encode($name,'"<>&\'');
14778: $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
14779: $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
14780: $name.': <br />'.$foldertitle;
14781: }
14782: if (wantarray) {
14783: return ($title,$foldertitle,$renametitle);
14784: }
14785: return $title;
14786: }
14787:
14788: sub recurse_supplemental {
14789: my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
14790: if ($suppmap) {
14791: my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
14792: if ($fatal) {
14793: $errors ++;
14794: } else {
14795: if ($#LONCAPA::map::resources > 0) {
14796: foreach my $res (@LONCAPA::map::resources) {
14797: my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
14798: if (($src ne '') && ($status eq 'res')) {
14799: if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
14800: ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
14801: } else {
14802: $numfiles ++;
14803: }
14804: }
14805: }
14806: }
14807: }
14808: }
14809: return ($numfiles,$errors);
14810: }
14811:
14812: sub symb_to_docspath {
14813: my ($symb) = @_;
14814: return unless ($symb);
14815: my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
14816: if ($resurl=~/\.(sequence|page)$/) {
14817: $mapurl=$resurl;
14818: } elsif ($resurl eq 'adm/navmaps') {
14819: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
14820: }
14821: my $mapresobj;
14822: my $navmap = Apache::lonnavmaps::navmap->new();
14823: if (ref($navmap)) {
14824: $mapresobj = $navmap->getResourceByUrl($mapurl);
14825: }
14826: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
14827: my $type=$2;
14828: my $path;
14829: if (ref($mapresobj)) {
14830: my $pcslist = $mapresobj->map_hierarchy();
14831: if ($pcslist ne '') {
14832: foreach my $pc (split(/,/,$pcslist)) {
14833: next if ($pc <= 1);
14834: my $res = $navmap->getByMapPc($pc);
14835: if (ref($res)) {
14836: my $thisurl = $res->src();
14837: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
14838: my $thistitle = $res->title();
14839: $path .= '&'.
14840: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
14841: &escape($thistitle).
14842: ':'.$res->randompick().
14843: ':'.$res->randomout().
14844: ':'.$res->encrypted().
14845: ':'.$res->randomorder().
14846: ':'.$res->is_page();
14847: }
14848: }
14849: }
14850: $path =~ s/^\&//;
14851: my $maptitle = $mapresobj->title();
14852: if ($mapurl eq 'default') {
14853: $maptitle = 'Main Content';
14854: }
14855: $path .= (($path ne '')? '&' : '').
14856: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14857: &escape($maptitle).
14858: ':'.$mapresobj->randompick().
14859: ':'.$mapresobj->randomout().
14860: ':'.$mapresobj->encrypted().
14861: ':'.$mapresobj->randomorder().
14862: ':'.$mapresobj->is_page();
14863: } else {
14864: my $maptitle = &Apache::lonnet::gettitle($mapurl);
14865: my $ispage = (($type eq 'page')? 1 : '');
14866: if ($mapurl eq 'default') {
14867: $maptitle = 'Main Content';
14868: }
14869: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14870: &escape($maptitle).':::::'.$ispage;
14871: }
14872: unless ($mapurl eq 'default') {
14873: $path = 'default&'.
14874: &escape('Main Content').
14875: ':::::&'.$path;
14876: }
14877: return $path;
14878: }
14879:
14880: sub captcha_display {
14881: my ($context,$lonhost) = @_;
14882: my ($output,$error);
14883: my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14884: if ($captcha eq 'original') {
14885: $output = &create_captcha();
14886: unless ($output) {
14887: $error = 'captcha';
14888: }
14889: } elsif ($captcha eq 'recaptcha') {
14890: $output = &create_recaptcha($pubkey);
14891: unless ($output) {
14892: $error = 'recaptcha';
14893: }
14894: }
14895: return ($output,$error);
14896: }
14897:
14898: sub captcha_response {
14899: my ($context,$lonhost) = @_;
14900: my ($captcha_chk,$captcha_error);
14901: my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14902: if ($captcha eq 'original') {
14903: ($captcha_chk,$captcha_error) = &check_captcha();
14904: } elsif ($captcha eq 'recaptcha') {
14905: $captcha_chk = &check_recaptcha($privkey);
14906: } else {
14907: $captcha_chk = 1;
14908: }
14909: return ($captcha_chk,$captcha_error);
14910: }
14911:
14912: sub get_captcha_config {
14913: my ($context,$lonhost) = @_;
14914: my ($captcha,$pubkey,$privkey,$hashtocheck);
14915: my $hostname = &Apache::lonnet::hostname($lonhost);
14916: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
14917: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
14918: if ($context eq 'usercreation') {
14919: my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
14920: if (ref($domconfig{$context}) eq 'HASH') {
14921: $hashtocheck = $domconfig{$context}{'cancreate'};
14922: if (ref($hashtocheck) eq 'HASH') {
14923: if ($hashtocheck->{'captcha'} eq 'recaptcha') {
14924: if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
14925: $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
14926: $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
14927: }
14928: if ($privkey && $pubkey) {
14929: $captcha = 'recaptcha';
14930: } else {
14931: $captcha = 'original';
14932: }
14933: } elsif ($hashtocheck->{'captcha'} ne 'notused') {
14934: $captcha = 'original';
14935: }
14936: }
14937: } else {
14938: $captcha = 'captcha';
14939: }
14940: } elsif ($context eq 'login') {
14941: my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
14942: if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
14943: $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
14944: $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
14945: if ($privkey && $pubkey) {
14946: $captcha = 'recaptcha';
14947: } else {
14948: $captcha = 'original';
14949: }
14950: } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
14951: $captcha = 'original';
14952: }
14953: }
14954: return ($captcha,$pubkey,$privkey);
14955: }
14956:
14957: sub create_captcha {
14958: my %captcha_params = &captcha_settings();
14959: my ($output,$maxtries,$tries) = ('',10,0);
14960: while ($tries < $maxtries) {
14961: $tries ++;
14962: my $captcha = Authen::Captcha->new (
14963: output_folder => $captcha_params{'output_dir'},
14964: data_folder => $captcha_params{'db_dir'},
14965: );
14966: my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
14967:
14968: if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
14969: $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
14970: &mt('Type in the letters/numbers shown below').' '.
14971: '<input type="text" size="5" name="code" value="" /><br />'.
14972: '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
14973: last;
14974: }
14975: }
14976: return $output;
14977: }
14978:
14979: sub captcha_settings {
14980: my %captcha_params = (
14981: output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'},
14982: www_output_dir => "/captchaspool",
14983: db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'},
14984: numchars => '5',
14985: );
14986: return %captcha_params;
14987: }
14988:
14989: sub check_captcha {
14990: my ($captcha_chk,$captcha_error);
14991: my $code = $env{'form.code'};
14992: my $md5sum = $env{'form.crypt'};
14993: my %captcha_params = &captcha_settings();
14994: my $captcha = Authen::Captcha->new(
14995: output_folder => $captcha_params{'output_dir'},
14996: data_folder => $captcha_params{'db_dir'},
14997: );
14998: $captcha_chk = $captcha->check_code($code,$md5sum);
14999: my %captcha_hash = (
15000: 0 => 'Code not checked (file error)',
15001: -1 => 'Failed: code expired',
15002: -2 => 'Failed: invalid code (not in database)',
15003: -3 => 'Failed: invalid code (code does not match crypt)',
15004: );
15005: if ($captcha_chk != 1) {
15006: $captcha_error = $captcha_hash{$captcha_chk}
15007: }
15008: return ($captcha_chk,$captcha_error);
15009: }
15010:
15011: sub create_recaptcha {
15012: my ($pubkey) = @_;
15013: my $use_ssl;
15014: if ($ENV{'SERVER_PORT'} == 443) {
15015: $use_ssl = 1;
15016: }
15017: my $captcha = Captcha::reCAPTCHA->new;
15018: return $captcha->get_options_setter({theme => 'white'})."\n".
15019: $captcha->get_html($pubkey,undef,$use_ssl).
15020: &mt('If either word is hard to read, [_1] will replace them.',
15021: '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
15022: '<br /><br />';
15023: }
15024:
15025: sub check_recaptcha {
15026: my ($privkey) = @_;
15027: my $captcha_chk;
15028: my $captcha = Captcha::reCAPTCHA->new;
15029: my $captcha_result =
15030: $captcha->check_answer(
15031: $privkey,
15032: $ENV{'REMOTE_ADDR'},
15033: $env{'form.recaptcha_challenge_field'},
15034: $env{'form.recaptcha_response_field'},
15035: );
15036: if ($captcha_result->{is_valid}) {
15037: $captcha_chk = 1;
15038: }
15039: return $captcha_chk;
15040: }
15041:
15042: sub cleanup_html {
15043: my ($incoming) = @_;
15044: my $outgoing;
15045: if ($incoming ne '') {
15046: $outgoing = $incoming;
15047: $outgoing =~ s/;/;/g;
15048: $outgoing =~ s/\#/#/g;
15049: $outgoing =~ s/\&/&/g;
15050: $outgoing =~ s/</</g;
15051: $outgoing =~ s/>/>/g;
15052: $outgoing =~ s/\(/(/g;
15053: $outgoing =~ s/\)/)/g;
15054: $outgoing =~ s/"/"/g;
15055: $outgoing =~ s/'/'/g;
15056: $outgoing =~ s/\$/$/g;
15057: $outgoing =~ s{/}{/}g;
15058: $outgoing =~ s/=/=/g;
15059: $outgoing =~ s/\\/\/g
15060: }
15061: return $outgoing;
15062: }
15063:
15064: =pod
15065:
15066: =back
15067:
15068: =cut
15069:
15070: 1;
15071: __END__;
15072:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>