File:
[LON-CAPA] /
loncom /
interface /
loncommon.pm
Revision
1.1203:
download - view:
text,
annotated -
select for diffs
Sat Dec 20 15:35:40 2014 UTC (9 years, 8 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Accommodate single quotes in resource URL in "Stored Links" and in "Edit" link
- Accommodate single quotes in URLs in options in "Select Recent" dropdown list
when browsing Resource Space.
- Consistent escaping of special characters for Stored Links added when displaying
a resource in a course, and when browsing Resource Space.
1: # The LearningOnline Network with CAPA
2: # a pile of common routines
3: #
4: # $Id: loncommon.pm,v 1.1203 2014/12/20 15:35:40 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28:
29: # Makes a table out of the previous attempts
30: # Inputs result_from_symbread, user, domain, course_id
31: # Reads in non-network-related .tab files
32:
33: # POD header:
34:
35: =pod
36:
37: =head1 NAME
38:
39: Apache::loncommon - pile of common routines
40:
41: =head1 SYNOPSIS
42:
43: Common routines for manipulating connections, student answers,
44: domains, common Javascript fragments, etc.
45:
46: =head1 OVERVIEW
47:
48: A collection of commonly used subroutines that don't have a natural
49: home anywhere else. This collection helps remove
50: redundancy from other modules and increase efficiency of memory usage.
51:
52: =cut
53:
54: # End of POD header
55: package Apache::loncommon;
56:
57: use strict;
58: use Apache::lonnet;
59: use GDBM_File;
60: use POSIX qw(strftime mktime);
61: use Apache::lonmenu();
62: use Apache::lonenc();
63: use Apache::lonlocal;
64: use Apache::lonnet();
65: use HTML::Entities;
66: use Apache::lonhtmlcommon();
67: use Apache::loncoursedata();
68: use Apache::lontexconvert();
69: use Apache::lonclonecourse();
70: use Apache::lonuserutils();
71: use Apache::lonuserstate();
72: use Apache::courseclassifier();
73: use LONCAPA qw(:DEFAULT :match);
74: use DateTime::TimeZone;
75: use DateTime::Locale::Catalog;
76: use Text::Aspell;
77: use Authen::Captcha;
78: use Captcha::reCAPTCHA;
79: use Crypt::DES;
80: use DynaLoader; # for Crypt::DES version
81:
82: # ---------------------------------------------- Designs
83: use vars qw(%defaultdesign);
84:
85: my $readit;
86:
87:
88: ##
89: ## Global Variables
90: ##
91:
92:
93: # ----------------------------------------------- SSI with retries:
94: #
95:
96: =pod
97:
98: =head1 Server Side include with retries:
99:
100: =over 4
101:
102: =item * &ssi_with_retries(resource,retries form)
103:
104: Performs an ssi with some number of retries. Retries continue either
105: until the result is ok or until the retry count supplied by the
106: caller is exhausted.
107:
108: Inputs:
109:
110: =over 4
111:
112: resource - Identifies the resource to insert.
113:
114: retries - Count of the number of retries allowed.
115:
116: form - Hash that identifies the rendering options.
117:
118: =back
119:
120: Returns:
121:
122: =over 4
123:
124: content - The content of the response. If retries were exhausted this is empty.
125:
126: response - The response from the last attempt (which may or may not have been successful.
127:
128: =back
129:
130: =back
131:
132: =cut
133:
134: sub ssi_with_retries {
135: my ($resource, $retries, %form) = @_;
136:
137:
138: my $ok = 0; # True if we got a good response.
139: my $content;
140: my $response;
141:
142: # Try to get the ssi done. within the retries count:
143:
144: do {
145: ($content, $response) = &Apache::lonnet::ssi($resource, %form);
146: $ok = $response->is_success;
147: if (!$ok) {
148: &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
149: }
150: $retries--;
151: } while (!$ok && ($retries > 0));
152:
153: if (!$ok) {
154: $content = ''; # On error return an empty content.
155: }
156: return ($content, $response);
157:
158: }
159:
160:
161:
162: # ----------------------------------------------- Filetypes/Languages/Copyright
163: my %language;
164: my %supported_language;
165: my %supported_codes;
166: my %latex_language; # For choosing hyphenation in <transl..>
167: my %latex_language_bykey; # for choosing hyphenation from metadata
168: my %cprtag;
169: my %scprtag;
170: my %fe; my %fd; my %fm;
171: my %category_extensions;
172:
173: # ---------------------------------------------- Thesaurus variables
174: #
175: # %Keywords:
176: # A hash used by &keyword to determine if a word is considered a keyword.
177: # $thesaurus_db_file
178: # Scalar containing the full path to the thesaurus database.
179:
180: my %Keywords;
181: my $thesaurus_db_file;
182:
183: #
184: # Initialize values from language.tab, copyright.tab, filetypes.tab,
185: # thesaurus.tab, and filecategories.tab.
186: #
187: BEGIN {
188: # Variable initialization
189: $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
190: #
191: unless ($readit) {
192: # ------------------------------------------------------------------- languages
193: {
194: my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
195: '/language.tab';
196: if ( open(my $fh,"<$langtabfile") ) {
197: while (my $line = <$fh>) {
198: next if ($line=~/^\#/);
199: chomp($line);
200: my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
201: $language{$key}=$val.' - '.$enc;
202: if ($sup) {
203: $supported_language{$key}=$sup;
204: $supported_codes{$key} = $code;
205: }
206: if ($latex) {
207: $latex_language_bykey{$key} = $latex;
208: $latex_language{$code} = $latex;
209: }
210: }
211: close($fh);
212: }
213: }
214: # ------------------------------------------------------------------ copyrights
215: {
216: my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
217: '/copyright.tab';
218: if ( open (my $fh,"<$copyrightfile") ) {
219: while (my $line = <$fh>) {
220: next if ($line=~/^\#/);
221: chomp($line);
222: my ($key,$val)=(split(/\s+/,$line,2));
223: $cprtag{$key}=$val;
224: }
225: close($fh);
226: }
227: }
228: # ----------------------------------------------------------- source copyrights
229: {
230: my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
231: '/source_copyright.tab';
232: if ( open (my $fh,"<$sourcecopyrightfile") ) {
233: while (my $line = <$fh>) {
234: next if ($line =~ /^\#/);
235: chomp($line);
236: my ($key,$val)=(split(/\s+/,$line,2));
237: $scprtag{$key}=$val;
238: }
239: close($fh);
240: }
241: }
242:
243: # -------------------------------------------------------------- default domain designs
244: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
245: my $designfile = $designdir.'/default.tab';
246: if ( open (my $fh,"<$designfile") ) {
247: while (my $line = <$fh>) {
248: next if ($line =~ /^\#/);
249: chomp($line);
250: my ($key,$val)=(split(/\=/,$line));
251: if ($val) { $defaultdesign{$key}=$val; }
252: }
253: close($fh);
254: }
255:
256: # ------------------------------------------------------------- file categories
257: {
258: my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
259: '/filecategories.tab';
260: if ( open (my $fh,"<$categoryfile") ) {
261: while (my $line = <$fh>) {
262: next if ($line =~ /^\#/);
263: chomp($line);
264: my ($extension,$category)=(split(/\s+/,$line,2));
265: push @{$category_extensions{lc($category)}},$extension;
266: }
267: close($fh);
268: }
269:
270: }
271: # ------------------------------------------------------------------ file types
272: {
273: my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
274: '/filetypes.tab';
275: if ( open (my $fh,"<$typesfile") ) {
276: while (my $line = <$fh>) {
277: next if ($line =~ /^\#/);
278: chomp($line);
279: my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
280: if ($descr ne '') {
281: $fe{$ending}=lc($emb);
282: $fd{$ending}=$descr;
283: if ($mime ne 'unk') { $fm{$ending}=$mime; }
284: }
285: }
286: close($fh);
287: }
288: }
289: &Apache::lonnet::logthis(
290: "<span style='color:yellow;'>INFO: Read file types</span>");
291: $readit=1;
292: } # end of unless($readit)
293:
294: }
295:
296: ###############################################################
297: ## HTML and Javascript Helper Functions ##
298: ###############################################################
299:
300: =pod
301:
302: =head1 HTML and Javascript Functions
303:
304: =over 4
305:
306: =item * &browser_and_searcher_javascript()
307:
308: X<browsing, javascript>X<searching, javascript>Returns a string
309: containing javascript with two functions, C<openbrowser> and
310: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
311: tags.
312:
313: =item * &openbrowser(formname,elementname,only,omit) [javascript]
314:
315: inputs: formname, elementname, only, omit
316:
317: formname and elementname indicate the name of the html form and name of
318: the element that the results of the browsing selection are to be placed in.
319:
320: Specifying 'only' will restrict the browser to displaying only files
321: with the given extension. Can be a comma separated list.
322:
323: Specifying 'omit' will restrict the browser to NOT displaying files
324: with the given extension. Can be a comma separated list.
325:
326: =item * &opensearcher(formname,elementname) [javascript]
327:
328: Inputs: formname, elementname
329:
330: formname and elementname specify the name of the html form and the name
331: of the element the selection from the search results will be placed in.
332:
333: =cut
334:
335: sub browser_and_searcher_javascript {
336: my ($mode)=@_;
337: if (!defined($mode)) { $mode='edit'; }
338: my $resurl=&escape_single(&lastresurl());
339: return <<END;
340: // <!-- BEGIN LON-CAPA Internal
341: var editbrowser = null;
342: function openbrowser(formname,elementname,only,omit,titleelement) {
343: var url = '$resurl/?';
344: if (editbrowser == null) {
345: url += 'launch=1&';
346: }
347: url += 'catalogmode=interactive&';
348: url += 'mode=$mode&';
349: url += 'inhibitmenu=yes&';
350: url += 'form=' + formname + '&';
351: if (only != null) {
352: url += 'only=' + only + '&';
353: } else {
354: url += 'only=&';
355: }
356: if (omit != null) {
357: url += 'omit=' + omit + '&';
358: } else {
359: url += 'omit=&';
360: }
361: if (titleelement != null) {
362: url += 'titleelement=' + titleelement + '&';
363: } else {
364: url += 'titleelement=&';
365: }
366: url += 'element=' + elementname + '';
367: var title = 'Browser';
368: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
369: options += ',width=700,height=600';
370: editbrowser = open(url,title,options,'1');
371: editbrowser.focus();
372: }
373: var editsearcher;
374: function opensearcher(formname,elementname,titleelement) {
375: var url = '/adm/searchcat?';
376: if (editsearcher == null) {
377: url += 'launch=1&';
378: }
379: url += 'catalogmode=interactive&';
380: url += 'mode=$mode&';
381: url += 'form=' + formname + '&';
382: if (titleelement != null) {
383: url += 'titleelement=' + titleelement + '&';
384: } else {
385: url += 'titleelement=&';
386: }
387: url += 'element=' + elementname + '';
388: var title = 'Search';
389: var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
390: options += ',width=700,height=600';
391: editsearcher = open(url,title,options,'1');
392: editsearcher.focus();
393: }
394: // END LON-CAPA Internal -->
395: END
396: }
397:
398: sub lastresurl {
399: if ($env{'environment.lastresurl'}) {
400: return $env{'environment.lastresurl'}
401: } else {
402: return '/res';
403: }
404: }
405:
406: sub storeresurl {
407: my $resurl=&Apache::lonnet::clutter(shift);
408: unless ($resurl=~/^\/res/) { return 0; }
409: $resurl=~s/\/$//;
410: &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
411: &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
412: return 1;
413: }
414:
415: sub studentbrowser_javascript {
416: unless (
417: (($env{'request.course.id'}) &&
418: (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
419: || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
420: '/'.$env{'request.course.sec'})
421: ))
422: || ($env{'request.role'}=~/^(au|dc|su)/)
423: ) { return ''; }
424: return (<<'ENDSTDBRW');
425: <script type="text/javascript" language="Javascript">
426: // <![CDATA[
427: var stdeditbrowser;
428: function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
429: var url = '/adm/pickstudent?';
430: var filter;
431: if (!ignorefilter) {
432: eval('filter=document.'+formname+'.'+uname+'.value;');
433: }
434: if (filter != null) {
435: if (filter != '') {
436: url += 'filter='+filter+'&';
437: }
438: }
439: url += 'form=' + formname + '&unameelement='+uname+
440: '&udomelement='+udom+
441: '&clicker='+clicker;
442: if (roleflag) { url+="&roles=1"; }
443: if (courseadvonly) { url+="&courseadvonly=1"; }
444: var title = 'Student_Browser';
445: var options = 'scrollbars=1,resizable=1,menubar=0';
446: options += ',width=700,height=600';
447: stdeditbrowser = open(url,title,options,'1');
448: stdeditbrowser.focus();
449: }
450: // ]]>
451: </script>
452: ENDSTDBRW
453: }
454:
455: sub resourcebrowser_javascript {
456: unless ($env{'request.course.id'}) { return ''; }
457: return (<<'ENDRESBRW');
458: <script type="text/javascript" language="Javascript">
459: // <![CDATA[
460: var reseditbrowser;
461: function openresbrowser(formname,reslink) {
462: var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
463: var title = 'Resource_Browser';
464: var options = 'scrollbars=1,resizable=1,menubar=0';
465: options += ',width=700,height=500';
466: reseditbrowser = open(url,title,options,'1');
467: reseditbrowser.focus();
468: }
469: // ]]>
470: </script>
471: ENDRESBRW
472: }
473:
474: sub selectstudent_link {
475: my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
476: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
477: &Apache::lonhtmlcommon::entity_encode($unameele)."','".
478: &Apache::lonhtmlcommon::entity_encode($udomele)."'";
479: if ($env{'request.course.id'}) {
480: if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
481: && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
482: '/'.$env{'request.course.sec'})) {
483: return '';
484: }
485: $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
486: if ($courseadvonly) {
487: $callargs .= ",'',1,1";
488: }
489: return '<span class="LC_nobreak">'.
490: '<a href="javascript:openstdbrowser('.$callargs.');">'.
491: &mt('Select User').'</a></span>';
492: }
493: if ($env{'request.role'}=~/^(au|dc|su)/) {
494: $callargs .= ",'',1";
495: return '<span class="LC_nobreak">'.
496: '<a href="javascript:openstdbrowser('.$callargs.');">'.
497: &mt('Select User').'</a></span>';
498: }
499: return '';
500: }
501:
502: sub selectresource_link {
503: my ($form,$reslink,$arg)=@_;
504:
505: my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
506: &Apache::lonhtmlcommon::entity_encode($reslink)."'";
507: unless ($env{'request.course.id'}) { return $arg; }
508: return '<span class="LC_nobreak">'.
509: '<a href="javascript:openresbrowser('.$callargs.');">'.
510: $arg.'</a></span>';
511: }
512:
513:
514:
515: sub authorbrowser_javascript {
516: return <<"ENDAUTHORBRW";
517: <script type="text/javascript" language="JavaScript">
518: // <![CDATA[
519: var stdeditbrowser;
520:
521: function openauthorbrowser(formname,udom) {
522: var url = '/adm/pickauthor?';
523: url += 'form='+formname+'&roledom='+udom;
524: var title = 'Author_Browser';
525: var options = 'scrollbars=1,resizable=1,menubar=0';
526: options += ',width=700,height=600';
527: stdeditbrowser = open(url,title,options,'1');
528: stdeditbrowser.focus();
529: }
530:
531: // ]]>
532: </script>
533: ENDAUTHORBRW
534: }
535:
536: sub coursebrowser_javascript {
537: my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
538: $credits_element) = @_;
539: my $wintitle = 'Course_Browser';
540: if ($crstype eq 'Community') {
541: $wintitle = 'Community_Browser';
542: }
543: my $id_functions = &javascript_index_functions();
544: my $output = '
545: <script type="text/javascript" language="JavaScript">
546: // <![CDATA[
547: var stdeditbrowser;'."\n";
548:
549: $output .= <<"ENDSTDBRW";
550: function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
551: var url = '/adm/pickcourse?';
552: var formid = getFormIdByName(formname);
553: var domainfilter = getDomainFromSelectbox(formname,udom);
554: if (domainfilter != null) {
555: if (domainfilter != '') {
556: url += 'domainfilter='+domainfilter+'&';
557: }
558: }
559: url += 'form=' + formname + '&cnumelement='+uname+
560: '&cdomelement='+udom+
561: '&cnameelement='+desc;
562: if (extra_element !=null && extra_element != '') {
563: if (formname == 'rolechoice' || formname == 'studentform') {
564: url += '&roleelement='+extra_element;
565: if (domainfilter == null || domainfilter == '') {
566: url += '&domainfilter='+extra_element;
567: }
568: }
569: else {
570: if (formname == 'portform') {
571: url += '&setroles='+extra_element;
572: } else {
573: if (formname == 'rules') {
574: url += '&fixeddom='+extra_element;
575: }
576: }
577: }
578: }
579: if (type != null && type != '') {
580: url += '&type='+type;
581: }
582: if (type_elem != null && type_elem != '') {
583: url += '&typeelement='+type_elem;
584: }
585: if (formname == 'ccrs') {
586: var ownername = document.forms[formid].ccuname.value;
587: var ownerdom = document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
588: url += '&cloner='+ownername+':'+ownerdom;
589: }
590: if (multflag !=null && multflag != '') {
591: url += '&multiple='+multflag;
592: }
593: var title = '$wintitle';
594: var options = 'scrollbars=1,resizable=1,menubar=0';
595: options += ',width=700,height=600';
596: stdeditbrowser = open(url,title,options,'1');
597: stdeditbrowser.focus();
598: }
599: $id_functions
600: ENDSTDBRW
601: if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
602: $output .= &setsec_javascript($sec_element,$formname,$role_element,
603: $credits_element);
604: }
605: $output .= '
606: // ]]>
607: </script>';
608: return $output;
609: }
610:
611: sub javascript_index_functions {
612: return <<"ENDJS";
613:
614: function getFormIdByName(formname) {
615: for (var i=0;i<document.forms.length;i++) {
616: if (document.forms[i].name == formname) {
617: return i;
618: }
619: }
620: return -1;
621: }
622:
623: function getIndexByName(formid,item) {
624: for (var i=0;i<document.forms[formid].elements.length;i++) {
625: if (document.forms[formid].elements[i].name == item) {
626: return i;
627: }
628: }
629: return -1;
630: }
631:
632: function getDomainFromSelectbox(formname,udom) {
633: var userdom;
634: var formid = getFormIdByName(formname);
635: if (formid > -1) {
636: var domid = getIndexByName(formid,udom);
637: if (domid > -1) {
638: if (document.forms[formid].elements[domid].type == 'select-one') {
639: userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
640: }
641: if (document.forms[formid].elements[domid].type == 'hidden') {
642: userdom=document.forms[formid].elements[domid].value;
643: }
644: }
645: }
646: return userdom;
647: }
648:
649: ENDJS
650:
651: }
652:
653: sub javascript_array_indexof {
654: return <<ENDJS;
655: <script type="text/javascript" language="JavaScript">
656: // <![CDATA[
657:
658: if (!Array.prototype.indexOf) {
659: Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
660: "use strict";
661: if (this === void 0 || this === null) {
662: throw new TypeError();
663: }
664: var t = Object(this);
665: var len = t.length >>> 0;
666: if (len === 0) {
667: return -1;
668: }
669: var n = 0;
670: if (arguments.length > 0) {
671: n = Number(arguments[1]);
672: if (n !== n) { // shortcut for verifying if it is NaN
673: n = 0;
674: } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
675: n = (n > 0 || -1) * Math.floor(Math.abs(n));
676: }
677: }
678: if (n >= len) {
679: return -1;
680: }
681: var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
682: for (; k < len; k++) {
683: if (k in t && t[k] === searchElement) {
684: return k;
685: }
686: }
687: return -1;
688: }
689: }
690:
691: // ]]>
692: </script>
693:
694: ENDJS
695:
696: }
697:
698: sub userbrowser_javascript {
699: my $id_functions = &javascript_index_functions();
700: return <<"ENDUSERBRW";
701:
702: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
703: var url = '/adm/pickuser?';
704: var userdom = getDomainFromSelectbox(formname,udom);
705: if (userdom != null) {
706: if (userdom != '') {
707: url += 'srchdom='+userdom+'&';
708: }
709: }
710: url += 'form=' + formname + '&unameelement='+uname+
711: '&udomelement='+udom+
712: '&ulastelement='+ulast+
713: '&ufirstelement='+ufirst+
714: '&uemailelement='+uemail+
715: '&hideudomelement='+hideudom+
716: '&coursedom='+crsdom;
717: if ((caller != null) && (caller != undefined)) {
718: url += '&caller='+caller;
719: }
720: var title = 'User_Browser';
721: var options = 'scrollbars=1,resizable=1,menubar=0';
722: options += ',width=700,height=600';
723: var stdeditbrowser = open(url,title,options,'1');
724: stdeditbrowser.focus();
725: }
726:
727: function fix_domain (formname,udom,origdom,uname) {
728: var formid = getFormIdByName(formname);
729: if (formid > -1) {
730: var unameid = getIndexByName(formid,uname);
731: var domid = getIndexByName(formid,udom);
732: var hidedomid = getIndexByName(formid,origdom);
733: if (hidedomid > -1) {
734: var fixeddom = document.forms[formid].elements[hidedomid].value;
735: var unameval = document.forms[formid].elements[unameid].value;
736: if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
737: if (domid > -1) {
738: var slct = document.forms[formid].elements[domid];
739: if (slct.type == 'select-one') {
740: var i;
741: for (i=0;i<slct.length;i++) {
742: if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
743: }
744: }
745: if (slct.type == 'hidden') {
746: slct.value = fixeddom;
747: }
748: }
749: }
750: }
751: }
752: return;
753: }
754:
755: $id_functions
756: ENDUSERBRW
757: }
758:
759: sub setsec_javascript {
760: my ($sec_element,$formname,$role_element,$credits_element) = @_;
761: my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
762: $communityrolestr);
763: if ($role_element ne '') {
764: my @allroles = ('st','ta','ep','in','ad');
765: foreach my $crstype ('Course','Community') {
766: if ($crstype eq 'Community') {
767: foreach my $role (@allroles) {
768: push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
769: }
770: push(@communityrolenames,&Apache::lonnet::plaintext('co'));
771: } else {
772: foreach my $role (@allroles) {
773: push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
774: }
775: push(@courserolenames,&Apache::lonnet::plaintext('cc'));
776: }
777: }
778: $rolestr = '"'.join('","',@allroles).'"';
779: $courserolestr = '"'.join('","',@courserolenames).'"';
780: $communityrolestr = '"'.join('","',@communityrolenames).'"';
781: }
782: my $setsections = qq|
783: function setSect(sectionlist) {
784: var sectionsArray = new Array();
785: if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
786: sectionsArray = sectionlist.split(",");
787: }
788: var numSections = sectionsArray.length;
789: document.$formname.$sec_element.length = 0;
790: if (numSections == 0) {
791: document.$formname.$sec_element.multiple=false;
792: document.$formname.$sec_element.size=1;
793: document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
794: } else {
795: if (numSections == 1) {
796: document.$formname.$sec_element.multiple=false;
797: document.$formname.$sec_element.size=1;
798: document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
799: document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
800: document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
801: } else {
802: for (var i=0; i<numSections; i++) {
803: document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
804: }
805: document.$formname.$sec_element.multiple=true
806: if (numSections < 3) {
807: document.$formname.$sec_element.size=numSections;
808: } else {
809: document.$formname.$sec_element.size=3;
810: }
811: document.$formname.$sec_element.options[0].selected = false
812: }
813: }
814: }
815:
816: function setRole(crstype) {
817: |;
818: if ($role_element eq '') {
819: $setsections .= ' return;
820: }
821: ';
822: } else {
823: $setsections .= qq|
824: var elementLength = document.$formname.$role_element.length;
825: var allroles = Array($rolestr);
826: var courserolenames = Array($courserolestr);
827: var communityrolenames = Array($communityrolestr);
828: if (elementLength != undefined) {
829: if (document.$formname.$role_element.options[5].value == 'cc') {
830: if (crstype == 'Course') {
831: return;
832: } else {
833: allroles[5] = 'co';
834: for (var i=0; i<6; i++) {
835: document.$formname.$role_element.options[i].value = allroles[i];
836: document.$formname.$role_element.options[i].text = communityrolenames[i];
837: }
838: }
839: } else {
840: if (crstype == 'Community') {
841: return;
842: } else {
843: allroles[5] = 'cc';
844: for (var i=0; i<6; i++) {
845: document.$formname.$role_element.options[i].value = allroles[i];
846: document.$formname.$role_element.options[i].text = courserolenames[i];
847: }
848: }
849: }
850: }
851: return;
852: }
853: |;
854: }
855: if ($credits_element) {
856: $setsections .= qq|
857: function setCredits(defaultcredits) {
858: document.$formname.$credits_element.value = defaultcredits;
859: return;
860: }
861: |;
862: }
863: return $setsections;
864: }
865:
866: sub selectcourse_link {
867: my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
868: $typeelement) = @_;
869: my $type = $selecttype;
870: my $linktext = &mt('Select Course');
871: if ($selecttype eq 'Community') {
872: $linktext = &mt('Select Community');
873: } elsif ($selecttype eq 'Course/Community') {
874: $linktext = &mt('Select Course/Community');
875: $type = '';
876: } elsif ($selecttype eq 'Select') {
877: $linktext = &mt('Select');
878: $type = '';
879: }
880: return '<span class="LC_nobreak">'
881: ."<a href='"
882: .'javascript:opencrsbrowser("'.$form.'","'.$unameele
883: .'","'.$udomele.'","'.$desc.'","'.$extra_element
884: .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
885: ."'>".$linktext.'</a>'
886: .'</span>';
887: }
888:
889: sub selectauthor_link {
890: my ($form,$udom)=@_;
891: return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
892: &mt('Select Author').'</a>';
893: }
894:
895: sub selectuser_link {
896: my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
897: $coursedom,$linktext,$caller) = @_;
898: return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
899: "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
900: ');">'.$linktext.'</a>';
901: }
902:
903: sub check_uncheck_jscript {
904: my $jscript = <<"ENDSCRT";
905: function checkAll(field) {
906: if (field.length > 0) {
907: for (i = 0; i < field.length; i++) {
908: if (!field[i].disabled) {
909: field[i].checked = true;
910: }
911: }
912: } else {
913: if (!field.disabled) {
914: field.checked = true;
915: }
916: }
917: }
918:
919: function uncheckAll(field) {
920: if (field.length > 0) {
921: for (i = 0; i < field.length; i++) {
922: field[i].checked = false ;
923: }
924: } else {
925: field.checked = false ;
926: }
927: }
928: ENDSCRT
929: return $jscript;
930: }
931:
932: sub select_timezone {
933: my ($name,$selected,$onchange,$includeempty)=@_;
934: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
935: if ($includeempty) {
936: $output .= '<option value=""';
937: if (($selected eq '') || ($selected eq 'local')) {
938: $output .= ' selected="selected" ';
939: }
940: $output .= '> </option>';
941: }
942: my @timezones = DateTime::TimeZone->all_names;
943: foreach my $tzone (@timezones) {
944: $output.= '<option value="'.$tzone.'"';
945: if ($tzone eq $selected) {
946: $output.=' selected="selected"';
947: }
948: $output.=">$tzone</option>\n";
949: }
950: $output.="</select>";
951: return $output;
952: }
953:
954: sub select_datelocale {
955: my ($name,$selected,$onchange,$includeempty)=@_;
956: my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
957: if ($includeempty) {
958: $output .= '<option value=""';
959: if ($selected eq '') {
960: $output .= ' selected="selected" ';
961: }
962: $output .= '> </option>';
963: }
964: my (@possibles,%locale_names);
965: my @locales = DateTime::Locale::Catalog::Locales;
966: foreach my $locale (@locales) {
967: if (ref($locale) eq 'HASH') {
968: my $id = $locale->{'id'};
969: if ($id ne '') {
970: my $en_terr = $locale->{'en_territory'};
971: my $native_terr = $locale->{'native_territory'};
972: my @languages = &Apache::lonlocal::preferred_languages();
973: if (grep(/^en$/,@languages) || !@languages) {
974: if ($en_terr ne '') {
975: $locale_names{$id} = '('.$en_terr.')';
976: } elsif ($native_terr ne '') {
977: $locale_names{$id} = $native_terr;
978: }
979: } else {
980: if ($native_terr ne '') {
981: $locale_names{$id} = $native_terr.' ';
982: } elsif ($en_terr ne '') {
983: $locale_names{$id} = '('.$en_terr.')';
984: }
985: }
986: push (@possibles,$id);
987: }
988: }
989: }
990: foreach my $item (sort(@possibles)) {
991: $output.= '<option value="'.$item.'"';
992: if ($item eq $selected) {
993: $output.=' selected="selected"';
994: }
995: $output.=">$item";
996: if ($locale_names{$item} ne '') {
997: $output.=" $locale_names{$item}</option>\n";
998: }
999: $output.="</option>\n";
1000: }
1001: $output.="</select>";
1002: return $output;
1003: }
1004:
1005: sub select_language {
1006: my ($name,$selected,$includeempty) = @_;
1007: my %langchoices;
1008: if ($includeempty) {
1009: %langchoices = ('' => 'No language preference');
1010: }
1011: foreach my $id (&languageids()) {
1012: my $code = &supportedlanguagecode($id);
1013: if ($code) {
1014: $langchoices{$code} = &plainlanguagedescription($id);
1015: }
1016: }
1017: %langchoices = &Apache::lonlocal::texthash(%langchoices);
1018: return &select_form($selected,$name,\%langchoices);
1019: }
1020:
1021: =pod
1022:
1023:
1024: =item * &list_languages()
1025:
1026: Returns an array reference that is suitable for use in language prompters.
1027: Each array element is itself a two element array. The first element
1028: is the language code. The second element a descsriptiuon of the
1029: language itself. This is suitable for use in e.g.
1030: &Apache::edit::select_arg (once dereferenced that is).
1031:
1032: =cut
1033:
1034: sub list_languages {
1035: my @lang_choices;
1036:
1037: foreach my $id (&languageids()) {
1038: my $code = &supportedlanguagecode($id);
1039: if ($code) {
1040: my $selector = $supported_codes{$id};
1041: my $description = &plainlanguagedescription($id);
1042: push (@lang_choices, [$selector, $description]);
1043: }
1044: }
1045: return \@lang_choices;
1046: }
1047:
1048: =pod
1049:
1050: =item * &linked_select_forms(...)
1051:
1052: linked_select_forms returns a string containing a <script></script> block
1053: and html for two <select> menus. The select menus will be linked in that
1054: changing the value of the first menu will result in new values being placed
1055: in the second menu. The values in the select menu will appear in alphabetical
1056: order unless a defined order is provided.
1057:
1058: linked_select_forms takes the following ordered inputs:
1059:
1060: =over 4
1061:
1062: =item * $formname, the name of the <form> tag
1063:
1064: =item * $middletext, the text which appears between the <select> tags
1065:
1066: =item * $firstdefault, the default value for the first menu
1067:
1068: =item * $firstselectname, the name of the first <select> tag
1069:
1070: =item * $secondselectname, the name of the second <select> tag
1071:
1072: =item * $hashref, a reference to a hash containing the data for the menus.
1073:
1074: =item * $menuorder, the order of values in the first menu
1075:
1076: =item * $onchangefirst, additional javascript call to execute for an onchange
1077: event for the first <select> tag
1078:
1079: =item * $onchangesecond, additional javascript call to execute for an onchange
1080: event for the second <select> tag
1081:
1082: =back
1083:
1084: Below is an example of such a hash. Only the 'text', 'default', and
1085: 'select2' keys must appear as stated. keys(%menu) are the possible
1086: values for the first select menu. The text that coincides with the
1087: first menu value is given in $menu{$choice1}->{'text'}. The values
1088: and text for the second menu are given in the hash pointed to by
1089: $menu{$choice1}->{'select2'}.
1090:
1091: my %menu = ( A1 => { text =>"Choice A1" ,
1092: default => "B3",
1093: select2 => {
1094: B1 => "Choice B1",
1095: B2 => "Choice B2",
1096: B3 => "Choice B3",
1097: B4 => "Choice B4"
1098: },
1099: order => ['B4','B3','B1','B2'],
1100: },
1101: A2 => { text =>"Choice A2" ,
1102: default => "C2",
1103: select2 => {
1104: C1 => "Choice C1",
1105: C2 => "Choice C2",
1106: C3 => "Choice C3"
1107: },
1108: order => ['C2','C1','C3'],
1109: },
1110: A3 => { text =>"Choice A3" ,
1111: default => "D6",
1112: select2 => {
1113: D1 => "Choice D1",
1114: D2 => "Choice D2",
1115: D3 => "Choice D3",
1116: D4 => "Choice D4",
1117: D5 => "Choice D5",
1118: D6 => "Choice D6",
1119: D7 => "Choice D7"
1120: },
1121: order => ['D4','D3','D2','D1','D7','D6','D5'],
1122: }
1123: );
1124:
1125: =cut
1126:
1127: sub linked_select_forms {
1128: my ($formname,
1129: $middletext,
1130: $firstdefault,
1131: $firstselectname,
1132: $secondselectname,
1133: $hashref,
1134: $menuorder,
1135: $onchangefirst,
1136: $onchangesecond
1137: ) = @_;
1138: my $second = "document.$formname.$secondselectname";
1139: my $first = "document.$formname.$firstselectname";
1140: # output the javascript to do the changing
1141: my $result = '';
1142: $result.='<script type="text/javascript" language="JavaScript">'."\n";
1143: $result.="// <![CDATA[\n";
1144: $result.="var select2data = new Object();\n";
1145: $" = '","';
1146: my $debug = '';
1147: foreach my $s1 (sort(keys(%$hashref))) {
1148: $result.="select2data.d_$s1 = new Object();\n";
1149: $result.="select2data.d_$s1.def = new String('".
1150: $hashref->{$s1}->{'default'}."');\n";
1151: $result.="select2data.d_$s1.values = new Array(";
1152: my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1153: if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
1154: @s2values = @{$hashref->{$s1}->{'order'}};
1155: }
1156: $result.="\"@s2values\");\n";
1157: $result.="select2data.d_$s1.texts = new Array(";
1158: my @s2texts;
1159: foreach my $value (@s2values) {
1160: push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
1161: }
1162: $result.="\"@s2texts\");\n";
1163: }
1164: $"=' ';
1165: $result.= <<"END";
1166:
1167: function select1_changed() {
1168: // Determine new choice
1169: var newvalue = "d_" + $first.value;
1170: // update select2
1171: var values = select2data[newvalue].values;
1172: var texts = select2data[newvalue].texts;
1173: var select2def = select2data[newvalue].def;
1174: var i;
1175: // out with the old
1176: for (i = 0; i < $second.options.length; i++) {
1177: $second.options[i] = null;
1178: }
1179: // in with the nuclear
1180: for (i=0;i<values.length; i++) {
1181: $second.options[i] = new Option(values[i]);
1182: $second.options[i].value = values[i];
1183: $second.options[i].text = texts[i];
1184: if (values[i] == select2def) {
1185: $second.options[i].selected = true;
1186: }
1187: }
1188: }
1189: // ]]>
1190: </script>
1191: END
1192: # output the initial values for the selection lists
1193: $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1194: my @order = sort(keys(%{$hashref}));
1195: if (ref($menuorder) eq 'ARRAY') {
1196: @order = @{$menuorder};
1197: }
1198: foreach my $value (@order) {
1199: $result.=" <option value=\"$value\" ";
1200: $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1201: $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1202: }
1203: $result .= "</select>\n";
1204: my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
1205: $result .= $middletext;
1206: $result .= "<select size=\"1\" name=\"$secondselectname\"";
1207: if ($onchangesecond) {
1208: $result .= ' onchange="'.$onchangesecond.'"';
1209: }
1210: $result .= ">\n";
1211: my $seconddefault = $hashref->{$firstdefault}->{'default'};
1212:
1213: my @secondorder = sort(keys(%select2));
1214: if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
1215: @secondorder = @{$hashref->{$firstdefault}->{'order'}};
1216: }
1217: foreach my $value (@secondorder) {
1218: $result.=" <option value=\"$value\" ";
1219: $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1220: $result.=">".&mt($select2{$value})."</option>\n";
1221: }
1222: $result .= "</select>\n";
1223: # return $debug;
1224: return $result;
1225: } # end of sub linked_select_forms {
1226:
1227: =pod
1228:
1229: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1230:
1231: Returns a string corresponding to an HTML link to the given help
1232: $topic, where $topic corresponds to the name of a .tex file in
1233: /home/httpd/html/adm/help/tex, with underscores replaced by
1234: spaces.
1235:
1236: $text will optionally be linked to the same topic, allowing you to
1237: link text in addition to the graphic. If you do not want to link
1238: text, but wish to specify one of the later parameters, pass an
1239: empty string.
1240:
1241: $stayOnPage is a value that will be interpreted as a boolean. If true,
1242: the link will not open a new window. If false, the link will open
1243: a new window using Javascript. (Default is false.)
1244:
1245: $width and $height are optional numerical parameters that will
1246: override the width and height of the popped up window, which may
1247: be useful for certain help topics with big pictures included.
1248:
1249: $imgid is the id of the img tag used for the help icon. This may be
1250: used in a javascript call to switch the image src. See
1251: lonhtmlcommon::htmlareaselectactive() for an example.
1252:
1253: =cut
1254:
1255: sub help_open_topic {
1256: my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1257: $text = "" if (not defined $text);
1258: $stayOnPage = 0 if (not defined $stayOnPage);
1259: $width = 500 if (not defined $width);
1260: $height = 400 if (not defined $height);
1261: my $filename = $topic;
1262: $filename =~ s/ /_/g;
1263:
1264: my $template = "";
1265: my $link;
1266:
1267: $topic=~s/\W/\_/g;
1268:
1269: if (!$stayOnPage) {
1270: $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1271: } elsif ($stayOnPage eq 'popup') {
1272: $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1273: } else {
1274: $link = "/adm/help/${filename}.hlp";
1275: }
1276:
1277: # Add the text
1278: if ($text ne "") {
1279: $template.='<span class="LC_help_open_topic">'
1280: .'<a target="_top" href="'.$link.'">'
1281: .$text.'</a>';
1282: }
1283:
1284: # (Always) Add the graphic
1285: my $title = &mt('Online Help');
1286: my $helpicon=&lonhttpdurl("/adm/help/help.png");
1287: if ($imgid ne '') {
1288: $imgid = ' id="'.$imgid.'"';
1289: }
1290: $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
1291: .'<img src="'.$helpicon.'" border="0"'
1292: .' alt="'.&mt('Help: [_1]',$topic).'"'
1293: .' title="'.$title.'" style="vertical-align:middle;"'.$imgid
1294: .' /></a>';
1295: if ($text ne "") {
1296: $template.='</span>';
1297: }
1298: return $template;
1299:
1300: }
1301:
1302: # This is a quicky function for Latex cheatsheet editing, since it
1303: # appears in at least four places
1304: sub helpLatexCheatsheet {
1305: my ($topic,$text,$not_author,$stayOnPage) = @_;
1306: my $out;
1307: my $addOther = '';
1308: if ($topic) {
1309: $addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1310: }
1311: $out = '<span>' # Start cheatsheet
1312: .$addOther
1313: .'<span>'
1314: .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1315: .'</span> <span>'
1316: .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1317: .'</span>';
1318: unless ($not_author) {
1319: $out .= '<span>'
1320: .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1321: .'</span> <span>'
1322: .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1323: .'</span>';
1324: }
1325: $out .= '</span>'; # End cheatsheet
1326: return $out;
1327: }
1328:
1329: sub general_help {
1330: my $helptopic='Student_Intro';
1331: if ($env{'request.role'}=~/^(ca|au)/) {
1332: $helptopic='Authoring_Intro';
1333: } elsif ($env{'request.role'}=~/^(cc|co)/) {
1334: $helptopic='Course_Coordination_Intro';
1335: } elsif ($env{'request.role'}=~/^dc/) {
1336: $helptopic='Domain_Coordination_Intro';
1337: }
1338: return $helptopic;
1339: }
1340:
1341: sub update_help_link {
1342: my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
1343: my $origurl = $ENV{'REQUEST_URI'};
1344: $origurl=~s|^/~|/priv/|;
1345: my $timestamp = time;
1346: foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
1347: $$datum = &escape($$datum);
1348: }
1349:
1350: my $banner_link = "/adm/helpmenu?page=banner&topic=$topic&component_help=$component_help&faq=$faq&bug=$bug&origurl=$origurl&stamp=$timestamp&stayonpage=$stayOnPage";
1351: my $output .= <<"ENDOUTPUT";
1352: <script type="text/javascript">
1353: // <![CDATA[
1354: banner_link = '$banner_link';
1355: // ]]>
1356: </script>
1357: ENDOUTPUT
1358: return $output;
1359: }
1360:
1361: # now just updates the help link and generates a blue icon
1362: sub help_open_menu {
1363: my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text)
1364: = @_;
1365: $stayOnPage = 1;
1366: my $output;
1367: if ($component_help) {
1368: if (!$text) {
1369: $output=&help_open_topic($component_help,undef,$stayOnPage,
1370: $width,$height);
1371: } else {
1372: my $help_text;
1373: $help_text=&unescape($topic);
1374: $output='<table><tr><td>'.
1375: &help_open_topic($component_help,$help_text,$stayOnPage,
1376: $width,$height).'</td></tr></table>';
1377: }
1378: }
1379: my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
1380: return $output.$banner_link;
1381: }
1382:
1383: sub top_nav_help {
1384: my ($text) = @_;
1385: $text = &mt($text);
1386: my $stay_on_page = 1;
1387:
1388: my ($link,$banner_link);
1389: unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
1390: $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1391: : "javascript:helpMenu('open')";
1392: $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1393: }
1394: my $title = &mt('Get help');
1395: if ($link) {
1396: return <<"END";
1397: $banner_link
1398: <a href="$link" title="$title">$text</a>
1399: END
1400: } else {
1401: return ' '.$text.' ';
1402: }
1403: }
1404:
1405: sub help_menu_js {
1406: my ($httphost) = @_;
1407: my $stayOnPage = 1;
1408: my $width = 620;
1409: my $height = 600;
1410: my $helptopic=&general_help();
1411: my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1412: my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1413: my $start_page =
1414: &Apache::loncommon::start_page('Help Menu', undef,
1415: {'frameset' => 1,
1416: 'js_ready' => 1,
1417: 'use_absolute' => $httphost,
1418: 'add_entries' => {
1419: 'border' => '0',
1420: 'rows' => "110,*",},});
1421: my $end_page =
1422: &Apache::loncommon::end_page({'frameset' => 1,
1423: 'js_ready' => 1,});
1424:
1425: my $template .= <<"ENDTEMPLATE";
1426: <script type="text/javascript">
1427: // <![CDATA[
1428: // <!-- BEGIN LON-CAPA Internal
1429: var banner_link = '';
1430: function helpMenu(target) {
1431: var caller = this;
1432: if (target == 'open') {
1433: var newWindow = null;
1434: try {
1435: newWindow = window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1436: }
1437: catch(error) {
1438: writeHelp(caller);
1439: return;
1440: }
1441: if (newWindow) {
1442: caller = newWindow;
1443: }
1444: }
1445: writeHelp(caller);
1446: return;
1447: }
1448: function writeHelp(caller) {
1449: caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
1450: caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
1451: caller.document.close();
1452: caller.focus();
1453: }
1454: // END LON-CAPA Internal -->
1455: // ]]>
1456: </script>
1457: ENDTEMPLATE
1458: return $template;
1459: }
1460:
1461: sub help_open_bug {
1462: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1463: unless ($env{'user.adv'}) { return ''; }
1464: unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
1465: $text = "" if (not defined $text);
1466: $stayOnPage=1;
1467: $width = 600 if (not defined $width);
1468: $height = 600 if (not defined $height);
1469:
1470: $topic=~s/\W+/\+/g;
1471: my $link='';
1472: my $template='';
1473: my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&bug_file_loc='.
1474: &escape($ENV{'REQUEST_URI'}).'&component='.$topic;
1475: if (!$stayOnPage)
1476: {
1477: $link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1478: }
1479: else
1480: {
1481: $link = $url;
1482: }
1483: # Add the text
1484: if ($text ne "")
1485: {
1486: $template .=
1487: "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1488: "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1489: }
1490:
1491: # Add the graphic
1492: my $title = &mt('Report a Bug');
1493: my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1494: $template .= <<"ENDTEMPLATE";
1495: <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1496: ENDTEMPLATE
1497: if ($text ne '') { $template.='</td></tr></table>' };
1498: return $template;
1499:
1500: }
1501:
1502: sub help_open_faq {
1503: my ($topic, $text, $stayOnPage, $width, $height) = @_;
1504: unless ($env{'user.adv'}) { return ''; }
1505: unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
1506: $text = "" if (not defined $text);
1507: $stayOnPage=1;
1508: $width = 350 if (not defined $width);
1509: $height = 400 if (not defined $height);
1510:
1511: $topic=~s/\W+/\+/g;
1512: my $link='';
1513: my $template='';
1514: my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
1515: if (!$stayOnPage)
1516: {
1517: $link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1518: }
1519: else
1520: {
1521: $link = $url;
1522: }
1523:
1524: # Add the text
1525: if ($text ne "")
1526: {
1527: $template .=
1528: "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1529: "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1530: }
1531:
1532: # Add the graphic
1533: my $title = &mt('View the FAQ');
1534: my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1535: $template .= <<"ENDTEMPLATE";
1536: <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1537: ENDTEMPLATE
1538: if ($text ne '') { $template.='</td></tr></table>' };
1539: return $template;
1540:
1541: }
1542:
1543: ###############################################################
1544: ###############################################################
1545:
1546: =pod
1547:
1548: =item * &change_content_javascript():
1549:
1550: This and the next function allow you to create small sections of an
1551: otherwise static HTML page that you can update on the fly with
1552: Javascript, even in Netscape 4.
1553:
1554: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
1555: must be written to the HTML page once. It will prove the Javascript
1556: function "change(name, content)". Calling the change function with the
1557: name of the section
1558: you want to update, matching the name passed to C<changable_area>, and
1559: the new content you want to put in there, will put the content into
1560: that area.
1561:
1562: B<Note>: Netscape 4 only reserves enough space for the changable area
1563: to contain room for the original contents. You need to "make space"
1564: for whatever changes you wish to make, and be B<sure> to check your
1565: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
1566: it's adequate for updating a one-line status display, but little more.
1567: This script will set the space to 100% width, so you only need to
1568: worry about height in Netscape 4.
1569:
1570: Modern browsers are much less limiting, and if you can commit to the
1571: user not using Netscape 4, this feature may be used freely with
1572: pretty much any HTML.
1573:
1574: =cut
1575:
1576: sub change_content_javascript {
1577: # If we're on Netscape 4, we need to use Layer-based code
1578: if ($env{'browser.type'} eq 'netscape' &&
1579: $env{'browser.version'} =~ /^4\./) {
1580: return (<<NETSCAPE4);
1581: function change(name, content) {
1582: doc = document.layers[name+"___escape"].layers[0].document;
1583: doc.open();
1584: doc.write(content);
1585: doc.close();
1586: }
1587: NETSCAPE4
1588: } else {
1589: # Otherwise, we need to use semi-standards-compliant code
1590: # (technically, "innerHTML" isn't standard but the equivalent
1591: # is really scary, and every useful browser supports it
1592: return (<<DOMBASED);
1593: function change(name, content) {
1594: element = document.getElementById(name);
1595: element.innerHTML = content;
1596: }
1597: DOMBASED
1598: }
1599: }
1600:
1601: =pod
1602:
1603: =item * &changable_area($name,$origContent):
1604:
1605: This provides a "changable area" that can be modified on the fly via
1606: the Javascript code provided in C<change_content_javascript>. $name is
1607: the name you will use to reference the area later; do not repeat the
1608: same name on a given HTML page more then once. $origContent is what
1609: the area will originally contain, which can be left blank.
1610:
1611: =cut
1612:
1613: sub changable_area {
1614: my ($name, $origContent) = @_;
1615:
1616: if ($env{'browser.type'} eq 'netscape' &&
1617: $env{'browser.version'} =~ /^4\./) {
1618: # If this is netscape 4, we need to use the Layer tag
1619: return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
1620: } else {
1621: return "<span id='$name'>$origContent</span>";
1622: }
1623: }
1624:
1625: =pod
1626:
1627: =item * &viewport_geometry_js
1628:
1629: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
1630:
1631: =cut
1632:
1633:
1634: sub viewport_geometry_js {
1635: return <<"GEOMETRY";
1636: var Geometry = {};
1637: function init_geometry() {
1638: if (Geometry.init) { return };
1639: Geometry.init=1;
1640: if (window.innerHeight) {
1641: Geometry.getViewportHeight = function() { return window.innerHeight; };
1642: Geometry.getViewportWidth = function() { return window.innerWidth; };
1643: Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
1644: Geometry.getVerticalScroll = function() { return window.pageYOffset; };
1645: }
1646: else if (document.documentElement && document.documentElement.clientHeight) {
1647: Geometry.getViewportHeight =
1648: function() { return document.documentElement.clientHeight; };
1649: Geometry.getViewportWidth =
1650: function() { return document.documentElement.clientWidth; };
1651:
1652: Geometry.getHorizontalScroll =
1653: function() { return document.documentElement.scrollLeft; };
1654: Geometry.getVerticalScroll =
1655: function() { return document.documentElement.scrollTop; };
1656: }
1657: else if (document.body.clientHeight) {
1658: Geometry.getViewportHeight =
1659: function() { return document.body.clientHeight; };
1660: Geometry.getViewportWidth =
1661: function() { return document.body.clientWidth; };
1662: Geometry.getHorizontalScroll =
1663: function() { return document.body.scrollLeft; };
1664: Geometry.getVerticalScroll =
1665: function() { return document.body.scrollTop; };
1666: }
1667: }
1668:
1669: GEOMETRY
1670: }
1671:
1672: =pod
1673:
1674: =item * &viewport_size_js()
1675:
1676: 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.
1677:
1678: =cut
1679:
1680: sub viewport_size_js {
1681: my $geometry = &viewport_geometry_js();
1682: return <<"DIMS";
1683:
1684: $geometry
1685:
1686: function getViewportDims(width,height) {
1687: init_geometry();
1688: width.value = Geometry.getViewportWidth();
1689: height.value = Geometry.getViewportHeight();
1690: return;
1691: }
1692:
1693: DIMS
1694: }
1695:
1696: =pod
1697:
1698: =item * &resize_textarea_js()
1699:
1700: emits the needed javascript to resize a textarea to be as big as possible
1701:
1702: creates a function resize_textrea that takes two IDs first should be
1703: the id of the element to resize, second should be the id of a div that
1704: surrounds everything that comes after the textarea, this routine needs
1705: to be attached to the <body> for the onload and onresize events.
1706:
1707: =back
1708:
1709: =cut
1710:
1711: sub resize_textarea_js {
1712: my $geometry = &viewport_geometry_js();
1713: return <<"RESIZE";
1714: <script type="text/javascript">
1715: // <![CDATA[
1716: $geometry
1717:
1718: function getX(element) {
1719: var x = 0;
1720: while (element) {
1721: x += element.offsetLeft;
1722: element = element.offsetParent;
1723: }
1724: return x;
1725: }
1726: function getY(element) {
1727: var y = 0;
1728: while (element) {
1729: y += element.offsetTop;
1730: element = element.offsetParent;
1731: }
1732: return y;
1733: }
1734:
1735:
1736: function resize_textarea(textarea_id,bottom_id) {
1737: init_geometry();
1738: var textarea = document.getElementById(textarea_id);
1739: //alert(textarea);
1740:
1741: var textarea_top = getY(textarea);
1742: var textarea_height = textarea.offsetHeight;
1743: var bottom = document.getElementById(bottom_id);
1744: var bottom_top = getY(bottom);
1745: var bottom_height = bottom.offsetHeight;
1746: var window_height = Geometry.getViewportHeight();
1747: var fudge = 23;
1748: var new_height = window_height-fudge-textarea_top-bottom_height;
1749: if (new_height < 300) {
1750: new_height = 300;
1751: }
1752: textarea.style.height=new_height+'px';
1753: }
1754: // ]]>
1755: </script>
1756: RESIZE
1757:
1758: }
1759:
1760: =pod
1761:
1762: =head1 Excel and CSV file utility routines
1763:
1764: =cut
1765:
1766: ###############################################################
1767: ###############################################################
1768:
1769: =pod
1770:
1771: =over 4
1772:
1773: =item * &csv_translate($text)
1774:
1775: Translate $text to allow it to be output as a 'comma separated values'
1776: format.
1777:
1778: =cut
1779:
1780: ###############################################################
1781: ###############################################################
1782: sub csv_translate {
1783: my $text = shift;
1784: $text =~ s/\"/\"\"/g;
1785: $text =~ s/\n/ /g;
1786: return $text;
1787: }
1788:
1789: ###############################################################
1790: ###############################################################
1791:
1792: =pod
1793:
1794: =item * &define_excel_formats()
1795:
1796: Define some commonly used Excel cell formats.
1797:
1798: Currently supported formats:
1799:
1800: =over 4
1801:
1802: =item header
1803:
1804: =item bold
1805:
1806: =item h1
1807:
1808: =item h2
1809:
1810: =item h3
1811:
1812: =item h4
1813:
1814: =item i
1815:
1816: =item date
1817:
1818: =back
1819:
1820: Inputs: $workbook
1821:
1822: Returns: $format, a hash reference.
1823:
1824:
1825: =cut
1826:
1827: ###############################################################
1828: ###############################################################
1829: sub define_excel_formats {
1830: my ($workbook) = @_;
1831: my $format;
1832: $format->{'header'} = $workbook->add_format(bold => 1,
1833: bottom => 1,
1834: align => 'center');
1835: $format->{'bold'} = $workbook->add_format(bold=>1);
1836: $format->{'h1'} = $workbook->add_format(bold=>1, size=>18);
1837: $format->{'h2'} = $workbook->add_format(bold=>1, size=>16);
1838: $format->{'h3'} = $workbook->add_format(bold=>1, size=>14);
1839: $format->{'h4'} = $workbook->add_format(bold=>1, size=>12);
1840: $format->{'i'} = $workbook->add_format(italic=>1);
1841: $format->{'date'} = $workbook->add_format(num_format=>
1842: 'mm/dd/yyyy hh:mm:ss');
1843: return $format;
1844: }
1845:
1846: ###############################################################
1847: ###############################################################
1848:
1849: =pod
1850:
1851: =item * &create_workbook()
1852:
1853: Create an Excel worksheet. If it fails, output message on the
1854: request object and return undefs.
1855:
1856: Inputs: Apache request object
1857:
1858: Returns (undef) on failure,
1859: Excel worksheet object, scalar with filename, and formats
1860: from &Apache::loncommon::define_excel_formats on success
1861:
1862: =cut
1863:
1864: ###############################################################
1865: ###############################################################
1866: sub create_workbook {
1867: my ($r) = @_;
1868: #
1869: # Create the excel spreadsheet
1870: my $filename = '/prtspool/'.
1871: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1872: time.'_'.rand(1000000000).'.xls';
1873: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1874: if (! defined($workbook)) {
1875: $r->log_error("Error creating excel spreadsheet $filename: $!");
1876: $r->print(
1877: '<p class="LC_error">'
1878: .&mt('Problems occurred in creating the new Excel file.')
1879: .' '.&mt('This error has been logged.')
1880: .' '.&mt('Please alert your LON-CAPA administrator.')
1881: .'</p>'
1882: );
1883: return (undef);
1884: }
1885: #
1886: $workbook->set_tempdir(LONCAPA::tempdir());
1887: #
1888: my $format = &Apache::loncommon::define_excel_formats($workbook);
1889: return ($workbook,$filename,$format);
1890: }
1891:
1892: ###############################################################
1893: ###############################################################
1894:
1895: =pod
1896:
1897: =item * &create_text_file()
1898:
1899: Create a file to write to and eventually make available to the user.
1900: If file creation fails, outputs an error message on the request object and
1901: return undefs.
1902:
1903: Inputs: Apache request object, and file suffix
1904:
1905: Returns (undef) on failure,
1906: Filehandle and filename on success.
1907:
1908: =cut
1909:
1910: ###############################################################
1911: ###############################################################
1912: sub create_text_file {
1913: my ($r,$suffix) = @_;
1914: if (! defined($suffix)) { $suffix = 'txt'; };
1915: my $fh;
1916: my $filename = '/prtspool/'.
1917: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1918: time.'_'.rand(1000000000).'.'.$suffix;
1919: $fh = Apache::File->new('>/home/httpd'.$filename);
1920: if (! defined($fh)) {
1921: $r->log_error("Couldn't open $filename for output $!");
1922: $r->print(
1923: '<p class="LC_error">'
1924: .&mt('Problems occurred in creating the output file.')
1925: .' '.&mt('This error has been logged.')
1926: .' '.&mt('Please alert your LON-CAPA administrator.')
1927: .'</p>'
1928: );
1929: }
1930: return ($fh,$filename)
1931: }
1932:
1933:
1934: =pod
1935:
1936: =back
1937:
1938: =cut
1939:
1940: ###############################################################
1941: ## Home server <option> list generating code ##
1942: ###############################################################
1943:
1944: # ------------------------------------------
1945:
1946: sub domain_select {
1947: my ($name,$value,$multiple)=@_;
1948: my %domains=map {
1949: $_ => $_.' '. &Apache::lonnet::domain($_,'description')
1950: } &Apache::lonnet::all_domains();
1951: if ($multiple) {
1952: $domains{''}=&mt('Any domain');
1953: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1954: return &multiple_select_form($name,$value,4,\%domains);
1955: } else {
1956: $domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1957: return &select_form($name,$value,\%domains);
1958: }
1959: }
1960:
1961: #-------------------------------------------
1962:
1963: =pod
1964:
1965: =head1 Routines for form select boxes
1966:
1967: =over 4
1968:
1969: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1970:
1971: Returns a string containing a <select> element int multiple mode
1972:
1973:
1974: Args:
1975: $name - name of the <select> element
1976: $value - scalar or array ref of values that should already be selected
1977: $size - number of rows long the select element is
1978: $hash - the elements should be 'option' => 'shown text'
1979: (shown text should already have been &mt())
1980: $order - (optional) array ref of the order to show the elements in
1981:
1982: =cut
1983:
1984: #-------------------------------------------
1985: sub multiple_select_form {
1986: my ($name,$value,$size,$hash,$order)=@_;
1987: my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
1988: my $output='';
1989: if (! defined($size)) {
1990: $size = 4;
1991: if (scalar(keys(%$hash))<4) {
1992: $size = scalar(keys(%$hash));
1993: }
1994: }
1995: $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1996: my @order;
1997: if (ref($order) eq 'ARRAY') {
1998: @order = @{$order};
1999: } else {
2000: @order = sort(keys(%$hash));
2001: }
2002: if (exists($$hash{'select_form_order'})) {
2003: @order = @{$$hash{'select_form_order'}};
2004: }
2005:
2006: foreach my $key (@order) {
2007: $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
2008: $output.='selected="selected" ' if ($selected{$key});
2009: $output.='>'.$hash->{$key}."</option>\n";
2010: }
2011: $output.="</select>\n";
2012: return $output;
2013: }
2014:
2015: #-------------------------------------------
2016:
2017: =pod
2018:
2019: =item * &select_form($defdom,$name,$hashref,$onchange)
2020:
2021: Returns a string containing a <select name='$name' size='1'> form to
2022: allow a user to select options from a ref to a hash containing:
2023: option_name => displayed text. An optional $onchange can include
2024: a javascript onchange item, e.g., onchange="this.form.submit();"
2025:
2026: See lonrights.pm for an example invocation and use.
2027:
2028: =cut
2029:
2030: #-------------------------------------------
2031: sub select_form {
2032: my ($def,$name,$hashref,$onchange) = @_;
2033: return unless (ref($hashref) eq 'HASH');
2034: if ($onchange) {
2035: $onchange = ' onchange="'.$onchange.'"';
2036: }
2037: my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
2038: my @keys;
2039: if (exists($hashref->{'select_form_order'})) {
2040: @keys=@{$hashref->{'select_form_order'}};
2041: } else {
2042: @keys=sort(keys(%{$hashref}));
2043: }
2044: foreach my $key (@keys) {
2045: $selectform.=
2046: '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
2047: ($key eq $def ? 'selected="selected" ' : '').
2048: ">".$hashref->{$key}."</option>\n";
2049: }
2050: $selectform.="</select>";
2051: return $selectform;
2052: }
2053:
2054: # For display filters
2055:
2056: sub display_filter {
2057: my ($context) = @_;
2058: if (!$env{'form.show'}) { $env{'form.show'}=10; }
2059: if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
2060: my $phraseinput = 'hidden';
2061: my $includeinput = 'hidden';
2062: my ($checked,$includetypestext);
2063: if ($env{'form.displayfilter'} eq 'containing') {
2064: $phraseinput = 'text';
2065: if ($context eq 'parmslog') {
2066: $includeinput = 'checkbox';
2067: if ($env{'form.includetypes'}) {
2068: $checked = ' checked="checked"';
2069: }
2070: $includetypestext = &mt('Include parameter types');
2071: }
2072: } else {
2073: $includetypestext = ' ';
2074: }
2075: my ($additional,$secondid,$thirdid);
2076: if ($context eq 'parmslog') {
2077: $additional =
2078: '<label><input type="'.$includeinput.'" name="includetypes"'.
2079: $checked.' name="includetypes" value="1" id="includetypes" />'.
2080: ' <span id="includetypestext">'.$includetypestext.'</span>'.
2081: '</label>';
2082: $secondid = 'includetypes';
2083: $thirdid = 'includetypestext';
2084: }
2085: my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
2086: '$secondid','$thirdid')";
2087: return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
2088: &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
2089: (&mt('all'),10,20,50,100,1000,10000))).
2090: '</label></span> <span class="LC_nobreak">'.
2091: &mt('Filter: [_1]',
2092: &select_form($env{'form.displayfilter'},
2093: 'displayfilter',
2094: {'currentfolder' => 'Current folder/page',
2095: 'containing' => 'Containing phrase',
2096: 'none' => 'None'},$onchange)).' '.
2097: '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
2098: &HTML::Entities::encode($env{'form.containingphrase'}).
2099: '" />'.$additional;
2100: }
2101:
2102: sub display_filter_js {
2103: my $includetext = &mt('Include parameter types');
2104: return <<"ENDJS";
2105:
2106: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
2107: var firstType = 'hidden';
2108: if (setter.options[setter.selectedIndex].value == 'containing') {
2109: firstType = 'text';
2110: }
2111: firstObject = document.getElementById(firstid);
2112: if (typeof(firstObject) == 'object') {
2113: if (firstObject.type != firstType) {
2114: changeInputType(firstObject,firstType);
2115: }
2116: }
2117: if (context == 'parmslog') {
2118: var secondType = 'hidden';
2119: if (firstType == 'text') {
2120: secondType = 'checkbox';
2121: }
2122: secondObject = document.getElementById(secondid);
2123: if (typeof(secondObject) == 'object') {
2124: if (secondObject.type != secondType) {
2125: changeInputType(secondObject,secondType);
2126: }
2127: }
2128: var textItem = document.getElementById(thirdid);
2129: var currtext = textItem.innerHTML;
2130: var newtext;
2131: if (firstType == 'text') {
2132: newtext = '$includetext';
2133: } else {
2134: newtext = ' ';
2135: }
2136: if (currtext != newtext) {
2137: textItem.innerHTML = newtext;
2138: }
2139: }
2140: return;
2141: }
2142:
2143: function changeInputType(oldObject,newType) {
2144: var newObject = document.createElement('input');
2145: newObject.type = newType;
2146: if (oldObject.size) {
2147: newObject.size = oldObject.size;
2148: }
2149: if (oldObject.value) {
2150: newObject.value = oldObject.value;
2151: }
2152: if (oldObject.name) {
2153: newObject.name = oldObject.name;
2154: }
2155: if (oldObject.id) {
2156: newObject.id = oldObject.id;
2157: }
2158: oldObject.parentNode.replaceChild(newObject,oldObject);
2159: return;
2160: }
2161:
2162: ENDJS
2163: }
2164:
2165: sub gradeleveldescription {
2166: my $gradelevel=shift;
2167: my %gradelevels=(0 => 'Not specified',
2168: 1 => 'Grade 1',
2169: 2 => 'Grade 2',
2170: 3 => 'Grade 3',
2171: 4 => 'Grade 4',
2172: 5 => 'Grade 5',
2173: 6 => 'Grade 6',
2174: 7 => 'Grade 7',
2175: 8 => 'Grade 8',
2176: 9 => 'Grade 9',
2177: 10 => 'Grade 10',
2178: 11 => 'Grade 11',
2179: 12 => 'Grade 12',
2180: 13 => 'Grade 13',
2181: 14 => '100 Level',
2182: 15 => '200 Level',
2183: 16 => '300 Level',
2184: 17 => '400 Level',
2185: 18 => 'Graduate Level');
2186: return &mt($gradelevels{$gradelevel});
2187: }
2188:
2189: sub select_level_form {
2190: my ($deflevel,$name)=@_;
2191: unless ($deflevel) { $deflevel=0; }
2192: my $selectform = "<select name=\"$name\" size=\"1\">\n";
2193: for (my $i=0; $i<=18; $i++) {
2194: $selectform.="<option value=\"$i\" ".
2195: ($i==$deflevel ? 'selected="selected" ' : '').
2196: ">".&gradeleveldescription($i)."</option>\n";
2197: }
2198: $selectform.="</select>";
2199: return $selectform;
2200: }
2201:
2202: #-------------------------------------------
2203:
2204: =pod
2205:
2206: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
2207:
2208: Returns a string containing a <select name='$name' size='1'> form to
2209: allow a user to select the domain to preform an operation in.
2210: See loncreateuser.pm for an example invocation and use.
2211:
2212: If the $includeempty flag is set, it also includes an empty choice ("no domain
2213: selected");
2214:
2215: If the $showdomdesc flag is set, the domain name is followed by the domain description.
2216:
2217: 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.
2218:
2219: The optional $incdoms is a reference to an array of domains which will be the only available options.
2220:
2221: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
2222:
2223: =cut
2224:
2225: #-------------------------------------------
2226: sub select_dom_form {
2227: my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
2228: if ($onchange) {
2229: $onchange = ' onchange="'.$onchange.'"';
2230: }
2231: my (@domains,%exclude);
2232: if (ref($incdoms) eq 'ARRAY') {
2233: @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
2234: } else {
2235: @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
2236: }
2237: if ($includeempty) { @domains=('',@domains); }
2238: if (ref($excdoms) eq 'ARRAY') {
2239: map { $exclude{$_} = 1; } @{$excdoms};
2240: }
2241: my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
2242: foreach my $dom (@domains) {
2243: next if ($exclude{$dom});
2244: $selectdomain.="<option value=\"$dom\" ".
2245: ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
2246: if ($showdomdesc) {
2247: if ($dom ne '') {
2248: my $domdesc = &Apache::lonnet::domain($dom,'description');
2249: if ($domdesc ne '') {
2250: $selectdomain .= ' ('.$domdesc.')';
2251: }
2252: }
2253: }
2254: $selectdomain .= "</option>\n";
2255: }
2256: $selectdomain.="</select>";
2257: return $selectdomain;
2258: }
2259:
2260: #-------------------------------------------
2261:
2262: =pod
2263:
2264: =item * &home_server_form_item($domain,$name,$defaultflag)
2265:
2266: input: 4 arguments (two required, two optional) -
2267: $domain - domain of new user
2268: $name - name of form element
2269: $default - Value of 'default' causes a default item to be first
2270: option, and selected by default.
2271: $hide - Value of 'hide' causes hiding of the name of the server,
2272: if 1 server found, or default, if 0 found.
2273: output: returns 2 items:
2274: (a) form element which contains either:
2275: (i) <select name="$name">
2276: <option value="$hostid1">$hostid $servers{$hostid}</option>
2277: <option value="$hostid2">$hostid $servers{$hostid}</option>
2278: </select>
2279: form item if there are multiple library servers in $domain, or
2280: (ii) an <input type="hidden" name="$name" value="$hostid" /> form item
2281: if there is only one library server in $domain.
2282:
2283: (b) number of library servers found.
2284:
2285: See loncreateuser.pm for example of use.
2286:
2287: =cut
2288:
2289: #-------------------------------------------
2290: sub home_server_form_item {
2291: my ($domain,$name,$default,$hide) = @_;
2292: my %servers = &Apache::lonnet::get_servers($domain,'library');
2293: my $result;
2294: my $numlib = keys(%servers);
2295: if ($numlib > 1) {
2296: $result .= '<select name="'.$name.'" />'."\n";
2297: if ($default) {
2298: $result .= '<option value="default" selected="selected">'.&mt('default').
2299: '</option>'."\n";
2300: }
2301: foreach my $hostid (sort(keys(%servers))) {
2302: $result.= '<option value="'.$hostid.'">'.
2303: $hostid.' '.$servers{$hostid}."</option>\n";
2304: }
2305: $result .= '</select>'."\n";
2306: } elsif ($numlib == 1) {
2307: my $hostid;
2308: foreach my $item (keys(%servers)) {
2309: $hostid = $item;
2310: }
2311: $result .= '<input type="hidden" name="'.$name.'" value="'.
2312: $hostid.'" />';
2313: if (!$hide) {
2314: $result .= $hostid.' '.$servers{$hostid};
2315: }
2316: $result .= "\n";
2317: } elsif ($default) {
2318: $result .= '<input type="hidden" name="'.$name.
2319: '" value="default" />';
2320: if (!$hide) {
2321: $result .= &mt('default');
2322: }
2323: $result .= "\n";
2324: }
2325: return ($result,$numlib);
2326: }
2327:
2328: =pod
2329:
2330: =back
2331:
2332: =cut
2333:
2334: ###############################################################
2335: ## Decoding User Agent ##
2336: ###############################################################
2337:
2338: =pod
2339:
2340: =head1 Decoding the User Agent
2341:
2342: =over 4
2343:
2344: =item * &decode_user_agent()
2345:
2346: Inputs: $r
2347:
2348: Outputs:
2349:
2350: =over 4
2351:
2352: =item * $httpbrowser
2353:
2354: =item * $clientbrowser
2355:
2356: =item * $clientversion
2357:
2358: =item * $clientmathml
2359:
2360: =item * $clientunicode
2361:
2362: =item * $clientos
2363:
2364: =item * $clientmobile
2365:
2366: =item * $clientinfo
2367:
2368: =item * $clientosversion
2369:
2370: =back
2371:
2372: =back
2373:
2374: =cut
2375:
2376: ###############################################################
2377: ###############################################################
2378: sub decode_user_agent {
2379: my ($r)=@_;
2380: my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
2381: my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
2382: my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
2383: if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
2384: my $clientbrowser='unknown';
2385: my $clientversion='0';
2386: my $clientmathml='';
2387: my $clientunicode='0';
2388: my $clientmobile=0;
2389: my $clientosversion='';
2390: for (my $i=0;$i<=$#browsertype;$i++) {
2391: my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
2392: if (($httpbrowser=~/$match/i) && ($httpbrowser!~/$notmatch/i)) {
2393: $clientbrowser=$bname;
2394: $httpbrowser=~/$vreg/i;
2395: $clientversion=$1;
2396: $clientmathml=($clientversion>=$minv);
2397: $clientunicode=($clientversion>=$univ);
2398: }
2399: }
2400: my $clientos='unknown';
2401: my $clientinfo;
2402: if (($httpbrowser=~/linux/i) ||
2403: ($httpbrowser=~/unix/i) ||
2404: ($httpbrowser=~/ux/i) ||
2405: ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
2406: if (($httpbrowser=~/vax/i) ||
2407: ($httpbrowser=~/vms/i)) { $clientos='vms'; }
2408: if ($httpbrowser=~/next/i) { $clientos='next'; }
2409: if (($httpbrowser=~/mac/i) ||
2410: ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
2411: if ($httpbrowser=~/win/i) {
2412: $clientos='win';
2413: if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
2414: $clientosversion = $1;
2415: }
2416: }
2417: if ($httpbrowser=~/embed/i) { $clientos='pda'; }
2418: if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
2419: $clientmobile=lc($1);
2420: }
2421: if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
2422: $clientinfo = 'firefox-'.$1;
2423: } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
2424: $clientinfo = 'chromeframe-'.$1;
2425: }
2426: return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
2427: $clientunicode,$clientos,$clientmobile,$clientinfo,
2428: $clientosversion);
2429: }
2430:
2431: ###############################################################
2432: ## Authentication changing form generation subroutines ##
2433: ###############################################################
2434: ##
2435: ## All of the authform_xxxxxxx subroutines take their inputs in a
2436: ## hash, and have reasonable default values.
2437: ##
2438: ## formname = the name given in the <form> tag.
2439: #-------------------------------------------
2440:
2441: =pod
2442:
2443: =head1 Authentication Routines
2444:
2445: =over 4
2446:
2447: =item * &authform_xxxxxx()
2448:
2449: The authform_xxxxxx subroutines provide javascript and html forms which
2450: handle some of the conveniences required for authentication forms.
2451: This is not an optimal method, but it works.
2452:
2453: =over 4
2454:
2455: =item * authform_header
2456:
2457: =item * authform_authorwarning
2458:
2459: =item * authform_nochange
2460:
2461: =item * authform_kerberos
2462:
2463: =item * authform_internal
2464:
2465: =item * authform_filesystem
2466:
2467: =back
2468:
2469: See loncreateuser.pm for invocation and use examples.
2470:
2471: =cut
2472:
2473: #-------------------------------------------
2474: sub authform_header{
2475: my %in = (
2476: formname => 'cu',
2477: kerb_def_dom => '',
2478: @_,
2479: );
2480: $in{'formname'} = 'document.' . $in{'formname'};
2481: my $result='';
2482:
2483: #---------------------------------------------- Code for upper case translation
2484: my $Javascript_toUpperCase;
2485: unless ($in{kerb_def_dom}) {
2486: $Javascript_toUpperCase =<<"END";
2487: switch (choice) {
2488: case 'krb': currentform.elements[choicearg].value =
2489: currentform.elements[choicearg].value.toUpperCase();
2490: break;
2491: default:
2492: }
2493: END
2494: } else {
2495: $Javascript_toUpperCase = "";
2496: }
2497:
2498: my $radioval = "'nochange'";
2499: if (defined($in{'curr_authtype'})) {
2500: if ($in{'curr_authtype'} ne '') {
2501: $radioval = "'".$in{'curr_authtype'}."arg'";
2502: }
2503: }
2504: my $argfield = 'null';
2505: if (defined($in{'mode'})) {
2506: if ($in{'mode'} eq 'modifycourse') {
2507: if (defined($in{'curr_autharg'})) {
2508: if ($in{'curr_autharg'} ne '') {
2509: $argfield = "'$in{'curr_autharg'}'";
2510: }
2511: }
2512: }
2513: }
2514:
2515: $result.=<<"END";
2516: var current = new Object();
2517: current.radiovalue = $radioval;
2518: current.argfield = $argfield;
2519:
2520: function changed_radio(choice,currentform) {
2521: var choicearg = choice + 'arg';
2522: // If a radio button in changed, we need to change the argfield
2523: if (current.radiovalue != choice) {
2524: current.radiovalue = choice;
2525: if (current.argfield != null) {
2526: currentform.elements[current.argfield].value = '';
2527: }
2528: if (choice == 'nochange') {
2529: current.argfield = null;
2530: } else {
2531: current.argfield = choicearg;
2532: switch(choice) {
2533: case 'krb':
2534: currentform.elements[current.argfield].value =
2535: "$in{'kerb_def_dom'}";
2536: break;
2537: default:
2538: break;
2539: }
2540: }
2541: }
2542: return;
2543: }
2544:
2545: function changed_text(choice,currentform) {
2546: var choicearg = choice + 'arg';
2547: if (currentform.elements[choicearg].value !='') {
2548: $Javascript_toUpperCase
2549: // clear old field
2550: if ((current.argfield != choicearg) && (current.argfield != null)) {
2551: currentform.elements[current.argfield].value = '';
2552: }
2553: current.argfield = choicearg;
2554: }
2555: set_auth_radio_buttons(choice,currentform);
2556: return;
2557: }
2558:
2559: function set_auth_radio_buttons(newvalue,currentform) {
2560: var numauthchoices = currentform.login.length;
2561: if (typeof numauthchoices == "undefined") {
2562: return;
2563: }
2564: var i=0;
2565: while (i < numauthchoices) {
2566: if (currentform.login[i].value == newvalue) { break; }
2567: i++;
2568: }
2569: if (i == numauthchoices) {
2570: return;
2571: }
2572: current.radiovalue = newvalue;
2573: currentform.login[i].checked = true;
2574: return;
2575: }
2576: END
2577: return $result;
2578: }
2579:
2580: sub authform_authorwarning {
2581: my $result='';
2582: $result='<i>'.
2583: &mt('As a general rule, only authors or co-authors should be '.
2584: 'filesystem authenticated '.
2585: '(which allows access to the server filesystem).')."</i>\n";
2586: return $result;
2587: }
2588:
2589: sub authform_nochange {
2590: my %in = (
2591: formname => 'document.cu',
2592: kerb_def_dom => 'MSU.EDU',
2593: @_,
2594: );
2595: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2596: my $result;
2597: if (!$authnum) {
2598: $result = &mt('Under your current role you are not permitted to change login settings for this user');
2599: } else {
2600: $result = '<label>'.&mt('[_1] Do not change login data',
2601: '<input type="radio" name="login" value="nochange" '.
2602: 'checked="checked" onclick="'.
2603: "javascript:changed_radio('nochange',$in{'formname'});".'" />').
2604: '</label>';
2605: }
2606: return $result;
2607: }
2608:
2609: sub authform_kerberos {
2610: my %in = (
2611: formname => 'document.cu',
2612: kerb_def_dom => 'MSU.EDU',
2613: kerb_def_auth => 'krb4',
2614: @_,
2615: );
2616: my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
2617: $autharg,$jscall);
2618: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2619: if ($in{'kerb_def_auth'} eq 'krb5') {
2620: $check5 = ' checked="checked"';
2621: } else {
2622: $check4 = ' checked="checked"';
2623: }
2624: $krbarg = $in{'kerb_def_dom'};
2625: if (defined($in{'curr_authtype'})) {
2626: if ($in{'curr_authtype'} eq 'krb') {
2627: $krbcheck = ' checked="checked"';
2628: if (defined($in{'mode'})) {
2629: if ($in{'mode'} eq 'modifyuser') {
2630: $krbcheck = '';
2631: }
2632: }
2633: if (defined($in{'curr_kerb_ver'})) {
2634: if ($in{'curr_krb_ver'} eq '5') {
2635: $check5 = ' checked="checked"';
2636: $check4 = '';
2637: } else {
2638: $check4 = ' checked="checked"';
2639: $check5 = '';
2640: }
2641: }
2642: if (defined($in{'curr_autharg'})) {
2643: $krbarg = $in{'curr_autharg'};
2644: }
2645: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2646: if (defined($in{'curr_autharg'})) {
2647: $result =
2648: &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
2649: $in{'curr_autharg'},$krbver);
2650: } else {
2651: $result =
2652: &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
2653: }
2654: return $result;
2655: }
2656: }
2657: } else {
2658: if ($authnum == 1) {
2659: $authtype = '<input type="hidden" name="login" value="krb" />';
2660: }
2661: }
2662: if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
2663: return;
2664: } elsif ($authtype eq '') {
2665: if (defined($in{'mode'})) {
2666: if ($in{'mode'} eq 'modifycourse') {
2667: if ($authnum == 1) {
2668: $authtype = '<input type="radio" name="login" value="krb" />';
2669: }
2670: }
2671: }
2672: }
2673: $jscall = "javascript:changed_radio('krb',$in{'formname'});";
2674: if ($authtype eq '') {
2675: $authtype = '<input type="radio" name="login" value="krb" '.
2676: 'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
2677: $krbcheck.' />';
2678: }
2679: if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
2680: ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
2681: $in{'curr_authtype'} eq 'krb5') ||
2682: (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
2683: $in{'curr_authtype'} eq 'krb4')) {
2684: $result .= &mt
2685: ('[_1] Kerberos authenticated with domain [_2] '.
2686: '[_3] Version 4 [_4] Version 5 [_5]',
2687: '<label>'.$authtype,
2688: '</label><input type="text" size="10" name="krbarg" '.
2689: 'value="'.$krbarg.'" '.
2690: 'onchange="'.$jscall.'" />',
2691: '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
2692: '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
2693: '</label>');
2694: } elsif ($can_assign{'krb4'}) {
2695: $result .= &mt
2696: ('[_1] Kerberos authenticated with domain [_2] '.
2697: '[_3] Version 4 [_4]',
2698: '<label>'.$authtype,
2699: '</label><input type="text" size="10" name="krbarg" '.
2700: 'value="'.$krbarg.'" '.
2701: 'onchange="'.$jscall.'" />',
2702: '<label><input type="hidden" name="krbver" value="4" />',
2703: '</label>');
2704: } elsif ($can_assign{'krb5'}) {
2705: $result .= &mt
2706: ('[_1] Kerberos authenticated with domain [_2] '.
2707: '[_3] Version 5 [_4]',
2708: '<label>'.$authtype,
2709: '</label><input type="text" size="10" name="krbarg" '.
2710: 'value="'.$krbarg.'" '.
2711: 'onchange="'.$jscall.'" />',
2712: '<label><input type="hidden" name="krbver" value="5" />',
2713: '</label>');
2714: }
2715: return $result;
2716: }
2717:
2718: sub authform_internal {
2719: my %in = (
2720: formname => 'document.cu',
2721: kerb_def_dom => 'MSU.EDU',
2722: @_,
2723: );
2724: my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
2725: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2726: if (defined($in{'curr_authtype'})) {
2727: if ($in{'curr_authtype'} eq 'int') {
2728: if ($can_assign{'int'}) {
2729: $intcheck = 'checked="checked" ';
2730: if (defined($in{'mode'})) {
2731: if ($in{'mode'} eq 'modifyuser') {
2732: $intcheck = '';
2733: }
2734: }
2735: if (defined($in{'curr_autharg'})) {
2736: $intarg = $in{'curr_autharg'};
2737: }
2738: } else {
2739: $result = &mt('Currently internally authenticated.');
2740: return $result;
2741: }
2742: }
2743: } else {
2744: if ($authnum == 1) {
2745: $authtype = '<input type="hidden" name="login" value="int" />';
2746: }
2747: }
2748: if (!$can_assign{'int'}) {
2749: return;
2750: } elsif ($authtype eq '') {
2751: if (defined($in{'mode'})) {
2752: if ($in{'mode'} eq 'modifycourse') {
2753: if ($authnum == 1) {
2754: $authtype = '<input type="radio" name="login" value="int" />';
2755: }
2756: }
2757: }
2758: }
2759: $jscall = "javascript:changed_radio('int',$in{'formname'});";
2760: if ($authtype eq '') {
2761: $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
2762: ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
2763: }
2764: $autharg = '<input type="password" size="10" name="intarg" value="'.
2765: $intarg.'" onchange="'.$jscall.'" />';
2766: $result = &mt
2767: ('[_1] Internally authenticated (with initial password [_2])',
2768: '<label>'.$authtype,'</label>'.$autharg);
2769: $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>';
2770: return $result;
2771: }
2772:
2773: sub authform_local {
2774: my %in = (
2775: formname => 'document.cu',
2776: kerb_def_dom => 'MSU.EDU',
2777: @_,
2778: );
2779: my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
2780: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2781: if (defined($in{'curr_authtype'})) {
2782: if ($in{'curr_authtype'} eq 'loc') {
2783: if ($can_assign{'loc'}) {
2784: $loccheck = 'checked="checked" ';
2785: if (defined($in{'mode'})) {
2786: if ($in{'mode'} eq 'modifyuser') {
2787: $loccheck = '';
2788: }
2789: }
2790: if (defined($in{'curr_autharg'})) {
2791: $locarg = $in{'curr_autharg'};
2792: }
2793: } else {
2794: $result = &mt('Currently using local (institutional) authentication.');
2795: return $result;
2796: }
2797: }
2798: } else {
2799: if ($authnum == 1) {
2800: $authtype = '<input type="hidden" name="login" value="loc" />';
2801: }
2802: }
2803: if (!$can_assign{'loc'}) {
2804: return;
2805: } elsif ($authtype eq '') {
2806: if (defined($in{'mode'})) {
2807: if ($in{'mode'} eq 'modifycourse') {
2808: if ($authnum == 1) {
2809: $authtype = '<input type="radio" name="login" value="loc" />';
2810: }
2811: }
2812: }
2813: }
2814: $jscall = "javascript:changed_radio('loc',$in{'formname'});";
2815: if ($authtype eq '') {
2816: $authtype = '<input type="radio" name="login" value="loc" '.
2817: $loccheck.' onchange="'.$jscall.'" onclick="'.
2818: $jscall.'" />';
2819: }
2820: $autharg = '<input type="text" size="10" name="locarg" value="'.
2821: $locarg.'" onchange="'.$jscall.'" />';
2822: $result = &mt('[_1] Local Authentication with argument [_2]',
2823: '<label>'.$authtype,'</label>'.$autharg);
2824: return $result;
2825: }
2826:
2827: sub authform_filesystem {
2828: my %in = (
2829: formname => 'document.cu',
2830: kerb_def_dom => 'MSU.EDU',
2831: @_,
2832: );
2833: my ($fsyscheck,$result,$authtype,$autharg,$jscall);
2834: my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
2835: if (defined($in{'curr_authtype'})) {
2836: if ($in{'curr_authtype'} eq 'fsys') {
2837: if ($can_assign{'fsys'}) {
2838: $fsyscheck = 'checked="checked" ';
2839: if (defined($in{'mode'})) {
2840: if ($in{'mode'} eq 'modifyuser') {
2841: $fsyscheck = '';
2842: }
2843: }
2844: } else {
2845: $result = &mt('Currently Filesystem Authenticated.');
2846: return $result;
2847: }
2848: }
2849: } else {
2850: if ($authnum == 1) {
2851: $authtype = '<input type="hidden" name="login" value="fsys" />';
2852: }
2853: }
2854: if (!$can_assign{'fsys'}) {
2855: return;
2856: } elsif ($authtype eq '') {
2857: if (defined($in{'mode'})) {
2858: if ($in{'mode'} eq 'modifycourse') {
2859: if ($authnum == 1) {
2860: $authtype = '<input type="radio" name="login" value="fsys" />';
2861: }
2862: }
2863: }
2864: }
2865: $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
2866: if ($authtype eq '') {
2867: $authtype = '<input type="radio" name="login" value="fsys" '.
2868: $fsyscheck.' onchange="'.$jscall.'" onclick="'.
2869: $jscall.'" />';
2870: }
2871: $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
2872: ' onchange="'.$jscall.'" />';
2873: $result = &mt
2874: ('[_1] Filesystem Authenticated (with initial password [_2])',
2875: '<label><input type="radio" name="login" value="fsys" '.
2876: $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
2877: '</label><input type="password" size="10" name="fsysarg" value="" '.
2878: 'onchange="'.$jscall.'" />');
2879: return $result;
2880: }
2881:
2882: sub get_assignable_auth {
2883: my ($dom) = @_;
2884: if ($dom eq '') {
2885: $dom = $env{'request.role.domain'};
2886: }
2887: my %can_assign = (
2888: krb4 => 1,
2889: krb5 => 1,
2890: int => 1,
2891: loc => 1,
2892: );
2893: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
2894: if (ref($domconfig{'usercreation'}) eq 'HASH') {
2895: if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
2896: my $authhash = $domconfig{'usercreation'}{'authtypes'};
2897: my $context;
2898: if ($env{'request.role'} =~ /^au/) {
2899: $context = 'author';
2900: } elsif ($env{'request.role'} =~ /^dc/) {
2901: $context = 'domain';
2902: } elsif ($env{'request.course.id'}) {
2903: $context = 'course';
2904: }
2905: if ($context) {
2906: if (ref($authhash->{$context}) eq 'HASH') {
2907: %can_assign = %{$authhash->{$context}};
2908: }
2909: }
2910: }
2911: }
2912: my $authnum = 0;
2913: foreach my $key (keys(%can_assign)) {
2914: if ($can_assign{$key}) {
2915: $authnum ++;
2916: }
2917: }
2918: if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
2919: $authnum --;
2920: }
2921: return ($authnum,%can_assign);
2922: }
2923:
2924: ###############################################################
2925: ## Get Kerberos Defaults for Domain ##
2926: ###############################################################
2927: ##
2928: ## Returns default kerberos version and an associated argument
2929: ## as listed in file domain.tab. If not listed, provides
2930: ## appropriate default domain and kerberos version.
2931: ##
2932: #-------------------------------------------
2933:
2934: =pod
2935:
2936: =item * &get_kerberos_defaults()
2937:
2938: get_kerberos_defaults($target_domain) returns the default kerberos
2939: version and domain. If not found, it defaults to version 4 and the
2940: domain of the server.
2941:
2942: =over 4
2943:
2944: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
2945:
2946: =back
2947:
2948: =back
2949:
2950: =cut
2951:
2952: #-------------------------------------------
2953: sub get_kerberos_defaults {
2954: my $domain=shift;
2955: my ($krbdef,$krbdefdom);
2956: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
2957: if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
2958: $krbdef = $domdefaults{'auth_def'};
2959: $krbdefdom = $domdefaults{'auth_arg_def'};
2960: } else {
2961: $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
2962: my $krbdefdom=$1;
2963: $krbdefdom=~tr/a-z/A-Z/;
2964: $krbdef = "krb4";
2965: }
2966: return ($krbdef,$krbdefdom);
2967: }
2968:
2969:
2970: ###############################################################
2971: ## Thesaurus Functions ##
2972: ###############################################################
2973:
2974: =pod
2975:
2976: =head1 Thesaurus Functions
2977:
2978: =over 4
2979:
2980: =item * &initialize_keywords()
2981:
2982: Initializes the package variable %Keywords if it is empty. Uses the
2983: package variable $thesaurus_db_file.
2984:
2985: =cut
2986:
2987: ###################################################
2988:
2989: sub initialize_keywords {
2990: return 1 if (scalar keys(%Keywords));
2991: # If we are here, %Keywords is empty, so fill it up
2992: # Make sure the file we need exists...
2993: if (! -e $thesaurus_db_file) {
2994: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
2995: " failed because it does not exist");
2996: return 0;
2997: }
2998: # Set up the hash as a database
2999: my %thesaurus_db;
3000: if (! tie(%thesaurus_db,'GDBM_File',
3001: $thesaurus_db_file,&GDBM_READER(),0640)){
3002: &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
3003: $thesaurus_db_file);
3004: return 0;
3005: }
3006: # Get the average number of appearances of a word.
3007: my $avecount = $thesaurus_db{'average.count'};
3008: # Put keywords (those that appear > average) into %Keywords
3009: while (my ($word,$data)=each (%thesaurus_db)) {
3010: my ($count,undef) = split /:/,$data;
3011: $Keywords{$word}++ if ($count > $avecount);
3012: }
3013: untie %thesaurus_db;
3014: # Remove special values from %Keywords.
3015: foreach my $value ('total.count','average.count') {
3016: delete($Keywords{$value}) if (exists($Keywords{$value}));
3017: }
3018: return 1;
3019: }
3020:
3021: ###################################################
3022:
3023: =pod
3024:
3025: =item * &keyword($word)
3026:
3027: Returns true if $word is a keyword. A keyword is a word that appears more
3028: than the average number of times in the thesaurus database. Calls
3029: &initialize_keywords
3030:
3031: =cut
3032:
3033: ###################################################
3034:
3035: sub keyword {
3036: return if (!&initialize_keywords());
3037: my $word=lc(shift());
3038: $word=~s/\W//g;
3039: return exists($Keywords{$word});
3040: }
3041:
3042: ###############################################################
3043:
3044: =pod
3045:
3046: =item * &get_related_words()
3047:
3048: Look up a word in the thesaurus. Takes a scalar argument and returns
3049: an array of words. If the keyword is not in the thesaurus, an empty array
3050: will be returned. The order of the words returned is determined by the
3051: database which holds them.
3052:
3053: Uses global $thesaurus_db_file.
3054:
3055:
3056: =cut
3057:
3058: ###############################################################
3059: sub get_related_words {
3060: my $keyword = shift;
3061: my %thesaurus_db;
3062: if (! -e $thesaurus_db_file) {
3063: &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
3064: "failed because the file does not exist");
3065: return ();
3066: }
3067: if (! tie(%thesaurus_db,'GDBM_File',
3068: $thesaurus_db_file,&GDBM_READER(),0640)){
3069: return ();
3070: }
3071: my @Words=();
3072: my $count=0;
3073: if (exists($thesaurus_db{$keyword})) {
3074: # The first element is the number of times
3075: # the word appears. We do not need it now.
3076: my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
3077: my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
3078: my $threshold=$mostfrequentcount/10;
3079: foreach my $possibleword (@RelatedWords) {
3080: my ($word,$wordcount)=split(/\,/,$possibleword);
3081: if ($wordcount>$threshold) {
3082: push(@Words,$word);
3083: $count++;
3084: if ($count>10) { last; }
3085: }
3086: }
3087: }
3088: untie %thesaurus_db;
3089: return @Words;
3090: }
3091: ###############################################################
3092: #
3093: # Spell checking
3094: #
3095:
3096: =pod
3097:
3098: =back
3099:
3100: =head1 Spell checking
3101:
3102: =over 4
3103:
3104: =item * &check_spelling($wordlist $language)
3105:
3106: Takes a string containing words and feeds it to an external
3107: spellcheck program via a pipeline. Returns a string containing
3108: them mis-spelled words.
3109:
3110: Parameters:
3111:
3112: =over 4
3113:
3114: =item - $wordlist
3115:
3116: String that will be fed into the spellcheck program.
3117:
3118: =item - $language
3119:
3120: Language string that specifies the language for which the spell
3121: check will be performed.
3122:
3123: =back
3124:
3125: =back
3126:
3127: Note: This sub assumes that aspell is installed.
3128:
3129:
3130: =cut
3131:
3132:
3133: sub check_spelling {
3134: my ($wordlist, $language) = @_;
3135: my @misspellings;
3136:
3137: # Generate the speller and set the langauge.
3138: # if explicitly selected:
3139:
3140: my $speller = Text::Aspell->new;
3141: if ($language) {
3142: $speller->set_option('lang', $language);
3143: }
3144:
3145: # Turn the word list into an array of words by splittingon whitespace
3146:
3147: my @words = split(/\s+/, $wordlist);
3148:
3149: foreach my $word (@words) {
3150: if(! $speller->check($word)) {
3151: push(@misspellings, $word);
3152: }
3153: }
3154: return join(' ', @misspellings);
3155:
3156: }
3157:
3158: # -------------------------------------------------------------- Plaintext name
3159: =pod
3160:
3161: =head1 User Name Functions
3162:
3163: =over 4
3164:
3165: =item * &plainname($uname,$udom,$first)
3166:
3167: Takes a users logon name and returns it as a string in
3168: "first middle last generation" form
3169: if $first is set to 'lastname' then it returns it as
3170: 'lastname generation, firstname middlename' if their is a lastname
3171:
3172: =cut
3173:
3174:
3175: ###############################################################
3176: sub plainname {
3177: my ($uname,$udom,$first)=@_;
3178: return if (!defined($uname) || !defined($udom));
3179: my %names=&getnames($uname,$udom);
3180: my $name=&Apache::lonnet::format_name($names{'firstname'},
3181: $names{'middlename'},
3182: $names{'lastname'},
3183: $names{'generation'},$first);
3184: $name=~s/^\s+//;
3185: $name=~s/\s+$//;
3186: $name=~s/\s+/ /g;
3187: if ($name !~ /\S/) { $name=$uname.':'.$udom; }
3188: return $name;
3189: }
3190:
3191: # -------------------------------------------------------------------- Nickname
3192: =pod
3193:
3194: =item * &nickname($uname,$udom)
3195:
3196: Gets a users name and returns it as a string as
3197:
3198: ""nickname""
3199:
3200: if the user has a nickname or
3201:
3202: "first middle last generation"
3203:
3204: if the user does not
3205:
3206: =cut
3207:
3208: sub nickname {
3209: my ($uname,$udom)=@_;
3210: return if (!defined($uname) || !defined($udom));
3211: my %names=&getnames($uname,$udom);
3212: my $name=$names{'nickname'};
3213: if ($name) {
3214: $name='"'.$name.'"';
3215: } else {
3216: $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
3217: $names{'lastname'}.' '.$names{'generation'};
3218: $name=~s/\s+$//;
3219: $name=~s/\s+/ /g;
3220: }
3221: return $name;
3222: }
3223:
3224: sub getnames {
3225: my ($uname,$udom)=@_;
3226: return if (!defined($uname) || !defined($udom));
3227: if ($udom eq 'public' && $uname eq 'public') {
3228: return ('lastname' => &mt('Public'));
3229: }
3230: my $id=$uname.':'.$udom;
3231: my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
3232: if ($cached) {
3233: return %{$names};
3234: } else {
3235: my %loadnames=&Apache::lonnet::get('environment',
3236: ['firstname','middlename','lastname','generation','nickname'],
3237: $udom,$uname);
3238: &Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
3239: return %loadnames;
3240: }
3241: }
3242:
3243: # -------------------------------------------------------------------- getemails
3244:
3245: =pod
3246:
3247: =item * &getemails($uname,$udom)
3248:
3249: Gets a user's email information and returns it as a hash with keys:
3250: notification, critnotification, permanentemail
3251:
3252: For notification and critnotification, values are comma-separated lists
3253: of e-mail addresses; for permanentemail, value is a single e-mail address.
3254:
3255:
3256: =cut
3257:
3258:
3259: sub getemails {
3260: my ($uname,$udom)=@_;
3261: if ($udom eq 'public' && $uname eq 'public') {
3262: return;
3263: }
3264: if (!$udom) { $udom=$env{'user.domain'}; }
3265: if (!$uname) { $uname=$env{'user.name'}; }
3266: my $id=$uname.':'.$udom;
3267: my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
3268: if ($cached) {
3269: return %{$names};
3270: } else {
3271: my %loadnames=&Apache::lonnet::get('environment',
3272: ['notification','critnotification',
3273: 'permanentemail'],
3274: $udom,$uname);
3275: &Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
3276: return %loadnames;
3277: }
3278: }
3279:
3280: sub flush_email_cache {
3281: my ($uname,$udom)=@_;
3282: if (!$udom) { $udom =$env{'user.domain'}; }
3283: if (!$uname) { $uname=$env{'user.name'}; }
3284: return if ($udom eq 'public' && $uname eq 'public');
3285: my $id=$uname.':'.$udom;
3286: &Apache::lonnet::devalidate_cache_new('emailscache',$id);
3287: }
3288:
3289: # -------------------------------------------------------------------- getlangs
3290:
3291: =pod
3292:
3293: =item * &getlangs($uname,$udom)
3294:
3295: Gets a user's language preference and returns it as a hash with key:
3296: language.
3297:
3298: =cut
3299:
3300:
3301: sub getlangs {
3302: my ($uname,$udom) = @_;
3303: if (!$udom) { $udom =$env{'user.domain'}; }
3304: if (!$uname) { $uname=$env{'user.name'}; }
3305: my $id=$uname.':'.$udom;
3306: my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
3307: if ($cached) {
3308: return %{$langs};
3309: } else {
3310: my %loadlangs=&Apache::lonnet::get('environment',['languages'],
3311: $udom,$uname);
3312: &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
3313: return %loadlangs;
3314: }
3315: }
3316:
3317: sub flush_langs_cache {
3318: my ($uname,$udom)=@_;
3319: if (!$udom) { $udom =$env{'user.domain'}; }
3320: if (!$uname) { $uname=$env{'user.name'}; }
3321: return if ($udom eq 'public' && $uname eq 'public');
3322: my $id=$uname.':'.$udom;
3323: &Apache::lonnet::devalidate_cache_new('userlangs',$id);
3324: }
3325:
3326: # ------------------------------------------------------------------ Screenname
3327:
3328: =pod
3329:
3330: =item * &screenname($uname,$udom)
3331:
3332: Gets a users screenname and returns it as a string
3333:
3334: =cut
3335:
3336: sub screenname {
3337: my ($uname,$udom)=@_;
3338: if ($uname eq $env{'user.name'} &&
3339: $udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
3340: my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
3341: return $names{'screenname'};
3342: }
3343:
3344:
3345: # ------------------------------------------------------------- Confirm Wrapper
3346: =pod
3347:
3348: =item * &confirmwrapper($message)
3349:
3350: Wrap messages about completion of operation in box
3351:
3352: =cut
3353:
3354: sub confirmwrapper {
3355: my ($message)=@_;
3356: if ($message) {
3357: return "\n".'<div class="LC_confirm_box">'."\n"
3358: .$message."\n"
3359: .'</div>'."\n";
3360: } else {
3361: return $message;
3362: }
3363: }
3364:
3365: # ------------------------------------------------------------- Message Wrapper
3366:
3367: sub messagewrapper {
3368: my ($link,$username,$domain,$subject,$text)=@_;
3369: return
3370: '<a href="/adm/email?compose=individual&'.
3371: 'recname='.$username.'&recdom='.$domain.
3372: '&subject='.&escape($subject).'&text='.&escape($text).'" '.
3373: 'title="'.&mt('Send message').'">'.$link.'</a>';
3374: }
3375:
3376: # --------------------------------------------------------------- Notes Wrapper
3377:
3378: sub noteswrapper {
3379: my ($link,$un,$do)=@_;
3380: return
3381: "<a href='/adm/email?recordftf=retrieve&recname=$un&recdom=$do'>$link</a>";
3382: }
3383:
3384: # ------------------------------------------------------------- Aboutme Wrapper
3385:
3386: sub aboutmewrapper {
3387: my ($link,$username,$domain,$target,$class)=@_;
3388: if (!defined($username) && !defined($domain)) {
3389: return;
3390: }
3391: return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
3392: ($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
3393: }
3394:
3395: # ------------------------------------------------------------ Syllabus Wrapper
3396:
3397: sub syllabuswrapper {
3398: my ($linktext,$coursedir,$domain)=@_;
3399: return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
3400: }
3401:
3402: # -----------------------------------------------------------------------------
3403:
3404: sub track_student_link {
3405: my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
3406: my $link ="/adm/trackstudent?";
3407: my $title = 'View recent activity';
3408: if (defined($sname) && $sname !~ /^\s*$/ &&
3409: defined($sdom) && $sdom !~ /^\s*$/) {
3410: $link .= "selected_student=$sname:$sdom";
3411: $title .= ' of this student';
3412: }
3413: if (defined($target) && $target !~ /^\s*$/) {
3414: $target = qq{target="$target"};
3415: } else {
3416: $target = '';
3417: }
3418: if ($start) { $link.='&start='.$start; }
3419: if ($only_body) { $link .= '&only_body=1'; }
3420: $title = &mt($title);
3421: $linktext = &mt($linktext);
3422: return qq{<a href="$link" title="$title" $target>$linktext</a>}.
3423: &help_open_topic('View_recent_activity');
3424: }
3425:
3426: sub slot_reservations_link {
3427: my ($linktext,$sname,$sdom,$target) = @_;
3428: my $link ="/adm/slotrequest?command=showresv&origin=aboutme";
3429: my $title = 'View slot reservation history';
3430: if (defined($sname) && $sname !~ /^\s*$/ &&
3431: defined($sdom) && $sdom !~ /^\s*$/) {
3432: $link .= "&uname=$sname&udom=$sdom";
3433: $title .= ' of this student';
3434: }
3435: if (defined($target) && $target !~ /^\s*$/) {
3436: $target = qq{target="$target"};
3437: } else {
3438: $target = '';
3439: }
3440: $title = &mt($title);
3441: $linktext = &mt($linktext);
3442: return qq{<a href="$link" title="$title" $target>$linktext</a>};
3443: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
3444:
3445: }
3446:
3447: # ===================================================== Display a student photo
3448:
3449:
3450: sub student_image_tag {
3451: my ($domain,$user)=@_;
3452: my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
3453: if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
3454: return '<img src="'.$imgsrc.'" align="right" />';
3455: } else {
3456: return '';
3457: }
3458: }
3459:
3460: =pod
3461:
3462: =back
3463:
3464: =head1 Access .tab File Data
3465:
3466: =over 4
3467:
3468: =item * &languageids()
3469:
3470: returns list of all language ids
3471:
3472: =cut
3473:
3474: sub languageids {
3475: return sort(keys(%language));
3476: }
3477:
3478: =pod
3479:
3480: =item * &languagedescription()
3481:
3482: returns description of a specified language id
3483:
3484: =cut
3485:
3486: sub languagedescription {
3487: my $code=shift;
3488: return ($supported_language{$code}?'* ':'').
3489: $language{$code}.
3490: ($supported_language{$code}?' ('.&mt('interface available').')':'');
3491: }
3492:
3493: =pod
3494:
3495: =item * &plainlanguagedescription
3496:
3497: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
3498: and the language character encoding (e.g. ISO) separated by a ' - ' string.
3499:
3500: =cut
3501:
3502: sub plainlanguagedescription {
3503: my $code=shift;
3504: return $language{$code};
3505: }
3506:
3507: =pod
3508:
3509: =item * &supportedlanguagecode
3510:
3511: Returns the supported language code (e.g. sptutf maps to pt) given a language
3512: code.
3513:
3514: =cut
3515:
3516: sub supportedlanguagecode {
3517: my $code=shift;
3518: return $supported_language{$code};
3519: }
3520:
3521: =pod
3522:
3523: =item * &latexlanguage()
3524:
3525: Given a language key code returns the correspondnig language to use
3526: to select the correct hyphenation on LaTeX printouts. This is undef if there
3527: is no supported hyphenation for the language code.
3528:
3529: =cut
3530:
3531: sub latexlanguage {
3532: my $code = shift;
3533: return $latex_language{$code};
3534: }
3535:
3536: =pod
3537:
3538: =item * &latexhyphenation()
3539:
3540: Same as above but what's supplied is the language as it might be stored
3541: in the metadata.
3542:
3543: =cut
3544:
3545: sub latexhyphenation {
3546: my $key = shift;
3547: return $latex_language_bykey{$key};
3548: }
3549:
3550: =pod
3551:
3552: =item * ©rightids()
3553:
3554: returns list of all copyrights
3555:
3556: =cut
3557:
3558: sub copyrightids {
3559: return sort(keys(%cprtag));
3560: }
3561:
3562: =pod
3563:
3564: =item * ©rightdescription()
3565:
3566: returns description of a specified copyright id
3567:
3568: =cut
3569:
3570: sub copyrightdescription {
3571: return &mt($cprtag{shift(@_)});
3572: }
3573:
3574: =pod
3575:
3576: =item * &source_copyrightids()
3577:
3578: returns list of all source copyrights
3579:
3580: =cut
3581:
3582: sub source_copyrightids {
3583: return sort(keys(%scprtag));
3584: }
3585:
3586: =pod
3587:
3588: =item * &source_copyrightdescription()
3589:
3590: returns description of a specified source copyright id
3591:
3592: =cut
3593:
3594: sub source_copyrightdescription {
3595: return &mt($scprtag{shift(@_)});
3596: }
3597:
3598: =pod
3599:
3600: =item * &filecategories()
3601:
3602: returns list of all file categories
3603:
3604: =cut
3605:
3606: sub filecategories {
3607: return sort(keys(%category_extensions));
3608: }
3609:
3610: =pod
3611:
3612: =item * &filecategorytypes()
3613:
3614: returns list of file types belonging to a given file
3615: category
3616:
3617: =cut
3618:
3619: sub filecategorytypes {
3620: my ($cat) = @_;
3621: return @{$category_extensions{lc($cat)}};
3622: }
3623:
3624: =pod
3625:
3626: =item * &fileembstyle()
3627:
3628: returns embedding style for a specified file type
3629:
3630: =cut
3631:
3632: sub fileembstyle {
3633: return $fe{lc(shift(@_))};
3634: }
3635:
3636: sub filemimetype {
3637: return $fm{lc(shift(@_))};
3638: }
3639:
3640:
3641: sub filecategoryselect {
3642: my ($name,$value)=@_;
3643: return &select_form($value,$name,
3644: {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
3645: }
3646:
3647: =pod
3648:
3649: =item * &filedescription()
3650:
3651: returns description for a specified file type
3652:
3653: =cut
3654:
3655: sub filedescription {
3656: my $file_description = $fd{lc(shift())};
3657: $file_description =~ s:([\[\]]):~$1:g;
3658: return &mt($file_description);
3659: }
3660:
3661: =pod
3662:
3663: =item * &filedescriptionex()
3664:
3665: returns description for a specified file type with
3666: extra formatting
3667:
3668: =cut
3669:
3670: sub filedescriptionex {
3671: my $ex=shift;
3672: my $file_description = $fd{lc($ex)};
3673: $file_description =~ s:([\[\]]):~$1:g;
3674: return '.'.$ex.' '.&mt($file_description);
3675: }
3676:
3677: # End of .tab access
3678: =pod
3679:
3680: =back
3681:
3682: =cut
3683:
3684: # ------------------------------------------------------------------ File Types
3685: sub fileextensions {
3686: return sort(keys(%fe));
3687: }
3688:
3689: # ----------------------------------------------------------- Display Languages
3690: # returns a hash with all desired display languages
3691: #
3692:
3693: sub display_languages {
3694: my %languages=();
3695: foreach my $lang (&Apache::lonlocal::preferred_languages()) {
3696: $languages{$lang}=1;
3697: }
3698: &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
3699: if ($env{'form.displaylanguage'}) {
3700: foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
3701: $languages{$lang}=1;
3702: }
3703: }
3704: return %languages;
3705: }
3706:
3707: sub languages {
3708: my ($possible_langs) = @_;
3709: my @preferred_langs = &Apache::lonlocal::preferred_languages();
3710: if (!ref($possible_langs)) {
3711: if( wantarray ) {
3712: return @preferred_langs;
3713: } else {
3714: return $preferred_langs[0];
3715: }
3716: }
3717: my %possibilities = map { $_ => 1 } (@$possible_langs);
3718: my @preferred_possibilities;
3719: foreach my $preferred_lang (@preferred_langs) {
3720: if (exists($possibilities{$preferred_lang})) {
3721: push(@preferred_possibilities, $preferred_lang);
3722: }
3723: }
3724: if( wantarray ) {
3725: return @preferred_possibilities;
3726: }
3727: return $preferred_possibilities[0];
3728: }
3729:
3730: sub user_lang {
3731: my ($touname,$toudom,$fromcid) = @_;
3732: my @userlangs;
3733: if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
3734: @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
3735: $env{'course.'.$fromcid.'.languages'}));
3736: } else {
3737: my %langhash = &getlangs($touname,$toudom);
3738: if ($langhash{'languages'} ne '') {
3739: @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
3740: } else {
3741: my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
3742: if ($domdefs{'lang_def'} ne '') {
3743: @userlangs = ($domdefs{'lang_def'});
3744: }
3745: }
3746: }
3747: my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
3748: my $user_lh = Apache::localize->get_handle(@languages);
3749: return $user_lh;
3750: }
3751:
3752:
3753: ###############################################################
3754: ## Student Answer Attempts ##
3755: ###############################################################
3756:
3757: =pod
3758:
3759: =head1 Alternate Problem Views
3760:
3761: =over 4
3762:
3763: =item * &get_previous_attempt($symb, $username, $domain, $course,
3764: $getattempt, $regexp, $gradesub, $usec, $identifier)
3765:
3766: Return string with previous attempt on problem. Arguments:
3767:
3768: =over 4
3769:
3770: =item * $symb: Problem, including path
3771:
3772: =item * $username: username of the desired student
3773:
3774: =item * $domain: domain of the desired student
3775:
3776: =item * $course: Course ID
3777:
3778: =item * $getattempt: Leave blank for all attempts, otherwise put
3779: something
3780:
3781: =item * $regexp: if string matches this regexp, the string will be
3782: sent to $gradesub
3783:
3784: =item * $gradesub: routine that processes the string if it matches $regexp
3785:
3786: =item * $usec: section of the desired student
3787:
3788: =item * $identifier: counter for student (multiple students one problem) or
3789: problem (one student; whole sequence).
3790:
3791: =back
3792:
3793: The output string is a table containing all desired attempts, if any.
3794:
3795: =cut
3796:
3797: sub get_previous_attempt {
3798: my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
3799: my $prevattempts='';
3800: no strict 'refs';
3801: if ($symb) {
3802: my (%returnhash)=
3803: &Apache::lonnet::restore($symb,$course,$domain,$username);
3804: if ($returnhash{'version'}) {
3805: my %lasthash=();
3806: my $version;
3807: for ($version=1;$version<=$returnhash{'version'};$version++) {
3808: foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
3809: $lasthash{$key}=$returnhash{$version.':'.$key};
3810: }
3811: }
3812: $prevattempts=&start_data_table().&start_data_table_header_row();
3813: $prevattempts.='<th>'.&mt('History').'</th>';
3814: my (%typeparts,%lasthidden,%regraded,%hidestatus);
3815: my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
3816: foreach my $key (sort(keys(%lasthash))) {
3817: my ($ign,@parts) = split(/\./,$key);
3818: if ($#parts > 0) {
3819: my $data=$parts[-1];
3820: next if ($data eq 'foilorder');
3821: pop(@parts);
3822: $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.' </th>';
3823: if ($data eq 'type') {
3824: unless ($showsurv) {
3825: my $id = join(',',@parts);
3826: $typeparts{$ign.'.'.$id} = $lasthash{$key};
3827: if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
3828: $lasthidden{$ign.'.'.$id} = 1;
3829: }
3830: }
3831: if ($identifier ne '') {
3832: my $id = join(',',@parts);
3833: if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
3834: $domain,$username,$usec,undef,$course) =~ /^no/) {
3835: $hidestatus{$ign.'.'.$id} = 1;
3836: }
3837: }
3838: } elsif ($data eq 'regrader') {
3839: if (($identifier ne '') && (@parts)) {
3840: my $id = join(',',@parts);
3841: $regraded{$ign.'.'.$id} = 1;
3842: }
3843: }
3844: } else {
3845: if ($#parts == 0) {
3846: $prevattempts.='<th>'.$parts[0].'</th>';
3847: } else {
3848: $prevattempts.='<th>'.$ign.'</th>';
3849: }
3850: }
3851: }
3852: $prevattempts.=&end_data_table_header_row();
3853: if ($getattempt eq '') {
3854: my (%solved,%resets,%probstatus);
3855: if (($identifier ne '') && (keys(%regraded) > 0)) {
3856: for ($version=1;$version<=$returnhash{'version'};$version++) {
3857: foreach my $id (keys(%regraded)) {
3858: if (($returnhash{$version.':'.$id.'.regrader'}) &&
3859: ($returnhash{$version.':'.$id.'.tries'} eq '') &&
3860: ($returnhash{$version.':'.$id.'.award'} eq '')) {
3861: push(@{$resets{$id}},$version);
3862: }
3863: }
3864: }
3865: }
3866: for ($version=1;$version<=$returnhash{'version'};$version++) {
3867: my (@hidden,@unsolved);
3868: if (%typeparts) {
3869: foreach my $id (keys(%typeparts)) {
3870: if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
3871: ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
3872: push(@hidden,$id);
3873: } elsif ($identifier ne '') {
3874: unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
3875: ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
3876: ($hidestatus{$id})) {
3877: next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
3878: if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
3879: push(@{$solved{$id}},$version);
3880: } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
3881: (ref($solved{$id}) eq 'ARRAY')) {
3882: my $skip;
3883: if (ref($resets{$id}) eq 'ARRAY') {
3884: foreach my $reset (@{$resets{$id}}) {
3885: if ($reset > $solved{$id}[-1]) {
3886: $skip=1;
3887: last;
3888: }
3889: }
3890: }
3891: unless ($skip) {
3892: my ($ign,$partslist) = split(/\./,$id,2);
3893: push(@unsolved,$partslist);
3894: }
3895: }
3896: }
3897: }
3898: }
3899: }
3900: $prevattempts.=&start_data_table_row().
3901: '<td>'.&mt('Transaction [_1]',$version);
3902: if (@unsolved) {
3903: $prevattempts .= '<span class="LC_nobreak"><label>'.
3904: '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
3905: &mt('Hide').'</label></span>';
3906: }
3907: $prevattempts .= '</td>';
3908: if (@hidden) {
3909: foreach my $key (sort(keys(%lasthash))) {
3910: next if ($key =~ /\.foilorder$/);
3911: my $hide;
3912: foreach my $id (@hidden) {
3913: if ($key =~ /^\Q$id\E/) {
3914: $hide = 1;
3915: last;
3916: }
3917: }
3918: if ($hide) {
3919: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
3920: if (($data eq 'award') || ($data eq 'awarddetail')) {
3921: my $value = &format_previous_attempt_value($key,
3922: $returnhash{$version.':'.$key});
3923: $prevattempts.='<td>'.$value.' </td>';
3924: } else {
3925: $prevattempts.='<td> </td>';
3926: }
3927: } else {
3928: if ($key =~ /\./) {
3929: my $value = &format_previous_attempt_value($key,
3930: $returnhash{$version.':'.$key});
3931: $prevattempts.='<td>'.$value.' </td>';
3932: } else {
3933: $prevattempts.='<td> </td>';
3934: }
3935: }
3936: }
3937: } else {
3938: foreach my $key (sort(keys(%lasthash))) {
3939: next if ($key =~ /\.foilorder$/);
3940: my $value = &format_previous_attempt_value($key,
3941: $returnhash{$version.':'.$key});
3942: $prevattempts.='<td>'.$value.' </td>';
3943: }
3944: }
3945: $prevattempts.=&end_data_table_row();
3946: }
3947: }
3948: my @currhidden = keys(%lasthidden);
3949: $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
3950: foreach my $key (sort(keys(%lasthash))) {
3951: next if ($key =~ /\.foilorder$/);
3952: if (%typeparts) {
3953: my $hidden;
3954: foreach my $id (@currhidden) {
3955: if ($key =~ /^\Q$id\E/) {
3956: $hidden = 1;
3957: last;
3958: }
3959: }
3960: if ($hidden) {
3961: my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
3962: if (($data eq 'award') || ($data eq 'awarddetail')) {
3963: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3964: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3965: $value = &$gradesub($value);
3966: }
3967: $prevattempts.='<td>'. $value.' </td>';
3968: } else {
3969: $prevattempts.='<td> </td>';
3970: }
3971: } else {
3972: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3973: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3974: $value = &$gradesub($value);
3975: }
3976: $prevattempts.='<td>'.$value.' </td>';
3977: }
3978: } else {
3979: my $value = &format_previous_attempt_value($key,$lasthash{$key});
3980: if ($key =~/$regexp$/ && (defined &$gradesub)) {
3981: $value = &$gradesub($value);
3982: }
3983: $prevattempts.='<td>'.$value.' </td>';
3984: }
3985: }
3986: $prevattempts.= &end_data_table_row().&end_data_table();
3987: } else {
3988: $prevattempts=
3989: &start_data_table().&start_data_table_row().
3990: '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
3991: &end_data_table_row().&end_data_table();
3992: }
3993: } else {
3994: $prevattempts=
3995: &start_data_table().&start_data_table_row().
3996: '<td>'.&mt('No data.').'</td>'.
3997: &end_data_table_row().&end_data_table();
3998: }
3999: }
4000:
4001: sub format_previous_attempt_value {
4002: my ($key,$value) = @_;
4003: if (($key =~ /timestamp/) || ($key=~/duedate/)) {
4004: $value = &Apache::lonlocal::locallocaltime($value);
4005: } elsif (ref($value) eq 'ARRAY') {
4006: $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
4007: } elsif ($key =~ /answerstring$/) {
4008: my %answers = &Apache::lonnet::str2hash($value);
4009: my @answer = %answers;
4010: %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
4011: my @anskeys = sort(keys(%answers));
4012: if (@anskeys == 1) {
4013: my $answer = $answers{$anskeys[0]};
4014: if ($answer =~ m{\0}) {
4015: $answer =~ s{\0}{,}g;
4016: }
4017: my $tag_internal_answer_name = 'INTERNAL';
4018: if ($anskeys[0] eq $tag_internal_answer_name) {
4019: $value = $answer;
4020: } else {
4021: $value = $anskeys[0].'='.$answer;
4022: }
4023: } else {
4024: foreach my $ans (@anskeys) {
4025: my $answer = $answers{$ans};
4026: if ($answer =~ m{\0}) {
4027: $answer =~ s{\0}{,}g;
4028: }
4029: $value .= $ans.'='.$answer.'<br />';;
4030: }
4031: }
4032: } else {
4033: $value = &HTML::Entities::encode(&unescape($value), '"<>&');
4034: }
4035: return $value;
4036: }
4037:
4038:
4039: sub relative_to_absolute {
4040: my ($url,$output)=@_;
4041: my $parser=HTML::TokeParser->new(\$output);
4042: my $token;
4043: my $thisdir=$url;
4044: my @rlinks=();
4045: while ($token=$parser->get_token) {
4046: if ($token->[0] eq 'S') {
4047: if ($token->[1] eq 'a') {
4048: if ($token->[2]->{'href'}) {
4049: $rlinks[$#rlinks+1]=$token->[2]->{'href'};
4050: }
4051: } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
4052: $rlinks[$#rlinks+1]=$token->[2]->{'src'};
4053: } elsif ($token->[1] eq 'base') {
4054: $thisdir=$token->[2]->{'href'};
4055: }
4056: }
4057: }
4058: $thisdir=~s-/[^/]*$--;
4059: foreach my $link (@rlinks) {
4060: unless (($link=~/^https?\:\/\//i) ||
4061: ($link=~/^\//) ||
4062: ($link=~/^javascript:/i) ||
4063: ($link=~/^mailto:/i) ||
4064: ($link=~/^\#/)) {
4065: my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
4066: $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
4067: }
4068: }
4069: # -------------------------------------------------- Deal with Applet codebases
4070: $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
4071: return $output;
4072: }
4073:
4074: =pod
4075:
4076: =item * &get_student_view()
4077:
4078: show a snapshot of what student was looking at
4079:
4080: =cut
4081:
4082: sub get_student_view {
4083: my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
4084: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4085: my (%form);
4086: my @elements=('symb','courseid','domain','username');
4087: foreach my $element (@elements) {
4088: $form{'grade_'.$element}=eval '$'.$element #'
4089: }
4090: if (defined($moreenv)) {
4091: %form=(%form,%{$moreenv});
4092: }
4093: if (defined($target)) { $form{'grade_target'} = $target; }
4094: $feedurl=&Apache::lonnet::clutter($feedurl);
4095: my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
4096: $userview=~s/\<body[^\>]*\>//gi;
4097: $userview=~s/\<\/body\>//gi;
4098: $userview=~s/\<html\>//gi;
4099: $userview=~s/\<\/html\>//gi;
4100: $userview=~s/\<head\>//gi;
4101: $userview=~s/\<\/head\>//gi;
4102: $userview=~s/action\s*\=/would_be_action\=/gi;
4103: $userview=&relative_to_absolute($feedurl,$userview);
4104: if (wantarray) {
4105: return ($userview,$response);
4106: } else {
4107: return $userview;
4108: }
4109: }
4110:
4111: sub get_student_view_with_retries {
4112: my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
4113:
4114: my $ok = 0; # True if we got a good response.
4115: my $content;
4116: my $response;
4117:
4118: # Try to get the student_view done. within the retries count:
4119:
4120: do {
4121: ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
4122: $ok = $response->is_success;
4123: if (!$ok) {
4124: &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
4125: }
4126: $retries--;
4127: } while (!$ok && ($retries > 0));
4128:
4129: if (!$ok) {
4130: $content = ''; # On error return an empty content.
4131: }
4132: if (wantarray) {
4133: return ($content, $response);
4134: } else {
4135: return $content;
4136: }
4137: }
4138:
4139: =pod
4140:
4141: =item * &get_student_answers()
4142:
4143: show a snapshot of how student was answering problem
4144:
4145: =cut
4146:
4147: sub get_student_answers {
4148: my ($symb,$username,$domain,$courseid,%form) = @_;
4149: my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
4150: my (%moreenv);
4151: my @elements=('symb','courseid','domain','username');
4152: foreach my $element (@elements) {
4153: $moreenv{'grade_'.$element}=eval '$'.$element #'
4154: }
4155: $moreenv{'grade_target'}='answer';
4156: %moreenv=(%form,%moreenv);
4157: $feedurl = &Apache::lonnet::clutter($feedurl);
4158: my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
4159: return $userview;
4160: }
4161:
4162: =pod
4163:
4164: =item * &submlink()
4165:
4166: Inputs: $text $uname $udom $symb $target
4167:
4168: Returns: A link to grades.pm such as to see the SUBM view of a student
4169:
4170: =cut
4171:
4172: ###############################################
4173: sub submlink {
4174: my ($text,$uname,$udom,$symb,$target)=@_;
4175: if (!($uname && $udom)) {
4176: (my $cursymb, my $courseid,$udom,$uname)=
4177: &Apache::lonnet::whichuser($symb);
4178: if (!$symb) { $symb=$cursymb; }
4179: }
4180: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4181: $symb=&escape($symb);
4182: if ($target) { $target=" target=\"$target\""; }
4183: return
4184: '<a href="/adm/grades?command=submission'.
4185: '&symb='.$symb.
4186: '&student='.$uname.
4187: '&userdom='.$udom.'"'.
4188: $target.'>'.$text.'</a>';
4189: }
4190: ##############################################
4191:
4192: =pod
4193:
4194: =item * &pgrdlink()
4195:
4196: Inputs: $text $uname $udom $symb $target
4197:
4198: Returns: A link to grades.pm such as to see the PGRD view of a student
4199:
4200: =cut
4201:
4202: ###############################################
4203: sub pgrdlink {
4204: my $link=&submlink(@_);
4205: $link=~s/(&command=submission)/$1&showgrading=yes/;
4206: return $link;
4207: }
4208: ##############################################
4209:
4210: =pod
4211:
4212: =item * &pprmlink()
4213:
4214: Inputs: $text $uname $udom $symb $target
4215:
4216: Returns: A link to parmset.pm such as to see the PPRM view of a
4217: student and a specific resource
4218:
4219: =cut
4220:
4221: ###############################################
4222: sub pprmlink {
4223: my ($text,$uname,$udom,$symb,$target)=@_;
4224: if (!($uname && $udom)) {
4225: (my $cursymb, my $courseid,$udom,$uname)=
4226: &Apache::lonnet::whichuser($symb);
4227: if (!$symb) { $symb=$cursymb; }
4228: }
4229: if (!$symb) { $symb=&Apache::lonnet::symbread(); }
4230: $symb=&escape($symb);
4231: if ($target) { $target="target=\"$target\""; }
4232: return '<a href="/adm/parmset?command=set&'.
4233: 'symb='.$symb.'&uname='.$uname.
4234: '&udom='.$udom.'" '.$target.'>'.$text.'</a>';
4235: }
4236: ##############################################
4237:
4238: =pod
4239:
4240: =back
4241:
4242: =cut
4243:
4244: ###############################################
4245:
4246:
4247: sub timehash {
4248: my ($thistime) = @_;
4249: my $timezone = &Apache::lonlocal::gettimezone();
4250: my $dt = DateTime->from_epoch(epoch => $thistime)
4251: ->set_time_zone($timezone);
4252: my $wday = $dt->day_of_week();
4253: if ($wday == 7) { $wday = 0; }
4254: return ( 'second' => $dt->second(),
4255: 'minute' => $dt->minute(),
4256: 'hour' => $dt->hour(),
4257: 'day' => $dt->day_of_month(),
4258: 'month' => $dt->month(),
4259: 'year' => $dt->year(),
4260: 'weekday' => $wday,
4261: 'dayyear' => $dt->day_of_year(),
4262: 'dlsav' => $dt->is_dst() );
4263: }
4264:
4265: sub utc_string {
4266: my ($date)=@_;
4267: return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
4268: }
4269:
4270: sub maketime {
4271: my %th=@_;
4272: my ($epoch_time,$timezone,$dt);
4273: $timezone = &Apache::lonlocal::gettimezone();
4274: eval {
4275: $dt = DateTime->new( year => $th{'year'},
4276: month => $th{'month'},
4277: day => $th{'day'},
4278: hour => $th{'hour'},
4279: minute => $th{'minute'},
4280: second => $th{'second'},
4281: time_zone => $timezone,
4282: );
4283: };
4284: if (!$@) {
4285: $epoch_time = $dt->epoch;
4286: if ($epoch_time) {
4287: return $epoch_time;
4288: }
4289: }
4290: return POSIX::mktime(
4291: ($th{'seconds'},$th{'minutes'},$th{'hours'},
4292: $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
4293: }
4294:
4295: #########################################
4296:
4297: sub findallcourses {
4298: my ($roles,$uname,$udom) = @_;
4299: my %roles;
4300: if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
4301: my %courses;
4302: my $now=time;
4303: if (!defined($uname)) {
4304: $uname = $env{'user.name'};
4305: }
4306: if (!defined($udom)) {
4307: $udom = $env{'user.domain'};
4308: }
4309: if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
4310: my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
4311: if (!%roles) {
4312: %roles = (
4313: cc => 1,
4314: co => 1,
4315: in => 1,
4316: ep => 1,
4317: ta => 1,
4318: cr => 1,
4319: st => 1,
4320: );
4321: }
4322: foreach my $entry (keys(%roleshash)) {
4323: my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
4324: if ($trole =~ /^cr/) {
4325: next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
4326: } else {
4327: next if (!exists($roles{$trole}));
4328: }
4329: if ($tend) {
4330: next if ($tend < $now);
4331: }
4332: if ($tstart) {
4333: next if ($tstart > $now);
4334: }
4335: my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
4336: (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
4337: my $value = $trole.'/'.$cdom.'/';
4338: if ($secpart eq '') {
4339: ($cnum,$role) = split(/_/,$cnumpart);
4340: $sec = 'none';
4341: $value .= $cnum.'/';
4342: } else {
4343: $cnum = $cnumpart;
4344: ($sec,$role) = split(/_/,$secpart);
4345: $value .= $cnum.'/'.$sec;
4346: }
4347: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4348: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4349: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4350: }
4351: } else {
4352: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4353: }
4354: }
4355: } else {
4356: foreach my $key (keys(%env)) {
4357: if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
4358: $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
4359: my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
4360: next if ($role eq 'ca' || $role eq 'aa');
4361: next if (%roles && !exists($roles{$role}));
4362: my ($starttime,$endtime)=split(/\./,$env{$key});
4363: my $active=1;
4364: if ($starttime) {
4365: if ($now<$starttime) { $active=0; }
4366: }
4367: if ($endtime) {
4368: if ($now>$endtime) { $active=0; }
4369: }
4370: if ($active) {
4371: my $value = $role.'/'.$cdom.'/'.$cnum.'/';
4372: if ($sec eq '') {
4373: $sec = 'none';
4374: } else {
4375: $value .= $sec;
4376: }
4377: if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
4378: unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
4379: push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
4380: }
4381: } else {
4382: @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
4383: }
4384: }
4385: }
4386: }
4387: }
4388: return %courses;
4389: }
4390:
4391: ###############################################
4392:
4393: sub blockcheck {
4394: my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
4395:
4396: if (defined($udom) && defined($uname)) {
4397: # If uname and udom are for a course, check for blocks in the course.
4398: if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
4399: my ($startblock,$endblock,$triggerblock) =
4400: &get_blocks($setters,$activity,$udom,$uname,$url);
4401: return ($startblock,$endblock,$triggerblock);
4402: }
4403: } else {
4404: $udom = $env{'user.domain'};
4405: $uname = $env{'user.name'};
4406: }
4407:
4408: my $startblock = 0;
4409: my $endblock = 0;
4410: my $triggerblock = '';
4411: my %live_courses = &findallcourses(undef,$uname,$udom);
4412:
4413: # If uname is for a user, and activity is course-specific, i.e.,
4414: # boards, chat or groups, check for blocking in current course only.
4415:
4416: if (($activity eq 'boards' || $activity eq 'chat' ||
4417: $activity eq 'groups' || $activity eq 'printout') &&
4418: ($env{'request.course.id'})) {
4419: foreach my $key (keys(%live_courses)) {
4420: if ($key ne $env{'request.course.id'}) {
4421: delete($live_courses{$key});
4422: }
4423: }
4424: }
4425:
4426: my $otheruser = 0;
4427: my %own_courses;
4428: if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
4429: # Resource belongs to user other than current user.
4430: $otheruser = 1;
4431: # Gather courses for current user
4432: %own_courses =
4433: &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
4434: }
4435:
4436: # Gather active course roles - course coordinator, instructor,
4437: # exam proctor, ta, student, or custom role.
4438:
4439: foreach my $course (keys(%live_courses)) {
4440: my ($cdom,$cnum);
4441: if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
4442: $cdom = $env{'course.'.$course.'.domain'};
4443: $cnum = $env{'course.'.$course.'.num'};
4444: } else {
4445: ($cdom,$cnum) = split(/_/,$course);
4446: }
4447: my $no_ownblock = 0;
4448: my $no_userblock = 0;
4449: if ($otheruser && $activity ne 'com') {
4450: # Check if current user has 'evb' priv for this
4451: if (defined($own_courses{$course})) {
4452: foreach my $sec (keys(%{$own_courses{$course}})) {
4453: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4454: if ($sec ne 'none') {
4455: $checkrole .= '/'.$sec;
4456: }
4457: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4458: $no_ownblock = 1;
4459: last;
4460: }
4461: }
4462: }
4463: # if they have 'evb' priv and are currently not playing student
4464: next if (($no_ownblock) &&
4465: ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
4466: }
4467: foreach my $sec (keys(%{$live_courses{$course}})) {
4468: my $checkrole = 'cm./'.$cdom.'/'.$cnum;
4469: if ($sec ne 'none') {
4470: $checkrole .= '/'.$sec;
4471: }
4472: if ($otheruser) {
4473: # Resource belongs to user other than current user.
4474: # Assemble privs for that user, and check for 'evb' priv.
4475: my (%allroles,%userroles);
4476: if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
4477: foreach my $entry (@{$live_courses{$course}{$sec}}) {
4478: my ($trole,$tdom,$tnum,$tsec);
4479: if ($entry =~ /^cr/) {
4480: ($trole,$tdom,$tnum,$tsec) =
4481: ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
4482: } else {
4483: ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
4484: }
4485: my ($spec,$area,$trest);
4486: $area = '/'.$tdom.'/'.$tnum;
4487: $trest = $tnum;
4488: if ($tsec ne '') {
4489: $area .= '/'.$tsec;
4490: $trest .= '/'.$tsec;
4491: }
4492: $spec = $trole.'.'.$area;
4493: if ($trole =~ /^cr/) {
4494: &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
4495: $tdom,$spec,$trest,$area);
4496: } else {
4497: &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
4498: $tdom,$spec,$trest,$area);
4499: }
4500: }
4501: my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
4502: if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
4503: if ($1) {
4504: $no_userblock = 1;
4505: last;
4506: }
4507: }
4508: }
4509: } else {
4510: # Resource belongs to current user
4511: # Check for 'evb' priv via lonnet::allowed().
4512: if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
4513: $no_ownblock = 1;
4514: last;
4515: }
4516: }
4517: }
4518: # if they have the evb priv and are currently not playing student
4519: next if (($no_ownblock) &&
4520: ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
4521: next if ($no_userblock);
4522:
4523: # Retrieve blocking times and identity of locker for course
4524: # of specified user, unless user has 'evb' privilege.
4525:
4526: my ($start,$end,$trigger) =
4527: &get_blocks($setters,$activity,$cdom,$cnum,$url);
4528: if (($start != 0) &&
4529: (($startblock == 0) || ($startblock > $start))) {
4530: $startblock = $start;
4531: if ($trigger ne '') {
4532: $triggerblock = $trigger;
4533: }
4534: }
4535: if (($end != 0) &&
4536: (($endblock == 0) || ($endblock < $end))) {
4537: $endblock = $end;
4538: if ($trigger ne '') {
4539: $triggerblock = $trigger;
4540: }
4541: }
4542: }
4543: return ($startblock,$endblock,$triggerblock);
4544: }
4545:
4546: sub get_blocks {
4547: my ($setters,$activity,$cdom,$cnum,$url) = @_;
4548: my $startblock = 0;
4549: my $endblock = 0;
4550: my $triggerblock = '';
4551: my $course = $cdom.'_'.$cnum;
4552: $setters->{$course} = {};
4553: $setters->{$course}{'staff'} = [];
4554: $setters->{$course}{'times'} = [];
4555: $setters->{$course}{'triggers'} = [];
4556: my (@blockers,%triggered);
4557: my $now = time;
4558: my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
4559: if ($activity eq 'docs') {
4560: @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
4561: foreach my $block (@blockers) {
4562: if ($block =~ /^firstaccess____(.+)$/) {
4563: my $item = $1;
4564: my $type = 'map';
4565: my $timersymb = $item;
4566: if ($item eq 'course') {
4567: $type = 'course';
4568: } elsif ($item =~ /___\d+___/) {
4569: $type = 'resource';
4570: } else {
4571: $timersymb = &Apache::lonnet::symbread($item);
4572: }
4573: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4574: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4575: $triggered{$block} = {
4576: start => $start,
4577: end => $end,
4578: type => $type,
4579: };
4580: }
4581: }
4582: } else {
4583: foreach my $block (keys(%commblocks)) {
4584: if ($block =~ m/^(\d+)____(\d+)$/) {
4585: my ($start,$end) = ($1,$2);
4586: if ($start <= time && $end >= time) {
4587: if (ref($commblocks{$block}) eq 'HASH') {
4588: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
4589: if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
4590: unless(grep(/^\Q$block\E$/,@blockers)) {
4591: push(@blockers,$block);
4592: }
4593: }
4594: }
4595: }
4596: }
4597: } elsif ($block =~ /^firstaccess____(.+)$/) {
4598: my $item = $1;
4599: my $timersymb = $item;
4600: my $type = 'map';
4601: if ($item eq 'course') {
4602: $type = 'course';
4603: } elsif ($item =~ /___\d+___/) {
4604: $type = 'resource';
4605: } else {
4606: $timersymb = &Apache::lonnet::symbread($item);
4607: }
4608: my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
4609: my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
4610: if ($start && $end) {
4611: if (($start <= time) && ($end >= time)) {
4612: unless (grep(/^\Q$block\E$/,@blockers)) {
4613: push(@blockers,$block);
4614: $triggered{$block} = {
4615: start => $start,
4616: end => $end,
4617: type => $type,
4618: };
4619: }
4620: }
4621: }
4622: }
4623: }
4624: }
4625: foreach my $blocker (@blockers) {
4626: my ($staff_name,$staff_dom,$title,$blocks) =
4627: &parse_block_record($commblocks{$blocker});
4628: push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
4629: my ($start,$end,$triggertype);
4630: if ($blocker =~ m/^(\d+)____(\d+)$/) {
4631: ($start,$end) = ($1,$2);
4632: } elsif (ref($triggered{$blocker}) eq 'HASH') {
4633: $start = $triggered{$blocker}{'start'};
4634: $end = $triggered{$blocker}{'end'};
4635: $triggertype = $triggered{$blocker}{'type'};
4636: }
4637: if ($start) {
4638: push(@{$$setters{$course}{'times'}}, [$start,$end]);
4639: if ($triggertype) {
4640: push(@{$$setters{$course}{'triggers'}},$triggertype);
4641: } else {
4642: push(@{$$setters{$course}{'triggers'}},0);
4643: }
4644: if ( ($startblock == 0) || ($startblock > $start) ) {
4645: $startblock = $start;
4646: if ($triggertype) {
4647: $triggerblock = $blocker;
4648: }
4649: }
4650: if ( ($endblock == 0) || ($endblock < $end) ) {
4651: $endblock = $end;
4652: if ($triggertype) {
4653: $triggerblock = $blocker;
4654: }
4655: }
4656: }
4657: }
4658: return ($startblock,$endblock,$triggerblock);
4659: }
4660:
4661: sub parse_block_record {
4662: my ($record) = @_;
4663: my ($setuname,$setudom,$title,$blocks);
4664: if (ref($record) eq 'HASH') {
4665: ($setuname,$setudom) = split(/:/,$record->{'setter'});
4666: $title = &unescape($record->{'event'});
4667: $blocks = $record->{'blocks'};
4668: } else {
4669: my @data = split(/:/,$record,3);
4670: if (scalar(@data) eq 2) {
4671: $title = $data[1];
4672: ($setuname,$setudom) = split(/@/,$data[0]);
4673: } else {
4674: ($setuname,$setudom,$title) = @data;
4675: }
4676: $blocks = { 'com' => 'on' };
4677: }
4678: return ($setuname,$setudom,$title,$blocks);
4679: }
4680:
4681: sub blocking_status {
4682: my ($activity,$uname,$udom,$url,$is_course) = @_;
4683: my %setters;
4684:
4685: # check for active blocking
4686: my ($startblock,$endblock,$triggerblock) =
4687: &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
4688: my $blocked = 0;
4689: if ($startblock && $endblock) {
4690: $blocked = 1;
4691: }
4692:
4693: # caller just wants to know whether a block is active
4694: if (!wantarray) { return $blocked; }
4695:
4696: # build a link to a popup window containing the details
4697: my $querystring = "?activity=$activity";
4698: # $uname and $udom decide whose portfolio the user is trying to look at
4699: if ($activity eq 'port') {
4700: $querystring .= "&udom=$udom" if $udom;
4701: $querystring .= "&uname=$uname" if $uname;
4702: } elsif ($activity eq 'docs') {
4703: $querystring .= '&url='.&HTML::Entities::encode($url,'&"');
4704: }
4705:
4706: my $output .= <<'END_MYBLOCK';
4707: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
4708: var options = "width=" + w + ",height=" + h + ",";
4709: options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
4710: options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
4711: var newWin = window.open(url, wdwName, options);
4712: newWin.focus();
4713: }
4714: END_MYBLOCK
4715:
4716: $output = Apache::lonhtmlcommon::scripttag($output);
4717:
4718: my $popupUrl = "/adm/blockingstatus/$querystring";
4719: my $text = &mt('Communication Blocked');
4720: if ($activity eq 'docs') {
4721: $text = &mt('Content Access Blocked');
4722: } elsif ($activity eq 'printout') {
4723: $text = &mt('Printing Blocked');
4724: }
4725: $output .= <<"END_BLOCK";
4726: <div class='LC_comblock'>
4727: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4728: title='$text'>
4729: <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
4730: <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
4731: title='$text'>$text</a>
4732: </div>
4733:
4734: END_BLOCK
4735:
4736: return ($blocked, $output);
4737: }
4738:
4739: ###############################################
4740:
4741: sub check_ip_acc {
4742: my ($acc,$clientip)=@_;
4743: &Apache::lonxml::debug("acc is $acc");
4744: if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
4745: return 1;
4746: }
4747: my $allowed=0;
4748: my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
4749:
4750: my $name;
4751: foreach my $pattern (split(',',$acc)) {
4752: $pattern =~ s/^\s*//;
4753: $pattern =~ s/\s*$//;
4754: if ($pattern =~ /\*$/) {
4755: #35.8.*
4756: $pattern=~s/\*//;
4757: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4758: } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
4759: #35.8.3.[34-56]
4760: my $low=$2;
4761: my $high=$3;
4762: $pattern=$1;
4763: if ($ip =~ /^\Q$pattern\E/) {
4764: my $last=(split(/\./,$ip))[3];
4765: if ($last <=$high && $last >=$low) { $allowed=1; }
4766: }
4767: } elsif ($pattern =~ /^\*/) {
4768: #*.msu.edu
4769: $pattern=~s/\*//;
4770: if (!defined($name)) {
4771: use Socket;
4772: my $netaddr=inet_aton($ip);
4773: ($name)=gethostbyaddr($netaddr,AF_INET);
4774: }
4775: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4776: } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
4777: #127.0.0.1
4778: if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
4779: } else {
4780: #some.name.com
4781: if (!defined($name)) {
4782: use Socket;
4783: my $netaddr=inet_aton($ip);
4784: ($name)=gethostbyaddr($netaddr,AF_INET);
4785: }
4786: if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
4787: }
4788: if ($allowed) { last; }
4789: }
4790: return $allowed;
4791: }
4792:
4793: ###############################################
4794:
4795: =pod
4796:
4797: =head1 Domain Template Functions
4798:
4799: =over 4
4800:
4801: =item * &determinedomain()
4802:
4803: Inputs: $domain (usually will be undef)
4804:
4805: Returns: Determines which domain should be used for designs
4806:
4807: =cut
4808:
4809: ###############################################
4810: sub determinedomain {
4811: my $domain=shift;
4812: if (! $domain) {
4813: # Determine domain if we have not been given one
4814: $domain = &Apache::lonnet::default_login_domain();
4815: if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
4816: if ($env{'request.role.domain'}) {
4817: $domain=$env{'request.role.domain'};
4818: }
4819: }
4820: return $domain;
4821: }
4822: ###############################################
4823:
4824: sub devalidate_domconfig_cache {
4825: my ($udom)=@_;
4826: &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
4827: }
4828:
4829: # ---------------------- Get domain configuration for a domain
4830: sub get_domainconf {
4831: my ($udom) = @_;
4832: my $cachetime=1800;
4833: my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
4834: if (defined($cached)) { return %{$result}; }
4835:
4836: my %domconfig = &Apache::lonnet::get_dom('configuration',
4837: ['login','rolecolors','autoenroll'],$udom);
4838: my (%designhash,%legacy);
4839: if (keys(%domconfig) > 0) {
4840: if (ref($domconfig{'login'}) eq 'HASH') {
4841: if (keys(%{$domconfig{'login'}})) {
4842: foreach my $key (keys(%{$domconfig{'login'}})) {
4843: if (ref($domconfig{'login'}{$key}) eq 'HASH') {
4844: if ($key eq 'loginvia') {
4845: if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
4846: foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
4847: if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
4848: if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
4849: my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
4850: $designhash{$udom.'.login.loginvia'} = $server;
4851: if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
4852:
4853: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
4854: } else {
4855: $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
4856: }
4857: if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
4858: $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
4859: }
4860: }
4861: }
4862: }
4863: }
4864: } else {
4865: foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
4866: $designhash{$udom.'.login.'.$key.'_'.$img} =
4867: $domconfig{'login'}{$key}{$img};
4868: }
4869: }
4870: } else {
4871: $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
4872: }
4873: }
4874: } else {
4875: $legacy{'login'} = 1;
4876: }
4877: } else {
4878: $legacy{'login'} = 1;
4879: }
4880: if (ref($domconfig{'rolecolors'}) eq 'HASH') {
4881: if (keys(%{$domconfig{'rolecolors'}})) {
4882: foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
4883: if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
4884: foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
4885: $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
4886: }
4887: }
4888: }
4889: } else {
4890: $legacy{'rolecolors'} = 1;
4891: }
4892: } else {
4893: $legacy{'rolecolors'} = 1;
4894: }
4895: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
4896: if ($domconfig{'autoenroll'}{'co-owners'}) {
4897: $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
4898: }
4899: }
4900: if (keys(%legacy) > 0) {
4901: my %legacyhash = &get_legacy_domconf($udom);
4902: foreach my $item (keys(%legacyhash)) {
4903: if ($item =~ /^\Q$udom\E\.login/) {
4904: if ($legacy{'login'}) {
4905: $designhash{$item} = $legacyhash{$item};
4906: }
4907: } else {
4908: if ($legacy{'rolecolors'}) {
4909: $designhash{$item} = $legacyhash{$item};
4910: }
4911: }
4912: }
4913: }
4914: } else {
4915: %designhash = &get_legacy_domconf($udom);
4916: }
4917: &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
4918: $cachetime);
4919: return %designhash;
4920: }
4921:
4922: sub get_legacy_domconf {
4923: my ($udom) = @_;
4924: my %legacyhash;
4925: my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
4926: my $designfile = $designdir.'/'.$udom.'.tab';
4927: if (-e $designfile) {
4928: if ( open (my $fh,"<$designfile") ) {
4929: while (my $line = <$fh>) {
4930: next if ($line =~ /^\#/);
4931: chomp($line);
4932: my ($key,$val)=(split(/\=/,$line));
4933: if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
4934: }
4935: close($fh);
4936: }
4937: }
4938: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
4939: $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
4940: }
4941: return %legacyhash;
4942: }
4943:
4944: =pod
4945:
4946: =item * &domainlogo()
4947:
4948: Inputs: $domain (usually will be undef)
4949:
4950: Returns: A link to a domain logo, if the domain logo exists.
4951: If the domain logo does not exist, a description of the domain.
4952:
4953: =cut
4954:
4955: ###############################################
4956: sub domainlogo {
4957: my $domain = &determinedomain(shift);
4958: my %designhash = &get_domainconf($domain);
4959: # See if there is a logo
4960: if ($designhash{$domain.'.login.domlogo'} ne '') {
4961: my $imgsrc = $designhash{$domain.'.login.domlogo'};
4962: if ($imgsrc =~ m{^/(adm|res)/}) {
4963: if ($imgsrc =~ m{^/res/}) {
4964: my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
4965: &Apache::lonnet::repcopy($local_name);
4966: }
4967: $imgsrc = &lonhttpdurl($imgsrc);
4968: }
4969: return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
4970: } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
4971: return &Apache::lonnet::domain($domain,'description');
4972: } else {
4973: return '';
4974: }
4975: }
4976: ##############################################
4977:
4978: =pod
4979:
4980: =item * &designparm()
4981:
4982: Inputs: $which parameter; $domain (usually will be undef)
4983:
4984: Returns: value of designparamter $which
4985:
4986: =cut
4987:
4988:
4989: ##############################################
4990: sub designparm {
4991: my ($which,$domain)=@_;
4992: if (exists($env{'environment.color.'.$which})) {
4993: return $env{'environment.color.'.$which};
4994: }
4995: $domain=&determinedomain($domain);
4996: my %domdesign;
4997: unless ($domain eq 'public') {
4998: %domdesign = &get_domainconf($domain);
4999: }
5000: my $output;
5001: if ($domdesign{$domain.'.'.$which} ne '') {
5002: $output = $domdesign{$domain.'.'.$which};
5003: } else {
5004: $output = $defaultdesign{$which};
5005: }
5006: if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
5007: ($which =~ /login\.(img|logo|domlogo|login)/)) {
5008: if ($output =~ m{^/(adm|res)/}) {
5009: if ($output =~ m{^/res/}) {
5010: my $local_name = &Apache::lonnet::filelocation('',$output);
5011: &Apache::lonnet::repcopy($local_name);
5012: }
5013: $output = &lonhttpdurl($output);
5014: }
5015: }
5016: return $output;
5017: }
5018:
5019: ##############################################
5020: =pod
5021:
5022: =item * &authorspace()
5023:
5024: Inputs: $url (usually will be undef).
5025:
5026: Returns: Path to Authoring Space containing the resource or
5027: directory being viewed (or for which action is being taken).
5028: If $url is provided, and begins /priv/<domain>/<uname>
5029: the path will be that portion of the $context argument.
5030: Otherwise the path will be for the author space of the current
5031: user when the current role is author, or for that of the
5032: co-author/assistant co-author space when the current role
5033: is co-author or assistant co-author.
5034:
5035: =cut
5036:
5037: sub authorspace {
5038: my ($url) = @_;
5039: if ($url ne '') {
5040: if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
5041: return $1;
5042: }
5043: }
5044: my $caname = '';
5045: my $cadom = '';
5046: if ($env{'request.role'} =~ /^(?:ca|aa)/) {
5047: ($cadom,$caname) =
5048: ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
5049: } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
5050: $caname = $env{'user.name'};
5051: $cadom = $env{'user.domain'};
5052: }
5053: if (($caname ne '') && ($cadom ne '')) {
5054: return "/priv/$cadom/$caname/";
5055: }
5056: return;
5057: }
5058:
5059: ##############################################
5060: =pod
5061:
5062: =item * &head_subbox()
5063:
5064: Inputs: $content (contains HTML code with page functions, etc.)
5065:
5066: Returns: HTML div with $content
5067: To be included in page header
5068:
5069: =cut
5070:
5071: sub head_subbox {
5072: my ($content)=@_;
5073: my $output =
5074: '<div class="LC_head_subbox">'
5075: .$content
5076: .'</div>'
5077: }
5078:
5079: ##############################################
5080: =pod
5081:
5082: =item * &CSTR_pageheader()
5083:
5084: Input: (optional) filename from which breadcrumb trail is built.
5085: In most cases no input as needed, as $env{'request.filename'}
5086: is appropriate for use in building the breadcrumb trail.
5087:
5088: Returns: HTML div with CSTR path and recent box
5089: To be included on Authoring Space pages
5090:
5091: =cut
5092:
5093: sub CSTR_pageheader {
5094: my ($trailfile) = @_;
5095: if ($trailfile eq '') {
5096: $trailfile = $env{'request.filename'};
5097: }
5098:
5099: # this is for resources; directories have customtitle, and crumbs
5100: # and select recent are created in lonpubdir.pm
5101:
5102: my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
5103: my ($udom,$uname,$thisdisfn)=
5104: ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
5105: my $formaction = "/priv/$udom/$uname/$thisdisfn";
5106: $formaction =~ s{/+}{/}g;
5107:
5108: my $parentpath = '';
5109: my $lastitem = '';
5110: if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
5111: $parentpath = $1;
5112: $lastitem = $2;
5113: } else {
5114: $lastitem = $thisdisfn;
5115: }
5116:
5117: my $output =
5118: '<div>'
5119: .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
5120: .'<b>'.&mt('Authoring Space:').'</b> '
5121: .'<form name="dirs" method="post" action="'.$formaction
5122: .'" target="_top">' #FIXME lonpubdir: target="_parent"
5123: .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
5124:
5125: if ($lastitem) {
5126: $output .=
5127: '<span class="LC_filename">'
5128: .$lastitem
5129: .'</span>';
5130: }
5131: $output .=
5132: '<br />'
5133: #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
5134: .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
5135: .'</form>'
5136: .&Apache::lonmenu::constspaceform()
5137: .'</div>';
5138:
5139: return $output;
5140: }
5141:
5142: ###############################################
5143: ###############################################
5144:
5145: =pod
5146:
5147: =back
5148:
5149: =head1 HTML Helpers
5150:
5151: =over 4
5152:
5153: =item * &bodytag()
5154:
5155: Returns a uniform header for LON-CAPA web pages.
5156:
5157: Inputs:
5158:
5159: =over 4
5160:
5161: =item * $title, A title to be displayed on the page.
5162:
5163: =item * $function, the current role (can be undef).
5164:
5165: =item * $addentries, extra parameters for the <body> tag.
5166:
5167: =item * $bodyonly, if defined, only return the <body> tag.
5168:
5169: =item * $domain, if defined, force a given domain.
5170:
5171: =item * $forcereg, if page should register as content page (relevant for
5172: text interface only)
5173:
5174: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
5175: navigational links
5176:
5177: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
5178:
5179: =item * $args, optional argument valid values are
5180: no_auto_mt_title -> prevents &mt()ing the title arg
5181: inherit_jsmath -> when creating popup window in a page,
5182: should it have jsmath forced on by the
5183: current page
5184:
5185: =item * $advtoolsref, optional argument, ref to an array containing
5186: inlineremote items to be added in "Functions" menu below
5187: breadcrumbs.
5188:
5189: =back
5190:
5191: Returns: A uniform header for LON-CAPA web pages.
5192: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
5193: If $bodyonly is undef or zero, an html string containing a <body> tag and
5194: other decorations will be returned.
5195:
5196: =cut
5197:
5198: sub bodytag {
5199: my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
5200: $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
5201:
5202: my $public;
5203: if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
5204: || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
5205: $public = 1;
5206: }
5207: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
5208: my $httphost = $args->{'use_absolute'};
5209:
5210: $function = &get_users_function() if (!$function);
5211: my $img = &designparm($function.'.img',$domain);
5212: my $font = &designparm($function.'.font',$domain);
5213: my $pgbg = $bgcolor || &designparm($function.'.pgbg',$domain);
5214:
5215: my %design = ( 'style' => 'margin-top: 0',
5216: 'bgcolor' => $pgbg,
5217: 'text' => $font,
5218: 'alink' => &designparm($function.'.alink',$domain),
5219: 'vlink' => &designparm($function.'.vlink',$domain),
5220: 'link' => &designparm($function.'.link',$domain),);
5221: @design{keys(%$addentries)} = @$addentries{keys(%$addentries)};
5222:
5223: # role and realm
5224: my ($role,$realm) = split(m{\./},$env{'request.role'},2);
5225: if ($realm) {
5226: $realm = '/'.$realm;
5227: }
5228: if ($role eq 'ca') {
5229: my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
5230: $realm = &plainname($rname,$rdom);
5231: }
5232: # realm
5233: if ($env{'request.course.id'}) {
5234: if ($env{'request.role'} !~ /^cr/) {
5235: $role = &Apache::lonnet::plaintext($role,&course_type());
5236: }
5237: if ($env{'request.course.sec'}) {
5238: $role .= (' 'x2).'- '.&mt('section:').' '.$env{'request.course.sec'};
5239: }
5240: $realm = $env{'course.'.$env{'request.course.id'}.'.description'};
5241: } else {
5242: $role = &Apache::lonnet::plaintext($role);
5243: }
5244:
5245: if (!$realm) { $realm=' '; }
5246:
5247: my $extra_body_attr = &make_attr_string($forcereg,\%design);
5248:
5249: # construct main body tag
5250: my $bodytag = "<body $extra_body_attr>".
5251: &Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
5252:
5253: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
5254:
5255: if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
5256: return $bodytag;
5257: }
5258:
5259: if ($public) {
5260: undef($role);
5261: }
5262:
5263: my $titleinfo = '<h1>'.$title.'</h1>';
5264: #
5265: # Extra info if you are the DC
5266: my $dc_info = '';
5267: if ($env{'user.adv'} && exists($env{'user.role.dc./'.
5268: $env{'course.'.$env{'request.course.id'}.
5269: '.domain'}.'/'})) {
5270: my $cid = $env{'request.course.id'};
5271: $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
5272: $dc_info =~ s/\s+$//;
5273: }
5274:
5275: $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
5276:
5277: if ($env{'request.state'} eq 'construct') { $forcereg=1; }
5278:
5279: # if ($env{'request.state'} eq 'construct') {
5280: # $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
5281: # }
5282:
5283: $bodytag .= Apache::lonhtmlcommon::scripttag(
5284: Apache::lonmenu::utilityfunctions($httphost), 'start');
5285:
5286: my ($left,$right) = Apache::lonmenu::primary_menu();
5287:
5288: if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
5289: if ($dc_info) {
5290: $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
5291: }
5292: $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
5293: <em>$realm</em> $dc_info</div>|;
5294: return $bodytag;
5295: }
5296:
5297: unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
5298: $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
5299: }
5300:
5301: $bodytag .= $right;
5302:
5303: if ($dc_info) {
5304: $dc_info = &dc_courseid_toggle($dc_info);
5305: }
5306: $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
5307:
5308: #if directed to not display the secondary menu, don't.
5309: if ($args->{'no_secondary_menu'}) {
5310: return $bodytag;
5311: }
5312: #don't show menus for public users
5313: if (!$public){
5314: $bodytag .= Apache::lonmenu::secondary_menu($httphost);
5315: $bodytag .= Apache::lonmenu::serverform();
5316: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5317: if ($env{'request.state'} eq 'construct') {
5318: $bodytag .= &Apache::lonmenu::innerregister($forcereg,
5319: $args->{'bread_crumbs'});
5320: } elsif ($forcereg) {
5321: $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
5322: $args->{'group'});
5323: } else {
5324: $bodytag .=
5325: &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
5326: $forcereg,$args->{'group'},
5327: $args->{'bread_crumbs'},
5328: $advtoolsref);
5329: }
5330: }else{
5331: # this is to seperate menu from content when there's no secondary
5332: # menu. Especially needed for public accessible ressources.
5333: $bodytag .= '<hr style="clear:both" />';
5334: $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
5335: }
5336:
5337: return $bodytag;
5338: }
5339:
5340: sub dc_courseid_toggle {
5341: my ($dc_info) = @_;
5342: return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
5343: '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
5344: &mt('(More ...)').'</a></span>'.
5345: '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
5346: }
5347:
5348: sub make_attr_string {
5349: my ($register,$attr_ref) = @_;
5350:
5351: if ($attr_ref && !ref($attr_ref)) {
5352: die("addentries Must be a hash ref ".
5353: join(':',caller(1))." ".
5354: join(':',caller(0))." ");
5355: }
5356:
5357: if ($register) {
5358: my ($on_load,$on_unload);
5359: foreach my $key (keys(%{$attr_ref})) {
5360: if (lc($key) eq 'onload') {
5361: $on_load.=$attr_ref->{$key}.';';
5362: delete($attr_ref->{$key});
5363:
5364: } elsif (lc($key) eq 'onunload') {
5365: $on_unload.=$attr_ref->{$key}.';';
5366: delete($attr_ref->{$key});
5367: }
5368: }
5369: $attr_ref->{'onload'} = $on_load;
5370: $attr_ref->{'onunload'}= $on_unload;
5371: }
5372:
5373: my $attr_string;
5374: foreach my $attr (sort(keys(%$attr_ref))) {
5375: $attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
5376: }
5377: return $attr_string;
5378: }
5379:
5380:
5381: ###############################################
5382: ###############################################
5383:
5384: =pod
5385:
5386: =item * &endbodytag()
5387:
5388: Returns a uniform footer for LON-CAPA web pages.
5389:
5390: Inputs: 1 - optional reference to an args hash
5391: If in the hash, key for noredirectlink has a value which evaluates to true,
5392: a 'Continue' link is not displayed if the page contains an
5393: internal redirect in the <head></head> section,
5394: i.e., $env{'internal.head.redirect'} exists
5395:
5396: =cut
5397:
5398: sub endbodytag {
5399: my ($args) = @_;
5400: my $endbodytag;
5401: unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
5402: $endbodytag='</body>';
5403: }
5404: $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
5405: if ( exists( $env{'internal.head.redirect'} ) ) {
5406: if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
5407: $endbodytag=
5408: "<br /><a href=\"$env{'internal.head.redirect'}\">".
5409: &mt('Continue').'</a>'.
5410: $endbodytag;
5411: }
5412: }
5413: return $endbodytag;
5414: }
5415:
5416: =pod
5417:
5418: =item * &standard_css()
5419:
5420: Returns a style sheet
5421:
5422: Inputs: (all optional)
5423: domain -> force to color decorate a page for a specific
5424: domain
5425: function -> force usage of a specific rolish color scheme
5426: bgcolor -> override the default page bgcolor
5427:
5428: =cut
5429:
5430: sub standard_css {
5431: my ($function,$domain,$bgcolor) = @_;
5432: $function = &get_users_function() if (!$function);
5433: my $img = &designparm($function.'.img', $domain);
5434: my $tabbg = &designparm($function.'.tabbg', $domain);
5435: my $font = &designparm($function.'.font', $domain);
5436: my $fontmenu = &designparm($function.'.fontmenu', $domain);
5437: #second colour for later usage
5438: my $sidebg = &designparm($function.'.sidebg',$domain);
5439: my $pgbg_or_bgcolor =
5440: $bgcolor ||
5441: &designparm($function.'.pgbg', $domain);
5442: my $pgbg = &designparm($function.'.pgbg', $domain);
5443: my $alink = &designparm($function.'.alink', $domain);
5444: my $vlink = &designparm($function.'.vlink', $domain);
5445: my $link = &designparm($function.'.link', $domain);
5446:
5447: my $sans = 'Verdana,Arial,Helvetica,sans-serif';
5448: my $mono = 'monospace';
5449: my $data_table_head = $sidebg;
5450: my $data_table_light = '#FAFAFA';
5451: my $data_table_dark = '#E0E0E0';
5452: my $data_table_darker = '#CCCCCC';
5453: my $data_table_highlight = '#FFFF00';
5454: my $mail_new = '#FFBB77';
5455: my $mail_new_hover = '#DD9955';
5456: my $mail_read = '#BBBB77';
5457: my $mail_read_hover = '#999944';
5458: my $mail_replied = '#AAAA88';
5459: my $mail_replied_hover = '#888855';
5460: my $mail_other = '#99BBBB';
5461: my $mail_other_hover = '#669999';
5462: my $table_header = '#DDDDDD';
5463: my $feedback_link_bg = '#BBBBBB';
5464: my $lg_border_color = '#C8C8C8';
5465: my $button_hover = '#BF2317';
5466:
5467: my $border = ($env{'browser.type'} eq 'explorer' ||
5468: $env{'browser.type'} eq 'safari' ) ? '0 2px 0 2px'
5469: : '0 3px 0 4px';
5470:
5471:
5472: return <<END;
5473:
5474: /* needed for iframe to allow 100% height in FF */
5475: body, html {
5476: margin: 0;
5477: padding: 0 0.5%;
5478: height: 99%; /* to avoid scrollbars */
5479: }
5480:
5481: body {
5482: font-family: $sans;
5483: line-height:130%;
5484: font-size:0.83em;
5485: color:$font;
5486: }
5487:
5488: a:focus,
5489: a:focus img {
5490: color: red;
5491: }
5492:
5493: form, .inline {
5494: display: inline;
5495: }
5496:
5497: .LC_right {
5498: text-align:right;
5499: }
5500:
5501: .LC_middle {
5502: vertical-align:middle;
5503: }
5504:
5505: .LC_floatleft {
5506: float: left;
5507: }
5508:
5509: .LC_floatright {
5510: float: right;
5511: }
5512:
5513: .LC_400Box {
5514: width:400px;
5515: }
5516:
5517: .LC_iframecontainer {
5518: width: 98%;
5519: margin: 0;
5520: position: fixed;
5521: top: 8.5em;
5522: bottom: 0;
5523: }
5524:
5525: .LC_iframecontainer iframe{
5526: border: none;
5527: width: 100%;
5528: height: 100%;
5529: }
5530:
5531: .LC_filename {
5532: font-family: $mono;
5533: white-space:pre;
5534: font-size: 120%;
5535: }
5536:
5537: .LC_fileicon {
5538: border: none;
5539: height: 1.3em;
5540: vertical-align: text-bottom;
5541: margin-right: 0.3em;
5542: text-decoration:none;
5543: }
5544:
5545: .LC_setting {
5546: text-decoration:underline;
5547: }
5548:
5549: .LC_error {
5550: color: red;
5551: }
5552:
5553: .LC_warning {
5554: color: darkorange;
5555: }
5556:
5557: .LC_diff_removed {
5558: color: red;
5559: }
5560:
5561: .LC_info,
5562: .LC_success,
5563: .LC_diff_added {
5564: color: green;
5565: }
5566:
5567: div.LC_confirm_box {
5568: background-color: #FAFAFA;
5569: border: 1px solid $lg_border_color;
5570: margin-right: 0;
5571: padding: 5px;
5572: }
5573:
5574: div.LC_confirm_box .LC_error img,
5575: div.LC_confirm_box .LC_success img {
5576: vertical-align: middle;
5577: }
5578:
5579: .LC_icon {
5580: border: none;
5581: vertical-align: middle;
5582: }
5583:
5584: .LC_docs_spacer {
5585: width: 25px;
5586: height: 1px;
5587: border: none;
5588: }
5589:
5590: .LC_internal_info {
5591: color: #999999;
5592: }
5593:
5594: .LC_discussion {
5595: background: $data_table_dark;
5596: border: 1px solid black;
5597: margin: 2px;
5598: }
5599:
5600: .LC_disc_action_left {
5601: background: $sidebg;
5602: text-align: left;
5603: padding: 4px;
5604: margin: 2px;
5605: }
5606:
5607: .LC_disc_action_right {
5608: background: $sidebg;
5609: text-align: right;
5610: padding: 4px;
5611: margin: 2px;
5612: }
5613:
5614: .LC_disc_new_item {
5615: background: white;
5616: border: 2px solid red;
5617: margin: 4px;
5618: padding: 4px;
5619: }
5620:
5621: .LC_disc_old_item {
5622: background: white;
5623: margin: 4px;
5624: padding: 4px;
5625: }
5626:
5627: table.LC_pastsubmission {
5628: border: 1px solid black;
5629: margin: 2px;
5630: }
5631:
5632: table#LC_menubuttons {
5633: width: 100%;
5634: background: $pgbg;
5635: border: 2px;
5636: border-collapse: separate;
5637: padding: 0;
5638: }
5639:
5640: table#LC_title_bar a {
5641: color: $fontmenu;
5642: }
5643:
5644: table#LC_title_bar {
5645: clear: both;
5646: display: none;
5647: }
5648:
5649: table#LC_title_bar,
5650: table.LC_breadcrumbs, /* obsolete? */
5651: table#LC_title_bar.LC_with_remote {
5652: width: 100%;
5653: border-color: $pgbg;
5654: border-style: solid;
5655: border-width: $border;
5656: background: $pgbg;
5657: color: $fontmenu;
5658: border-collapse: collapse;
5659: padding: 0;
5660: margin: 0;
5661: }
5662:
5663: ul.LC_breadcrumb_tools_outerlist {
5664: margin: 0;
5665: padding: 0;
5666: position: relative;
5667: list-style: none;
5668: }
5669: ul.LC_breadcrumb_tools_outerlist li {
5670: display: inline;
5671: }
5672:
5673: .LC_breadcrumb_tools_navigation {
5674: padding: 0;
5675: margin: 0;
5676: float: left;
5677: }
5678: .LC_breadcrumb_tools_tools {
5679: padding: 0;
5680: margin: 0;
5681: float: right;
5682: }
5683:
5684: table#LC_title_bar td {
5685: background: $tabbg;
5686: }
5687:
5688: table#LC_menubuttons img {
5689: border: none;
5690: }
5691:
5692: .LC_breadcrumbs_component {
5693: float: right;
5694: margin: 0 1em;
5695: }
5696: .LC_breadcrumbs_component img {
5697: vertical-align: middle;
5698: }
5699:
5700: td.LC_table_cell_checkbox {
5701: text-align: center;
5702: }
5703:
5704: .LC_fontsize_small {
5705: font-size: 70%;
5706: }
5707:
5708: #LC_breadcrumbs {
5709: clear:both;
5710: background: $sidebg;
5711: border-bottom: 1px solid $lg_border_color;
5712: line-height: 2.5em;
5713: overflow: hidden;
5714: margin: 0;
5715: padding: 0;
5716: text-align: left;
5717: }
5718:
5719: .LC_head_subbox, .LC_actionbox {
5720: clear:both;
5721: background: #F8F8F8; /* $sidebg; */
5722: border: 1px solid $sidebg;
5723: margin: 0 0 10px 0;
5724: padding: 3px;
5725: text-align: left;
5726: }
5727:
5728: .LC_fontsize_medium {
5729: font-size: 85%;
5730: }
5731:
5732: .LC_fontsize_large {
5733: font-size: 120%;
5734: }
5735:
5736: .LC_menubuttons_inline_text {
5737: color: $font;
5738: font-size: 90%;
5739: padding-left:3px;
5740: }
5741:
5742: .LC_menubuttons_inline_text img{
5743: vertical-align: middle;
5744: }
5745:
5746: li.LC_menubuttons_inline_text img {
5747: cursor:pointer;
5748: text-decoration: none;
5749: }
5750:
5751: .LC_menubuttons_link {
5752: text-decoration: none;
5753: }
5754:
5755: .LC_menubuttons_category {
5756: color: $font;
5757: background: $pgbg;
5758: font-size: larger;
5759: font-weight: bold;
5760: }
5761:
5762: td.LC_menubuttons_text {
5763: color: $font;
5764: }
5765:
5766: .LC_current_location {
5767: background: $tabbg;
5768: }
5769:
5770: table.LC_data_table {
5771: border: 1px solid #000000;
5772: border-collapse: separate;
5773: border-spacing: 1px;
5774: background: $pgbg;
5775: }
5776:
5777: .LC_data_table_dense {
5778: font-size: small;
5779: }
5780:
5781: table.LC_nested_outer {
5782: border: 1px solid #000000;
5783: border-collapse: collapse;
5784: border-spacing: 0;
5785: width: 100%;
5786: }
5787:
5788: table.LC_innerpickbox,
5789: table.LC_nested {
5790: border: none;
5791: border-collapse: collapse;
5792: border-spacing: 0;
5793: width: 100%;
5794: }
5795:
5796: table.LC_data_table tr th,
5797: table.LC_calendar tr th,
5798: table.LC_prior_tries tr th,
5799: table.LC_innerpickbox tr th {
5800: font-weight: bold;
5801: background-color: $data_table_head;
5802: color:$fontmenu;
5803: font-size:90%;
5804: }
5805:
5806: table.LC_innerpickbox tr th,
5807: table.LC_innerpickbox tr td {
5808: vertical-align: top;
5809: }
5810:
5811: table.LC_data_table tr.LC_info_row > td {
5812: background-color: #CCCCCC;
5813: font-weight: bold;
5814: text-align: left;
5815: }
5816:
5817: table.LC_data_table tr.LC_odd_row > td {
5818: background-color: $data_table_light;
5819: padding: 2px;
5820: vertical-align: top;
5821: }
5822:
5823: table.LC_pick_box tr > td.LC_odd_row {
5824: background-color: $data_table_light;
5825: vertical-align: top;
5826: }
5827:
5828: table.LC_data_table tr.LC_even_row > td {
5829: background-color: $data_table_dark;
5830: padding: 2px;
5831: vertical-align: top;
5832: }
5833:
5834: table.LC_pick_box tr > td.LC_even_row {
5835: background-color: $data_table_dark;
5836: vertical-align: top;
5837: }
5838:
5839: table.LC_data_table tr.LC_data_table_highlight td {
5840: background-color: $data_table_darker;
5841: }
5842:
5843: table.LC_data_table tr td.LC_leftcol_header {
5844: background-color: $data_table_head;
5845: font-weight: bold;
5846: }
5847:
5848: table.LC_data_table tr.LC_empty_row td,
5849: table.LC_nested tr.LC_empty_row td {
5850: font-weight: bold;
5851: font-style: italic;
5852: text-align: center;
5853: padding: 8px;
5854: }
5855:
5856: table.LC_data_table tr.LC_empty_row td,
5857: table.LC_data_table tr.LC_footer_row td {
5858: background-color: $sidebg;
5859: }
5860:
5861: table.LC_nested tr.LC_empty_row td {
5862: background-color: #FFFFFF;
5863: }
5864:
5865: table.LC_caption {
5866: }
5867:
5868: table.LC_nested tr.LC_empty_row td {
5869: padding: 4ex
5870: }
5871:
5872: table.LC_nested_outer tr th {
5873: font-weight: bold;
5874: color:$fontmenu;
5875: background-color: $data_table_head;
5876: font-size: small;
5877: border-bottom: 1px solid #000000;
5878: }
5879:
5880: table.LC_nested_outer tr td.LC_subheader {
5881: background-color: $data_table_head;
5882: font-weight: bold;
5883: font-size: small;
5884: border-bottom: 1px solid #000000;
5885: text-align: right;
5886: }
5887:
5888: table.LC_nested tr.LC_info_row td {
5889: background-color: #CCCCCC;
5890: font-weight: bold;
5891: font-size: small;
5892: text-align: center;
5893: }
5894:
5895: table.LC_nested tr.LC_info_row td.LC_left_item,
5896: table.LC_nested_outer tr th.LC_left_item {
5897: text-align: left;
5898: }
5899:
5900: table.LC_nested td {
5901: background-color: #FFFFFF;
5902: font-size: small;
5903: }
5904:
5905: table.LC_nested_outer tr th.LC_right_item,
5906: table.LC_nested tr.LC_info_row td.LC_right_item,
5907: table.LC_nested tr.LC_odd_row td.LC_right_item,
5908: table.LC_nested tr td.LC_right_item {
5909: text-align: right;
5910: }
5911:
5912: table.LC_nested tr.LC_odd_row td {
5913: background-color: #EEEEEE;
5914: }
5915:
5916: table.LC_createuser {
5917: }
5918:
5919: table.LC_createuser tr.LC_section_row td {
5920: font-size: small;
5921: }
5922:
5923: table.LC_createuser tr.LC_info_row td {
5924: background-color: #CCCCCC;
5925: font-weight: bold;
5926: text-align: center;
5927: }
5928:
5929: table.LC_calendar {
5930: border: 1px solid #000000;
5931: border-collapse: collapse;
5932: width: 98%;
5933: }
5934:
5935: table.LC_calendar_pickdate {
5936: font-size: xx-small;
5937: }
5938:
5939: table.LC_calendar tr td {
5940: border: 1px solid #000000;
5941: vertical-align: top;
5942: width: 14%;
5943: }
5944:
5945: table.LC_calendar tr td.LC_calendar_day_empty {
5946: background-color: $data_table_dark;
5947: }
5948:
5949: table.LC_calendar tr td.LC_calendar_day_current {
5950: background-color: $data_table_highlight;
5951: }
5952:
5953: table.LC_data_table tr td.LC_mail_new {
5954: background-color: $mail_new;
5955: }
5956:
5957: table.LC_data_table tr.LC_mail_new:hover {
5958: background-color: $mail_new_hover;
5959: }
5960:
5961: table.LC_data_table tr td.LC_mail_read {
5962: background-color: $mail_read;
5963: }
5964:
5965: /*
5966: table.LC_data_table tr.LC_mail_read:hover {
5967: background-color: $mail_read_hover;
5968: }
5969: */
5970:
5971: table.LC_data_table tr td.LC_mail_replied {
5972: background-color: $mail_replied;
5973: }
5974:
5975: /*
5976: table.LC_data_table tr.LC_mail_replied:hover {
5977: background-color: $mail_replied_hover;
5978: }
5979: */
5980:
5981: table.LC_data_table tr td.LC_mail_other {
5982: background-color: $mail_other;
5983: }
5984:
5985: /*
5986: table.LC_data_table tr.LC_mail_other:hover {
5987: background-color: $mail_other_hover;
5988: }
5989: */
5990:
5991: table.LC_data_table tr > td.LC_browser_file,
5992: table.LC_data_table tr > td.LC_browser_file_published {
5993: background: #AAEE77;
5994: }
5995:
5996: table.LC_data_table tr > td.LC_browser_file_locked,
5997: table.LC_data_table tr > td.LC_browser_file_unpublished {
5998: background: #FFAA99;
5999: }
6000:
6001: table.LC_data_table tr > td.LC_browser_file_obsolete {
6002: background: #888888;
6003: }
6004:
6005: table.LC_data_table tr > td.LC_browser_file_modified,
6006: table.LC_data_table tr > td.LC_browser_file_metamodified {
6007: background: #F8F866;
6008: }
6009:
6010: table.LC_data_table tr.LC_browser_folder > td {
6011: background: #E0E8FF;
6012: }
6013:
6014: table.LC_data_table tr > td.LC_roles_is {
6015: /* background: #77FF77; */
6016: }
6017:
6018: table.LC_data_table tr > td.LC_roles_future {
6019: border-right: 8px solid #FFFF77;
6020: }
6021:
6022: table.LC_data_table tr > td.LC_roles_will {
6023: border-right: 8px solid #FFAA77;
6024: }
6025:
6026: table.LC_data_table tr > td.LC_roles_expired {
6027: border-right: 8px solid #FF7777;
6028: }
6029:
6030: table.LC_data_table tr > td.LC_roles_will_not {
6031: border-right: 8px solid #AAFF77;
6032: }
6033:
6034: table.LC_data_table tr > td.LC_roles_selected {
6035: border-right: 8px solid #11CC55;
6036: }
6037:
6038: span.LC_current_location {
6039: font-size:larger;
6040: background: $pgbg;
6041: }
6042:
6043: span.LC_current_nav_location {
6044: font-weight:bold;
6045: background: $sidebg;
6046: }
6047:
6048: span.LC_parm_menu_item {
6049: font-size: larger;
6050: }
6051:
6052: span.LC_parm_scope_all {
6053: color: red;
6054: }
6055:
6056: span.LC_parm_scope_folder {
6057: color: green;
6058: }
6059:
6060: span.LC_parm_scope_resource {
6061: color: orange;
6062: }
6063:
6064: span.LC_parm_part {
6065: color: blue;
6066: }
6067:
6068: span.LC_parm_folder,
6069: span.LC_parm_symb {
6070: font-size: x-small;
6071: font-family: $mono;
6072: color: #AAAAAA;
6073: }
6074:
6075: ul.LC_parm_parmlist li {
6076: display: inline-block;
6077: padding: 0.3em 0.8em;
6078: vertical-align: top;
6079: width: 150px;
6080: border-top:1px solid $lg_border_color;
6081: }
6082:
6083: td.LC_parm_overview_level_menu,
6084: td.LC_parm_overview_map_menu,
6085: td.LC_parm_overview_parm_selectors,
6086: td.LC_parm_overview_restrictions {
6087: border: 1px solid black;
6088: border-collapse: collapse;
6089: }
6090:
6091: table.LC_parm_overview_restrictions td {
6092: border-width: 1px 4px 1px 4px;
6093: border-style: solid;
6094: border-color: $pgbg;
6095: text-align: center;
6096: }
6097:
6098: table.LC_parm_overview_restrictions th {
6099: background: $tabbg;
6100: border-width: 1px 4px 1px 4px;
6101: border-style: solid;
6102: border-color: $pgbg;
6103: }
6104:
6105: table#LC_helpmenu {
6106: border: none;
6107: height: 55px;
6108: border-spacing: 0;
6109: }
6110:
6111: table#LC_helpmenu fieldset legend {
6112: font-size: larger;
6113: }
6114:
6115: table#LC_helpmenu_links {
6116: width: 100%;
6117: border: 1px solid black;
6118: background: $pgbg;
6119: padding: 0;
6120: border-spacing: 1px;
6121: }
6122:
6123: table#LC_helpmenu_links tr td {
6124: padding: 1px;
6125: background: $tabbg;
6126: text-align: center;
6127: font-weight: bold;
6128: }
6129:
6130: table#LC_helpmenu_links a:link,
6131: table#LC_helpmenu_links a:visited,
6132: table#LC_helpmenu_links a:active {
6133: text-decoration: none;
6134: color: $font;
6135: }
6136:
6137: table#LC_helpmenu_links a:hover {
6138: text-decoration: underline;
6139: color: $vlink;
6140: }
6141:
6142: .LC_chrt_popup_exists {
6143: border: 1px solid #339933;
6144: margin: -1px;
6145: }
6146:
6147: .LC_chrt_popup_up {
6148: border: 1px solid yellow;
6149: margin: -1px;
6150: }
6151:
6152: .LC_chrt_popup {
6153: border: 1px solid #8888FF;
6154: background: #CCCCFF;
6155: }
6156:
6157: table.LC_pick_box {
6158: border-collapse: separate;
6159: background: white;
6160: border: 1px solid black;
6161: border-spacing: 1px;
6162: }
6163:
6164: table.LC_pick_box td.LC_pick_box_title {
6165: background: $sidebg;
6166: font-weight: bold;
6167: text-align: left;
6168: vertical-align: top;
6169: width: 184px;
6170: padding: 8px;
6171: }
6172:
6173: table.LC_pick_box td.LC_pick_box_value {
6174: text-align: left;
6175: padding: 8px;
6176: }
6177:
6178: table.LC_pick_box td.LC_pick_box_select {
6179: text-align: left;
6180: padding: 8px;
6181: }
6182:
6183: table.LC_pick_box td.LC_pick_box_separator {
6184: padding: 0;
6185: height: 1px;
6186: background: black;
6187: }
6188:
6189: table.LC_pick_box td.LC_pick_box_submit {
6190: text-align: right;
6191: }
6192:
6193: table.LC_pick_box td.LC_evenrow_value {
6194: text-align: left;
6195: padding: 8px;
6196: background-color: $data_table_light;
6197: }
6198:
6199: table.LC_pick_box td.LC_oddrow_value {
6200: text-align: left;
6201: padding: 8px;
6202: background-color: $data_table_light;
6203: }
6204:
6205: span.LC_helpform_receipt_cat {
6206: font-weight: bold;
6207: }
6208:
6209: table.LC_group_priv_box {
6210: background: white;
6211: border: 1px solid black;
6212: border-spacing: 1px;
6213: }
6214:
6215: table.LC_group_priv_box td.LC_pick_box_title {
6216: background: $tabbg;
6217: font-weight: bold;
6218: text-align: right;
6219: width: 184px;
6220: }
6221:
6222: table.LC_group_priv_box td.LC_groups_fixed {
6223: background: $data_table_light;
6224: text-align: center;
6225: }
6226:
6227: table.LC_group_priv_box td.LC_groups_optional {
6228: background: $data_table_dark;
6229: text-align: center;
6230: }
6231:
6232: table.LC_group_priv_box td.LC_groups_functionality {
6233: background: $data_table_darker;
6234: text-align: center;
6235: font-weight: bold;
6236: }
6237:
6238: table.LC_group_priv td {
6239: text-align: left;
6240: padding: 0;
6241: }
6242:
6243: .LC_navbuttons {
6244: margin: 2ex 0ex 2ex 0ex;
6245: }
6246:
6247: .LC_topic_bar {
6248: font-weight: bold;
6249: background: $tabbg;
6250: margin: 1em 0em 1em 2em;
6251: padding: 3px;
6252: font-size: 1.2em;
6253: }
6254:
6255: .LC_topic_bar span {
6256: left: 0.5em;
6257: position: absolute;
6258: vertical-align: middle;
6259: font-size: 1.2em;
6260: }
6261:
6262: table.LC_course_group_status {
6263: margin: 20px;
6264: }
6265:
6266: table.LC_status_selector td {
6267: vertical-align: top;
6268: text-align: center;
6269: padding: 4px;
6270: }
6271:
6272: div.LC_feedback_link {
6273: clear: both;
6274: background: $sidebg;
6275: width: 100%;
6276: padding-bottom: 10px;
6277: border: 1px $tabbg solid;
6278: height: 22px;
6279: line-height: 22px;
6280: padding-top: 5px;
6281: }
6282:
6283: div.LC_feedback_link img {
6284: height: 22px;
6285: vertical-align:middle;
6286: }
6287:
6288: div.LC_feedback_link a {
6289: text-decoration: none;
6290: }
6291:
6292: div.LC_comblock {
6293: display:inline;
6294: color:$font;
6295: font-size:90%;
6296: }
6297:
6298: div.LC_feedback_link div.LC_comblock {
6299: padding-left:5px;
6300: }
6301:
6302: div.LC_feedback_link div.LC_comblock a {
6303: color:$font;
6304: }
6305:
6306: span.LC_feedback_link {
6307: /* background: $feedback_link_bg; */
6308: font-size: larger;
6309: }
6310:
6311: span.LC_message_link {
6312: /* background: $feedback_link_bg; */
6313: font-size: larger;
6314: position: absolute;
6315: right: 1em;
6316: }
6317:
6318: table.LC_prior_tries {
6319: border: 1px solid #000000;
6320: border-collapse: separate;
6321: border-spacing: 1px;
6322: }
6323:
6324: table.LC_prior_tries td {
6325: padding: 2px;
6326: }
6327:
6328: .LC_answer_correct {
6329: background: lightgreen;
6330: color: darkgreen;
6331: padding: 6px;
6332: }
6333:
6334: .LC_answer_charged_try {
6335: background: #FFAAAA;
6336: color: darkred;
6337: padding: 6px;
6338: }
6339:
6340: .LC_answer_not_charged_try,
6341: .LC_answer_no_grade,
6342: .LC_answer_late {
6343: background: lightyellow;
6344: color: black;
6345: padding: 6px;
6346: }
6347:
6348: .LC_answer_previous {
6349: background: lightblue;
6350: color: darkblue;
6351: padding: 6px;
6352: }
6353:
6354: .LC_answer_no_message {
6355: background: #FFFFFF;
6356: color: black;
6357: padding: 6px;
6358: }
6359:
6360: .LC_answer_unknown {
6361: background: orange;
6362: color: black;
6363: padding: 6px;
6364: }
6365:
6366: span.LC_prior_numerical,
6367: span.LC_prior_string,
6368: span.LC_prior_custom,
6369: span.LC_prior_reaction,
6370: span.LC_prior_math {
6371: font-family: $mono;
6372: white-space: pre;
6373: }
6374:
6375: span.LC_prior_string {
6376: font-family: $mono;
6377: white-space: pre;
6378: }
6379:
6380: table.LC_prior_option {
6381: width: 100%;
6382: border-collapse: collapse;
6383: }
6384:
6385: table.LC_prior_rank,
6386: table.LC_prior_match {
6387: border-collapse: collapse;
6388: }
6389:
6390: table.LC_prior_option tr td,
6391: table.LC_prior_rank tr td,
6392: table.LC_prior_match tr td {
6393: border: 1px solid #000000;
6394: }
6395:
6396: .LC_nobreak {
6397: white-space: nowrap;
6398: }
6399:
6400: span.LC_cusr_emph {
6401: font-style: italic;
6402: }
6403:
6404: span.LC_cusr_subheading {
6405: font-weight: normal;
6406: font-size: 85%;
6407: }
6408:
6409: div.LC_docs_entry_move {
6410: border: 1px solid #BBBBBB;
6411: background: #DDDDDD;
6412: width: 22px;
6413: padding: 1px;
6414: margin: 0;
6415: }
6416:
6417: table.LC_data_table tr > td.LC_docs_entry_commands,
6418: table.LC_data_table tr > td.LC_docs_entry_parameter {
6419: font-size: x-small;
6420: }
6421:
6422: .LC_docs_entry_parameter {
6423: white-space: nowrap;
6424: }
6425:
6426: .LC_docs_copy {
6427: color: #000099;
6428: }
6429:
6430: .LC_docs_cut {
6431: color: #550044;
6432: }
6433:
6434: .LC_docs_rename {
6435: color: #009900;
6436: }
6437:
6438: .LC_docs_remove {
6439: color: #990000;
6440: }
6441:
6442: .LC_docs_reinit_warn,
6443: .LC_docs_ext_edit {
6444: font-size: x-small;
6445: }
6446:
6447: table.LC_docs_adddocs td,
6448: table.LC_docs_adddocs th {
6449: border: 1px solid #BBBBBB;
6450: padding: 4px;
6451: background: #DDDDDD;
6452: }
6453:
6454: table.LC_sty_begin {
6455: background: #BBFFBB;
6456: }
6457:
6458: table.LC_sty_end {
6459: background: #FFBBBB;
6460: }
6461:
6462: table.LC_double_column {
6463: border-width: 0;
6464: border-collapse: collapse;
6465: width: 100%;
6466: padding: 2px;
6467: }
6468:
6469: table.LC_double_column tr td.LC_left_col {
6470: top: 2px;
6471: left: 2px;
6472: width: 47%;
6473: vertical-align: top;
6474: }
6475:
6476: table.LC_double_column tr td.LC_right_col {
6477: top: 2px;
6478: right: 2px;
6479: width: 47%;
6480: vertical-align: top;
6481: }
6482:
6483: div.LC_left_float {
6484: float: left;
6485: padding-right: 5%;
6486: padding-bottom: 4px;
6487: }
6488:
6489: div.LC_clear_float_header {
6490: padding-bottom: 2px;
6491: }
6492:
6493: div.LC_clear_float_footer {
6494: padding-top: 10px;
6495: clear: both;
6496: }
6497:
6498: div.LC_grade_show_user {
6499: /* border-left: 5px solid $sidebg; */
6500: border-top: 5px solid #000000;
6501: margin: 50px 0 0 0;
6502: padding: 15px 0 5px 10px;
6503: }
6504:
6505: div.LC_grade_show_user_odd_row {
6506: /* border-left: 5px solid #000000; */
6507: }
6508:
6509: div.LC_grade_show_user div.LC_Box {
6510: margin-right: 50px;
6511: }
6512:
6513: div.LC_grade_submissions,
6514: div.LC_grade_message_center,
6515: div.LC_grade_info_links {
6516: margin: 5px;
6517: width: 99%;
6518: background: #FFFFFF;
6519: }
6520:
6521: div.LC_grade_submissions_header,
6522: div.LC_grade_message_center_header {
6523: font-weight: bold;
6524: font-size: large;
6525: }
6526:
6527: div.LC_grade_submissions_body,
6528: div.LC_grade_message_center_body {
6529: border: 1px solid black;
6530: width: 99%;
6531: background: #FFFFFF;
6532: }
6533:
6534: table.LC_scantron_action {
6535: width: 100%;
6536: }
6537:
6538: table.LC_scantron_action tr th {
6539: font-weight:bold;
6540: font-style:normal;
6541: }
6542:
6543: .LC_edit_problem_header,
6544: div.LC_edit_problem_footer {
6545: font-weight: normal;
6546: font-size: medium;
6547: margin: 2px;
6548: background-color: $sidebg;
6549: }
6550:
6551: div.LC_edit_problem_header,
6552: div.LC_edit_problem_header div,
6553: div.LC_edit_problem_footer,
6554: div.LC_edit_problem_footer div,
6555: div.LC_edit_problem_editxml_header,
6556: div.LC_edit_problem_editxml_header div {
6557: margin-top: 5px;
6558: }
6559:
6560: div.LC_edit_problem_header_title {
6561: font-weight: bold;
6562: font-size: larger;
6563: background: $tabbg;
6564: padding: 3px;
6565: margin: 0 0 5px 0;
6566: }
6567:
6568: table.LC_edit_problem_header_title {
6569: width: 100%;
6570: background: $tabbg;
6571: }
6572:
6573: div.LC_edit_problem_discards {
6574: float: left;
6575: padding-bottom: 5px;
6576: }
6577:
6578: div.LC_edit_problem_saves {
6579: float: right;
6580: padding-bottom: 5px;
6581: }
6582:
6583: .LC_edit_opt {
6584: padding-left: 1em;
6585: white-space: nowrap;
6586: }
6587:
6588: .LC_edit_problem_latexhelper{
6589: text-align: right;
6590: }
6591:
6592: #LC_edit_problem_colorful div{
6593: margin-left: 40px;
6594: }
6595:
6596: img.stift {
6597: border-width: 0;
6598: vertical-align: middle;
6599: }
6600:
6601: table td.LC_mainmenu_col_fieldset {
6602: vertical-align: top;
6603: }
6604:
6605: div.LC_createcourse {
6606: margin: 10px 10px 10px 10px;
6607: }
6608:
6609: .LC_dccid {
6610: float: right;
6611: margin: 0.2em 0 0 0;
6612: padding: 0;
6613: font-size: 90%;
6614: display:none;
6615: }
6616:
6617: ol.LC_primary_menu a:hover,
6618: ol#LC_MenuBreadcrumbs a:hover,
6619: ol#LC_PathBreadcrumbs a:hover,
6620: ul#LC_secondary_menu a:hover,
6621: .LC_FormSectionClearButton input:hover
6622: ul.LC_TabContent li:hover a {
6623: color:$button_hover;
6624: text-decoration:none;
6625: }
6626:
6627: h1 {
6628: padding: 0;
6629: line-height:130%;
6630: }
6631:
6632: h2,
6633: h3,
6634: h4,
6635: h5,
6636: h6 {
6637: margin: 5px 0 5px 0;
6638: padding: 0;
6639: line-height:130%;
6640: }
6641:
6642: .LC_hcell {
6643: padding:3px 15px 3px 15px;
6644: margin: 0;
6645: background-color:$tabbg;
6646: color:$fontmenu;
6647: border-bottom:solid 1px $lg_border_color;
6648: }
6649:
6650: .LC_Box > .LC_hcell {
6651: margin: 0 -10px 10px -10px;
6652: }
6653:
6654: .LC_noBorder {
6655: border: 0;
6656: }
6657:
6658: .LC_FormSectionClearButton input {
6659: background-color:transparent;
6660: border: none;
6661: cursor:pointer;
6662: text-decoration:underline;
6663: }
6664:
6665: .LC_help_open_topic {
6666: color: #FFFFFF;
6667: background-color: #EEEEFF;
6668: margin: 1px;
6669: padding: 4px;
6670: border: 1px solid #000033;
6671: white-space: nowrap;
6672: /* vertical-align: middle; */
6673: }
6674:
6675: dl,
6676: ul,
6677: div,
6678: fieldset {
6679: margin: 10px 10px 10px 0;
6680: /* overflow: hidden; */
6681: }
6682:
6683: fieldset > legend {
6684: font-weight: bold;
6685: padding: 0 5px 0 5px;
6686: }
6687:
6688: #LC_nav_bar {
6689: float: left;
6690: background-color: $pgbg_or_bgcolor;
6691: margin: 0 0 2px 0;
6692: }
6693:
6694: #LC_realm {
6695: margin: 0.2em 0 0 0;
6696: padding: 0;
6697: font-weight: bold;
6698: text-align: center;
6699: background-color: $pgbg_or_bgcolor;
6700: }
6701:
6702: #LC_nav_bar em {
6703: font-weight: bold;
6704: font-style: normal;
6705: }
6706:
6707: ol.LC_primary_menu {
6708: margin: 0;
6709: padding: 0;
6710: background-color: $pgbg_or_bgcolor;
6711: }
6712:
6713: ol#LC_PathBreadcrumbs {
6714: margin: 0;
6715: }
6716:
6717: ol.LC_primary_menu li {
6718: color: RGB(80, 80, 80);
6719: vertical-align: middle;
6720: text-align: left;
6721: list-style: none;
6722: float: left;
6723: }
6724:
6725: ol.LC_primary_menu li a {
6726: display: block;
6727: margin: 0;
6728: padding: 0 5px 0 10px;
6729: text-decoration: none;
6730: }
6731:
6732: ol.LC_primary_menu li ul {
6733: display: none;
6734: width: 10em;
6735: background-color: $data_table_light;
6736: }
6737:
6738: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
6739: display: block;
6740: position: absolute;
6741: margin: 0;
6742: padding: 0;
6743: z-index: 2;
6744: }
6745:
6746: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
6747: font-size: 90%;
6748: vertical-align: top;
6749: float: none;
6750: border-left: 1px solid black;
6751: border-right: 1px solid black;
6752: }
6753:
6754: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
6755: background-color:$data_table_light;
6756: }
6757:
6758: ol.LC_primary_menu li li a:hover {
6759: color:$button_hover;
6760: background-color:$data_table_dark;
6761: }
6762:
6763: ol.LC_primary_menu li img {
6764: vertical-align: bottom;
6765: height: 1.1em;
6766: margin: 0.2em 0 0 0;
6767: }
6768:
6769: ol.LC_primary_menu a {
6770: color: RGB(80, 80, 80);
6771: text-decoration: none;
6772: }
6773:
6774: ol.LC_primary_menu a.LC_new_message {
6775: font-weight:bold;
6776: color: darkred;
6777: }
6778:
6779: ol.LC_docs_parameters {
6780: margin-left: 0;
6781: padding: 0;
6782: list-style: none;
6783: }
6784:
6785: ol.LC_docs_parameters li {
6786: margin: 0;
6787: padding-right: 20px;
6788: display: inline;
6789: }
6790:
6791: ol.LC_docs_parameters li:before {
6792: content: "\\002022 \\0020";
6793: }
6794:
6795: li.LC_docs_parameters_title {
6796: font-weight: bold;
6797: }
6798:
6799: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
6800: content: "";
6801: }
6802:
6803: ul#LC_secondary_menu {
6804: clear: right;
6805: color: $fontmenu;
6806: background: $tabbg;
6807: list-style: none;
6808: padding: 0;
6809: margin: 0;
6810: width: 100%;
6811: text-align: left;
6812: float: left;
6813: }
6814:
6815: ul#LC_secondary_menu li {
6816: font-weight: bold;
6817: line-height: 1.8em;
6818: border-right: 1px solid black;
6819: float: left;
6820: }
6821:
6822: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
6823: background-color: $data_table_light;
6824: }
6825:
6826: ul#LC_secondary_menu li a {
6827: padding: 0 0.8em;
6828: }
6829:
6830: ul#LC_secondary_menu li ul {
6831: display: none;
6832: }
6833:
6834: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
6835: display: block;
6836: position: absolute;
6837: margin: 0;
6838: padding: 0;
6839: list-style:none;
6840: float: none;
6841: background-color: $data_table_light;
6842: z-index: 2;
6843: margin-left: -1px;
6844: }
6845:
6846: ul#LC_secondary_menu li ul li {
6847: font-size: 90%;
6848: vertical-align: top;
6849: border-left: 1px solid black;
6850: border-right: 1px solid black;
6851: background-color: $data_table_light;
6852: list-style:none;
6853: float: none;
6854: }
6855:
6856: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
6857: background-color: $data_table_dark;
6858: }
6859:
6860: ul.LC_TabContent {
6861: display:block;
6862: background: $sidebg;
6863: border-bottom: solid 1px $lg_border_color;
6864: list-style:none;
6865: margin: -1px -10px 0 -10px;
6866: padding: 0;
6867: }
6868:
6869: ul.LC_TabContent li,
6870: ul.LC_TabContentBigger li {
6871: float:left;
6872: }
6873:
6874: ul#LC_secondary_menu li a {
6875: color: $fontmenu;
6876: text-decoration: none;
6877: }
6878:
6879: ul.LC_TabContent {
6880: min-height:20px;
6881: }
6882:
6883: ul.LC_TabContent li {
6884: vertical-align:middle;
6885: padding: 0 16px 0 10px;
6886: background-color:$tabbg;
6887: border-bottom:solid 1px $lg_border_color;
6888: border-left: solid 1px $font;
6889: }
6890:
6891: ul.LC_TabContent .right {
6892: float:right;
6893: }
6894:
6895: ul.LC_TabContent li a,
6896: ul.LC_TabContent li {
6897: color:rgb(47,47,47);
6898: text-decoration:none;
6899: font-size:95%;
6900: font-weight:bold;
6901: min-height:20px;
6902: }
6903:
6904: ul.LC_TabContent li a:hover,
6905: ul.LC_TabContent li a:focus {
6906: color: $button_hover;
6907: background:none;
6908: outline:none;
6909: }
6910:
6911: ul.LC_TabContent li:hover {
6912: color: $button_hover;
6913: cursor:pointer;
6914: }
6915:
6916: ul.LC_TabContent li.active {
6917: color: $font;
6918: background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
6919: border-bottom:solid 1px #FFFFFF;
6920: cursor: default;
6921: }
6922:
6923: ul.LC_TabContent li.active a {
6924: color:$font;
6925: background:#FFFFFF;
6926: outline: none;
6927: }
6928:
6929: ul.LC_TabContent li.goback {
6930: float: left;
6931: border-left: none;
6932: }
6933:
6934: #maincoursedoc {
6935: clear:both;
6936: }
6937:
6938: ul.LC_TabContentBigger {
6939: display:block;
6940: list-style:none;
6941: padding: 0;
6942: }
6943:
6944: ul.LC_TabContentBigger li {
6945: vertical-align:bottom;
6946: height: 30px;
6947: font-size:110%;
6948: font-weight:bold;
6949: color: #737373;
6950: }
6951:
6952: ul.LC_TabContentBigger li.active {
6953: position: relative;
6954: top: 1px;
6955: }
6956:
6957: ul.LC_TabContentBigger li a {
6958: background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
6959: height: 30px;
6960: line-height: 30px;
6961: text-align: center;
6962: display: block;
6963: text-decoration: none;
6964: outline: none;
6965: }
6966:
6967: ul.LC_TabContentBigger li.active a {
6968: background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
6969: color:$font;
6970: }
6971:
6972: ul.LC_TabContentBigger li b {
6973: background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
6974: display: block;
6975: float: left;
6976: padding: 0 30px;
6977: border-bottom: 1px solid $lg_border_color;
6978: }
6979:
6980: ul.LC_TabContentBigger li:hover b {
6981: color:$button_hover;
6982: }
6983:
6984: ul.LC_TabContentBigger li.active b {
6985: background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
6986: color:$font;
6987: border: 0;
6988: }
6989:
6990:
6991: ul.LC_CourseBreadcrumbs {
6992: background: $sidebg;
6993: height: 2em;
6994: padding-left: 10px;
6995: margin: 0;
6996: list-style-position: inside;
6997: }
6998:
6999: ol#LC_MenuBreadcrumbs,
7000: ol#LC_PathBreadcrumbs {
7001: padding-left: 10px;
7002: margin: 0;
7003: height: 2.5em; /* equal to #LC_breadcrumbs line-height */
7004: }
7005:
7006: ol#LC_MenuBreadcrumbs li,
7007: ol#LC_PathBreadcrumbs li,
7008: ul.LC_CourseBreadcrumbs li {
7009: display: inline;
7010: white-space: normal;
7011: }
7012:
7013: ol#LC_MenuBreadcrumbs li a,
7014: ul.LC_CourseBreadcrumbs li a {
7015: text-decoration: none;
7016: font-size:90%;
7017: }
7018:
7019: ol#LC_MenuBreadcrumbs h1 {
7020: display: inline;
7021: font-size: 90%;
7022: line-height: 2.5em;
7023: margin: 0;
7024: padding: 0;
7025: }
7026:
7027: ol#LC_PathBreadcrumbs li a {
7028: text-decoration:none;
7029: font-size:100%;
7030: font-weight:bold;
7031: }
7032:
7033: .LC_Box {
7034: border: solid 1px $lg_border_color;
7035: padding: 0 10px 10px 10px;
7036: }
7037:
7038: .LC_DocsBox {
7039: border: solid 1px $lg_border_color;
7040: padding: 0 0 10px 10px;
7041: }
7042:
7043: .LC_AboutMe_Image {
7044: float:left;
7045: margin-right:10px;
7046: }
7047:
7048: .LC_Clear_AboutMe_Image {
7049: clear:left;
7050: }
7051:
7052: dl.LC_ListStyleClean dt {
7053: padding-right: 5px;
7054: display: table-header-group;
7055: }
7056:
7057: dl.LC_ListStyleClean dd {
7058: display: table-row;
7059: }
7060:
7061: .LC_ListStyleClean,
7062: .LC_ListStyleSimple,
7063: .LC_ListStyleNormal,
7064: .LC_ListStyleSpecial {
7065: /* display:block; */
7066: list-style-position: inside;
7067: list-style-type: none;
7068: overflow: hidden;
7069: padding: 0;
7070: }
7071:
7072: .LC_ListStyleSimple li,
7073: .LC_ListStyleSimple dd,
7074: .LC_ListStyleNormal li,
7075: .LC_ListStyleNormal dd,
7076: .LC_ListStyleSpecial li,
7077: .LC_ListStyleSpecial dd {
7078: margin: 0;
7079: padding: 5px 5px 5px 10px;
7080: clear: both;
7081: }
7082:
7083: .LC_ListStyleClean li,
7084: .LC_ListStyleClean dd {
7085: padding-top: 0;
7086: padding-bottom: 0;
7087: }
7088:
7089: .LC_ListStyleSimple dd,
7090: .LC_ListStyleSimple li {
7091: border-bottom: solid 1px $lg_border_color;
7092: }
7093:
7094: .LC_ListStyleSpecial li,
7095: .LC_ListStyleSpecial dd {
7096: list-style-type: none;
7097: background-color: RGB(220, 220, 220);
7098: margin-bottom: 4px;
7099: }
7100:
7101: table.LC_SimpleTable {
7102: margin:5px;
7103: border:solid 1px $lg_border_color;
7104: }
7105:
7106: table.LC_SimpleTable tr {
7107: padding: 0;
7108: border:solid 1px $lg_border_color;
7109: }
7110:
7111: table.LC_SimpleTable thead {
7112: background:rgb(220,220,220);
7113: }
7114:
7115: div.LC_columnSection {
7116: display: block;
7117: clear: both;
7118: overflow: hidden;
7119: margin: 0;
7120: }
7121:
7122: div.LC_columnSection>* {
7123: float: left;
7124: margin: 10px 20px 10px 0;
7125: overflow:hidden;
7126: }
7127:
7128: table em {
7129: font-weight: bold;
7130: font-style: normal;
7131: }
7132:
7133: table.LC_tableBrowseRes,
7134: table.LC_tableOfContent {
7135: border:none;
7136: border-spacing: 1px;
7137: padding: 3px;
7138: background-color: #FFFFFF;
7139: font-size: 90%;
7140: }
7141:
7142: table.LC_tableOfContent {
7143: border-collapse: collapse;
7144: }
7145:
7146: table.LC_tableBrowseRes a,
7147: table.LC_tableOfContent a {
7148: background-color: transparent;
7149: text-decoration: none;
7150: }
7151:
7152: table.LC_tableOfContent img {
7153: border: none;
7154: height: 1.3em;
7155: vertical-align: text-bottom;
7156: margin-right: 0.3em;
7157: }
7158:
7159: a#LC_content_toolbar_firsthomework {
7160: background-image:url(/res/adm/pages/open-first-problem.gif);
7161: }
7162:
7163: a#LC_content_toolbar_everything {
7164: background-image:url(/res/adm/pages/show-all.gif);
7165: }
7166:
7167: a#LC_content_toolbar_uncompleted {
7168: background-image:url(/res/adm/pages/show-incomplete-problems.gif);
7169: }
7170:
7171: #LC_content_toolbar_clearbubbles {
7172: background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
7173: }
7174:
7175: a#LC_content_toolbar_changefolder {
7176: background : url(/res/adm/pages/close-all-folders.gif) top center ;
7177: }
7178:
7179: a#LC_content_toolbar_changefolder_toggled {
7180: background-image:url(/res/adm/pages/open-all-folders.gif);
7181: }
7182:
7183: a#LC_content_toolbar_edittoplevel {
7184: background-image:url(/res/adm/pages/edittoplevel.gif);
7185: }
7186:
7187: ul#LC_toolbar li a:hover {
7188: background-position: bottom center;
7189: }
7190:
7191: ul#LC_toolbar {
7192: padding: 0;
7193: margin: 2px;
7194: list-style:none;
7195: position:relative;
7196: background-color:white;
7197: overflow: auto;
7198: }
7199:
7200: ul#LC_toolbar li {
7201: border:1px solid white;
7202: padding: 0;
7203: margin: 0;
7204: float: left;
7205: display:inline;
7206: vertical-align:middle;
7207: white-space: nowrap;
7208: }
7209:
7210:
7211: a.LC_toolbarItem {
7212: display:block;
7213: padding: 0;
7214: margin: 0;
7215: height: 32px;
7216: width: 32px;
7217: color:white;
7218: border: none;
7219: background-repeat:no-repeat;
7220: background-color:transparent;
7221: }
7222:
7223: ul.LC_funclist {
7224: margin: 0;
7225: padding: 0.5em 1em 0.5em 0;
7226: }
7227:
7228: ul.LC_funclist > li:first-child {
7229: font-weight:bold;
7230: margin-left:0.8em;
7231: }
7232:
7233: ul.LC_funclist + ul.LC_funclist {
7234: /*
7235: left border as a seperator if we have more than
7236: one list
7237: */
7238: border-left: 1px solid $sidebg;
7239: /*
7240: this hides the left border behind the border of the
7241: outer box if element is wrapped to the next 'line'
7242: */
7243: margin-left: -1px;
7244: }
7245:
7246: ul.LC_funclist li {
7247: display: inline;
7248: white-space: nowrap;
7249: margin: 0 0 0 25px;
7250: line-height: 150%;
7251: }
7252:
7253: .LC_hidden {
7254: display: none;
7255: }
7256:
7257: .LCmodal-overlay {
7258: position:fixed;
7259: top:0;
7260: right:0;
7261: bottom:0;
7262: left:0;
7263: height:100%;
7264: width:100%;
7265: margin:0;
7266: padding:0;
7267: background:#999;
7268: opacity:.75;
7269: filter: alpha(opacity=75);
7270: -moz-opacity: 0.75;
7271: z-index:101;
7272: }
7273:
7274: * html .LCmodal-overlay {
7275: position: absolute;
7276: height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
7277: }
7278:
7279: .LCmodal-window {
7280: position:fixed;
7281: top:50%;
7282: left:50%;
7283: margin:0;
7284: padding:0;
7285: z-index:102;
7286: }
7287:
7288: * html .LCmodal-window {
7289: position:absolute;
7290: }
7291:
7292: .LCclose-window {
7293: position:absolute;
7294: width:32px;
7295: height:32px;
7296: right:8px;
7297: top:8px;
7298: background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
7299: text-indent:-99999px;
7300: overflow:hidden;
7301: cursor:pointer;
7302: }
7303:
7304: /*
7305: styles used by TTH when "Default set of options to pass to tth/m
7306: when converting TeX" in course settings has been set
7307:
7308: option passed: -t
7309:
7310: */
7311:
7312: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
7313: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
7314: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
7315: td div.norm {line-height:normal;}
7316:
7317: /*
7318: option passed -y3
7319: */
7320:
7321: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
7322: span.overacc2 {position: relative; left: .8em; top: -1.2ex;}
7323: span.overacc1 {position: relative; left: .6em; top: -1.2ex;}
7324:
7325: END
7326: }
7327:
7328: =pod
7329:
7330: =item * &headtag()
7331:
7332: Returns a uniform footer for LON-CAPA web pages.
7333:
7334: Inputs: $title - optional title for the head
7335: $head_extra - optional extra HTML to put inside the <head>
7336: $args - optional arguments
7337: force_register - if is true call registerurl so the remote is
7338: informed
7339: redirect -> array ref of
7340: 1- seconds before redirect occurs
7341: 2- url to redirect to
7342: 3- whether the side effect should occur
7343: (side effect of setting
7344: $env{'internal.head.redirect'} to the url
7345: redirected too)
7346: domain -> force to color decorate a page for a specific
7347: domain
7348: function -> force usage of a specific rolish color scheme
7349: bgcolor -> override the default page bgcolor
7350: no_auto_mt_title
7351: -> prevent &mt()ing the title arg
7352:
7353: =cut
7354:
7355: sub headtag {
7356: my ($title,$head_extra,$args) = @_;
7357:
7358: my $function = $args->{'function'} || &get_users_function();
7359: my $domain = $args->{'domain'} || &determinedomain();
7360: my $bgcolor = $args->{'bgcolor'} || &designparm($function.'.pgbg',$domain);
7361: my $httphost = $args->{'use_absolute'};
7362: my $url = join(':',$env{'user.name'},$env{'user.domain'},
7363: $Apache::lonnet::perlvar{'lonVersion'},
7364: #time(),
7365: $env{'environment.color.timestamp'},
7366: $function,$domain,$bgcolor);
7367:
7368: $url = '/adm/css/'.&escape($url).'.css';
7369:
7370: my $result =
7371: '<head>'.
7372: &font_settings($args);
7373:
7374: my $inhibitprint;
7375: if ($args->{'print_suppress'}) {
7376: $inhibitprint = &print_suppression();
7377: }
7378:
7379: if (!$args->{'frameset'}) {
7380: $result .= &Apache::lonhtmlcommon::htmlareaheaders();
7381: }
7382: if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
7383: $result .= Apache::lonxml::display_title();
7384: }
7385: if (!$args->{'no_nav_bar'}
7386: && !$args->{'only_body'}
7387: && !$args->{'frameset'}) {
7388: $result .= &help_menu_js($httphost);
7389: $result.=&modal_window();
7390: $result.=&togglebox_script();
7391: $result.=&wishlist_window();
7392: $result.=&LCprogressbarUpdate_script();
7393: } else {
7394: if ($args->{'add_modal'}) {
7395: $result.=&modal_window();
7396: }
7397: if ($args->{'add_wishlist'}) {
7398: $result.=&wishlist_window();
7399: }
7400: if ($args->{'add_togglebox'}) {
7401: $result.=&togglebox_script();
7402: }
7403: if ($args->{'add_progressbar'}) {
7404: $result.=&LCprogressbarUpdate_script();
7405: }
7406: }
7407: if (ref($args->{'redirect'})) {
7408: my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
7409: $url = &Apache::lonenc::check_encrypt($url);
7410: if (!$inhibit_continue) {
7411: $env{'internal.head.redirect'} = $url;
7412: }
7413: $result.=<<ADDMETA
7414: <meta http-equiv="pragma" content="no-cache" />
7415: <meta http-equiv="Refresh" content="$time; url=$url" />
7416: ADDMETA
7417: }
7418: if (!defined($title)) {
7419: $title = 'The LearningOnline Network with CAPA';
7420: }
7421: if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
7422: $result .= '<title> LON-CAPA '.$title.'</title>'
7423: .'<link rel="stylesheet" type="text/css" href="'.$url.'"';
7424: if (!$args->{'frameset'}) {
7425: $result .= ' /';
7426: }
7427: $result .= '>'
7428: .$inhibitprint
7429: .$head_extra;
7430: if ($env{'browser.mobile'}) {
7431: $result .= '
7432: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
7433: <meta name="apple-mobile-web-app-capable" content="yes" />';
7434: }
7435: return $result.'</head>';
7436: }
7437:
7438: =pod
7439:
7440: =item * &font_settings()
7441:
7442: Returns neccessary <meta> to set the proper encoding
7443:
7444: Inputs: optional reference to HASH -- $args passed to &headtag()
7445:
7446: =cut
7447:
7448: sub font_settings {
7449: my ($args) = @_;
7450: my $headerstring='';
7451: if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
7452: ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
7453: $headerstring.=
7454: '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
7455: if (!$args->{'frameset'}) {
7456: $headerstring.= ' /';
7457: }
7458: $headerstring .= '>'."\n";
7459: }
7460: return $headerstring;
7461: }
7462:
7463: =pod
7464:
7465: =item * &print_suppression()
7466:
7467: In course context returns css which causes the body to be blank when media="print",
7468: if printout generation is unavailable for the current resource.
7469:
7470: This could be because:
7471:
7472: (a) printstartdate is in the future
7473:
7474: (b) printenddate is in the past
7475:
7476: (c) there is an active exam block with "printout"
7477: functionality blocked
7478:
7479: Users with pav, pfo or evb privileges are exempt.
7480:
7481: Inputs: none
7482:
7483: =cut
7484:
7485:
7486: sub print_suppression {
7487: my $noprint;
7488: if ($env{'request.course.id'}) {
7489: my $scope = $env{'request.course.id'};
7490: if ((&Apache::lonnet::allowed('pav',$scope)) ||
7491: (&Apache::lonnet::allowed('pfo',$scope))) {
7492: return;
7493: }
7494: if ($env{'request.course.sec'} ne '') {
7495: $scope .= "/$env{'request.course.sec'}";
7496: if ((&Apache::lonnet::allowed('pav',$scope)) ||
7497: (&Apache::lonnet::allowed('pfo',$scope))) {
7498: return;
7499: }
7500: }
7501: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7502: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7503: my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
7504: if ($blocked) {
7505: my $checkrole = "cm./$cdom/$cnum";
7506: if ($env{'request.course.sec'} ne '') {
7507: $checkrole .= "/$env{'request.course.sec'}";
7508: }
7509: unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
7510: ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
7511: $noprint = 1;
7512: }
7513: }
7514: unless ($noprint) {
7515: my $symb = &Apache::lonnet::symbread();
7516: if ($symb ne '') {
7517: my $navmap = Apache::lonnavmaps::navmap->new();
7518: if (ref($navmap)) {
7519: my $res = $navmap->getBySymb($symb);
7520: if (ref($res)) {
7521: if (!$res->resprintable()) {
7522: $noprint = 1;
7523: }
7524: }
7525: }
7526: }
7527: }
7528: if ($noprint) {
7529: return <<"ENDSTYLE";
7530: <style type="text/css" media="print">
7531: body { display:none }
7532: </style>
7533: ENDSTYLE
7534: }
7535: }
7536: return;
7537: }
7538:
7539: =pod
7540:
7541: =item * &xml_begin()
7542:
7543: Returns the needed doctype and <html>
7544:
7545: Inputs: none
7546:
7547: =cut
7548:
7549: sub xml_begin {
7550: my ($is_frameset) = @_;
7551: my $output='';
7552:
7553: if ($env{'browser.mathml'}) {
7554: $output='<?xml version="1.0"?>'
7555: #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
7556: # .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
7557:
7558: # .'<!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">] >'
7559: .'<!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">'
7560: .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" '
7561: .'xmlns="http://www.w3.org/1999/xhtml">';
7562: } elsif ($is_frameset) {
7563: $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
7564: '<html>'."\n";
7565: } else {
7566: $output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
7567: '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
7568: }
7569: return $output;
7570: }
7571:
7572: =pod
7573:
7574: =item * &start_page()
7575:
7576: Returns a complete <html> .. <body> section for LON-CAPA web pages.
7577:
7578: Inputs:
7579:
7580: =over 4
7581:
7582: $title - optional title for the page
7583:
7584: $head_extra - optional extra HTML to incude inside the <head>
7585:
7586: $args - additional optional args supported are:
7587:
7588: =over 8
7589:
7590: only_body -> is true will set &bodytag() onlybodytag
7591: arg on
7592: no_nav_bar -> is true will set &bodytag() no_nav_bar arg on
7593: add_entries -> additional attributes to add to the <body>
7594: domain -> force to color decorate a page for a
7595: specific domain
7596: function -> force usage of a specific rolish color
7597: scheme
7598: redirect -> see &headtag()
7599: bgcolor -> override the default page bg color
7600: js_ready -> return a string ready for being used in
7601: a javascript writeln
7602: html_encode -> return a string ready for being used in
7603: a html attribute
7604: force_register -> if is true will turn on the &bodytag()
7605: $forcereg arg
7606: frameset -> if true will start with a <frameset>
7607: rather than <body>
7608: skip_phases -> hash ref of
7609: head -> skip the <html><head> generation
7610: body -> skip all <body> generation
7611: no_auto_mt_title -> prevent &mt()ing the title arg
7612: inherit_jsmath -> when creating popup window in a page,
7613: should it have jsmath forced on by the
7614: current page
7615: bread_crumbs -> Array containing breadcrumbs
7616: bread_crumbs_component -> if exists show it as headline else show only the breadcrumbs
7617: group -> includes the current group, if page is for a
7618: specific group
7619:
7620: =back
7621:
7622: =back
7623:
7624: =cut
7625:
7626: sub start_page {
7627: my ($title,$head_extra,$args) = @_;
7628: #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
7629:
7630: $env{'internal.start_page'}++;
7631: my ($result,@advtools);
7632:
7633: if (! exists($args->{'skip_phases'}{'head'}) ) {
7634: $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
7635: }
7636:
7637: if (! exists($args->{'skip_phases'}{'body'}) ) {
7638: if ($args->{'frameset'}) {
7639: my $attr_string = &make_attr_string($args->{'force_register'},
7640: $args->{'add_entries'});
7641: $result .= "\n<frameset $attr_string>\n";
7642: } else {
7643: $result .=
7644: &bodytag($title,
7645: $args->{'function'}, $args->{'add_entries'},
7646: $args->{'only_body'}, $args->{'domain'},
7647: $args->{'force_register'}, $args->{'no_nav_bar'},
7648: $args->{'bgcolor'}, $args,
7649: \@advtools);
7650: }
7651: }
7652:
7653: if ($args->{'js_ready'}) {
7654: $result = &js_ready($result);
7655: }
7656: if ($args->{'html_encode'}) {
7657: $result = &html_encode($result);
7658: }
7659:
7660: # Preparation for new and consistent functionlist at top of screen
7661: # if ($args->{'functionlist'}) {
7662: # $result .= &build_functionlist();
7663: #}
7664:
7665: # Don't add anything more if only_body wanted or in const space
7666: return $result if $args->{'only_body'}
7667: || $env{'request.state'} eq 'construct';
7668:
7669: #Breadcrumbs
7670: if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
7671: &Apache::lonhtmlcommon::clear_breadcrumbs();
7672: #if any br links exists, add them to the breadcrumbs
7673: if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {
7674: foreach my $crumb (@{$args->{'bread_crumbs'}}){
7675: &Apache::lonhtmlcommon::add_breadcrumb($crumb);
7676: }
7677: }
7678: # if @advtools array contains items add then to the breadcrumbs
7679: if (@advtools > 0) {
7680: &Apache::lonmenu::advtools_crumbs(@advtools);
7681: }
7682:
7683: #if bread_crumbs_component exists show it as headline else show only the breadcrumbs
7684: if(exists($args->{'bread_crumbs_component'})){
7685: $result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
7686: }else{
7687: $result .= &Apache::lonhtmlcommon::breadcrumbs();
7688: }
7689: }
7690: return $result;
7691: }
7692:
7693: sub end_page {
7694: my ($args) = @_;
7695: $env{'internal.end_page'}++;
7696: my $result;
7697: if ($args->{'discussion'}) {
7698: my ($target,$parser);
7699: if (ref($args->{'discussion'})) {
7700: ($target,$parser) =($args->{'discussion'}{'target'},
7701: $args->{'discussion'}{'parser'});
7702: }
7703: $result .= &Apache::lonxml::xmlend($target,$parser);
7704: }
7705: if ($args->{'frameset'}) {
7706: $result .= '</frameset>';
7707: } else {
7708: $result .= &endbodytag($args);
7709: }
7710: unless ($args->{'notbody'}) {
7711: $result .= "\n</html>";
7712: }
7713:
7714: if ($args->{'js_ready'}) {
7715: $result = &js_ready($result);
7716: }
7717:
7718: if ($args->{'html_encode'}) {
7719: $result = &html_encode($result);
7720: }
7721:
7722: return $result;
7723: }
7724:
7725: sub wishlist_window {
7726: return(<<'ENDWISHLIST');
7727: <script type="text/javascript">
7728: // <![CDATA[
7729: // <!-- BEGIN LON-CAPA Internal
7730: function set_wishlistlink(title, path) {
7731: if (!title) {
7732: title = document.title;
7733: title = title.replace(/^LON-CAPA /,'');
7734: }
7735: title = encodeURIComponent(title);
7736: title = title.replace("'","\\\'");
7737: if (!path) {
7738: path = location.pathname;
7739: }
7740: path = encodeURIComponent(path);
7741: path = path.replace("'","\\\'");
7742: Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
7743: 'wishlistNewLink','width=560,height=350,scrollbars=0');
7744: }
7745: // END LON-CAPA Internal -->
7746: // ]]>
7747: </script>
7748: ENDWISHLIST
7749: }
7750:
7751: sub modal_window {
7752: return(<<'ENDMODAL');
7753: <script type="text/javascript">
7754: // <![CDATA[
7755: // <!-- BEGIN LON-CAPA Internal
7756: var modalWindow = {
7757: parent:"body",
7758: windowId:null,
7759: content:null,
7760: width:null,
7761: height:null,
7762: close:function()
7763: {
7764: $(".LCmodal-window").remove();
7765: $(".LCmodal-overlay").remove();
7766: },
7767: open:function()
7768: {
7769: var modal = "";
7770: modal += "<div class=\"LCmodal-overlay\"></div>";
7771: 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;\">";
7772: modal += this.content;
7773: modal += "</div>";
7774:
7775: $(this.parent).append(modal);
7776:
7777: $(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
7778: $(".LCclose-window").click(function(){modalWindow.close();});
7779: $(".LCmodal-overlay").click(function(){modalWindow.close();});
7780: }
7781: };
7782: var openMyModal = function(source,width,height,scrolling,transparency,style)
7783: {
7784: source = source.replace("'","'");
7785: modalWindow.windowId = "myModal";
7786: modalWindow.width = width;
7787: modalWindow.height = height;
7788: modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
7789: modalWindow.open();
7790: };
7791: // END LON-CAPA Internal -->
7792: // ]]>
7793: </script>
7794: ENDMODAL
7795: }
7796:
7797: sub modal_link {
7798: my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
7799: unless ($width) { $width=480; }
7800: unless ($height) { $height=400; }
7801: unless ($scrolling) { $scrolling='yes'; }
7802: unless ($transparency) { $transparency='true'; }
7803:
7804: my $target_attr;
7805: if (defined($target)) {
7806: $target_attr = 'target="'.$target.'"';
7807: }
7808: return <<"ENDLINK";
7809: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
7810: $linktext</a>
7811: ENDLINK
7812: }
7813:
7814: sub modal_adhoc_script {
7815: my ($funcname,$width,$height,$content)=@_;
7816: return (<<ENDADHOC);
7817: <script type="text/javascript">
7818: // <![CDATA[
7819: var $funcname = function()
7820: {
7821: modalWindow.windowId = "myModal";
7822: modalWindow.width = $width;
7823: modalWindow.height = $height;
7824: modalWindow.content = '$content';
7825: modalWindow.open();
7826: };
7827: // ]]>
7828: </script>
7829: ENDADHOC
7830: }
7831:
7832: sub modal_adhoc_inner {
7833: my ($funcname,$width,$height,$content)=@_;
7834: my $innerwidth=$width-20;
7835: $content=&js_ready(
7836: &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
7837: &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
7838: $content.
7839: &end_scrollbox().
7840: &end_page()
7841: );
7842: return &modal_adhoc_script($funcname,$width,$height,$content);
7843: }
7844:
7845: sub modal_adhoc_window {
7846: my ($funcname,$width,$height,$content,$linktext)=@_;
7847: return &modal_adhoc_inner($funcname,$width,$height,$content).
7848: "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
7849: }
7850:
7851: sub modal_adhoc_launch {
7852: my ($funcname,$width,$height,$content)=@_;
7853: return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
7854: <script type="text/javascript">
7855: // <![CDATA[
7856: $funcname();
7857: // ]]>
7858: </script>
7859: ENDLAUNCH
7860: }
7861:
7862: sub modal_adhoc_close {
7863: return (<<ENDCLOSE);
7864: <script type="text/javascript">
7865: // <![CDATA[
7866: modalWindow.close();
7867: // ]]>
7868: </script>
7869: ENDCLOSE
7870: }
7871:
7872: sub togglebox_script {
7873: return(<<ENDTOGGLE);
7874: <script type="text/javascript">
7875: // <![CDATA[
7876: function LCtoggleDisplay(id,hidetext,showtext) {
7877: link = document.getElementById(id + "link").childNodes[0];
7878: with (document.getElementById(id).style) {
7879: if (display == "none" ) {
7880: display = "inline";
7881: link.nodeValue = hidetext;
7882: } else {
7883: display = "none";
7884: link.nodeValue = showtext;
7885: }
7886: }
7887: }
7888: // ]]>
7889: </script>
7890: ENDTOGGLE
7891: }
7892:
7893: sub start_togglebox {
7894: my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
7895: unless ($heading) { $heading=''; } else { $heading.=' '; }
7896: unless ($showtext) { $showtext=&mt('show'); }
7897: unless ($hidetext) { $hidetext=&mt('hide'); }
7898: unless ($headerbg) { $headerbg='#FFFFFF'; }
7899: return &start_data_table().
7900: &start_data_table_header_row().
7901: '<td bgcolor="'.$headerbg.'">'.$heading.
7902: '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
7903: $showtext.'\')">'.$showtext.'</a>]</td>'.
7904: &end_data_table_header_row().
7905: '<tr id="'.$id.'" style="display:none""><td>';
7906: }
7907:
7908: sub end_togglebox {
7909: return '</td></tr>'.&end_data_table();
7910: }
7911:
7912: sub LCprogressbar_script {
7913: my ($id)=@_;
7914: return(<<ENDPROGRESS);
7915: <script type="text/javascript">
7916: // <![CDATA[
7917: \$('#progressbar$id').progressbar({
7918: value: 0,
7919: change: function(event, ui) {
7920: var newVal = \$(this).progressbar('option', 'value');
7921: \$('.pblabel', this).text(LCprogressTxt);
7922: }
7923: });
7924: // ]]>
7925: </script>
7926: ENDPROGRESS
7927: }
7928:
7929: sub LCprogressbarUpdate_script {
7930: return(<<ENDPROGRESSUPDATE);
7931: <style type="text/css">
7932: .ui-progressbar { position:relative; }
7933: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
7934: </style>
7935: <script type="text/javascript">
7936: // <![CDATA[
7937: var LCprogressTxt='---';
7938:
7939: function LCupdateProgress(percent,progresstext,id) {
7940: LCprogressTxt=progresstext;
7941: \$('#progressbar'+id).progressbar('value',percent);
7942: }
7943: // ]]>
7944: </script>
7945: ENDPROGRESSUPDATE
7946: }
7947:
7948: my $LClastpercent;
7949: my $LCidcnt;
7950: my $LCcurrentid;
7951:
7952: sub LCprogressbar {
7953: my ($r)=(@_);
7954: $LClastpercent=0;
7955: $LCidcnt++;
7956: $LCcurrentid=$$.'_'.$LCidcnt;
7957: my $starting=&mt('Starting');
7958: my $content=(<<ENDPROGBAR);
7959: <div id="progressbar$LCcurrentid">
7960: <span class="pblabel">$starting</span>
7961: </div>
7962: ENDPROGBAR
7963: &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
7964: }
7965:
7966: sub LCprogressbarUpdate {
7967: my ($r,$val,$text)=@_;
7968: unless ($val) {
7969: if ($LClastpercent) {
7970: $val=$LClastpercent;
7971: } else {
7972: $val=0;
7973: }
7974: }
7975: if ($val<0) { $val=0; }
7976: if ($val>100) { $val=0; }
7977: $LClastpercent=$val;
7978: unless ($text) { $text=$val.'%'; }
7979: $text=&js_ready($text);
7980: &r_print($r,<<ENDUPDATE);
7981: <script type="text/javascript">
7982: // <![CDATA[
7983: LCupdateProgress($val,'$text','$LCcurrentid');
7984: // ]]>
7985: </script>
7986: ENDUPDATE
7987: }
7988:
7989: sub LCprogressbarClose {
7990: my ($r)=@_;
7991: $LClastpercent=0;
7992: &r_print($r,<<ENDCLOSE);
7993: <script type="text/javascript">
7994: // <![CDATA[
7995: \$("#progressbar$LCcurrentid").hide('slow');
7996: // ]]>
7997: </script>
7998: ENDCLOSE
7999: }
8000:
8001: sub r_print {
8002: my ($r,$to_print)=@_;
8003: if ($r) {
8004: $r->print($to_print);
8005: $r->rflush();
8006: } else {
8007: print($to_print);
8008: }
8009: }
8010:
8011: sub html_encode {
8012: my ($result) = @_;
8013:
8014: $result = &HTML::Entities::encode($result,'<>&"');
8015:
8016: return $result;
8017: }
8018:
8019: sub js_ready {
8020: my ($result) = @_;
8021:
8022: $result =~ s/[\n\r]/ /xmsg;
8023: $result =~ s/\\/\\\\/xmsg;
8024: $result =~ s/'/\\'/xmsg;
8025: $result =~ s{</}{<\\/}xmsg;
8026:
8027: return $result;
8028: }
8029:
8030: sub validate_page {
8031: if ( exists($env{'internal.start_page'})
8032: && $env{'internal.start_page'} > 1) {
8033: &Apache::lonnet::logthis('start_page called multiple times '.
8034: $env{'internal.start_page'}.' '.
8035: $ENV{'request.filename'});
8036: }
8037: if ( exists($env{'internal.end_page'})
8038: && $env{'internal.end_page'} > 1) {
8039: &Apache::lonnet::logthis('end_page called multiple times '.
8040: $env{'internal.end_page'}.' '.
8041: $env{'request.filename'});
8042: }
8043: if ( exists($env{'internal.start_page'})
8044: && ! exists($env{'internal.end_page'})) {
8045: &Apache::lonnet::logthis('start_page called without end_page '.
8046: $env{'request.filename'});
8047: }
8048: if ( ! exists($env{'internal.start_page'})
8049: && exists($env{'internal.end_page'})) {
8050: &Apache::lonnet::logthis('end_page called without start_page'.
8051: $env{'request.filename'});
8052: }
8053: }
8054:
8055:
8056: sub start_scrollbox {
8057: my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
8058: unless ($outerwidth) { $outerwidth='520px'; }
8059: unless ($width) { $width='500px'; }
8060: unless ($height) { $height='200px'; }
8061: my ($table_id,$div_id,$tdcol);
8062: if ($id ne '') {
8063: $table_id = ' id="table_'.$id.'"';
8064: $div_id = ' id="div_'.$id.'"';
8065: }
8066: if ($bgcolor ne '') {
8067: $tdcol = "background-color: $bgcolor;";
8068: }
8069: my $nicescroll_js;
8070: if ($env{'browser.mobile'}) {
8071: $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
8072: }
8073: return <<"END";
8074: $nicescroll_js
8075:
8076: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
8077: <div style="overflow:auto; width:$width; height:$height;"$div_id>
8078: END
8079: }
8080:
8081: sub end_scrollbox {
8082: return '</div></td></tr></table>';
8083: }
8084:
8085: sub nicescroll_javascript {
8086: my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
8087: my %options;
8088: if (ref($cursor) eq 'HASH') {
8089: %options = %{$cursor};
8090: }
8091: unless ($options{'railalign'} =~ /^left|right$/) {
8092: $options{'railalign'} = 'left';
8093: }
8094: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
8095: my $function = &get_users_function();
8096: $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
8097: unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
8098: $options{'cursorcolor'} = '#00F';
8099: }
8100: }
8101: if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
8102: unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
8103: $options{'cursoropacity'}='1.0';
8104: }
8105: } else {
8106: $options{'cursoropacity'}='1.0';
8107: }
8108: if ($options{'cursorfixedheight'} eq 'none') {
8109: delete($options{'cursorfixedheight'});
8110: } else {
8111: unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
8112: }
8113: unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
8114: delete($options{'railoffset'});
8115: }
8116: my @niceoptions;
8117: while (my($key,$value) = each(%options)) {
8118: if ($value =~ /^\{.+\}$/) {
8119: push(@niceoptions,$key.':'.$value);
8120: } else {
8121: push(@niceoptions,$key.':"'.$value.'"');
8122: }
8123: }
8124: my $nicescroll_js = '
8125: $(document).ready(
8126: function() {
8127: $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
8128: }
8129: );
8130: ';
8131: if ($framecheck) {
8132: $nicescroll_js .= '
8133: function expand_div(caller) {
8134: if (top === self) {
8135: document.getElementById("'.$id.'").style.width = "auto";
8136: document.getElementById("'.$id.'").style.height = "auto";
8137: } else {
8138: try {
8139: if (parent.frames) {
8140: if (parent.frames.length > 1) {
8141: var framesrc = parent.frames[1].location.href;
8142: var currsrc = framesrc.replace(/\#.*$/,"");
8143: if ((caller == "search") || (currsrc == "'.$location.'")) {
8144: document.getElementById("'.$id.'").style.width = "auto";
8145: document.getElementById("'.$id.'").style.height = "auto";
8146: }
8147: }
8148: }
8149: } catch (e) {
8150: return;
8151: }
8152: }
8153: return;
8154: }
8155: ';
8156: }
8157: if ($needjsready) {
8158: $nicescroll_js = '
8159: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
8160: } else {
8161: $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
8162: }
8163: return $nicescroll_js;
8164: }
8165:
8166: sub simple_error_page {
8167: my ($r,$title,$msg,$args) = @_;
8168: if (ref($args) eq 'HASH') {
8169: if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
8170: } else {
8171: $msg = &mt($msg);
8172: }
8173:
8174: my $page =
8175: &Apache::loncommon::start_page($title).
8176: '<p class="LC_error">'.$msg.'</p>'.
8177: &Apache::loncommon::end_page();
8178: if (ref($r)) {
8179: $r->print($page);
8180: return;
8181: }
8182: return $page;
8183: }
8184:
8185: {
8186: my @row_count;
8187:
8188: sub start_data_table_count {
8189: unshift(@row_count, 0);
8190: return;
8191: }
8192:
8193: sub end_data_table_count {
8194: shift(@row_count);
8195: return;
8196: }
8197:
8198: sub start_data_table {
8199: my ($add_class,$id) = @_;
8200: my $css_class = (join(' ','LC_data_table',$add_class));
8201: my $table_id;
8202: if (defined($id)) {
8203: $table_id = ' id="'.$id.'"';
8204: }
8205: &start_data_table_count();
8206: return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
8207: }
8208:
8209: sub end_data_table {
8210: &end_data_table_count();
8211: return '</table>'."\n";;
8212: }
8213:
8214: sub start_data_table_row {
8215: my ($add_class, $id) = @_;
8216: $row_count[0]++;
8217: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
8218: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
8219: $id = (' id="'.$id.'"') unless ($id eq '');
8220: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
8221: }
8222:
8223: sub continue_data_table_row {
8224: my ($add_class, $id) = @_;
8225: my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
8226: $css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
8227: $id = (' id="'.$id.'"') unless ($id eq '');
8228: return '<tr class="'.$css_class.'"'.$id.'>'."\n";
8229: }
8230:
8231: sub end_data_table_row {
8232: return '</tr>'."\n";;
8233: }
8234:
8235: sub start_data_table_empty_row {
8236: # $row_count[0]++;
8237: return '<tr class="LC_empty_row" >'."\n";;
8238: }
8239:
8240: sub end_data_table_empty_row {
8241: return '</tr>'."\n";;
8242: }
8243:
8244: sub start_data_table_header_row {
8245: return '<tr class="LC_header_row">'."\n";;
8246: }
8247:
8248: sub end_data_table_header_row {
8249: return '</tr>'."\n";;
8250: }
8251:
8252: sub data_table_caption {
8253: my $caption = shift;
8254: return "<caption class=\"LC_caption\">$caption</caption>";
8255: }
8256: }
8257:
8258: =pod
8259:
8260: =item * &inhibit_menu_check($arg)
8261:
8262: Checks for a inhibitmenu state and generates output to preserve it
8263:
8264: Inputs: $arg - can be any of
8265: - undef - in which case the return value is a string
8266: to add into arguments list of a uri
8267: - 'input' - in which case the return value is a HTML
8268: <form> <input> field of type hidden to
8269: preserve the value
8270: - a url - in which case the return value is the url with
8271: the neccesary cgi args added to preserve the
8272: inhibitmenu state
8273: - a ref to a url - no return value, but the string is
8274: updated to include the neccessary cgi
8275: args to preserve the inhibitmenu state
8276:
8277: =cut
8278:
8279: sub inhibit_menu_check {
8280: my ($arg) = @_;
8281: &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
8282: if ($arg eq 'input') {
8283: if ($env{'form.inhibitmenu'}) {
8284: return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
8285: } else {
8286: return
8287: }
8288: }
8289: if ($env{'form.inhibitmenu'}) {
8290: if (ref($arg)) {
8291: $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
8292: } elsif ($arg eq '') {
8293: $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
8294: } else {
8295: $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
8296: }
8297: }
8298: if (!ref($arg)) {
8299: return $arg;
8300: }
8301: }
8302:
8303: ###############################################
8304:
8305: =pod
8306:
8307: =back
8308:
8309: =head1 User Information Routines
8310:
8311: =over 4
8312:
8313: =item * &get_users_function()
8314:
8315: Used by &bodytag to determine the current users primary role.
8316: Returns either 'student','coordinator','admin', or 'author'.
8317:
8318: =cut
8319:
8320: ###############################################
8321: sub get_users_function {
8322: my $function = 'norole';
8323: if ($env{'request.role'}=~/^(st)/) {
8324: $function='student';
8325: }
8326: if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
8327: $function='coordinator';
8328: }
8329: if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
8330: $function='admin';
8331: }
8332: if (($env{'request.role'}=~/^(au|ca|aa)/) ||
8333: ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
8334: $function='author';
8335: }
8336: return $function;
8337: }
8338:
8339: ###############################################
8340:
8341: =pod
8342:
8343: =item * &show_course()
8344:
8345: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
8346: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
8347:
8348: Inputs:
8349: None
8350:
8351: Outputs:
8352: Scalar: 1 if 'Course' to be used, 0 otherwise.
8353:
8354: =cut
8355:
8356: ###############################################
8357: sub show_course {
8358: my $course = !$env{'user.adv'};
8359: if (!$env{'user.adv'}) {
8360: foreach my $env (keys(%env)) {
8361: next if ($env !~ m/^user\.priv\./);
8362: if ($env !~ m/^user\.priv\.(?:st|cm)/) {
8363: $course = 0;
8364: last;
8365: }
8366: }
8367: }
8368: return $course;
8369: }
8370:
8371: ###############################################
8372:
8373: =pod
8374:
8375: =item * &check_user_status()
8376:
8377: Determines current status of supplied role for a
8378: specific user. Roles can be active, previous or future.
8379:
8380: Inputs:
8381: user's domain, user's username, course's domain,
8382: course's number, optional section ID.
8383:
8384: Outputs:
8385: role status: active, previous or future.
8386:
8387: =cut
8388:
8389: sub check_user_status {
8390: my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
8391: my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
8392: my @uroles = keys(%userinfo);
8393: my $srchstr;
8394: my $active_chk = 'none';
8395: my $now = time;
8396: if (@uroles > 0) {
8397: if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
8398: $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
8399: } else {
8400: $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
8401: }
8402: if (grep/^\Q$srchstr\E$/,@uroles) {
8403: my $role_end = 0;
8404: my $role_start = 0;
8405: $active_chk = 'active';
8406: if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
8407: $role_end = $1;
8408: if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
8409: $role_start = $1;
8410: }
8411: }
8412: if ($role_start > 0) {
8413: if ($now < $role_start) {
8414: $active_chk = 'future';
8415: }
8416: }
8417: if ($role_end > 0) {
8418: if ($now > $role_end) {
8419: $active_chk = 'previous';
8420: }
8421: }
8422: }
8423: }
8424: return $active_chk;
8425: }
8426:
8427: ###############################################
8428:
8429: =pod
8430:
8431: =item * &get_sections()
8432:
8433: Determines all the sections for a course including
8434: sections with students and sections containing other roles.
8435: Incoming parameters:
8436:
8437: 1. domain
8438: 2. course number
8439: 3. reference to array containing roles for which sections should
8440: be gathered (optional).
8441: 4. reference to array containing status types for which sections
8442: should be gathered (optional).
8443:
8444: If the third argument is undefined, sections are gathered for any role.
8445: If the fourth argument is undefined, sections are gathered for any status.
8446: Permissible values are 'active' or 'future' or 'previous'.
8447:
8448: Returns section hash (keys are section IDs, values are
8449: number of users in each section), subject to the
8450: optional roles filter, optional status filter
8451:
8452: =cut
8453:
8454: ###############################################
8455: sub get_sections {
8456: my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
8457: if (!defined($cdom) || !defined($cnum)) {
8458: my $cid = $env{'request.course.id'};
8459:
8460: return if (!defined($cid));
8461:
8462: $cdom = $env{'course.'.$cid.'.domain'};
8463: $cnum = $env{'course.'.$cid.'.num'};
8464: }
8465:
8466: my %sectioncount;
8467: my $now = time;
8468:
8469: my $check_students = 1;
8470: my $only_students = 0;
8471: if (ref($possible_roles) eq 'ARRAY') {
8472: if (grep(/^st$/,@{$possible_roles})) {
8473: if (@{$possible_roles} == 1) {
8474: $only_students = 1;
8475: }
8476: } else {
8477: $check_students = 0;
8478: }
8479: }
8480:
8481: if ($check_students) {
8482: my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
8483: my $sec_index = &Apache::loncoursedata::CL_SECTION();
8484: my $status_index = &Apache::loncoursedata::CL_STATUS();
8485: my $start_index = &Apache::loncoursedata::CL_START();
8486: my $end_index = &Apache::loncoursedata::CL_END();
8487: my $status;
8488: while (my ($student,$data) = each(%$classlist)) {
8489: my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
8490: $data->[$status_index],
8491: $data->[$start_index],
8492: $data->[$end_index]);
8493: if ($stu_status eq 'Active') {
8494: $status = 'active';
8495: } elsif ($end < $now) {
8496: $status = 'previous';
8497: } elsif ($start > $now) {
8498: $status = 'future';
8499: }
8500: if ($section ne '-1' && $section !~ /^\s*$/) {
8501: if ((!defined($possible_status)) || (($status ne '') &&
8502: (grep/^\Q$status\E$/,@{$possible_status}))) {
8503: $sectioncount{$section}++;
8504: }
8505: }
8506: }
8507: }
8508: if ($only_students) {
8509: return %sectioncount;
8510: }
8511: my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
8512: foreach my $user (sort(keys(%courseroles))) {
8513: if ($user !~ /^(\w{2})/) { next; }
8514: my ($role) = ($user =~ /^(\w{2})/);
8515: if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
8516: my ($section,$status);
8517: if ($role eq 'cr' &&
8518: $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
8519: $section=$1;
8520: }
8521: if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
8522: if (!defined($section) || $section eq '-1') { next; }
8523: my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
8524: if ($end == -1 && $start == -1) {
8525: next; #deleted role
8526: }
8527: if (!defined($possible_status)) {
8528: $sectioncount{$section}++;
8529: } else {
8530: if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
8531: $status = 'active';
8532: } elsif ($end < $now) {
8533: $status = 'future';
8534: } elsif ($start > $now) {
8535: $status = 'previous';
8536: }
8537: if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
8538: $sectioncount{$section}++;
8539: }
8540: }
8541: }
8542: return %sectioncount;
8543: }
8544:
8545: ###############################################
8546:
8547: =pod
8548:
8549: =item * &get_course_users()
8550:
8551: Retrieves usernames:domains for users in the specified course
8552: with specific role(s), and access status.
8553:
8554: Incoming parameters:
8555: 1. course domain
8556: 2. course number
8557: 3. access status: users must have - either active,
8558: previous, future, or all.
8559: 4. reference to array of permissible roles
8560: 5. reference to array of section restrictions (optional)
8561: 6. reference to results object (hash of hashes).
8562: 7. reference to optional userdata hash
8563: 8. reference to optional statushash
8564: 9. flag if privileged users (except those set to unhide in
8565: course settings) should be excluded
8566: Keys of top level results hash are roles.
8567: Keys of inner hashes are username:domain, with
8568: values set to access type.
8569: Optional userdata hash returns an array with arguments in the
8570: same order as loncoursedata::get_classlist() for student data.
8571:
8572: Optional statushash returns
8573:
8574: Entries for end, start, section and status are blank because
8575: of the possibility of multiple values for non-student roles.
8576:
8577: =cut
8578:
8579: ###############################################
8580:
8581: sub get_course_users {
8582: my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
8583: my %idx = ();
8584: my %seclists;
8585:
8586: $idx{udom} = &Apache::loncoursedata::CL_SDOM();
8587: $idx{uname} = &Apache::loncoursedata::CL_SNAME();
8588: $idx{end} = &Apache::loncoursedata::CL_END();
8589: $idx{start} = &Apache::loncoursedata::CL_START();
8590: $idx{id} = &Apache::loncoursedata::CL_ID();
8591: $idx{section} = &Apache::loncoursedata::CL_SECTION();
8592: $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
8593: $idx{status} = &Apache::loncoursedata::CL_STATUS();
8594:
8595: if (grep(/^st$/,@{$roles})) {
8596: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
8597: my $now = time;
8598: foreach my $student (keys(%{$classlist})) {
8599: my $match = 0;
8600: my $secmatch = 0;
8601: my $section = $$classlist{$student}[$idx{section}];
8602: my $status = $$classlist{$student}[$idx{status}];
8603: if ($section eq '') {
8604: $section = 'none';
8605: }
8606: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
8607: if (grep(/^all$/,@{$sections})) {
8608: $secmatch = 1;
8609: } elsif ($$classlist{$student}[$idx{section}] eq '') {
8610: if (grep(/^none$/,@{$sections})) {
8611: $secmatch = 1;
8612: }
8613: } else {
8614: if (grep(/^\Q$section\E$/,@{$sections})) {
8615: $secmatch = 1;
8616: }
8617: }
8618: if (!$secmatch) {
8619: next;
8620: }
8621: }
8622: if (defined($$types{'active'})) {
8623: if ($$classlist{$student}[$idx{status}] eq 'Active') {
8624: push(@{$$users{st}{$student}},'active');
8625: $match = 1;
8626: }
8627: }
8628: if (defined($$types{'previous'})) {
8629: if ($$classlist{$student}[$idx{status}] eq 'Expired') {
8630: push(@{$$users{st}{$student}},'previous');
8631: $match = 1;
8632: }
8633: }
8634: if (defined($$types{'future'})) {
8635: if ($$classlist{$student}[$idx{status}] eq 'Future') {
8636: push(@{$$users{st}{$student}},'future');
8637: $match = 1;
8638: }
8639: }
8640: if ($match) {
8641: push(@{$seclists{$student}},$section);
8642: if (ref($userdata) eq 'HASH') {
8643: $$userdata{$student} = $$classlist{$student};
8644: }
8645: if (ref($statushash) eq 'HASH') {
8646: $statushash->{$student}{'st'}{$section} = $status;
8647: }
8648: }
8649: }
8650: }
8651: if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
8652: my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
8653: my $now = time;
8654: my %displaystatus = ( previous => 'Expired',
8655: active => 'Active',
8656: future => 'Future',
8657: );
8658: my (%nothide,@possdoms);
8659: if ($hidepriv) {
8660: my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
8661: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
8662: if ($user !~ /:/) {
8663: $nothide{join(':',split(/[\@]/,$user))}=1;
8664: } else {
8665: $nothide{$user} = 1;
8666: }
8667: }
8668: my @possdoms = ($cdom);
8669: if ($coursehash{'checkforpriv'}) {
8670: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
8671: }
8672: }
8673: foreach my $person (sort(keys(%coursepersonnel))) {
8674: my $match = 0;
8675: my $secmatch = 0;
8676: my $status;
8677: my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
8678: $user =~ s/:$//;
8679: my ($end,$start) = split(/:/,$coursepersonnel{$person});
8680: if ($end == -1 || $start == -1) {
8681: next;
8682: }
8683: if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
8684: (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
8685: my ($uname,$udom) = split(/:/,$user);
8686: if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
8687: if (grep(/^all$/,@{$sections})) {
8688: $secmatch = 1;
8689: } elsif ($usec eq '') {
8690: if (grep(/^none$/,@{$sections})) {
8691: $secmatch = 1;
8692: }
8693: } else {
8694: if (grep(/^\Q$usec\E$/,@{$sections})) {
8695: $secmatch = 1;
8696: }
8697: }
8698: if (!$secmatch) {
8699: next;
8700: }
8701: }
8702: if ($usec eq '') {
8703: $usec = 'none';
8704: }
8705: if ($uname ne '' && $udom ne '') {
8706: if ($hidepriv) {
8707: if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
8708: (!$nothide{$uname.':'.$udom})) {
8709: next;
8710: }
8711: }
8712: if ($end > 0 && $end < $now) {
8713: $status = 'previous';
8714: } elsif ($start > $now) {
8715: $status = 'future';
8716: } else {
8717: $status = 'active';
8718: }
8719: foreach my $type (keys(%{$types})) {
8720: if ($status eq $type) {
8721: if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
8722: push(@{$$users{$role}{$user}},$type);
8723: }
8724: $match = 1;
8725: }
8726: }
8727: if (($match) && (ref($userdata) eq 'HASH')) {
8728: if (!exists($$userdata{$uname.':'.$udom})) {
8729: &get_user_info($udom,$uname,\%idx,$userdata);
8730: }
8731: if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
8732: push(@{$seclists{$uname.':'.$udom}},$usec);
8733: }
8734: if (ref($statushash) eq 'HASH') {
8735: $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
8736: }
8737: }
8738: }
8739: }
8740: }
8741: if (grep(/^ow$/,@{$roles})) {
8742: if ((defined($cdom)) && (defined($cnum))) {
8743: my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
8744: if ( defined($csettings{'internal.courseowner'}) ) {
8745: my $owner = $csettings{'internal.courseowner'};
8746: next if ($owner eq '');
8747: my ($ownername,$ownerdom);
8748: if ($owner =~ /^([^:]+):([^:]+)$/) {
8749: $ownername = $1;
8750: $ownerdom = $2;
8751: } else {
8752: $ownername = $owner;
8753: $ownerdom = $cdom;
8754: $owner = $ownername.':'.$ownerdom;
8755: }
8756: @{$$users{'ow'}{$owner}} = 'any';
8757: if (defined($userdata) &&
8758: !exists($$userdata{$owner})) {
8759: &get_user_info($ownerdom,$ownername,\%idx,$userdata);
8760: if (!grep(/^none$/,@{$seclists{$owner}})) {
8761: push(@{$seclists{$owner}},'none');
8762: }
8763: if (ref($statushash) eq 'HASH') {
8764: $statushash->{$owner}{'ow'}{'none'} = 'Any';
8765: }
8766: }
8767: }
8768: }
8769: }
8770: foreach my $user (keys(%seclists)) {
8771: @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
8772: $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
8773: }
8774: }
8775: return;
8776: }
8777:
8778: sub get_user_info {
8779: my ($udom,$uname,$idx,$userdata) = @_;
8780: $$userdata{$uname.':'.$udom}[$$idx{fullname}] =
8781: &plainname($uname,$udom,'lastname');
8782: $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
8783: $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
8784: my %idhash = &Apache::lonnet::idrget($udom,($uname));
8785: $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname};
8786: return;
8787: }
8788:
8789: ###############################################
8790:
8791: =pod
8792:
8793: =item * &get_user_quota()
8794:
8795: Retrieves quota assigned for storage of user files.
8796: Default is to report quota for portfolio files.
8797:
8798: Incoming parameters:
8799: 1. user's username
8800: 2. user's domain
8801: 3. quota name - portfolio, author, or course
8802: (if no quota name provided, defaults to portfolio).
8803: 4. crstype - official, unofficial, textbook or community, if quota name is
8804: course
8805:
8806: Returns:
8807: 1. Disk quota (in MB) assigned to student.
8808: 2. (Optional) Type of setting: custom or default
8809: (individually assigned or default for user's
8810: institutional status).
8811: 3. (Optional) - User's institutional status (e.g., faculty, staff
8812: or student - types as defined in localenroll::inst_usertypes
8813: for user's domain, which determines default quota for user.
8814: 4. (Optional) - Default quota which would apply to the user.
8815:
8816: If a value has been stored in the user's environment,
8817: it will return that, otherwise it returns the maximal default
8818: defined for the user's institutional status(es) in the domain.
8819:
8820: =cut
8821:
8822: ###############################################
8823:
8824:
8825: sub get_user_quota {
8826: my ($uname,$udom,$quotaname,$crstype) = @_;
8827: my ($quota,$quotatype,$settingstatus,$defquota);
8828: if (!defined($udom)) {
8829: $udom = $env{'user.domain'};
8830: }
8831: if (!defined($uname)) {
8832: $uname = $env{'user.name'};
8833: }
8834: if (($udom eq '' || $uname eq '') ||
8835: ($udom eq 'public') && ($uname eq 'public')) {
8836: $quota = 0;
8837: $quotatype = 'default';
8838: $defquota = 0;
8839: } else {
8840: my $inststatus;
8841: if ($quotaname eq 'course') {
8842: if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
8843: ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
8844: $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
8845: } else {
8846: my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
8847: $quota = $cenv{'internal.uploadquota'};
8848: }
8849: } else {
8850: if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
8851: if ($quotaname eq 'author') {
8852: $quota = $env{'environment.authorquota'};
8853: } else {
8854: $quota = $env{'environment.portfolioquota'};
8855: }
8856: $inststatus = $env{'environment.inststatus'};
8857: } else {
8858: my %userenv =
8859: &Apache::lonnet::get('environment',['portfolioquota',
8860: 'authorquota','inststatus'],$udom,$uname);
8861: my ($tmp) = keys(%userenv);
8862: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8863: if ($quotaname eq 'author') {
8864: $quota = $userenv{'authorquota'};
8865: } else {
8866: $quota = $userenv{'portfolioquota'};
8867: }
8868: $inststatus = $userenv{'inststatus'};
8869: } else {
8870: undef(%userenv);
8871: }
8872: }
8873: }
8874: if ($quota eq '' || wantarray) {
8875: if ($quotaname eq 'course') {
8876: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
8877: if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
8878: ($crstype eq 'community') || ($crstype eq 'textbook')) {
8879: $defquota = $domdefs{$crstype.'quota'};
8880: }
8881: if ($defquota eq '') {
8882: $defquota = 500;
8883: }
8884: } else {
8885: ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
8886: }
8887: if ($quota eq '') {
8888: $quota = $defquota;
8889: $quotatype = 'default';
8890: } else {
8891: $quotatype = 'custom';
8892: }
8893: }
8894: }
8895: if (wantarray) {
8896: return ($quota,$quotatype,$settingstatus,$defquota);
8897: } else {
8898: return $quota;
8899: }
8900: }
8901:
8902: ###############################################
8903:
8904: =pod
8905:
8906: =item * &default_quota()
8907:
8908: Retrieves default quota assigned for storage of user portfolio files,
8909: given an (optional) user's institutional status.
8910:
8911: Incoming parameters:
8912:
8913: 1. domain
8914: 2. (Optional) institutional status(es). This is a : separated list of
8915: status types (e.g., faculty, staff, student etc.)
8916: which apply to the user for whom the default is being retrieved.
8917: If the institutional status string in undefined, the domain
8918: default quota will be returned.
8919: 3. quota name - portfolio, author, or course
8920: (if no quota name provided, defaults to portfolio).
8921:
8922: Returns:
8923:
8924: 1. Default disk quota (in MB) for user portfolios in the domain.
8925: 2. (Optional) institutional type which determined the value of the
8926: default quota.
8927:
8928: If a value has been stored in the domain's configuration db,
8929: it will return that, otherwise it returns 20 (for backwards
8930: compatibility with domains which have not set up a configuration
8931: db file; the original statically defined portfolio quota was 20 MB).
8932:
8933: If the user's status includes multiple types (e.g., staff and student),
8934: the largest default quota which applies to the user determines the
8935: default quota returned.
8936:
8937: =cut
8938:
8939: ###############################################
8940:
8941:
8942: sub default_quota {
8943: my ($udom,$inststatus,$quotaname) = @_;
8944: my ($defquota,$settingstatus);
8945: my %quotahash = &Apache::lonnet::get_dom('configuration',
8946: ['quotas'],$udom);
8947: my $key = 'defaultquota';
8948: if ($quotaname eq 'author') {
8949: $key = 'authorquota';
8950: }
8951: if (ref($quotahash{'quotas'}) eq 'HASH') {
8952: if ($inststatus ne '') {
8953: my @statuses = map { &unescape($_); } split(/:/,$inststatus);
8954: foreach my $item (@statuses) {
8955: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
8956: if ($quotahash{'quotas'}{$key}{$item} ne '') {
8957: if ($defquota eq '') {
8958: $defquota = $quotahash{'quotas'}{$key}{$item};
8959: $settingstatus = $item;
8960: } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
8961: $defquota = $quotahash{'quotas'}{$key}{$item};
8962: $settingstatus = $item;
8963: }
8964: }
8965: } elsif ($key eq 'defaultquota') {
8966: if ($quotahash{'quotas'}{$item} ne '') {
8967: if ($defquota eq '') {
8968: $defquota = $quotahash{'quotas'}{$item};
8969: $settingstatus = $item;
8970: } elsif ($quotahash{'quotas'}{$item} > $defquota) {
8971: $defquota = $quotahash{'quotas'}{$item};
8972: $settingstatus = $item;
8973: }
8974: }
8975: }
8976: }
8977: }
8978: if ($defquota eq '') {
8979: if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
8980: $defquota = $quotahash{'quotas'}{$key}{'default'};
8981: } elsif ($key eq 'defaultquota') {
8982: $defquota = $quotahash{'quotas'}{'default'};
8983: }
8984: $settingstatus = 'default';
8985: if ($defquota eq '') {
8986: if ($quotaname eq 'author') {
8987: $defquota = 500;
8988: }
8989: }
8990: }
8991: } else {
8992: $settingstatus = 'default';
8993: if ($quotaname eq 'author') {
8994: $defquota = 500;
8995: } else {
8996: $defquota = 20;
8997: }
8998: }
8999: if (wantarray) {
9000: return ($defquota,$settingstatus);
9001: } else {
9002: return $defquota;
9003: }
9004: }
9005:
9006: ###############################################
9007:
9008: =pod
9009:
9010: =item * &excess_filesize_warning()
9011:
9012: Returns warning message if upload of file to authoring space, or copying
9013: of existing file within authoring space will cause quota for the authoring
9014: space to be exceeded.
9015:
9016: Same, if upload of a file directly to a course/community via Course Editor
9017: will cause quota for uploaded content for the course to be exceeded.
9018:
9019: Inputs: 7
9020: 1. username or coursenum
9021: 2. domain
9022: 3. context ('author' or 'course')
9023: 4. filename of file for which action is being requested
9024: 5. filesize (kB) of file
9025: 6. action being taken: copy or upload.
9026: 7. quotatype (in course context -- official, unofficial, community or textbook).
9027:
9028: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
9029: otherwise return null.
9030:
9031: =back
9032:
9033: =cut
9034:
9035: sub excess_filesize_warning {
9036: my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
9037: my $current_disk_usage = 0;
9038: my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
9039: if ($context eq 'author') {
9040: my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
9041: $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
9042: } else {
9043: foreach my $subdir ('docs','supplemental') {
9044: $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
9045: }
9046: }
9047: $disk_quota = int($disk_quota * 1000);
9048: if (($current_disk_usage + $filesize) > $disk_quota) {
9049: return '<p class="LC_warning">'.
9050: &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
9051: '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
9052: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
9053: $disk_quota,$current_disk_usage).
9054: '</p>';
9055: }
9056: return;
9057: }
9058:
9059: ###############################################
9060:
9061:
9062:
9063:
9064: sub get_secgrprole_info {
9065: my ($cdom,$cnum,$needroles,$type) = @_;
9066: my %sections_count = &get_sections($cdom,$cnum);
9067: my @sections = (sort {$a <=> $b} keys(%sections_count));
9068: my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
9069: my @groups = sort(keys(%curr_groups));
9070: my $allroles = [];
9071: my $rolehash;
9072: my $accesshash = {
9073: active => 'Currently has access',
9074: future => 'Will have future access',
9075: previous => 'Previously had access',
9076: };
9077: if ($needroles) {
9078: $rolehash = {'all' => 'all'};
9079: my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
9080: if (&Apache::lonnet::error(%user_roles)) {
9081: undef(%user_roles);
9082: }
9083: foreach my $item (keys(%user_roles)) {
9084: my ($role)=split(/\:/,$item,2);
9085: if ($role eq 'cr') { next; }
9086: if ($role =~ /^cr/) {
9087: $$rolehash{$role} = (split('/',$role))[3];
9088: } else {
9089: $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
9090: }
9091: }
9092: foreach my $key (sort(keys(%{$rolehash}))) {
9093: push(@{$allroles},$key);
9094: }
9095: push (@{$allroles},'st');
9096: $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
9097: }
9098: return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
9099: }
9100:
9101: sub user_picker {
9102: my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
9103: my $currdom = $dom;
9104: my %curr_selected = (
9105: srchin => 'dom',
9106: srchby => 'lastname',
9107: );
9108: my $srchterm;
9109: if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
9110: if ($srch->{'srchby'} ne '') {
9111: $curr_selected{'srchby'} = $srch->{'srchby'};
9112: }
9113: if ($srch->{'srchin'} ne '') {
9114: $curr_selected{'srchin'} = $srch->{'srchin'};
9115: }
9116: if ($srch->{'srchtype'} ne '') {
9117: $curr_selected{'srchtype'} = $srch->{'srchtype'};
9118: }
9119: if ($srch->{'srchdomain'} ne '') {
9120: $currdom = $srch->{'srchdomain'};
9121: }
9122: $srchterm = $srch->{'srchterm'};
9123: }
9124: my %lt=&Apache::lonlocal::texthash(
9125: 'usr' => 'Search criteria',
9126: 'doma' => 'Domain/institution to search',
9127: 'uname' => 'username',
9128: 'lastname' => 'last name',
9129: 'lastfirst' => 'last name, first name',
9130: 'crs' => 'in this course',
9131: 'dom' => 'in selected LON-CAPA domain',
9132: 'alc' => 'all LON-CAPA',
9133: 'instd' => 'in institutional directory for selected domain',
9134: 'exact' => 'is',
9135: 'contains' => 'contains',
9136: 'begins' => 'begins with',
9137: 'youm' => "You must include some text to search for.",
9138: 'thte' => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
9139: 'thet' => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
9140: 'yomc' => "You must choose a domain when using an institutional directory search.",
9141: 'ymcd' => "You must choose a domain when using a domain search.",
9142: 'whus' => "When using searching by last,first you must include a comma as separator between last name and first name.",
9143: 'whse' => "When searching by last,first you must include at least one character in the first name.",
9144: 'thfo' => "The following need to be corrected before the search can be run:",
9145: );
9146: my $domform = &select_dom_form($currdom,'srchdomain',1,1);
9147: my $srchinsel = ' <select name="srchin">';
9148:
9149: my @srchins = ('crs','dom','alc','instd');
9150:
9151: foreach my $option (@srchins) {
9152: # FIXME 'alc' option unavailable until
9153: # loncreateuser::print_user_query_page()
9154: # has been completed.
9155: next if ($option eq 'alc');
9156: next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));
9157: next if ($option eq 'crs' && !$env{'request.course.id'});
9158: if ($curr_selected{'srchin'} eq $option) {
9159: $srchinsel .= '
9160: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
9161: } else {
9162: $srchinsel .= '
9163: <option value="'.$option.'">'.$lt{$option}.'</option>';
9164: }
9165: }
9166: $srchinsel .= "\n </select>\n";
9167:
9168: my $srchbysel = ' <select name="srchby">';
9169: foreach my $option ('lastname','lastfirst','uname') {
9170: if ($curr_selected{'srchby'} eq $option) {
9171: $srchbysel .= '
9172: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
9173: } else {
9174: $srchbysel .= '
9175: <option value="'.$option.'">'.$lt{$option}.'</option>';
9176: }
9177: }
9178: $srchbysel .= "\n </select>\n";
9179:
9180: my $srchtypesel = ' <select name="srchtype">';
9181: foreach my $option ('begins','contains','exact') {
9182: if ($curr_selected{'srchtype'} eq $option) {
9183: $srchtypesel .= '
9184: <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
9185: } else {
9186: $srchtypesel .= '
9187: <option value="'.$option.'">'.$lt{$option}.'</option>';
9188: }
9189: }
9190: $srchtypesel .= "\n </select>\n";
9191:
9192: my ($newuserscript,$new_user_create);
9193: my $context_dom = $env{'request.role.domain'};
9194: if ($context eq 'requestcrs') {
9195: if ($env{'form.coursedom'} ne '') {
9196: $context_dom = $env{'form.coursedom'};
9197: }
9198: }
9199: if ($forcenewuser) {
9200: if (ref($srch) eq 'HASH') {
9201: if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
9202: if ($cancreate) {
9203: $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>';
9204: } else {
9205: my $helplink = 'javascript:helpMenu('."'display'".')';
9206: my %usertypetext = (
9207: official => 'institutional',
9208: unofficial => 'non-institutional',
9209: );
9210: $new_user_create = '<p class="LC_warning">'
9211: .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
9212: .' '
9213: .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
9214: ,'<a href="'.$helplink.'">','</a>')
9215: .'</p><br />';
9216: }
9217: }
9218: }
9219:
9220: $newuserscript = <<"ENDSCRIPT";
9221:
9222: function setSearch(createnew,callingForm) {
9223: if (createnew == 1) {
9224: for (var i=0; i<callingForm.srchby.length; i++) {
9225: if (callingForm.srchby.options[i].value == 'uname') {
9226: callingForm.srchby.selectedIndex = i;
9227: }
9228: }
9229: for (var i=0; i<callingForm.srchin.length; i++) {
9230: if ( callingForm.srchin.options[i].value == 'dom') {
9231: callingForm.srchin.selectedIndex = i;
9232: }
9233: }
9234: for (var i=0; i<callingForm.srchtype.length; i++) {
9235: if (callingForm.srchtype.options[i].value == 'exact') {
9236: callingForm.srchtype.selectedIndex = i;
9237: }
9238: }
9239: for (var i=0; i<callingForm.srchdomain.length; i++) {
9240: if (callingForm.srchdomain.options[i].value == '$context_dom') {
9241: callingForm.srchdomain.selectedIndex = i;
9242: }
9243: }
9244: }
9245: }
9246: ENDSCRIPT
9247:
9248: }
9249:
9250: my $output = <<"END_BLOCK";
9251: <script type="text/javascript">
9252: // <![CDATA[
9253: function validateEntry(callingForm) {
9254:
9255: var checkok = 1;
9256: var srchin;
9257: for (var i=0; i<callingForm.srchin.length; i++) {
9258: if ( callingForm.srchin[i].checked ) {
9259: srchin = callingForm.srchin[i].value;
9260: }
9261: }
9262:
9263: var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
9264: var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
9265: var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
9266: var srchterm = callingForm.srchterm.value;
9267: var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
9268: var msg = "";
9269:
9270: if (srchterm == "") {
9271: checkok = 0;
9272: msg += "$lt{'youm'}\\n";
9273: }
9274:
9275: if (srchtype== 'begins') {
9276: if (srchterm.length < 2) {
9277: checkok = 0;
9278: msg += "$lt{'thte'}\\n";
9279: }
9280: }
9281:
9282: if (srchtype== 'contains') {
9283: if (srchterm.length < 3) {
9284: checkok = 0;
9285: msg += "$lt{'thet'}\\n";
9286: }
9287: }
9288: if (srchin == 'instd') {
9289: if (srchdomain == '') {
9290: checkok = 0;
9291: msg += "$lt{'yomc'}\\n";
9292: }
9293: }
9294: if (srchin == 'dom') {
9295: if (srchdomain == '') {
9296: checkok = 0;
9297: msg += "$lt{'ymcd'}\\n";
9298: }
9299: }
9300: if (srchby == 'lastfirst') {
9301: if (srchterm.indexOf(",") == -1) {
9302: checkok = 0;
9303: msg += "$lt{'whus'}\\n";
9304: }
9305: if (srchterm.indexOf(",") == srchterm.length -1) {
9306: checkok = 0;
9307: msg += "$lt{'whse'}\\n";
9308: }
9309: }
9310: if (checkok == 0) {
9311: alert("$lt{'thfo'}\\n"+msg);
9312: return;
9313: }
9314: if (checkok == 1) {
9315: callingForm.submit();
9316: }
9317: }
9318:
9319: $newuserscript
9320:
9321: // ]]>
9322: </script>
9323:
9324: $new_user_create
9325:
9326: END_BLOCK
9327:
9328: $output .= &Apache::lonhtmlcommon::start_pick_box().
9329: &Apache::lonhtmlcommon::row_title($lt{'doma'}).
9330: $domform.
9331: &Apache::lonhtmlcommon::row_closure().
9332: &Apache::lonhtmlcommon::row_title($lt{'usr'}).
9333: $srchbysel.
9334: $srchtypesel.
9335: '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
9336: $srchinsel.
9337: &Apache::lonhtmlcommon::row_closure(1).
9338: &Apache::lonhtmlcommon::end_pick_box().
9339: '<br />';
9340: return $output;
9341: }
9342:
9343: sub user_rule_check {
9344: my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
9345: my $response;
9346: if (ref($usershash) eq 'HASH') {
9347: foreach my $user (keys(%{$usershash})) {
9348: my ($uname,$udom) = split(/:/,$user);
9349: next if ($udom eq '' || $uname eq '');
9350: my ($id,$newuser);
9351: if (ref($usershash->{$user}) eq 'HASH') {
9352: $newuser = $usershash->{$user}->{'newuser'};
9353: $id = $usershash->{$user}->{'id'};
9354: }
9355: my $inst_response;
9356: if (ref($checks) eq 'HASH') {
9357: if (defined($checks->{'username'})) {
9358: ($inst_response,%{$inst_results->{$user}}) =
9359: &Apache::lonnet::get_instuser($udom,$uname);
9360: } elsif (defined($checks->{'id'})) {
9361: ($inst_response,%{$inst_results->{$user}}) =
9362: &Apache::lonnet::get_instuser($udom,undef,$id);
9363: }
9364: } else {
9365: ($inst_response,%{$inst_results->{$user}}) =
9366: &Apache::lonnet::get_instuser($udom,$uname);
9367: return;
9368: }
9369: if (!$got_rules->{$udom}) {
9370: my %domconfig = &Apache::lonnet::get_dom('configuration',
9371: ['usercreation'],$udom);
9372: if (ref($domconfig{'usercreation'}) eq 'HASH') {
9373: foreach my $item ('username','id') {
9374: if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
9375: $$curr_rules{$udom}{$item} =
9376: $domconfig{'usercreation'}{$item.'_rule'};
9377: }
9378: }
9379: }
9380: $got_rules->{$udom} = 1;
9381: }
9382: foreach my $item (keys(%{$checks})) {
9383: if (ref($$curr_rules{$udom}) eq 'HASH') {
9384: if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
9385: if (@{$$curr_rules{$udom}{$item}} > 0) {
9386: my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
9387: foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
9388: if ($rule_check{$rule}) {
9389: $$rulematch{$user}{$item} = $rule;
9390: if ($inst_response eq 'ok') {
9391: if (ref($inst_results) eq 'HASH') {
9392: if (ref($inst_results->{$user}) eq 'HASH') {
9393: if (keys(%{$inst_results->{$user}}) == 0) {
9394: $$alerts{$item}{$udom}{$uname} = 1;
9395: }
9396: }
9397: }
9398: }
9399: last;
9400: }
9401: }
9402: }
9403: }
9404: }
9405: }
9406: }
9407: }
9408: return;
9409: }
9410:
9411: sub user_rule_formats {
9412: my ($domain,$domdesc,$curr_rules,$check) = @_;
9413: my %text = (
9414: 'username' => 'Usernames',
9415: 'id' => 'IDs',
9416: );
9417: my $output;
9418: my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
9419: if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
9420: if (@{$ruleorder} > 0) {
9421: $output = '<br />'.
9422: &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
9423: '<span class="LC_cusr_emph">','</span>',$domdesc).
9424: ' <ul>';
9425: foreach my $rule (@{$ruleorder}) {
9426: if (ref($curr_rules) eq 'ARRAY') {
9427: if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
9428: if (ref($rules->{$rule}) eq 'HASH') {
9429: $output .= '<li>'.$rules->{$rule}{'name'}.': '.
9430: $rules->{$rule}{'desc'}.'</li>';
9431: }
9432: }
9433: }
9434: }
9435: $output .= '</ul>';
9436: }
9437: }
9438: return $output;
9439: }
9440:
9441: sub instrule_disallow_msg {
9442: my ($checkitem,$domdesc,$count,$mode) = @_;
9443: my $response;
9444: my %text = (
9445: item => 'username',
9446: items => 'usernames',
9447: match => 'matches',
9448: do => 'does',
9449: action => 'a username',
9450: one => 'one',
9451: );
9452: if ($count > 1) {
9453: $text{'item'} = 'usernames';
9454: $text{'match'} ='match';
9455: $text{'do'} = 'do';
9456: $text{'action'} = 'usernames',
9457: $text{'one'} = 'ones';
9458: }
9459: if ($checkitem eq 'id') {
9460: $text{'items'} = 'IDs';
9461: $text{'item'} = 'ID';
9462: $text{'action'} = 'an ID';
9463: if ($count > 1) {
9464: $text{'item'} = 'IDs';
9465: $text{'action'} = 'IDs';
9466: }
9467: }
9468: $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 />';
9469: if ($mode eq 'upload') {
9470: if ($checkitem eq 'username') {
9471: $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'}.");
9472: } elsif ($checkitem eq 'id') {
9473: $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.");
9474: }
9475: } elsif ($mode eq 'selfcreate') {
9476: if ($checkitem eq 'id') {
9477: $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.");
9478: }
9479: } else {
9480: if ($checkitem eq 'username') {
9481: $response .= &mt("You must choose $text{'action'} with a different format -- $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
9482: } elsif ($checkitem eq 'id') {
9483: $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.");
9484: }
9485: }
9486: return $response;
9487: }
9488:
9489: sub personal_data_fieldtitles {
9490: my %fieldtitles = &Apache::lonlocal::texthash (
9491: id => 'Student/Employee ID',
9492: permanentemail => 'E-mail address',
9493: lastname => 'Last Name',
9494: firstname => 'First Name',
9495: middlename => 'Middle Name',
9496: generation => 'Generation',
9497: gen => 'Generation',
9498: inststatus => 'Affiliation',
9499: );
9500: return %fieldtitles;
9501: }
9502:
9503: sub sorted_inst_types {
9504: my ($dom) = @_;
9505: my ($usertypes,$order);
9506: my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
9507: if (ref($domdefaults{'inststatus'}) eq 'HASH') {
9508: $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
9509: $order = $domdefaults{'inststatus'}{'inststatusorder'};
9510: } else {
9511: ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
9512: }
9513: my $othertitle = &mt('All users');
9514: if ($env{'request.course.id'}) {
9515: $othertitle = &mt('Any users');
9516: }
9517: my @types;
9518: if (ref($order) eq 'ARRAY') {
9519: @types = @{$order};
9520: }
9521: if (@types == 0) {
9522: if (ref($usertypes) eq 'HASH') {
9523: @types = sort(keys(%{$usertypes}));
9524: }
9525: }
9526: if (keys(%{$usertypes}) > 0) {
9527: $othertitle = &mt('Other users');
9528: }
9529: return ($othertitle,$usertypes,\@types);
9530: }
9531:
9532: sub get_institutional_codes {
9533: my ($settings,$allcourses,$LC_code) = @_;
9534: # Get complete list of course sections to update
9535: my @currsections = ();
9536: my @currxlists = ();
9537: my $coursecode = $$settings{'internal.coursecode'};
9538:
9539: if ($$settings{'internal.sectionnums'} ne '') {
9540: @currsections = split(/,/,$$settings{'internal.sectionnums'});
9541: }
9542:
9543: if ($$settings{'internal.crosslistings'} ne '') {
9544: @currxlists = split(/,/,$$settings{'internal.crosslistings'});
9545: }
9546:
9547: if (@currxlists > 0) {
9548: foreach (@currxlists) {
9549: if (m/^([^:]+):(\w*)$/) {
9550: unless (grep/^$1$/,@{$allcourses}) {
9551: push @{$allcourses},$1;
9552: $$LC_code{$1} = $2;
9553: }
9554: }
9555: }
9556: }
9557:
9558: if (@currsections > 0) {
9559: foreach (@currsections) {
9560: if (m/^(\w+):(\w*)$/) {
9561: my $sec = $coursecode.$1;
9562: my $lc_sec = $2;
9563: unless (grep/^$sec$/,@{$allcourses}) {
9564: push @{$allcourses},$sec;
9565: $$LC_code{$sec} = $lc_sec;
9566: }
9567: }
9568: }
9569: }
9570: return;
9571: }
9572:
9573: sub get_standard_codeitems {
9574: return ('Year','Semester','Department','Number','Section');
9575: }
9576:
9577: =pod
9578:
9579: =head1 Slot Helpers
9580:
9581: =over 4
9582:
9583: =item * sorted_slots()
9584:
9585: Sorts an array of slot names in order of an optional sort key,
9586: default sort is by slot start time (earliest first).
9587:
9588: Inputs:
9589:
9590: =over 4
9591:
9592: slotsarr - Reference to array of unsorted slot names.
9593:
9594: slots - Reference to hash of hash, where outer hash keys are slot names.
9595:
9596: sortkey - Name of key in inner hash to be sorted on (e.g., starttime).
9597:
9598: =back
9599:
9600: Returns:
9601:
9602: =over 4
9603:
9604: sorted - An array of slot names sorted by a specified sort key
9605: (default sort key is start time of the slot).
9606:
9607: =back
9608:
9609: =cut
9610:
9611:
9612: sub sorted_slots {
9613: my ($slotsarr,$slots,$sortkey) = @_;
9614: if ($sortkey eq '') {
9615: $sortkey = 'starttime';
9616: }
9617: my @sorted;
9618: if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
9619: @sorted =
9620: sort {
9621: if (ref($slots->{$a}) && ref($slots->{$b})) {
9622: return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
9623: }
9624: if (ref($slots->{$a})) { return -1;}
9625: if (ref($slots->{$b})) { return 1;}
9626: return 0;
9627: } @{$slotsarr};
9628: }
9629: return @sorted;
9630: }
9631:
9632: =pod
9633:
9634: =item * get_future_slots()
9635:
9636: Inputs:
9637:
9638: =over 4
9639:
9640: cnum - course number
9641:
9642: cdom - course domain
9643:
9644: now - current UNIX time
9645:
9646: symb - optional symb
9647:
9648: =back
9649:
9650: Returns:
9651:
9652: =over 4
9653:
9654: sorted_reservable - ref to array of student_schedulable slots currently
9655: reservable, ordered by end date of reservation period.
9656:
9657: reservable_now - ref to hash of student_schedulable slots currently
9658: reservable.
9659:
9660: Keys in inner hash are:
9661: (a) symb: either blank or symb to which slot use is restricted.
9662: (b) endreserve: end date of reservation period.
9663:
9664: sorted_future - ref to array of student_schedulable slots reservable in
9665: the future, ordered by start date of reservation period.
9666:
9667: future_reservable - ref to hash of student_schedulable slots reservable
9668: in the future.
9669:
9670: Keys in inner hash are:
9671: (a) symb: either blank or symb to which slot use is restricted.
9672: (b) startreserve: start date of reservation period.
9673:
9674: =back
9675:
9676: =cut
9677:
9678: sub get_future_slots {
9679: my ($cnum,$cdom,$now,$symb) = @_;
9680: my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
9681: my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
9682: foreach my $slot (keys(%slots)) {
9683: next unless($slots{$slot}->{'type'} eq 'schedulable_student');
9684: if ($symb) {
9685: next if (($slots{$slot}->{'symb'} ne '') &&
9686: ($slots{$slot}->{'symb'} ne $symb));
9687: }
9688: if (($slots{$slot}->{'starttime'} > $now) &&
9689: ($slots{$slot}->{'endtime'} > $now)) {
9690: if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
9691: my $userallowed = 0;
9692: if ($slots{$slot}->{'allowedsections'}) {
9693: my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
9694: if (!defined($env{'request.role.sec'})
9695: && grep(/^No section assigned$/,@allowed_sec)) {
9696: $userallowed=1;
9697: } else {
9698: if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
9699: $userallowed=1;
9700: }
9701: }
9702: unless ($userallowed) {
9703: if (defined($env{'request.course.groups'})) {
9704: my @groups = split(/:/,$env{'request.course.groups'});
9705: foreach my $group (@groups) {
9706: if (grep(/^\Q$group\E$/,@allowed_sec)) {
9707: $userallowed=1;
9708: last;
9709: }
9710: }
9711: }
9712: }
9713: }
9714: if ($slots{$slot}->{'allowedusers'}) {
9715: my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
9716: my $user = $env{'user.name'}.':'.$env{'user.domain'};
9717: if (grep(/^\Q$user\E$/,@allowed_users)) {
9718: $userallowed = 1;
9719: }
9720: }
9721: next unless($userallowed);
9722: }
9723: my $startreserve = $slots{$slot}->{'startreserve'};
9724: my $endreserve = $slots{$slot}->{'endreserve'};
9725: my $symb = $slots{$slot}->{'symb'};
9726: if (($startreserve < $now) &&
9727: (!$endreserve || $endreserve > $now)) {
9728: my $lastres = $endreserve;
9729: if (!$lastres) {
9730: $lastres = $slots{$slot}->{'starttime'};
9731: }
9732: $reservable_now{$slot} = {
9733: symb => $symb,
9734: endreserve => $lastres
9735: };
9736: } elsif (($startreserve > $now) &&
9737: (!$endreserve || $endreserve > $startreserve)) {
9738: $future_reservable{$slot} = {
9739: symb => $symb,
9740: startreserve => $startreserve
9741: };
9742: }
9743: }
9744: }
9745: my @unsorted_reservable = keys(%reservable_now);
9746: if (@unsorted_reservable > 0) {
9747: @sorted_reservable =
9748: &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
9749: }
9750: my @unsorted_future = keys(%future_reservable);
9751: if (@unsorted_future > 0) {
9752: @sorted_future =
9753: &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
9754: }
9755: return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
9756: }
9757:
9758: =pod
9759:
9760: =back
9761:
9762: =head1 HTTP Helpers
9763:
9764: =over 4
9765:
9766: =item * &get_unprocessed_cgi($query,$possible_names)
9767:
9768: Modify the %env hash to contain unprocessed CGI form parameters held in
9769: $query. The parameters listed in $possible_names (an array reference),
9770: will be set in $env{'form.name'} if they do not already exist.
9771:
9772: Typically called with $ENV{'QUERY_STRING'} as the first parameter.
9773: $possible_names is an ref to an array of form element names. As an example:
9774: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
9775: will result in $env{'form.uname'} and $env{'form.udom'} being set.
9776:
9777: =cut
9778:
9779: sub get_unprocessed_cgi {
9780: my ($query,$possible_names)= @_;
9781: # $Apache::lonxml::debug=1;
9782: foreach my $pair (split(/&/,$query)) {
9783: my ($name, $value) = split(/=/,$pair);
9784: $name = &unescape($name);
9785: if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
9786: $value =~ tr/+/ /;
9787: $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
9788: unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
9789: }
9790: }
9791: }
9792:
9793: =pod
9794:
9795: =item * &cacheheader()
9796:
9797: returns cache-controlling header code
9798:
9799: =cut
9800:
9801: sub cacheheader {
9802: unless ($env{'request.method'} eq 'GET') { return ''; }
9803: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
9804: my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
9805: <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
9806: <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
9807: return $output;
9808: }
9809:
9810: =pod
9811:
9812: =item * &no_cache($r)
9813:
9814: specifies header code to not have cache
9815:
9816: =cut
9817:
9818: sub no_cache {
9819: my ($r) = @_;
9820: if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
9821: $env{'request.method'} ne 'GET') { return ''; }
9822: my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
9823: $r->no_cache(1);
9824: $r->header_out("Expires" => $date);
9825: $r->header_out("Pragma" => "no-cache");
9826: }
9827:
9828: sub content_type {
9829: my ($r,$type,$charset) = @_;
9830: if ($r) {
9831: # Note that printout.pl calls this with undef for $r.
9832: &no_cache($r);
9833: }
9834: if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
9835: unless ($charset) {
9836: $charset=&Apache::lonlocal::current_encoding;
9837: }
9838: if ($charset) { $type.='; charset='.$charset; }
9839: if ($r) {
9840: $r->content_type($type);
9841: } else {
9842: print("Content-type: $type\n\n");
9843: }
9844: }
9845:
9846: =pod
9847:
9848: =item * &add_to_env($name,$value)
9849:
9850: adds $name to the %env hash with value
9851: $value, if $name already exists, the entry is converted to an array
9852: reference and $value is added to the array.
9853:
9854: =cut
9855:
9856: sub add_to_env {
9857: my ($name,$value)=@_;
9858: if (defined($env{$name})) {
9859: if (ref($env{$name})) {
9860: #already have multiple values
9861: push(@{ $env{$name} },$value);
9862: } else {
9863: #first time seeing multiple values, convert hash entry to an arrayref
9864: my $first=$env{$name};
9865: undef($env{$name});
9866: push(@{ $env{$name} },$first,$value);
9867: }
9868: } else {
9869: $env{$name}=$value;
9870: }
9871: }
9872:
9873: =pod
9874:
9875: =item * &get_env_multiple($name)
9876:
9877: gets $name from the %env hash, it seemlessly handles the cases where multiple
9878: values may be defined and end up as an array ref.
9879:
9880: returns an array of values
9881:
9882: =cut
9883:
9884: sub get_env_multiple {
9885: my ($name) = @_;
9886: my @values;
9887: if (defined($env{$name})) {
9888: # exists is it an array
9889: if (ref($env{$name})) {
9890: @values=@{ $env{$name} };
9891: } else {
9892: $values[0]=$env{$name};
9893: }
9894: }
9895: return(@values);
9896: }
9897:
9898: sub ask_for_embedded_content {
9899: my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
9900: my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
9901: %currsubfile,%unused,$rem);
9902: my $counter = 0;
9903: my $numnew = 0;
9904: my $numremref = 0;
9905: my $numinvalid = 0;
9906: my $numpathchg = 0;
9907: my $numexisting = 0;
9908: my $numunused = 0;
9909: my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
9910: $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
9911: my $heading = &mt('Upload embedded files');
9912: my $buttontext = &mt('Upload');
9913:
9914: if ($env{'request.course.id'}) {
9915: if ($actionurl eq '/adm/dependencies') {
9916: $navmap = Apache::lonnavmaps::navmap->new();
9917: }
9918: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9919: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9920: }
9921: if (($actionurl eq '/adm/portfolio') ||
9922: ($actionurl eq '/adm/coursegrp_portfolio')) {
9923: my $current_path='/';
9924: if ($env{'form.currentpath'}) {
9925: $current_path = $env{'form.currentpath'};
9926: }
9927: if ($actionurl eq '/adm/coursegrp_portfolio') {
9928: $udom = $cdom;
9929: $uname = $cnum;
9930: $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
9931: } else {
9932: $udom = $env{'user.domain'};
9933: $uname = $env{'user.name'};
9934: $url = '/userfiles/portfolio';
9935: }
9936: $toplevel = $url.'/';
9937: $url .= $current_path;
9938: $getpropath = 1;
9939: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
9940: ($actionurl eq '/adm/imsimport')) {
9941: my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
9942: $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
9943: $toplevel = $url;
9944: if ($rest ne '') {
9945: $url .= $rest;
9946: }
9947: } elsif ($actionurl eq '/adm/coursedocs') {
9948: if (ref($args) eq 'HASH') {
9949: $url = $args->{'docs_url'};
9950: $toplevel = $url;
9951: if ($args->{'context'} eq 'paste') {
9952: ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
9953: ($path) =
9954: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
9955: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
9956: $fileloc =~ s{^/}{};
9957: }
9958: }
9959: } elsif ($actionurl eq '/adm/dependencies') {
9960: if ($env{'request.course.id'} ne '') {
9961: if (ref($args) eq 'HASH') {
9962: $url = $args->{'docs_url'};
9963: $title = $args->{'docs_title'};
9964: $toplevel = $url;
9965: unless ($toplevel =~ m{^/}) {
9966: $toplevel = "/$url";
9967: }
9968: ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
9969: if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
9970: $path = $1;
9971: } else {
9972: ($path) =
9973: ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
9974: }
9975: if ($toplevel=~/^\/*(uploaded|editupload)/) {
9976: $fileloc = $toplevel;
9977: $fileloc=~ s/^\s*(\S+)\s*$/$1/;
9978: my ($udom,$uname,$fname) =
9979: ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
9980: $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
9981: } else {
9982: $fileloc = &Apache::lonnet::filelocation('',$toplevel);
9983: }
9984: $fileloc =~ s{^/}{};
9985: ($filename) = ($fileloc =~ m{.+/([^/]+)$});
9986: $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
9987: }
9988: }
9989: } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
9990: $udom = $cdom;
9991: $uname = $cnum;
9992: $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
9993: $toplevel = $url;
9994: $path = $url;
9995: $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
9996: $fileloc =~ s{^/}{};
9997: }
9998: foreach my $file (keys(%{$allfiles})) {
9999: my $embed_file;
10000: if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
10001: $embed_file = $1;
10002: } else {
10003: $embed_file = $file;
10004: }
10005: my ($absolutepath,$cleaned_file);
10006: if ($embed_file =~ m{^\w+://}) {
10007: $cleaned_file = $embed_file;
10008: $newfiles{$cleaned_file} = 1;
10009: $mapping{$cleaned_file} = $embed_file;
10010: } else {
10011: $cleaned_file = &clean_path($embed_file);
10012: if ($embed_file =~ m{^/}) {
10013: $absolutepath = $embed_file;
10014: }
10015: if ($cleaned_file =~ m{/}) {
10016: my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
10017: $path = &check_for_traversal($path,$url,$toplevel);
10018: my $item = $fname;
10019: if ($path ne '') {
10020: $item = $path.'/'.$fname;
10021: $subdependencies{$path}{$fname} = 1;
10022: } else {
10023: $dependencies{$item} = 1;
10024: }
10025: if ($absolutepath) {
10026: $mapping{$item} = $absolutepath;
10027: } else {
10028: $mapping{$item} = $embed_file;
10029: }
10030: } else {
10031: $dependencies{$embed_file} = 1;
10032: if ($absolutepath) {
10033: $mapping{$cleaned_file} = $absolutepath;
10034: } else {
10035: $mapping{$cleaned_file} = $embed_file;
10036: }
10037: }
10038: }
10039: }
10040: my $dirptr = 16384;
10041: foreach my $path (keys(%subdependencies)) {
10042: $currsubfile{$path} = {};
10043: if (($actionurl eq '/adm/portfolio') ||
10044: ($actionurl eq '/adm/coursegrp_portfolio')) {
10045: my ($sublistref,$listerror) =
10046: &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
10047: if (ref($sublistref) eq 'ARRAY') {
10048: foreach my $line (@{$sublistref}) {
10049: my ($file_name,$rest) = split(/\&/,$line,2);
10050: $currsubfile{$path}{$file_name} = 1;
10051: }
10052: }
10053: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10054: if (opendir(my $dir,$url.'/'.$path)) {
10055: my @subdir_list = grep(!/^\./,readdir($dir));
10056: map {$currsubfile{$path}{$_} = 1;} @subdir_list;
10057: }
10058: } elsif (($actionurl eq '/adm/dependencies') ||
10059: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10060: ($args->{'context'} eq 'paste')) ||
10061: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10062: if ($env{'request.course.id'} ne '') {
10063: my $dir;
10064: if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10065: $dir = $fileloc;
10066: } else {
10067: ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10068: }
10069: if ($dir ne '') {
10070: my ($sublistref,$listerror) =
10071: &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
10072: if (ref($sublistref) eq 'ARRAY') {
10073: foreach my $line (@{$sublistref}) {
10074: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
10075: undef,$mtime)=split(/\&/,$line,12);
10076: unless (($testdir&$dirptr) ||
10077: ($file_name =~ /^\.\.?$/)) {
10078: $currsubfile{$path}{$file_name} = [$size,$mtime];
10079: }
10080: }
10081: }
10082: }
10083: }
10084: }
10085: foreach my $file (keys(%{$subdependencies{$path}})) {
10086: if (exists($currsubfile{$path}{$file})) {
10087: my $item = $path.'/'.$file;
10088: unless ($mapping{$item} eq $item) {
10089: $pathchanges{$item} = 1;
10090: }
10091: $existing{$item} = 1;
10092: $numexisting ++;
10093: } else {
10094: $newfiles{$path.'/'.$file} = 1;
10095: }
10096: }
10097: if ($actionurl eq '/adm/dependencies') {
10098: foreach my $path (keys(%currsubfile)) {
10099: if (ref($currsubfile{$path}) eq 'HASH') {
10100: foreach my $file (keys(%{$currsubfile{$path}})) {
10101: unless ($subdependencies{$path}{$file}) {
10102: next if (($rem ne '') &&
10103: (($env{"httpref.$rem"."$path/$file"} ne '') ||
10104: (ref($navmap) &&
10105: (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10106: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10107: ($navmap->getResourceByUrl($rem."$path/$1")))))));
10108: $unused{$path.'/'.$file} = 1;
10109: }
10110: }
10111: }
10112: }
10113: }
10114: }
10115: my %currfile;
10116: if (($actionurl eq '/adm/portfolio') ||
10117: ($actionurl eq '/adm/coursegrp_portfolio')) {
10118: my ($dirlistref,$listerror) =
10119: &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10120: if (ref($dirlistref) eq 'ARRAY') {
10121: foreach my $line (@{$dirlistref}) {
10122: my ($file_name,$rest) = split(/\&/,$line,2);
10123: $currfile{$file_name} = 1;
10124: }
10125: }
10126: } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10127: if (opendir(my $dir,$url)) {
10128: my @dir_list = grep(!/^\./,readdir($dir));
10129: map {$currfile{$_} = 1;} @dir_list;
10130: }
10131: } elsif (($actionurl eq '/adm/dependencies') ||
10132: (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10133: ($args->{'context'} eq 'paste')) ||
10134: ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10135: if ($env{'request.course.id'} ne '') {
10136: my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10137: if ($dir ne '') {
10138: my ($dirlistref,$listerror) =
10139: &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10140: if (ref($dirlistref) eq 'ARRAY') {
10141: foreach my $line (@{$dirlistref}) {
10142: my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10143: $size,undef,$mtime)=split(/\&/,$line,12);
10144: unless (($testdir&$dirptr) ||
10145: ($file_name =~ /^\.\.?$/)) {
10146: $currfile{$file_name} = [$size,$mtime];
10147: }
10148: }
10149: }
10150: }
10151: }
10152: }
10153: foreach my $file (keys(%dependencies)) {
10154: if (exists($currfile{$file})) {
10155: unless ($mapping{$file} eq $file) {
10156: $pathchanges{$file} = 1;
10157: }
10158: $existing{$file} = 1;
10159: $numexisting ++;
10160: } else {
10161: $newfiles{$file} = 1;
10162: }
10163: }
10164: foreach my $file (keys(%currfile)) {
10165: unless (($file eq $filename) ||
10166: ($file eq $filename.'.bak') ||
10167: ($dependencies{$file})) {
10168: if ($actionurl eq '/adm/dependencies') {
10169: unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10170: next if (($rem ne '') &&
10171: (($env{"httpref.$rem".$file} ne '') ||
10172: (ref($navmap) &&
10173: (($navmap->getResourceByUrl($rem.$file) ne '') ||
10174: (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10175: ($navmap->getResourceByUrl($rem.$1)))))));
10176: }
10177: }
10178: $unused{$file} = 1;
10179: }
10180: }
10181: if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10182: ($args->{'context'} eq 'paste')) {
10183: $counter = scalar(keys(%existing));
10184: $numpathchg = scalar(keys(%pathchanges));
10185: return ($output,$counter,$numpathchg,\%existing);
10186: } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
10187: (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10188: $counter = scalar(keys(%existing));
10189: $numpathchg = scalar(keys(%pathchanges));
10190: return ($output,$counter,$numpathchg,\%existing,\%mapping);
10191: }
10192: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10193: if ($actionurl eq '/adm/dependencies') {
10194: next if ($embed_file =~ m{^\w+://});
10195: }
10196: $upload_output .= &start_data_table_row().
10197: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
10198: '<span class="LC_filename">'.$embed_file.'</span>';
10199: unless ($mapping{$embed_file} eq $embed_file) {
10200: $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10201: &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10202: }
10203: $upload_output .= '</td>';
10204: if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) {
10205: $upload_output.='<td align="right">'.
10206: '<span class="LC_info LC_fontsize_medium">'.
10207: &mt("URL points to web address").'</span>';
10208: $numremref++;
10209: } elsif ($args->{'error_on_invalid_names'}
10210: && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10211: $upload_output.='<td align="right"><span class="LC_warning">'.
10212: &mt('Invalid characters').'</span>';
10213: $numinvalid++;
10214: } else {
10215: $upload_output .= '<td>'.
10216: &embedded_file_element('upload_embedded',$counter,
10217: $embed_file,\%mapping,
10218: $allfiles,$codebase,'upload');
10219: $counter ++;
10220: $numnew ++;
10221: }
10222: $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10223: }
10224: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10225: if ($actionurl eq '/adm/dependencies') {
10226: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10227: $modify_output .= &start_data_table_row().
10228: '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10229: '<img src="'.&icon($embed_file).'" border="0" />'.
10230: ' <span class="LC_filename">'.$embed_file.'</span></a></td>'.
10231: '<td>'.$size.'</td>'.
10232: '<td>'.$mtime.'</td>'.
10233: '<td><label><input type="checkbox" name="mod_upload_dep" '.
10234: 'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10235: $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10236: '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10237: &embedded_file_element('upload_embedded',$counter,
10238: $embed_file,\%mapping,
10239: $allfiles,$codebase,'modify').
10240: '</div></td>'.
10241: &end_data_table_row()."\n";
10242: $counter ++;
10243: } else {
10244: $upload_output .= &start_data_table_row().
10245: '<td valign="top"><img src="'.&icon($embed_file).'" /> '.
10246: '<span class="LC_filename">'.$embed_file.'</span></td>'.
10247: '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10248: &Apache::loncommon::end_data_table_row()."\n";
10249: }
10250: }
10251: my $delidx = $counter;
10252: foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10253: my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10254: $delete_output .= &start_data_table_row().
10255: '<td><img src="'.&icon($oldfile).'" />'.
10256: ' <span class="LC_filename">'.$oldfile.'</span></td>'.
10257: '<td>'.$size.'</td>'.
10258: '<td>'.$mtime.'</td>'.
10259: '<td><label><input type="checkbox" name="del_upload_dep" '.
10260: ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10261: &embedded_file_element('upload_embedded',$delidx,
10262: $oldfile,\%mapping,$allfiles,
10263: $codebase,'delete').'</td>'.
10264: &end_data_table_row()."\n";
10265: $numunused ++;
10266: $delidx ++;
10267: }
10268: if ($upload_output) {
10269: $upload_output = &start_data_table().
10270: $upload_output.
10271: &end_data_table()."\n";
10272: }
10273: if ($modify_output) {
10274: $modify_output = &start_data_table().
10275: &start_data_table_header_row().
10276: '<th>'.&mt('File').'</th>'.
10277: '<th>'.&mt('Size (KB)').'</th>'.
10278: '<th>'.&mt('Modified').'</th>'.
10279: '<th>'.&mt('Upload replacement?').'</th>'.
10280: &end_data_table_header_row().
10281: $modify_output.
10282: &end_data_table()."\n";
10283: }
10284: if ($delete_output) {
10285: $delete_output = &start_data_table().
10286: &start_data_table_header_row().
10287: '<th>'.&mt('File').'</th>'.
10288: '<th>'.&mt('Size (KB)').'</th>'.
10289: '<th>'.&mt('Modified').'</th>'.
10290: '<th>'.&mt('Delete?').'</th>'.
10291: &end_data_table_header_row().
10292: $delete_output.
10293: &end_data_table()."\n";
10294: }
10295: my $applies = 0;
10296: if ($numremref) {
10297: $applies ++;
10298: }
10299: if ($numinvalid) {
10300: $applies ++;
10301: }
10302: if ($numexisting) {
10303: $applies ++;
10304: }
10305: if ($counter || $numunused) {
10306: $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10307: ' method="post" enctype="multipart/form-data">'."\n".
10308: $state.'<h3>'.$heading.'</h3>';
10309: if ($actionurl eq '/adm/dependencies') {
10310: if ($numnew) {
10311: $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10312: '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10313: $upload_output.'<br />'."\n";
10314: }
10315: if ($numexisting) {
10316: $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10317: '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10318: $modify_output.'<br />'."\n";
10319: $buttontext = &mt('Save changes');
10320: }
10321: if ($numunused) {
10322: $output .= '<h4>'.&mt('Unused files').'</h4>'.
10323: '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
10324: $delete_output.'<br />'."\n";
10325: $buttontext = &mt('Save changes');
10326: }
10327: } else {
10328: $output .= $upload_output.'<br />'."\n";
10329: }
10330: $output .= '<input type ="hidden" name="number_embedded_items" value="'.
10331: $counter.'" />'."\n";
10332: if ($actionurl eq '/adm/dependencies') {
10333: $output .= '<input type ="hidden" name="number_newemb_items" value="'.
10334: $numnew.'" />'."\n";
10335: } elsif ($actionurl eq '') {
10336: $output .= '<input type="hidden" name="phase" value="three" />';
10337: }
10338: } elsif ($applies) {
10339: $output = '<b>'.&mt('Referenced files').'</b>:<br />';
10340: if ($applies > 1) {
10341: $output .=
10342: &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
10343: if ($numremref) {
10344: $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
10345: }
10346: if ($numinvalid) {
10347: $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
10348: }
10349: if ($numexisting) {
10350: $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
10351: }
10352: $output .= '</ul><br />';
10353: } elsif ($numremref) {
10354: $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
10355: } elsif ($numinvalid) {
10356: $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
10357: } elsif ($numexisting) {
10358: $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
10359: }
10360: $output .= $upload_output.'<br />';
10361: }
10362: my ($pathchange_output,$chgcount);
10363: $chgcount = $counter;
10364: if (keys(%pathchanges) > 0) {
10365: foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
10366: if ($counter) {
10367: $output .= &embedded_file_element('pathchange',$chgcount,
10368: $embed_file,\%mapping,
10369: $allfiles,$codebase,'change');
10370: } else {
10371: $pathchange_output .=
10372: &start_data_table_row().
10373: '<td><input type ="checkbox" name="namechange" value="'.
10374: $chgcount.'" checked="checked" /></td>'.
10375: '<td>'.$mapping{$embed_file}.'</td>'.
10376: '<td>'.$embed_file.
10377: &embedded_file_element('pathchange',$numpathchg,$embed_file,
10378: \%mapping,$allfiles,$codebase,'change').
10379: '</td>'.&end_data_table_row();
10380: }
10381: $numpathchg ++;
10382: $chgcount ++;
10383: }
10384: }
10385: if (($counter) || ($numunused)) {
10386: if ($numpathchg) {
10387: $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
10388: $numpathchg.'" />'."\n";
10389: }
10390: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10391: ($actionurl eq '/adm/imsimport')) {
10392: $output .= '<input type="hidden" name="phase" value="three" />'."\n";
10393: } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
10394: $output .= '<input type="hidden" name="action" value="upload_embedded" />';
10395: } elsif ($actionurl eq '/adm/dependencies') {
10396: $output .= '<input type="hidden" name="action" value="process_changes" />';
10397: }
10398: $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
10399: } elsif ($numpathchg) {
10400: my %pathchange = ();
10401: $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
10402: if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10403: $output .= '<p>'.&mt('or').'</p>';
10404: }
10405: }
10406: return ($output,$counter,$numpathchg);
10407: }
10408:
10409: =pod
10410:
10411: =item * clean_path($name)
10412:
10413: Performs clean-up of directories, subdirectories and filename in an
10414: embedded object, referenced in an HTML file which is being uploaded
10415: to a course or portfolio, where
10416: "Upload embedded images/multimedia files if HTML file" checkbox was
10417: checked.
10418:
10419: Clean-up is similar to replacements in lonnet::clean_filename()
10420: except each / between sub-directory and next level is preserved.
10421:
10422: =cut
10423:
10424: sub clean_path {
10425: my ($embed_file) = @_;
10426: $embed_file =~s{^/+}{};
10427: my @contents;
10428: if ($embed_file =~ m{/}) {
10429: @contents = split(/\//,$embed_file);
10430: } else {
10431: @contents = ($embed_file);
10432: }
10433: my $lastidx = scalar(@contents)-1;
10434: for (my $i=0; $i<=$lastidx; $i++) {
10435: $contents[$i]=~s{\\}{/}g;
10436: $contents[$i]=~s/\s+/\_/g;
10437: $contents[$i]=~s{[^/\w\.\-]}{}g;
10438: if ($i == $lastidx) {
10439: $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
10440: }
10441: }
10442: if ($lastidx > 0) {
10443: return join('/',@contents);
10444: } else {
10445: return $contents[0];
10446: }
10447: }
10448:
10449: sub embedded_file_element {
10450: my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
10451: return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
10452: (ref($codebase) eq 'HASH'));
10453: my $output;
10454: if (($context eq 'upload_embedded') && ($type ne 'delete')) {
10455: $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
10456: }
10457: $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
10458: &escape($embed_file).'" />';
10459: unless (($context eq 'upload_embedded') &&
10460: ($mapping->{$embed_file} eq $embed_file)) {
10461: $output .='
10462: <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
10463: }
10464: my $attrib;
10465: if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
10466: $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
10467: }
10468: $output .=
10469: "\n\t\t".
10470: '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
10471: $attrib.'" />';
10472: if (exists($codebase->{$mapping->{$embed_file}})) {
10473: $output .=
10474: "\n\t\t".
10475: '<input name="codebase_'.$num.'" type="hidden" value="'.
10476: &escape($codebase->{$mapping->{$embed_file}}).'" />';
10477: }
10478: return $output;
10479: }
10480:
10481: sub get_dependency_details {
10482: my ($currfile,$currsubfile,$embed_file) = @_;
10483: my ($size,$mtime,$showsize,$showmtime);
10484: if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
10485: if ($embed_file =~ m{/}) {
10486: my ($path,$fname) = split(/\//,$embed_file);
10487: if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
10488: ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
10489: }
10490: } else {
10491: if (ref($currfile->{$embed_file}) eq 'ARRAY') {
10492: ($size,$mtime) = @{$currfile->{$embed_file}};
10493: }
10494: }
10495: $showsize = $size/1024.0;
10496: $showsize = sprintf("%.1f",$showsize);
10497: if ($mtime > 0) {
10498: $showmtime = &Apache::lonlocal::locallocaltime($mtime);
10499: }
10500: }
10501: return ($showsize,$showmtime);
10502: }
10503:
10504: sub ask_embedded_js {
10505: return <<"END";
10506: <script type="text/javascript"">
10507: // <![CDATA[
10508: function toggleBrowse(counter) {
10509: var chkboxid = document.getElementById('mod_upload_dep_'+counter);
10510: var fileid = document.getElementById('embedded_item_'+counter);
10511: var uploaddivid = document.getElementById('moduploaddep_'+counter);
10512: if (chkboxid.checked == true) {
10513: uploaddivid.style.display='block';
10514: } else {
10515: uploaddivid.style.display='none';
10516: fileid.value = '';
10517: }
10518: }
10519: // ]]>
10520: </script>
10521:
10522: END
10523: }
10524:
10525: sub upload_embedded {
10526: my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
10527: $current_disk_usage,$hiddenstate,$actionurl) = @_;
10528: my (%pathchange,$output,$modifyform,$footer,$returnflag);
10529: for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
10530: next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
10531: my $orig_uploaded_filename =
10532: $env{'form.embedded_item_'.$i.'.filename'};
10533: foreach my $type ('orig','ref','attrib','codebase') {
10534: if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
10535: $env{'form.embedded_'.$type.'_'.$i} =
10536: &unescape($env{'form.embedded_'.$type.'_'.$i});
10537: }
10538: }
10539: my ($path,$fname) =
10540: ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
10541: # no path, whole string is fname
10542: if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
10543: $fname = &Apache::lonnet::clean_filename($fname);
10544: # See if there is anything left
10545: next if ($fname eq '');
10546:
10547: # Check if file already exists as a file or directory.
10548: my ($state,$msg);
10549: if ($context eq 'portfolio') {
10550: my $port_path = $dirpath;
10551: if ($group ne '') {
10552: $port_path = "groups/$group/$port_path";
10553: }
10554: ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
10555: $fname,$group,'embedded_item_'.$i,
10556: $dir_root,$port_path,$disk_quota,
10557: $current_disk_usage,$uname,$udom);
10558: if ($state eq 'will_exceed_quota'
10559: || $state eq 'file_locked') {
10560: $output .= $msg;
10561: next;
10562: }
10563: } elsif (($context eq 'author') || ($context eq 'testbank')) {
10564: ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
10565: if ($state eq 'exists') {
10566: $output .= $msg;
10567: next;
10568: }
10569: }
10570: # Check if extension is valid
10571: if (($fname =~ /\.(\w+)$/) &&
10572: (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10573: $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
10574: .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
10575: next;
10576: } elsif (($fname =~ /\.(\w+)$/) &&
10577: (!defined(&Apache::loncommon::fileembstyle($1)))) {
10578: $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10579: next;
10580: } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10581: $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10582: next;
10583: }
10584: $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10585: my $subdir = $path;
10586: $subdir =~ s{/+$}{};
10587: if ($context eq 'portfolio') {
10588: my $result;
10589: if ($state eq 'existingfile') {
10590: $result=
10591: &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10592: $dirpath.$env{'form.currentpath'}.$subdir);
10593: } else {
10594: $result=
10595: &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10596: $dirpath.
10597: $env{'form.currentpath'}.$subdir);
10598: if ($result !~ m|^/uploaded/|) {
10599: $output .= '<span class="LC_error">'
10600: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10601: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10602: .'</span><br />';
10603: next;
10604: } else {
10605: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10606: $path.$fname.'</span>').'<br />';
10607: }
10608: }
10609: } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
10610: my $extendedsubdir = $dirpath.'/'.$subdir;
10611: $extendedsubdir =~ s{/+$}{};
10612: my $result =
10613: &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
10614: if ($result !~ m|^/uploaded/|) {
10615: $output .= '<span class="LC_error">'
10616: .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10617: ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10618: .'</span><br />';
10619: next;
10620: } else {
10621: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10622: $path.$fname.'</span>').'<br />';
10623: if ($context eq 'syllabus') {
10624: &Apache::lonnet::make_public_indefinitely($result);
10625: }
10626: }
10627: } else {
10628: # Save the file
10629: my $target = $env{'form.embedded_item_'.$i};
10630: my $fullpath = $dir_root.$dirpath.'/'.$path;
10631: my $dest = $fullpath.$fname;
10632: my $url = $url_root.$dirpath.'/'.$path.$fname;
10633: my @parts=split(/\//,"$dirpath/$path");
10634: my $count;
10635: my $filepath = $dir_root;
10636: foreach my $subdir (@parts) {
10637: $filepath .= "/$subdir";
10638: if (!-e $filepath) {
10639: mkdir($filepath,0770);
10640: }
10641: }
10642: my $fh;
10643: if (!open($fh,'>'.$dest)) {
10644: &Apache::lonnet::logthis('Failed to create '.$dest);
10645: $output .= '<span class="LC_error">'.
10646: &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10647: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10648: '</span><br />';
10649: } else {
10650: if (!print $fh $env{'form.embedded_item_'.$i}) {
10651: &Apache::lonnet::logthis('Failed to write to '.$dest);
10652: $output .= '<span class="LC_error">'.
10653: &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10654: $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10655: '</span><br />';
10656: } else {
10657: $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10658: $url.'</span>').'<br />';
10659: unless ($context eq 'testbank') {
10660: $footer .= &mt('View embedded file: [_1]',
10661: '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10662: }
10663: }
10664: close($fh);
10665: }
10666: }
10667: if ($env{'form.embedded_ref_'.$i}) {
10668: $pathchange{$i} = 1;
10669: }
10670: }
10671: if ($output) {
10672: $output = '<p>'.$output.'</p>';
10673: }
10674: $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10675: $returnflag = 'ok';
10676: my $numpathchgs = scalar(keys(%pathchange));
10677: if ($numpathchgs > 0) {
10678: if ($context eq 'portfolio') {
10679: $output .= '<p>'.&mt('or').'</p>';
10680: } elsif ($context eq 'testbank') {
10681: $output .= '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10682: '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10683: $returnflag = 'modify_orightml';
10684: }
10685: }
10686: return ($output.$footer,$returnflag,$numpathchgs);
10687: }
10688:
10689: sub modify_html_form {
10690: my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10691: my $end = 0;
10692: my $modifyform;
10693: if ($context eq 'upload_embedded') {
10694: return unless (ref($pathchange) eq 'HASH');
10695: if ($env{'form.number_embedded_items'}) {
10696: $end += $env{'form.number_embedded_items'};
10697: }
10698: if ($env{'form.number_pathchange_items'}) {
10699: $end += $env{'form.number_pathchange_items'};
10700: }
10701: if ($end) {
10702: for (my $i=0; $i<$end; $i++) {
10703: if ($i < $env{'form.number_embedded_items'}) {
10704: next unless($pathchange->{$i});
10705: }
10706: $modifyform .=
10707: &start_data_table_row().
10708: '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10709: 'checked="checked" /></td>'.
10710: '<td>'.$env{'form.embedded_ref_'.$i}.
10711: '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10712: &escape($env{'form.embedded_ref_'.$i}).'" />'.
10713: '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10714: &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10715: '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10716: &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10717: '<td>'.$env{'form.embedded_orig_'.$i}.
10718: '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10719: &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10720: &end_data_table_row();
10721: }
10722: }
10723: } else {
10724: $modifyform = $pathchgtable;
10725: if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10726: $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10727: } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10728: $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10729: }
10730: }
10731: if ($modifyform) {
10732: if ($actionurl eq '/adm/dependencies') {
10733: $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10734: }
10735: return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10736: '<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".
10737: '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10738: '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10739: '</ol></p>'."\n".'<p>'.
10740: &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10741: '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10742: &start_data_table()."\n".
10743: &start_data_table_header_row().
10744: '<th>'.&mt('Change?').'</th>'.
10745: '<th>'.&mt('Current reference').'</th>'.
10746: '<th>'.&mt('Required reference').'</th>'.
10747: &end_data_table_header_row()."\n".
10748: $modifyform.
10749: &end_data_table().'<br />'."\n".$hiddenstate.
10750: '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10751: '</form>'."\n";
10752: }
10753: return;
10754: }
10755:
10756: sub modify_html_refs {
10757: my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
10758: my $container;
10759: if ($context eq 'portfolio') {
10760: $container = $env{'form.container'};
10761: } elsif ($context eq 'coursedoc') {
10762: $container = $env{'form.primaryurl'};
10763: } elsif ($context eq 'manage_dependencies') {
10764: (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10765: $container = "/$container";
10766: } elsif ($context eq 'syllabus') {
10767: $container = $url;
10768: } else {
10769: $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10770: }
10771: my (%allfiles,%codebase,$output,$content);
10772: my @changes = &get_env_multiple('form.namechange');
10773: unless ((@changes > 0) || ($context eq 'syllabus')) {
10774: if (wantarray) {
10775: return ('',0,0);
10776: } else {
10777: return;
10778: }
10779: }
10780: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
10781: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10782: unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10783: if (wantarray) {
10784: return ('',0,0);
10785: } else {
10786: return;
10787: }
10788: }
10789: $content = &Apache::lonnet::getfile($container);
10790: if ($content eq '-1') {
10791: if (wantarray) {
10792: return ('',0,0);
10793: } else {
10794: return;
10795: }
10796: }
10797: } else {
10798: unless ($container =~ /^\Q$dir_root\E/) {
10799: if (wantarray) {
10800: return ('',0,0);
10801: } else {
10802: return;
10803: }
10804: }
10805: if (open(my $fh,"<$container")) {
10806: $content = join('', <$fh>);
10807: close($fh);
10808: } else {
10809: if (wantarray) {
10810: return ('',0,0);
10811: } else {
10812: return;
10813: }
10814: }
10815: }
10816: my ($count,$codebasecount) = (0,0);
10817: my $mm = new File::MMagic;
10818: my $mime_type = $mm->checktype_contents($content);
10819: if ($mime_type eq 'text/html') {
10820: my $parse_result =
10821: &Apache::lonnet::extract_embedded_items($container,\%allfiles,
10822: \%codebase,\$content);
10823: if ($parse_result eq 'ok') {
10824: foreach my $i (@changes) {
10825: my $orig = &unescape($env{'form.embedded_orig_'.$i});
10826: my $ref = &unescape($env{'form.embedded_ref_'.$i});
10827: if ($allfiles{$ref}) {
10828: my $newname = $orig;
10829: my ($attrib_regexp,$codebase);
10830: $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
10831: if ($attrib_regexp =~ /:/) {
10832: $attrib_regexp =~ s/\:/|/g;
10833: }
10834: if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10835: my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10836: $count += $numchg;
10837: $allfiles{$newname} = $allfiles{$ref};
10838: delete($allfiles{$ref});
10839: }
10840: if ($env{'form.embedded_codebase_'.$i} ne '') {
10841: $codebase = &unescape($env{'form.embedded_codebase_'.$i});
10842: my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
10843: $codebasecount ++;
10844: }
10845: }
10846: }
10847: my $skiprewrites;
10848: if ($count || $codebasecount) {
10849: my $saveresult;
10850: if (($context eq 'portfolio') || ($context eq 'coursedoc') ||
10851: ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10852: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10853: if ($url eq $container) {
10854: my ($fname) = ($container =~ m{/([^/]+)$});
10855: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10856: $count,'<span class="LC_filename">'.
10857: $fname.'</span>').'</p>';
10858: } else {
10859: $output = '<p class="LC_error">'.
10860: &mt('Error: update failed for: [_1].',
10861: '<span class="LC_filename">'.
10862: $container.'</span>').'</p>';
10863: }
10864: if ($context eq 'syllabus') {
10865: unless ($saveresult eq 'ok') {
10866: $skiprewrites = 1;
10867: }
10868: }
10869: } else {
10870: if (open(my $fh,">$container")) {
10871: print $fh $content;
10872: close($fh);
10873: $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10874: $count,'<span class="LC_filename">'.
10875: $container.'</span>').'</p>';
10876: } else {
10877: $output = '<p class="LC_error">'.
10878: &mt('Error: could not update [_1].',
10879: '<span class="LC_filename">'.
10880: $container.'</span>').'</p>';
10881: }
10882: }
10883: }
10884: if (($context eq 'syllabus') && (!$skiprewrites)) {
10885: my ($actionurl,$state);
10886: $actionurl = "/public/$udom/$uname/syllabus";
10887: my ($ignore,$num,$numpathchanges,$existing,$mapping) =
10888: &ask_for_embedded_content($actionurl,$state,\%allfiles,
10889: \%codebase,
10890: {'context' => 'rewrites',
10891: 'ignore_remote_references' => 1,});
10892: if (ref($mapping) eq 'HASH') {
10893: my $rewrites = 0;
10894: foreach my $key (keys(%{$mapping})) {
10895: next if ($key =~ m{^https?://});
10896: my $ref = $mapping->{$key};
10897: my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
10898: my $attrib;
10899: if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
10900: $attrib = join('|',@{$allfiles{$mapping->{$key}}});
10901: }
10902: if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10903: my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10904: $rewrites += $numchg;
10905: }
10906: }
10907: if ($rewrites) {
10908: my $saveresult;
10909: my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10910: if ($url eq $container) {
10911: my ($fname) = ($container =~ m{/([^/]+)$});
10912: $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
10913: $count,'<span class="LC_filename">'.
10914: $fname.'</span>').'</p>';
10915: } else {
10916: $output .= '<p class="LC_error">'.
10917: &mt('Error: could not update links in [_1].',
10918: '<span class="LC_filename">'.
10919: $container.'</span>').'</p>';
10920:
10921: }
10922: }
10923: }
10924: }
10925: } else {
10926: &logthis('Failed to parse '.$container.
10927: ' to modify references: '.$parse_result);
10928: }
10929: }
10930: if (wantarray) {
10931: return ($output,$count,$codebasecount);
10932: } else {
10933: return $output;
10934: }
10935: }
10936:
10937: sub check_for_existing {
10938: my ($path,$fname,$element) = @_;
10939: my ($state,$msg);
10940: if (-d $path.'/'.$fname) {
10941: $state = 'exists';
10942: $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10943: } elsif (-e $path.'/'.$fname) {
10944: $state = 'exists';
10945: $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10946: }
10947: if ($state eq 'exists') {
10948: $msg = '<span class="LC_error">'.$msg.'</span><br />';
10949: }
10950: return ($state,$msg);
10951: }
10952:
10953: sub check_for_upload {
10954: my ($path,$fname,$group,$element,$portfolio_root,$port_path,
10955: $disk_quota,$current_disk_usage,$uname,$udom) = @_;
10956: my $filesize = length($env{'form.'.$element});
10957: if (!$filesize) {
10958: my $msg = '<span class="LC_error">'.
10959: &mt('Unable to upload [_1]. (size = [_2] bytes)',
10960: '<span class="LC_filename">'.$fname.'</span>',
10961: $filesize).'<br />'.
10962: &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
10963: '</span>';
10964: return ('zero_bytes',$msg);
10965: }
10966: $filesize = $filesize/1000; #express in k (1024?)
10967: my $getpropath = 1;
10968: my ($dirlistref,$listerror) =
10969: &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
10970: my $found_file = 0;
10971: my $locked_file = 0;
10972: my @lockers;
10973: my $navmap;
10974: if ($env{'request.course.id'}) {
10975: $navmap = Apache::lonnavmaps::navmap->new();
10976: }
10977: if (ref($dirlistref) eq 'ARRAY') {
10978: foreach my $line (@{$dirlistref}) {
10979: my ($file_name,$rest)=split(/\&/,$line,2);
10980: if ($file_name eq $fname){
10981: $file_name = $path.$file_name;
10982: if ($group ne '') {
10983: $file_name = $group.$file_name;
10984: }
10985: $found_file = 1;
10986: if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
10987: foreach my $lock (@lockers) {
10988: if (ref($lock) eq 'ARRAY') {
10989: my ($symb,$crsid) = @{$lock};
10990: if ($crsid eq $env{'request.course.id'}) {
10991: if (ref($navmap)) {
10992: my $res = $navmap->getBySymb($symb);
10993: foreach my $part (@{$res->parts()}) {
10994: my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
10995: unless (($slot_status == $res->RESERVED) ||
10996: ($slot_status == $res->RESERVED_LOCATION)) {
10997: $locked_file = 1;
10998: }
10999: }
11000: } else {
11001: $locked_file = 1;
11002: }
11003: } else {
11004: $locked_file = 1;
11005: }
11006: }
11007: }
11008: } else {
11009: my @info = split(/\&/,$rest);
11010: my $currsize = $info[6]/1000;
11011: if ($currsize < $filesize) {
11012: my $extra = $filesize - $currsize;
11013: if (($current_disk_usage + $extra) > $disk_quota) {
11014: my $msg = '<p class="LC_warning">'.
11015: &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.',
11016: '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
11017: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11018: $disk_quota,$current_disk_usage).'</p>';
11019: return ('will_exceed_quota',$msg);
11020: }
11021: }
11022: }
11023: }
11024: }
11025: }
11026: if (($current_disk_usage + $filesize) > $disk_quota){
11027: my $msg = '<p class="LC_warning">'.
11028: &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
11029: '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
11030: return ('will_exceed_quota',$msg);
11031: } elsif ($found_file) {
11032: if ($locked_file) {
11033: my $msg = '<p class="LC_warning">';
11034: $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>');
11035: $msg .= '</p>';
11036: $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
11037: return ('file_locked',$msg);
11038: } else {
11039: my $msg = '<p class="LC_error">';
11040: $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
11041: $msg .= '</p>';
11042: return ('existingfile',$msg);
11043: }
11044: }
11045: }
11046:
11047: sub check_for_traversal {
11048: my ($path,$url,$toplevel) = @_;
11049: my @parts=split(/\//,$path);
11050: my $cleanpath;
11051: my $fullpath = $url;
11052: for (my $i=0;$i<@parts;$i++) {
11053: next if ($parts[$i] eq '.');
11054: if ($parts[$i] eq '..') {
11055: $fullpath =~ s{([^/]+/)$}{};
11056: } else {
11057: $fullpath .= $parts[$i].'/';
11058: }
11059: }
11060: if ($fullpath =~ /^\Q$url\E(.*)$/) {
11061: $cleanpath = $1;
11062: } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
11063: my $curr_toprel = $1;
11064: my @parts = split(/\//,$curr_toprel);
11065: my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
11066: my @urlparts = split(/\//,$url_toprel);
11067: my $doubledots;
11068: my $startdiff = -1;
11069: for (my $i=0; $i<@urlparts; $i++) {
11070: if ($startdiff == -1) {
11071: unless ($urlparts[$i] eq $parts[$i]) {
11072: $startdiff = $i;
11073: $doubledots .= '../';
11074: }
11075: } else {
11076: $doubledots .= '../';
11077: }
11078: }
11079: if ($startdiff > -1) {
11080: $cleanpath = $doubledots;
11081: for (my $i=$startdiff; $i<@parts; $i++) {
11082: $cleanpath .= $parts[$i].'/';
11083: }
11084: }
11085: }
11086: $cleanpath =~ s{(/)$}{};
11087: return $cleanpath;
11088: }
11089:
11090: sub is_archive_file {
11091: my ($mimetype) = @_;
11092: if (($mimetype eq 'application/octet-stream') ||
11093: ($mimetype eq 'application/x-stuffit') ||
11094: ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
11095: return 1;
11096: }
11097: return;
11098: }
11099:
11100: sub decompress_form {
11101: my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11102: my %lt = &Apache::lonlocal::texthash (
11103: this => 'This file is an archive file.',
11104: camt => 'This file is a Camtasia archive file.',
11105: itsc => 'Its contents are as follows:',
11106: youm => 'You may wish to extract its contents.',
11107: extr => 'Extract contents',
11108: auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11109: proa => 'Process automatically?',
11110: yes => 'Yes',
11111: no => 'No',
11112: fold => 'Title for folder containing movie',
11113: movi => 'Title for page containing embedded movie',
11114: );
11115: my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11116: my ($is_camtasia,$topdir,%toplevel,@paths);
11117: my $info = &list_archive_contents($fileloc,\@paths);
11118: if (@paths) {
11119: foreach my $path (@paths) {
11120: $path =~ s{^/}{};
11121: if ($path =~ m{^([^/]+)/$}) {
11122: $topdir = $1;
11123: }
11124: if ($path =~ m{^([^/]+)/}) {
11125: $toplevel{$1} = $path;
11126: } else {
11127: $toplevel{$path} = $path;
11128: }
11129: }
11130: }
11131: if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11132: my @camtasia6 = ("$topdir/","$topdir/index.html",
11133: "$topdir/media/",
11134: "$topdir/media/$topdir.mp4",
11135: "$topdir/media/FirstFrame.png",
11136: "$topdir/media/player.swf",
11137: "$topdir/media/swfobject.js",
11138: "$topdir/media/expressInstall.swf");
11139: my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
11140: "$topdir/$topdir.mp4",
11141: "$topdir/$topdir\_config.xml",
11142: "$topdir/$topdir\_controller.swf",
11143: "$topdir/$topdir\_embed.css",
11144: "$topdir/$topdir\_First_Frame.png",
11145: "$topdir/$topdir\_player.html",
11146: "$topdir/$topdir\_Thumbnails.png",
11147: "$topdir/playerProductInstall.swf",
11148: "$topdir/scripts/",
11149: "$topdir/scripts/config_xml.js",
11150: "$topdir/scripts/handlebars.js",
11151: "$topdir/scripts/jquery-1.7.1.min.js",
11152: "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11153: "$topdir/scripts/modernizr.js",
11154: "$topdir/scripts/player-min.js",
11155: "$topdir/scripts/swfobject.js",
11156: "$topdir/skins/",
11157: "$topdir/skins/configuration_express.xml",
11158: "$topdir/skins/express_show/",
11159: "$topdir/skins/express_show/player-min.css",
11160: "$topdir/skins/express_show/spritesheet.png");
11161: my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
11162: "$topdir/$topdir.mp4",
11163: "$topdir/$topdir\_config.xml",
11164: "$topdir/$topdir\_controller.swf",
11165: "$topdir/$topdir\_embed.css",
11166: "$topdir/$topdir\_First_Frame.png",
11167: "$topdir/$topdir\_player.html",
11168: "$topdir/$topdir\_Thumbnails.png",
11169: "$topdir/playerProductInstall.swf",
11170: "$topdir/scripts/",
11171: "$topdir/scripts/config_xml.js",
11172: "$topdir/scripts/techsmith-smart-player.min.js",
11173: "$topdir/skins/",
11174: "$topdir/skins/configuration_express.xml",
11175: "$topdir/skins/express_show/",
11176: "$topdir/skins/express_show/spritesheet.min.css",
11177: "$topdir/skins/express_show/spritesheet.png",
11178: "$topdir/skins/express_show/techsmith-smart-player.min.css");
11179: my @diffs = &compare_arrays(\@paths,\@camtasia6);
11180: if (@diffs == 0) {
11181: $is_camtasia = 6;
11182: } else {
11183: @diffs = &compare_arrays(\@paths,\@camtasia8_1);
11184: if (@diffs == 0) {
11185: $is_camtasia = 8;
11186: } else {
11187: @diffs = &compare_arrays(\@paths,\@camtasia8_4);
11188: if (@diffs == 0) {
11189: $is_camtasia = 8;
11190: }
11191: }
11192: }
11193: }
11194: my $output;
11195: if ($is_camtasia) {
11196: $output = <<"ENDCAM";
11197: <script type="text/javascript" language="Javascript">
11198: // <![CDATA[
11199:
11200: function camtasiaToggle() {
11201: for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11202: if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11203: if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11204:
11205: document.getElementById('camtasia_titles').style.display='block';
11206: } else {
11207: document.getElementById('camtasia_titles').style.display='none';
11208: }
11209: }
11210: }
11211: return;
11212: }
11213:
11214: // ]]>
11215: </script>
11216: <p>$lt{'camt'}</p>
11217: ENDCAM
11218: } else {
11219: $output = '<p>'.$lt{'this'};
11220: if ($info eq '') {
11221: $output .= ' '.$lt{'youm'}.'</p>'."\n";
11222: } else {
11223: $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11224: '<div><pre>'.$info.'</pre></div>';
11225: }
11226: }
11227: $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11228: my $duplicates;
11229: my $num = 0;
11230: if (ref($dirlist) eq 'ARRAY') {
11231: foreach my $item (@{$dirlist}) {
11232: if (ref($item) eq 'ARRAY') {
11233: if (exists($toplevel{$item->[0]})) {
11234: $duplicates .=
11235: &start_data_table_row().
11236: '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11237: 'value="0" checked="checked" />'.&mt('No').'</label>'.
11238: ' <label><input type="radio" name="archive_overwrite_'.$num.'" '.
11239: 'value="1" />'.&mt('Yes').'</label>'.
11240: '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11241: '<td>'.$item->[0].'</td>';
11242: if ($item->[2]) {
11243: $duplicates .= '<td>'.&mt('Directory').'</td>';
11244: } else {
11245: $duplicates .= '<td>'.&mt('File').'</td>';
11246: }
11247: $duplicates .= '<td>'.$item->[3].'</td>'.
11248: '<td>'.
11249: &Apache::lonlocal::locallocaltime($item->[4]).
11250: '</td>'.
11251: &end_data_table_row();
11252: $num ++;
11253: }
11254: }
11255: }
11256: }
11257: my $itemcount;
11258: if (@paths > 0) {
11259: $itemcount = scalar(@paths);
11260: } else {
11261: $itemcount = 1;
11262: }
11263: if ($is_camtasia) {
11264: $output .= $lt{'auto'}.'<br />'.
11265: '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11266: '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11267: $lt{'yes'}.'</label> <label>'.
11268: '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11269: $lt{'no'}.'</label></span><br />'.
11270: '<div id="camtasia_titles" style="display:block">'.
11271: &Apache::lonhtmlcommon::start_pick_box().
11272: &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11273: '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11274: &Apache::lonhtmlcommon::row_closure().
11275: &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11276: '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11277: &Apache::lonhtmlcommon::row_closure(1).
11278: &Apache::lonhtmlcommon::end_pick_box().
11279: '</div>';
11280: }
11281: $output .=
11282: '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11283: '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11284: "\n";
11285: if ($duplicates ne '') {
11286: $output .= '<p><span class="LC_warning">'.
11287: &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.
11288: &start_data_table().
11289: &start_data_table_header_row().
11290: '<th>'.&mt('Overwrite?').'</th>'.
11291: '<th>'.&mt('Name').'</th>'.
11292: '<th>'.&mt('Type').'</th>'.
11293: '<th>'.&mt('Size').'</th>'.
11294: '<th>'.&mt('Last modified').'</th>'.
11295: &end_data_table_header_row().
11296: $duplicates.
11297: &end_data_table().
11298: '</p>';
11299: }
11300: $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11301: if (ref($hiddenelements) eq 'HASH') {
11302: foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11303: $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11304: }
11305: }
11306: $output .= <<"END";
11307: <br />
11308: <input type="submit" name="decompress" value="$lt{'extr'}" />
11309: </form>
11310: $noextract
11311: END
11312: return $output;
11313: }
11314:
11315: sub decompression_utility {
11316: my ($program) = @_;
11317: my @utilities = ('tar','gunzip','bunzip2','unzip');
11318: my $location;
11319: if (grep(/^\Q$program\E$/,@utilities)) {
11320: foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
11321: '/usr/sbin/') {
11322: if (-x $dir.$program) {
11323: $location = $dir.$program;
11324: last;
11325: }
11326: }
11327: }
11328: return $location;
11329: }
11330:
11331: sub list_archive_contents {
11332: my ($file,$pathsref) = @_;
11333: my (@cmd,$output);
11334: my $needsregexp;
11335: if ($file =~ /\.zip$/) {
11336: @cmd = (&decompression_utility('unzip'),"-l");
11337: $needsregexp = 1;
11338: } elsif (($file =~ m/\.tar\.gz$/) ||
11339: ($file =~ /\.tgz$/)) {
11340: @cmd = (&decompression_utility('tar'),"-ztf");
11341: } elsif ($file =~ /\.tar\.bz2$/) {
11342: @cmd = (&decompression_utility('tar'),"-jtf");
11343: } elsif ($file =~ m|\.tar$|) {
11344: @cmd = (&decompression_utility('tar'),"-tf");
11345: }
11346: if (@cmd) {
11347: undef($!);
11348: undef($@);
11349: if (open(my $fh,"-|", @cmd, $file)) {
11350: while (my $line = <$fh>) {
11351: $output .= $line;
11352: chomp($line);
11353: my $item;
11354: if ($needsregexp) {
11355: ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/);
11356: } else {
11357: $item = $line;
11358: }
11359: if ($item ne '') {
11360: unless (grep(/^\Q$item\E$/,@{$pathsref})) {
11361: push(@{$pathsref},$item);
11362: }
11363: }
11364: }
11365: close($fh);
11366: }
11367: }
11368: return $output;
11369: }
11370:
11371: sub decompress_uploaded_file {
11372: my ($file,$dir) = @_;
11373: &Apache::lonnet::appenv({'cgi.file' => $file});
11374: &Apache::lonnet::appenv({'cgi.dir' => $dir});
11375: my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
11376: my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
11377: my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
11378: &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
11379: my $decompressed = $env{'cgi.decompressed'};
11380: &Apache::lonnet::delenv('cgi.file');
11381: &Apache::lonnet::delenv('cgi.dir');
11382: &Apache::lonnet::delenv('cgi.decompressed');
11383: return ($decompressed,$result);
11384: }
11385:
11386: sub process_decompression {
11387: my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
11388: my ($dir,$error,$warning,$output);
11389: if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
11390: $error = &mt('Filename not a supported archive file type.').
11391: '<br />'.&mt('Filename should end with one of: [_1].',
11392: '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
11393: } else {
11394: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11395: if ($docuhome eq 'no_host') {
11396: $error = &mt('Could not determine home server for course.');
11397: } else {
11398: my @ids=&Apache::lonnet::current_machine_ids();
11399: my $currdir = "$dir_root/$destination";
11400: if (grep(/^\Q$docuhome\E$/,@ids)) {
11401: $dir = &LONCAPA::propath($docudom,$docuname).
11402: "$dir_root/$destination";
11403: } else {
11404: $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
11405: "$dir_root/$docudom/$docuname/$destination";
11406: unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
11407: $error = &mt('Archive file not found.');
11408: }
11409: }
11410: my (@to_overwrite,@to_skip);
11411: if ($env{'form.archive_overwrite_total'} > 0) {
11412: my $total = $env{'form.archive_overwrite_total'};
11413: for (my $i=0; $i<$total; $i++) {
11414: if ($env{'form.archive_overwrite_'.$i} == 1) {
11415: push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
11416: } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
11417: push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
11418: }
11419: }
11420: }
11421: my $numskip = scalar(@to_skip);
11422: if (($numskip > 0) &&
11423: ($numskip == $env{'form.archive_itemcount'})) {
11424: $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');
11425: } elsif ($dir eq '') {
11426: $error = &mt('Directory containing archive file unavailable.');
11427: } elsif (!$error) {
11428: my ($decompressed,$display);
11429: if ($numskip > 0) {
11430: my $tempdir = time.'_'.$$.int(rand(10000));
11431: mkdir("$dir/$tempdir",0755);
11432: system("mv $dir/$file $dir/$tempdir/$file");
11433: ($decompressed,$display) =
11434: &decompress_uploaded_file($file,"$dir/$tempdir");
11435: foreach my $item (@to_skip) {
11436: if (($item ne '') && ($item !~ /\.\./)) {
11437: if (-f "$dir/$tempdir/$item") {
11438: unlink("$dir/$tempdir/$item");
11439: } elsif (-d "$dir/$tempdir/$item") {
11440: system("rm -rf $dir/$tempdir/$item");
11441: }
11442: }
11443: }
11444: system("mv $dir/$tempdir/* $dir");
11445: rmdir("$dir/$tempdir");
11446: } else {
11447: ($decompressed,$display) =
11448: &decompress_uploaded_file($file,$dir);
11449: }
11450: if ($decompressed eq 'ok') {
11451: $output = '<p class="LC_info">'.
11452: &mt('Files extracted successfully from archive.').
11453: '</p>'."\n";
11454: my ($warning,$result,@contents);
11455: my ($newdirlistref,$newlisterror) =
11456: &Apache::lonnet::dirlist($currdir,$docudom,
11457: $docuname,1);
11458: my (%is_dir,%changes,@newitems);
11459: my $dirptr = 16384;
11460: if (ref($newdirlistref) eq 'ARRAY') {
11461: foreach my $dir_line (@{$newdirlistref}) {
11462: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11463: unless (($item =~ /^\.+$/) || ($item eq $file) ||
11464: ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
11465: push(@newitems,$item);
11466: if ($dirptr&$testdir) {
11467: $is_dir{$item} = 1;
11468: }
11469: $changes{$item} = 1;
11470: }
11471: }
11472: }
11473: if (keys(%changes) > 0) {
11474: foreach my $item (sort(@newitems)) {
11475: if ($changes{$item}) {
11476: push(@contents,$item);
11477: }
11478: }
11479: }
11480: if (@contents > 0) {
11481: my $wantform;
11482: unless ($env{'form.autoextract_camtasia'}) {
11483: $wantform = 1;
11484: }
11485: my (%children,%parent,%dirorder,%titles);
11486: my ($count,$datatable) = &get_extracted($docudom,$docuname,
11487: $currdir,\%is_dir,
11488: \%children,\%parent,
11489: \@contents,\%dirorder,
11490: \%titles,$wantform);
11491: if ($datatable ne '') {
11492: $output .= &archive_options_form('decompressed',$datatable,
11493: $count,$hiddenelem);
11494: my $startcount = 6;
11495: $output .= &archive_javascript($startcount,$count,
11496: \%titles,\%children);
11497: }
11498: if ($env{'form.autoextract_camtasia'}) {
11499: my $version = $env{'form.autoextract_camtasia'};
11500: my %displayed;
11501: my $total = 1;
11502: $env{'form.archive_directory'} = [];
11503: foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
11504: my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
11505: $path =~ s{/$}{};
11506: my $item;
11507: if ($path ne '') {
11508: $item = "$path/$titles{$i}";
11509: } else {
11510: $item = $titles{$i};
11511: }
11512: $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
11513: if ($item eq $contents[0]) {
11514: push(@{$env{'form.archive_directory'}},$i);
11515: $env{'form.archive_'.$i} = 'display';
11516: $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
11517: $displayed{'folder'} = $i;
11518: } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
11519: (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
11520: $env{'form.archive_'.$i} = 'display';
11521: $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
11522: $displayed{'web'} = $i;
11523: } else {
11524: if ((($item eq "$contents[0]/media") && ($version == 6)) ||
11525: ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
11526: ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
11527: push(@{$env{'form.archive_directory'}},$i);
11528: }
11529: $env{'form.archive_'.$i} = 'dependency';
11530: }
11531: $total ++;
11532: }
11533: for (my $i=1; $i<$total; $i++) {
11534: next if ($i == $displayed{'web'});
11535: next if ($i == $displayed{'folder'});
11536: $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
11537: }
11538: $env{'form.phase'} = 'decompress_cleanup';
11539: $env{'form.archivedelete'} = 1;
11540: $env{'form.archive_count'} = $total-1;
11541: $output .=
11542: &process_extracted_files('coursedocs',$docudom,
11543: $docuname,$destination,
11544: $dir_root,$hiddenelem);
11545: }
11546: } else {
11547: $warning = &mt('No new items extracted from archive file.');
11548: }
11549: } else {
11550: $output = $display;
11551: $error = &mt('An error occurred during extraction from the archive file.');
11552: }
11553: }
11554: }
11555: }
11556: if ($error) {
11557: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11558: $error.'</p>'."\n";
11559: }
11560: if ($warning) {
11561: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11562: }
11563: return $output;
11564: }
11565:
11566: sub get_extracted {
11567: my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
11568: $titles,$wantform) = @_;
11569: my $count = 0;
11570: my $depth = 0;
11571: my $datatable;
11572: my @hierarchy;
11573: return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
11574: (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
11575: (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
11576: foreach my $item (@{$contents}) {
11577: $count ++;
11578: @{$dirorder->{$count}} = @hierarchy;
11579: $titles->{$count} = $item;
11580: &archive_hierarchy($depth,$count,$parent,$children);
11581: if ($wantform) {
11582: $datatable .= &archive_row($is_dir->{$item},$item,
11583: $currdir,$depth,$count);
11584: }
11585: if ($is_dir->{$item}) {
11586: $depth ++;
11587: push(@hierarchy,$count);
11588: $parent->{$depth} = $count;
11589: $datatable .=
11590: &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
11591: \$depth,\$count,\@hierarchy,$dirorder,
11592: $children,$parent,$titles,$wantform);
11593: $depth --;
11594: pop(@hierarchy);
11595: }
11596: }
11597: return ($count,$datatable);
11598: }
11599:
11600: sub recurse_extracted_archive {
11601: my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
11602: $children,$parent,$titles,$wantform) = @_;
11603: my $result='';
11604: unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
11605: (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
11606: (ref($dirorder) eq 'HASH')) {
11607: return $result;
11608: }
11609: my $dirptr = 16384;
11610: my ($newdirlistref,$newlisterror) =
11611: &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
11612: if (ref($newdirlistref) eq 'ARRAY') {
11613: foreach my $dir_line (@{$newdirlistref}) {
11614: my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11615: unless ($item =~ /^\.+$/) {
11616: $$count ++;
11617: @{$dirorder->{$$count}} = @{$hierarchy};
11618: $titles->{$$count} = $item;
11619: &archive_hierarchy($$depth,$$count,$parent,$children);
11620:
11621: my $is_dir;
11622: if ($dirptr&$testdir) {
11623: $is_dir = 1;
11624: }
11625: if ($wantform) {
11626: $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
11627: }
11628: if ($is_dir) {
11629: $$depth ++;
11630: push(@{$hierarchy},$$count);
11631: $parent->{$$depth} = $$count;
11632: $result .=
11633: &recurse_extracted_archive("$currdir/$item",$docudom,
11634: $docuname,$depth,$count,
11635: $hierarchy,$dirorder,$children,
11636: $parent,$titles,$wantform);
11637: $$depth --;
11638: pop(@{$hierarchy});
11639: }
11640: }
11641: }
11642: }
11643: return $result;
11644: }
11645:
11646: sub archive_hierarchy {
11647: my ($depth,$count,$parent,$children) =@_;
11648: if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
11649: if (exists($parent->{$depth})) {
11650: $children->{$parent->{$depth}} .= $count.':';
11651: }
11652: }
11653: return;
11654: }
11655:
11656: sub archive_row {
11657: my ($is_dir,$item,$currdir,$depth,$count) = @_;
11658: my ($name) = ($item =~ m{([^/]+)$});
11659: my %choices = &Apache::lonlocal::texthash (
11660: 'display' => 'Add as file',
11661: 'dependency' => 'Include as dependency',
11662: 'discard' => 'Discard',
11663: );
11664: if ($is_dir) {
11665: $choices{'display'} = &mt('Add as folder');
11666: }
11667: my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
11668: my $offset = 0;
11669: foreach my $action ('display','dependency','discard') {
11670: $offset ++;
11671: if ($action ne 'display') {
11672: $offset ++;
11673: }
11674: $output .= '<td><span class="LC_nobreak">'.
11675: '<label><input type="radio" name="archive_'.$count.
11676: '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
11677: my $text = $choices{$action};
11678: if ($is_dir) {
11679: $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
11680: if ($action eq 'display') {
11681: $text = &mt('Add as folder');
11682: }
11683: } else {
11684: $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
11685:
11686: }
11687: $output .= ' /> '.$choices{$action}.'</label></span>';
11688: if ($action eq 'dependency') {
11689: $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
11690: &mt('Used by:').' <select name="archive_dependent_on_'.$count.'" '.
11691: 'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
11692: '<option value=""></option>'."\n".
11693: '</select>'."\n".
11694: '</div>';
11695: } elsif ($action eq 'display') {
11696: $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11697: &mt('Title:').' <input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11698: '</div>';
11699: }
11700: $output .= '</td>';
11701: }
11702: $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11703: &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.(' ' x 2);
11704: for (my $i=0; $i<$depth; $i++) {
11705: $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11706: }
11707: if ($is_dir) {
11708: $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" /> '."\n".
11709: '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11710: } else {
11711: $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11712: }
11713: $output .= ' '.$name.'</td>'."\n".
11714: &end_data_table_row();
11715: return $output;
11716: }
11717:
11718: sub archive_options_form {
11719: my ($form,$display,$count,$hiddenelem) = @_;
11720: my %lt = &Apache::lonlocal::texthash(
11721: perm => 'Permanently remove archive file?',
11722: hows => 'How should each extracted item be incorporated in the course?',
11723: cont => 'Content actions for all',
11724: addf => 'Add as folder/file',
11725: incd => 'Include as dependency for a displayed file',
11726: disc => 'Discard',
11727: no => 'No',
11728: yes => 'Yes',
11729: save => 'Save',
11730: );
11731: my $output = <<"END";
11732: <form name="$form" method="post" action="">
11733: <p><span class="LC_nobreak">$lt{'perm'}
11734: <label>
11735: <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11736: </label>
11737:
11738: <label>
11739: <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11740: </span>
11741: </p>
11742: <input type="hidden" name="phase" value="decompress_cleanup" />
11743: <br />$lt{'hows'}
11744: <div class="LC_columnSection">
11745: <fieldset>
11746: <legend>$lt{'cont'}</legend>
11747: <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" />
11748: <input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11749: <input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11750: </fieldset>
11751: </div>
11752: END
11753: return $output.
11754: &start_data_table()."\n".
11755: $display."\n".
11756: &end_data_table()."\n".
11757: '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11758: $hiddenelem.
11759: '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11760: '</form>';
11761: }
11762:
11763: sub archive_javascript {
11764: my ($startcount,$numitems,$titles,$children) = @_;
11765: return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11766: my $maintitle = $env{'form.comment'};
11767: my $scripttag = <<START;
11768: <script type="text/javascript">
11769: // <![CDATA[
11770:
11771: function checkAll(form,prefix) {
11772: var idstr = new RegExp("^archive_"+prefix+"_\\\\d+\$");
11773: for (var i=0; i < form.elements.length; i++) {
11774: var id = form.elements[i].id;
11775: if ((id != '') && (id != undefined)) {
11776: if (idstr.test(id)) {
11777: if (form.elements[i].type == 'radio') {
11778: form.elements[i].checked = true;
11779: var nostart = i-$startcount;
11780: var offset = nostart%7;
11781: var count = (nostart-offset)/7;
11782: dependencyCheck(form,count,offset);
11783: }
11784: }
11785: }
11786: }
11787: }
11788:
11789: function propagateCheck(form,count) {
11790: if (count > 0) {
11791: var startelement = $startcount + ((count-1) * 7);
11792: for (var j=1; j<6; j++) {
11793: if ((j != 2) && (j != 4)) {
11794: var item = startelement + j;
11795: if (form.elements[item].type == 'radio') {
11796: if (form.elements[item].checked) {
11797: containerCheck(form,count,j);
11798: break;
11799: }
11800: }
11801: }
11802: }
11803: }
11804: }
11805:
11806: numitems = $numitems
11807: var titles = new Array(numitems);
11808: var parents = new Array(numitems);
11809: for (var i=0; i<numitems; i++) {
11810: parents[i] = new Array;
11811: }
11812: var maintitle = '$maintitle';
11813:
11814: START
11815:
11816: foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
11817: my @contents = split(/:/,$children->{$container});
11818: for (my $i=0; $i<@contents; $i ++) {
11819: $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
11820: }
11821: }
11822:
11823: foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
11824: $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
11825: }
11826:
11827: $scripttag .= <<END;
11828:
11829: function containerCheck(form,count,offset) {
11830: if (count > 0) {
11831: dependencyCheck(form,count,offset);
11832: var item = (offset+$startcount)+7*(count-1);
11833: form.elements[item].checked = true;
11834: if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
11835: if (parents[count].length > 0) {
11836: for (var j=0; j<parents[count].length; j++) {
11837: containerCheck(form,parents[count][j],offset);
11838: }
11839: }
11840: }
11841: }
11842: }
11843:
11844: function dependencyCheck(form,count,offset) {
11845: if (count > 0) {
11846: var chosen = (offset+$startcount)+7*(count-1);
11847: var depitem = $startcount + ((count-1) * 7) + 4;
11848: var currtype = form.elements[depitem].type;
11849: if (form.elements[chosen].value == 'dependency') {
11850: document.getElementById('arc_depon_'+count).style.display='block';
11851: form.elements[depitem].options.length = 0;
11852: form.elements[depitem].options[0] = new Option('Select','',true,true);
11853: for (var i=1; i<=numitems; i++) {
11854: if (i == count) {
11855: continue;
11856: }
11857: var startelement = $startcount + (i-1) * 7;
11858: for (var j=1; j<6; j++) {
11859: if ((j != 2) && (j!= 4)) {
11860: var item = startelement + j;
11861: if (form.elements[item].type == 'radio') {
11862: if (form.elements[item].checked) {
11863: if (form.elements[item].value == 'display') {
11864: var n = form.elements[depitem].options.length;
11865: form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
11866: }
11867: }
11868: }
11869: }
11870: }
11871: }
11872: } else {
11873: document.getElementById('arc_depon_'+count).style.display='none';
11874: form.elements[depitem].options.length = 0;
11875: form.elements[depitem].options[0] = new Option('Select','',true,true);
11876: }
11877: titleCheck(form,count,offset);
11878: }
11879: }
11880:
11881: function propagateSelect(form,count,offset) {
11882: if (count > 0) {
11883: var item = (1+offset+$startcount)+7*(count-1);
11884: var picked = form.elements[item].options[form.elements[item].selectedIndex].value;
11885: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11886: if (parents[count].length > 0) {
11887: for (var j=0; j<parents[count].length; j++) {
11888: containerSelect(form,parents[count][j],offset,picked);
11889: }
11890: }
11891: }
11892: }
11893: }
11894:
11895: function containerSelect(form,count,offset,picked) {
11896: if (count > 0) {
11897: var item = (offset+$startcount)+7*(count-1);
11898: if (form.elements[item].type == 'radio') {
11899: if (form.elements[item].value == 'dependency') {
11900: if (form.elements[item+1].type == 'select-one') {
11901: for (var i=0; i<form.elements[item+1].options.length; i++) {
11902: if (form.elements[item+1].options[i].value == picked) {
11903: form.elements[item+1].selectedIndex = i;
11904: break;
11905: }
11906: }
11907: }
11908: if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11909: if (parents[count].length > 0) {
11910: for (var j=0; j<parents[count].length; j++) {
11911: containerSelect(form,parents[count][j],offset,picked);
11912: }
11913: }
11914: }
11915: }
11916: }
11917: }
11918: }
11919:
11920: function titleCheck(form,count,offset) {
11921: if (count > 0) {
11922: var chosen = (offset+$startcount)+7*(count-1);
11923: var depitem = $startcount + ((count-1) * 7) + 2;
11924: var currtype = form.elements[depitem].type;
11925: if (form.elements[chosen].value == 'display') {
11926: document.getElementById('arc_title_'+count).style.display='block';
11927: if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
11928: document.getElementById('archive_title_'+count).value=maintitle;
11929: }
11930: } else {
11931: document.getElementById('arc_title_'+count).style.display='none';
11932: if (currtype == 'text') {
11933: document.getElementById('archive_title_'+count).value='';
11934: }
11935: }
11936: }
11937: return;
11938: }
11939:
11940: // ]]>
11941: </script>
11942: END
11943: return $scripttag;
11944: }
11945:
11946: sub process_extracted_files {
11947: my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
11948: my $numitems = $env{'form.archive_count'};
11949: return unless ($numitems);
11950: my @ids=&Apache::lonnet::current_machine_ids();
11951: my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
11952: %folders,%containers,%mapinner,%prompttofetch);
11953: my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11954: if (grep(/^\Q$docuhome\E$/,@ids)) {
11955: $prefix = &LONCAPA::propath($docudom,$docuname);
11956: $pathtocheck = "$dir_root/$destination";
11957: $dir = $dir_root;
11958: $ishome = 1;
11959: } else {
11960: $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
11961: $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
11962: $dir = "$dir_root/$docudom/$docuname";
11963: }
11964: my $currdir = "$dir_root/$destination";
11965: (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
11966: if ($env{'form.folderpath'}) {
11967: my @items = split('&',$env{'form.folderpath'});
11968: $folders{'0'} = $items[-2];
11969: if ($env{'form.folderpath'} =~ /\:1$/) {
11970: $containers{'0'}='page';
11971: } else {
11972: $containers{'0'}='sequence';
11973: }
11974: }
11975: my @archdirs = &get_env_multiple('form.archive_directory');
11976: if ($numitems) {
11977: for (my $i=1; $i<=$numitems; $i++) {
11978: my $path = $env{'form.archive_content_'.$i};
11979: if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
11980: my $item = $1;
11981: $toplevelitems{$item} = $i;
11982: if (grep(/^\Q$i\E$/,@archdirs)) {
11983: $is_dir{$item} = 1;
11984: }
11985: }
11986: }
11987: }
11988: my ($output,%children,%parent,%titles,%dirorder,$result);
11989: if (keys(%toplevelitems) > 0) {
11990: my @contents = sort(keys(%toplevelitems));
11991: (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
11992: \%parent,\@contents,\%dirorder,\%titles);
11993: }
11994: my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
11995: if ($numitems) {
11996: for (my $i=1; $i<=$numitems; $i++) {
11997: next if ($env{'form.archive_'.$i} eq 'dependency');
11998: my $path = $env{'form.archive_content_'.$i};
11999: if ($path =~ /^\Q$pathtocheck\E/) {
12000: if ($env{'form.archive_'.$i} eq 'discard') {
12001: if ($prefix ne '' && $path ne '') {
12002: if (-e $prefix.$path) {
12003: if ((@archdirs > 0) &&
12004: (grep(/^\Q$i\E$/,@archdirs))) {
12005: $todeletedir{$prefix.$path} = 1;
12006: } else {
12007: $todelete{$prefix.$path} = 1;
12008: }
12009: }
12010: }
12011: } elsif ($env{'form.archive_'.$i} eq 'display') {
12012: my ($docstitle,$title,$url,$outer);
12013: ($title) = ($path =~ m{/([^/]+)$});
12014: $docstitle = $env{'form.archive_title_'.$i};
12015: if ($docstitle eq '') {
12016: $docstitle = $title;
12017: }
12018: $outer = 0;
12019: if (ref($dirorder{$i}) eq 'ARRAY') {
12020: if (@{$dirorder{$i}} > 0) {
12021: foreach my $item (reverse(@{$dirorder{$i}})) {
12022: if ($env{'form.archive_'.$item} eq 'display') {
12023: $outer = $item;
12024: last;
12025: }
12026: }
12027: }
12028: }
12029: my ($errtext,$fatal) =
12030: &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
12031: '/'.$folders{$outer}.'.'.
12032: $containers{$outer});
12033: next if ($fatal);
12034: if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
12035: if ($context eq 'coursedocs') {
12036: $mapinner{$i} = time;
12037: $folders{$i} = 'default_'.$mapinner{$i};
12038: $containers{$i} = 'sequence';
12039: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12040: $folders{$i}.'.'.$containers{$i};
12041: my $newidx = &LONCAPA::map::getresidx();
12042: $LONCAPA::map::resources[$newidx]=
12043: $docstitle.':'.$url.':false:normal:res';
12044: push(@LONCAPA::map::order,$newidx);
12045: my ($outtext,$errtext) =
12046: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12047: $docuname.'/'.$folders{$outer}.
12048: '.'.$containers{$outer},1,1);
12049: $newseqid{$i} = $newidx;
12050: unless ($errtext) {
12051: $result .= '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
12052: }
12053: }
12054: } else {
12055: if ($context eq 'coursedocs') {
12056: my $newidx=&LONCAPA::map::getresidx();
12057: my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12058: $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
12059: $title;
12060: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
12061: mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
12062: }
12063: if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12064: mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
12065: }
12066: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12067: system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
12068: $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
12069: unless ($ishome) {
12070: my $fetch = "$newdest{$i}/$title";
12071: $fetch =~ s/^\Q$prefix$dir\E//;
12072: $prompttofetch{$fetch} = 1;
12073: }
12074: }
12075: $LONCAPA::map::resources[$newidx]=
12076: $docstitle.':'.$url.':false:normal:res';
12077: push(@LONCAPA::map::order, $newidx);
12078: my ($outtext,$errtext)=
12079: &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12080: $docuname.'/'.$folders{$outer}.
12081: '.'.$containers{$outer},1,1);
12082: unless ($errtext) {
12083: if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
12084: $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
12085: }
12086: }
12087: }
12088: }
12089: }
12090: } else {
12091: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
12092: }
12093: }
12094: for (my $i=1; $i<=$numitems; $i++) {
12095: next unless ($env{'form.archive_'.$i} eq 'dependency');
12096: my $path = $env{'form.archive_content_'.$i};
12097: if ($path =~ /^\Q$pathtocheck\E/) {
12098: my ($title) = ($path =~ m{/([^/]+)$});
12099: $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
12100: if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
12101: if (ref($dirorder{$i}) eq 'ARRAY') {
12102: my ($itemidx,$fullpath,$relpath);
12103: if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
12104: my $container = $dirorder{$referrer{$i}}->[-1];
12105: for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
12106: if ($dirorder{$i}->[$j] eq $container) {
12107: $itemidx = $j;
12108: }
12109: }
12110: }
12111: if ($itemidx eq '') {
12112: $itemidx = 0;
12113: }
12114: if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
12115: if ($mapinner{$referrer{$i}}) {
12116: $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
12117: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12118: if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12119: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12120: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12121: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12122: if (!-e $fullpath) {
12123: mkdir($fullpath,0755);
12124: }
12125: }
12126: } else {
12127: last;
12128: }
12129: }
12130: }
12131: } elsif ($newdest{$referrer{$i}}) {
12132: $fullpath = $newdest{$referrer{$i}};
12133: for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12134: if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12135: $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12136: last;
12137: } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12138: unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12139: $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12140: $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12141: if (!-e $fullpath) {
12142: mkdir($fullpath,0755);
12143: }
12144: }
12145: } else {
12146: last;
12147: }
12148: }
12149: }
12150: if ($fullpath ne '') {
12151: if (-e "$prefix$path") {
12152: system("mv $prefix$path $fullpath/$title");
12153: }
12154: if (-e "$fullpath/$title") {
12155: my $showpath;
12156: if ($relpath ne '') {
12157: $showpath = "$relpath/$title";
12158: } else {
12159: $showpath = "/$title";
12160: }
12161: $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
12162: }
12163: unless ($ishome) {
12164: my $fetch = "$fullpath/$title";
12165: $fetch =~ s/^\Q$prefix$dir\E//;
12166: $prompttofetch{$fetch} = 1;
12167: }
12168: }
12169: }
12170: } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12171: $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12172: $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
12173: }
12174: } else {
12175: $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
12176: }
12177: }
12178: if (keys(%todelete)) {
12179: foreach my $key (keys(%todelete)) {
12180: unlink($key);
12181: }
12182: }
12183: if (keys(%todeletedir)) {
12184: foreach my $key (keys(%todeletedir)) {
12185: rmdir($key);
12186: }
12187: }
12188: foreach my $dir (sort(keys(%is_dir))) {
12189: if (($pathtocheck ne '') && ($dir ne '')) {
12190: &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12191: }
12192: }
12193: if ($result ne '') {
12194: $output .= '<ul>'."\n".
12195: $result."\n".
12196: '</ul>';
12197: }
12198: unless ($ishome) {
12199: my $replicationfail;
12200: foreach my $item (keys(%prompttofetch)) {
12201: my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12202: unless ($fetchresult eq 'ok') {
12203: $replicationfail .= '<li>'.$item.'</li>'."\n";
12204: }
12205: }
12206: if ($replicationfail) {
12207: $output .= '<p class="LC_error">'.
12208: &mt('Course home server failed to retrieve:').'<ul>'.
12209: $replicationfail.
12210: '</ul></p>';
12211: }
12212: }
12213: } else {
12214: $warning = &mt('No items found in archive.');
12215: }
12216: if ($error) {
12217: $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12218: $error.'</p>'."\n";
12219: }
12220: if ($warning) {
12221: $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12222: }
12223: return $output;
12224: }
12225:
12226: sub cleanup_empty_dirs {
12227: my ($path) = @_;
12228: if (($path ne '') && (-d $path)) {
12229: if (opendir(my $dirh,$path)) {
12230: my @dircontents = grep(!/^\./,readdir($dirh));
12231: my $numitems = 0;
12232: foreach my $item (@dircontents) {
12233: if (-d "$path/$item") {
12234: &cleanup_empty_dirs("$path/$item");
12235: if (-e "$path/$item") {
12236: $numitems ++;
12237: }
12238: } else {
12239: $numitems ++;
12240: }
12241: }
12242: if ($numitems == 0) {
12243: rmdir($path);
12244: }
12245: closedir($dirh);
12246: }
12247: }
12248: return;
12249: }
12250:
12251: =pod
12252:
12253: =item * &get_folder_hierarchy()
12254:
12255: Provides hierarchy of names of folders/sub-folders containing the current
12256: item,
12257:
12258: Inputs: 3
12259: - $navmap - navmaps object
12260:
12261: - $map - url for map (either the trigger itself, or map containing
12262: the resource, which is the trigger).
12263:
12264: - $showitem - 1 => show title for map itself; 0 => do not show.
12265:
12266: Outputs: 1 @pathitems - array of folder/subfolder names.
12267:
12268: =cut
12269:
12270: sub get_folder_hierarchy {
12271: my ($navmap,$map,$showitem) = @_;
12272: my @pathitems;
12273: if (ref($navmap)) {
12274: my $mapres = $navmap->getResourceByUrl($map);
12275: if (ref($mapres)) {
12276: my $pcslist = $mapres->map_hierarchy();
12277: if ($pcslist ne '') {
12278: my @pcs = split(/,/,$pcslist);
12279: foreach my $pc (@pcs) {
12280: if ($pc == 1) {
12281: push(@pathitems,&mt('Main Content'));
12282: } else {
12283: my $res = $navmap->getByMapPc($pc);
12284: if (ref($res)) {
12285: my $title = $res->compTitle();
12286: $title =~ s/\W+/_/g;
12287: if ($title ne '') {
12288: push(@pathitems,$title);
12289: }
12290: }
12291: }
12292: }
12293: }
12294: if ($showitem) {
12295: if ($mapres->{ID} eq '0.0') {
12296: push(@pathitems,&mt('Main Content'));
12297: } else {
12298: my $maptitle = $mapres->compTitle();
12299: $maptitle =~ s/\W+/_/g;
12300: if ($maptitle ne '') {
12301: push(@pathitems,$maptitle);
12302: }
12303: }
12304: }
12305: }
12306: }
12307: return @pathitems;
12308: }
12309:
12310: =pod
12311:
12312: =item * &get_turnedin_filepath()
12313:
12314: Determines path in a user's portfolio file for storage of files uploaded
12315: to a specific essayresponse or dropbox item.
12316:
12317: Inputs: 3 required + 1 optional.
12318: $symb is symb for resource, $uname and $udom are for current user (required).
12319: $caller is optional (can be "submission", if routine is called when storing
12320: an upoaded file when "Submit Answer" button was pressed).
12321:
12322: Returns array containing $path and $multiresp.
12323: $path is path in portfolio. $multiresp is 1 if this resource contains more
12324: than one file upload item. Callers of routine should append partid as a
12325: subdirectory to $path in cases where $multiresp is 1.
12326:
12327: Called by: homework/essayresponse.pm and homework/structuretags.pm
12328:
12329: =cut
12330:
12331: sub get_turnedin_filepath {
12332: my ($symb,$uname,$udom,$caller) = @_;
12333: my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
12334: my $turnindir;
12335: my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
12336: $turnindir = $userhash{'turnindir'};
12337: my ($path,$multiresp);
12338: if ($turnindir eq '') {
12339: if ($caller eq 'submission') {
12340: $turnindir = &mt('turned in');
12341: $turnindir =~ s/\W+/_/g;
12342: my %newhash = (
12343: 'turnindir' => $turnindir,
12344: );
12345: &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
12346: }
12347: }
12348: if ($turnindir ne '') {
12349: $path = '/'.$turnindir.'/';
12350: my ($multipart,$turnin,@pathitems);
12351: my $navmap = Apache::lonnavmaps::navmap->new();
12352: if (defined($navmap)) {
12353: my $mapres = $navmap->getResourceByUrl($map);
12354: if (ref($mapres)) {
12355: my $pcslist = $mapres->map_hierarchy();
12356: if ($pcslist ne '') {
12357: foreach my $pc (split(/,/,$pcslist)) {
12358: my $res = $navmap->getByMapPc($pc);
12359: if (ref($res)) {
12360: my $title = $res->compTitle();
12361: $title =~ s/\W+/_/g;
12362: if ($title ne '') {
12363: if (($pc > 1) && (length($title) > 12)) {
12364: $title = substr($title,0,12);
12365: }
12366: push(@pathitems,$title);
12367: }
12368: }
12369: }
12370: }
12371: my $maptitle = $mapres->compTitle();
12372: $maptitle =~ s/\W+/_/g;
12373: if ($maptitle ne '') {
12374: if (length($maptitle) > 12) {
12375: $maptitle = substr($maptitle,0,12);
12376: }
12377: push(@pathitems,$maptitle);
12378: }
12379: unless ($env{'request.state'} eq 'construct') {
12380: my $res = $navmap->getBySymb($symb);
12381: if (ref($res)) {
12382: my $partlist = $res->parts();
12383: my $totaluploads = 0;
12384: if (ref($partlist) eq 'ARRAY') {
12385: foreach my $part (@{$partlist}) {
12386: my @types = $res->responseType($part);
12387: my @ids = $res->responseIds($part);
12388: for (my $i=0; $i < scalar(@ids); $i++) {
12389: if ($types[$i] eq 'essay') {
12390: my $partid = $part.'_'.$ids[$i];
12391: if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
12392: $totaluploads ++;
12393: }
12394: }
12395: }
12396: }
12397: if ($totaluploads > 1) {
12398: $multiresp = 1;
12399: }
12400: }
12401: }
12402: }
12403: } else {
12404: return;
12405: }
12406: } else {
12407: return;
12408: }
12409: my $restitle=&Apache::lonnet::gettitle($symb);
12410: $restitle =~ s/\W+/_/g;
12411: if ($restitle eq '') {
12412: $restitle = ($resurl =~ m{/[^/]+$});
12413: if ($restitle eq '') {
12414: $restitle = time;
12415: }
12416: }
12417: if (length($restitle) > 12) {
12418: $restitle = substr($restitle,0,12);
12419: }
12420: push(@pathitems,$restitle);
12421: $path .= join('/',@pathitems);
12422: }
12423: return ($path,$multiresp);
12424: }
12425:
12426: =pod
12427:
12428: =back
12429:
12430: =head1 CSV Upload/Handling functions
12431:
12432: =over 4
12433:
12434: =item * &upfile_store($r)
12435:
12436: Store uploaded file, $r should be the HTTP Request object,
12437: needs $env{'form.upfile'}
12438: returns $datatoken to be put into hidden field
12439:
12440: =cut
12441:
12442: sub upfile_store {
12443: my $r=shift;
12444: $env{'form.upfile'}=~s/\r/\n/gs;
12445: $env{'form.upfile'}=~s/\f/\n/gs;
12446: $env{'form.upfile'}=~s/\n+/\n/gs;
12447: $env{'form.upfile'}=~s/\n+$//gs;
12448:
12449: my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
12450: '_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
12451: {
12452: my $datafile = $r->dir_config('lonDaemons').
12453: '/tmp/'.$datatoken.'.tmp';
12454: if ( open(my $fh,">$datafile") ) {
12455: print $fh $env{'form.upfile'};
12456: close($fh);
12457: }
12458: }
12459: return $datatoken;
12460: }
12461:
12462: =pod
12463:
12464: =item * &load_tmp_file($r)
12465:
12466: Load uploaded file from tmp, $r should be the HTTP Request object,
12467: needs $env{'form.datatoken'},
12468: sets $env{'form.upfile'} to the contents of the file
12469:
12470: =cut
12471:
12472: sub load_tmp_file {
12473: my $r=shift;
12474: my @studentdata=();
12475: {
12476: my $studentfile = $r->dir_config('lonDaemons').
12477: '/tmp/'.$env{'form.datatoken'}.'.tmp';
12478: if ( open(my $fh,"<$studentfile") ) {
12479: @studentdata=<$fh>;
12480: close($fh);
12481: }
12482: }
12483: $env{'form.upfile'}=join('',@studentdata);
12484: }
12485:
12486: =pod
12487:
12488: =item * &upfile_record_sep()
12489:
12490: Separate uploaded file into records
12491: returns array of records,
12492: needs $env{'form.upfile'} and $env{'form.upfiletype'}
12493:
12494: =cut
12495:
12496: sub upfile_record_sep {
12497: if ($env{'form.upfiletype'} eq 'xml') {
12498: } else {
12499: my @records;
12500: foreach my $line (split(/\n/,$env{'form.upfile'})) {
12501: if ($line=~/^\s*$/) { next; }
12502: push(@records,$line);
12503: }
12504: return @records;
12505: }
12506: }
12507:
12508: =pod
12509:
12510: =item * &record_sep($record)
12511:
12512: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
12513:
12514: =cut
12515:
12516: sub takeleft {
12517: my $index=shift;
12518: return substr('0000'.$index,-4,4);
12519: }
12520:
12521: sub record_sep {
12522: my $record=shift;
12523: my %components=();
12524: if ($env{'form.upfiletype'} eq 'xml') {
12525: } elsif ($env{'form.upfiletype'} eq 'space') {
12526: my $i=0;
12527: foreach my $field (split(/\s+/,$record)) {
12528: $field=~s/^(\"|\')//;
12529: $field=~s/(\"|\')$//;
12530: $components{&takeleft($i)}=$field;
12531: $i++;
12532: }
12533: } elsif ($env{'form.upfiletype'} eq 'tab') {
12534: my $i=0;
12535: foreach my $field (split(/\t/,$record)) {
12536: $field=~s/^(\"|\')//;
12537: $field=~s/(\"|\')$//;
12538: $components{&takeleft($i)}=$field;
12539: $i++;
12540: }
12541: } else {
12542: my $separator=',';
12543: if ($env{'form.upfiletype'} eq 'semisv') {
12544: $separator=';';
12545: }
12546: my $i=0;
12547: # the character we are looking for to indicate the end of a quote or a record
12548: my $looking_for=$separator;
12549: # do not add the characters to the fields
12550: my $ignore=0;
12551: # we just encountered a separator (or the beginning of the record)
12552: my $just_found_separator=1;
12553: # store the field we are working on here
12554: my $field='';
12555: # work our way through all characters in record
12556: foreach my $character ($record=~/(.)/g) {
12557: if ($character eq $looking_for) {
12558: if ($character ne $separator) {
12559: # Found the end of a quote, again looking for separator
12560: $looking_for=$separator;
12561: $ignore=1;
12562: } else {
12563: # Found a separator, store away what we got
12564: $components{&takeleft($i)}=$field;
12565: $i++;
12566: $just_found_separator=1;
12567: $ignore=0;
12568: $field='';
12569: }
12570: next;
12571: }
12572: # single or double quotation marks after a separator indicate beginning of a quote
12573: # we are now looking for the end of the quote and need to ignore separators
12574: if ((($character eq '"') || ($character eq "'")) && ($just_found_separator)) {
12575: $looking_for=$character;
12576: next;
12577: }
12578: # ignore would be true after we reached the end of a quote
12579: if ($ignore) { next; }
12580: if (($just_found_separator) && ($character=~/\s/)) { next; }
12581: $field.=$character;
12582: $just_found_separator=0;
12583: }
12584: # catch the very last entry, since we never encountered the separator
12585: $components{&takeleft($i)}=$field;
12586: }
12587: return %components;
12588: }
12589:
12590: ######################################################
12591: ######################################################
12592:
12593: =pod
12594:
12595: =item * &upfile_select_html()
12596:
12597: Return HTML code to select a file from the users machine and specify
12598: the file type.
12599:
12600: =cut
12601:
12602: ######################################################
12603: ######################################################
12604: sub upfile_select_html {
12605: my %Types = (
12606: csv => &mt('CSV (comma separated values, spreadsheet)'),
12607: semisv => &mt('Semicolon separated values'),
12608: space => &mt('Space separated'),
12609: tab => &mt('Tabulator separated'),
12610: # xml => &mt('HTML/XML'),
12611: );
12612: my $Str = '<input type="file" name="upfile" size="50" />'.
12613: '<br />'.&mt('Type').': <select name="upfiletype">';
12614: foreach my $type (sort(keys(%Types))) {
12615: $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
12616: }
12617: $Str .= "</select>\n";
12618: return $Str;
12619: }
12620:
12621: sub get_samples {
12622: my ($records,$toget) = @_;
12623: my @samples=({});
12624: my $got=0;
12625: foreach my $rec (@$records) {
12626: my %temp = &record_sep($rec);
12627: if (! grep(/\S/, values(%temp))) { next; }
12628: if (%temp) {
12629: $samples[$got]=\%temp;
12630: $got++;
12631: if ($got == $toget) { last; }
12632: }
12633: }
12634: return \@samples;
12635: }
12636:
12637: ######################################################
12638: ######################################################
12639:
12640: =pod
12641:
12642: =item * &csv_print_samples($r,$records)
12643:
12644: Prints a table of sample values from each column uploaded $r is an
12645: Apache Request ref, $records is an arrayref from
12646: &Apache::loncommon::upfile_record_sep
12647:
12648: =cut
12649:
12650: ######################################################
12651: ######################################################
12652: sub csv_print_samples {
12653: my ($r,$records) = @_;
12654: my $samples = &get_samples($records,5);
12655:
12656: $r->print(&mt('Samples').'<br />'.&start_data_table().
12657: &start_data_table_header_row());
12658: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12659: $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
12660: $r->print(&end_data_table_header_row());
12661: foreach my $hash (@$samples) {
12662: $r->print(&start_data_table_row());
12663: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12664: $r->print('<td>');
12665: if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
12666: $r->print('</td>');
12667: }
12668: $r->print(&end_data_table_row());
12669: }
12670: $r->print(&end_data_table().'<br />'."\n");
12671: }
12672:
12673: ######################################################
12674: ######################################################
12675:
12676: =pod
12677:
12678: =item * &csv_print_select_table($r,$records,$d)
12679:
12680: Prints a table to create associations between values and table columns.
12681:
12682: $r is an Apache Request ref,
12683: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12684: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
12685:
12686: =cut
12687:
12688: ######################################################
12689: ######################################################
12690: sub csv_print_select_table {
12691: my ($r,$records,$d) = @_;
12692: my $i=0;
12693: my $samples = &get_samples($records,1);
12694: $r->print(&mt('Associate columns with student attributes.')."\n".
12695: &start_data_table().&start_data_table_header_row().
12696: '<th>'.&mt('Attribute').'</th>'.
12697: '<th>'.&mt('Column').'</th>'.
12698: &end_data_table_header_row()."\n");
12699: foreach my $array_ref (@$d) {
12700: my ($value,$display,$defaultcol)=@{ $array_ref };
12701: $r->print(&start_data_table_row().'<td>'.$display.'</td>');
12702:
12703: $r->print('<td><select name="f'.$i.'"'.
12704: ' onchange="javascript:flip(this.form,'.$i.');">');
12705: $r->print('<option value="none"></option>');
12706: foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12707: $r->print('<option value="'.$sample.'"'.
12708: ($sample eq $defaultcol ? ' selected="selected" ' : '').
12709: '>'.&mt('Column [_1]',($sample+1)).'</option>');
12710: }
12711: $r->print('</select></td>'.&end_data_table_row()."\n");
12712: $i++;
12713: }
12714: $r->print(&end_data_table());
12715: $i--;
12716: return $i;
12717: }
12718:
12719: ######################################################
12720: ######################################################
12721:
12722: =pod
12723:
12724: =item * &csv_samples_select_table($r,$records,$d)
12725:
12726: Prints a table of sample values from the upload and can make associate samples to internal names.
12727:
12728: $r is an Apache Request ref,
12729: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12730: $d is an array of 2 element arrays (internal name, displayed name)
12731:
12732: =cut
12733:
12734: ######################################################
12735: ######################################################
12736: sub csv_samples_select_table {
12737: my ($r,$records,$d) = @_;
12738: my $i=0;
12739: #
12740: my $max_samples = 5;
12741: my $samples = &get_samples($records,$max_samples);
12742: $r->print(&start_data_table().
12743: &start_data_table_header_row().'<th>'.
12744: &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12745: &end_data_table_header_row());
12746:
12747: foreach my $key (sort(keys(%{ $samples->[0] }))) {
12748: $r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12749: ' onchange="javascript:flip(this.form,'.$i.');">');
12750: foreach my $option (@$d) {
12751: my ($value,$display,$defaultcol)=@{ $option };
12752: $r->print('<option value="'.$value.'"'.
12753: ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12754: $display.'</option>');
12755: }
12756: $r->print('</select></td><td>');
12757: foreach my $line (0..($max_samples-1)) {
12758: if (defined($samples->[$line]{$key})) {
12759: $r->print($samples->[$line]{$key}."<br />\n");
12760: }
12761: }
12762: $r->print('</td>'.&end_data_table_row());
12763: $i++;
12764: }
12765: $r->print(&end_data_table());
12766: $i--;
12767: return($i);
12768: }
12769:
12770: ######################################################
12771: ######################################################
12772:
12773: =pod
12774:
12775: =item * &clean_excel_name($name)
12776:
12777: Returns a replacement for $name which does not contain any illegal characters.
12778:
12779: =cut
12780:
12781: ######################################################
12782: ######################################################
12783: sub clean_excel_name {
12784: my ($name) = @_;
12785: $name =~ s/[:\*\?\/\\]//g;
12786: if (length($name) > 31) {
12787: $name = substr($name,0,31);
12788: }
12789: return $name;
12790: }
12791:
12792: =pod
12793:
12794: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
12795:
12796: Returns either 1 or undef
12797:
12798: 1 if the part is to be hidden, undef if it is to be shown
12799:
12800: Arguments are:
12801:
12802: $id the id of the part to be checked
12803: $symb, optional the symb of the resource to check
12804: $udom, optional the domain of the user to check for
12805: $uname, optional the username of the user to check for
12806:
12807: =cut
12808:
12809: sub check_if_partid_hidden {
12810: my ($id,$symb,$udom,$uname) = @_;
12811: my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
12812: $symb,$udom,$uname);
12813: my $truth=1;
12814: #if the string starts with !, then the list is the list to show not hide
12815: if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
12816: my @hiddenlist=split(/,/,$hiddenparts);
12817: foreach my $checkid (@hiddenlist) {
12818: if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
12819: }
12820: return !$truth;
12821: }
12822:
12823:
12824: ############################################################
12825: ############################################################
12826:
12827: =pod
12828:
12829: =back
12830:
12831: =head1 cgi-bin script and graphing routines
12832:
12833: =over 4
12834:
12835: =item * &get_cgi_id()
12836:
12837: Inputs: none
12838:
12839: Returns an id which can be used to pass environment variables
12840: to various cgi-bin scripts. These environment variables will
12841: be removed from the users environment after a given time by
12842: the routine &Apache::lonnet::transfer_profile_to_env.
12843:
12844: =cut
12845:
12846: ############################################################
12847: ############################################################
12848: my $uniq=0;
12849: sub get_cgi_id {
12850: $uniq=($uniq+1)%100000;
12851: return (time.'_'.$$.'_'.$uniq);
12852: }
12853:
12854: ############################################################
12855: ############################################################
12856:
12857: =pod
12858:
12859: =item * &DrawBarGraph()
12860:
12861: Facilitates the plotting of data in a (stacked) bar graph.
12862: Puts plot definition data into the users environment in order for
12863: graph.png to plot it. Returns an <img> tag for the plot.
12864: The bars on the plot are labeled '1','2',...,'n'.
12865:
12866: Inputs:
12867:
12868: =over 4
12869:
12870: =item $Title: string, the title of the plot
12871:
12872: =item $xlabel: string, text describing the X-axis of the plot
12873:
12874: =item $ylabel: string, text describing the Y-axis of the plot
12875:
12876: =item $Max: scalar, the maximum Y value to use in the plot
12877: If $Max is < any data point, the graph will not be rendered.
12878:
12879: =item $colors: array ref holding the colors to be used for the data sets when
12880: they are plotted. If undefined, default values will be used.
12881:
12882: =item $labels: array ref holding the labels to use on the x-axis for the bars.
12883:
12884: =item @Values: An array of array references. Each array reference holds data
12885: to be plotted in a stacked bar chart.
12886:
12887: =item If the final element of @Values is a hash reference the key/value
12888: pairs will be added to the graph definition.
12889:
12890: =back
12891:
12892: Returns:
12893:
12894: An <img> tag which references graph.png and the appropriate identifying
12895: information for the plot.
12896:
12897: =cut
12898:
12899: ############################################################
12900: ############################################################
12901: sub DrawBarGraph {
12902: my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
12903: #
12904: if (! defined($colors)) {
12905: $colors = ['#33ff00',
12906: '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
12907: '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
12908: ];
12909: }
12910: my $extra_settings = {};
12911: if (ref($Values[-1]) eq 'HASH') {
12912: $extra_settings = pop(@Values);
12913: }
12914: #
12915: my $identifier = &get_cgi_id();
12916: my $id = 'cgi.'.$identifier;
12917: if (! @Values || ref($Values[0]) ne 'ARRAY') {
12918: return '';
12919: }
12920: #
12921: my @Labels;
12922: if (defined($labels)) {
12923: @Labels = @$labels;
12924: } else {
12925: for (my $i=0;$i<@{$Values[0]};$i++) {
12926: push (@Labels,$i+1);
12927: }
12928: }
12929: #
12930: my $NumBars = scalar(@{$Values[0]});
12931: if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
12932: my %ValuesHash;
12933: my $NumSets=1;
12934: foreach my $array (@Values) {
12935: next if (! ref($array));
12936: $ValuesHash{$id.'.data.'.$NumSets++} =
12937: join(',',@$array);
12938: }
12939: #
12940: my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
12941: if ($NumBars < 3) {
12942: $width = 120+$NumBars*32;
12943: $xskip = 1;
12944: $bar_width = 30;
12945: } elsif ($NumBars < 5) {
12946: $width = 120+$NumBars*20;
12947: $xskip = 1;
12948: $bar_width = 20;
12949: } elsif ($NumBars < 10) {
12950: $width = 120+$NumBars*15;
12951: $xskip = 1;
12952: $bar_width = 15;
12953: } elsif ($NumBars <= 25) {
12954: $width = 120+$NumBars*11;
12955: $xskip = 5;
12956: $bar_width = 8;
12957: } elsif ($NumBars <= 50) {
12958: $width = 120+$NumBars*8;
12959: $xskip = 5;
12960: $bar_width = 4;
12961: } else {
12962: $width = 120+$NumBars*8;
12963: $xskip = 5;
12964: $bar_width = 4;
12965: }
12966: #
12967: $Max = 1 if ($Max < 1);
12968: if ( int($Max) < $Max ) {
12969: $Max++;
12970: $Max = int($Max);
12971: }
12972: $Title = '' if (! defined($Title));
12973: $xlabel = '' if (! defined($xlabel));
12974: $ylabel = '' if (! defined($ylabel));
12975: $ValuesHash{$id.'.title'} = &escape($Title);
12976: $ValuesHash{$id.'.xlabel'} = &escape($xlabel);
12977: $ValuesHash{$id.'.ylabel'} = &escape($ylabel);
12978: $ValuesHash{$id.'.y_max_value'} = $Max;
12979: $ValuesHash{$id.'.NumBars'} = $NumBars;
12980: $ValuesHash{$id.'.NumSets'} = $NumSets;
12981: $ValuesHash{$id.'.PlotType'} = 'bar';
12982: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
12983: $ValuesHash{$id.'.height'} = $height;
12984: $ValuesHash{$id.'.width'} = $width;
12985: $ValuesHash{$id.'.xskip'} = $xskip;
12986: $ValuesHash{$id.'.bar_width'} = $bar_width;
12987: $ValuesHash{$id.'.labels'} = join(',',@Labels);
12988: #
12989: # Deal with other parameters
12990: while (my ($key,$value) = each(%$extra_settings)) {
12991: $ValuesHash{$id.'.'.$key} = $value;
12992: }
12993: #
12994: &Apache::lonnet::appenv(\%ValuesHash);
12995: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12996: }
12997:
12998: ############################################################
12999: ############################################################
13000:
13001: =pod
13002:
13003: =item * &DrawXYGraph()
13004:
13005: Facilitates the plotting of data in an XY graph.
13006: Puts plot definition data into the users environment in order for
13007: graph.png to plot it. Returns an <img> tag for the plot.
13008:
13009: Inputs:
13010:
13011: =over 4
13012:
13013: =item $Title: string, the title of the plot
13014:
13015: =item $xlabel: string, text describing the X-axis of the plot
13016:
13017: =item $ylabel: string, text describing the Y-axis of the plot
13018:
13019: =item $Max: scalar, the maximum Y value to use in the plot
13020: If $Max is < any data point, the graph will not be rendered.
13021:
13022: =item $colors: Array ref containing the hex color codes for the data to be
13023: plotted in. If undefined, default values will be used.
13024:
13025: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13026:
13027: =item $Ydata: Array ref containing Array refs.
13028: Each of the contained arrays will be plotted as a separate curve.
13029:
13030: =item %Values: hash indicating or overriding any default values which are
13031: passed to graph.png.
13032: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13033:
13034: =back
13035:
13036: Returns:
13037:
13038: An <img> tag which references graph.png and the appropriate identifying
13039: information for the plot.
13040:
13041: =cut
13042:
13043: ############################################################
13044: ############################################################
13045: sub DrawXYGraph {
13046: my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
13047: #
13048: # Create the identifier for the graph
13049: my $identifier = &get_cgi_id();
13050: my $id = 'cgi.'.$identifier;
13051: #
13052: $Title = '' if (! defined($Title));
13053: $xlabel = '' if (! defined($xlabel));
13054: $ylabel = '' if (! defined($ylabel));
13055: my %ValuesHash =
13056: (
13057: $id.'.title' => &escape($Title),
13058: $id.'.xlabel' => &escape($xlabel),
13059: $id.'.ylabel' => &escape($ylabel),
13060: $id.'.y_max_value'=> $Max,
13061: $id.'.labels' => join(',',@$Xlabels),
13062: $id.'.PlotType' => 'XY',
13063: );
13064: #
13065: if (defined($colors) && ref($colors) eq 'ARRAY') {
13066: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
13067: }
13068: #
13069: if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
13070: return '';
13071: }
13072: my $NumSets=1;
13073: foreach my $array (@{$Ydata}){
13074: next if (! ref($array));
13075: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13076: }
13077: $ValuesHash{$id.'.NumSets'} = $NumSets-1;
13078: #
13079: # Deal with other parameters
13080: while (my ($key,$value) = each(%Values)) {
13081: $ValuesHash{$id.'.'.$key} = $value;
13082: }
13083: #
13084: &Apache::lonnet::appenv(\%ValuesHash);
13085: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13086: }
13087:
13088: ############################################################
13089: ############################################################
13090:
13091: =pod
13092:
13093: =item * &DrawXYYGraph()
13094:
13095: Facilitates the plotting of data in an XY graph with two Y axes.
13096: Puts plot definition data into the users environment in order for
13097: graph.png to plot it. Returns an <img> tag for the plot.
13098:
13099: Inputs:
13100:
13101: =over 4
13102:
13103: =item $Title: string, the title of the plot
13104:
13105: =item $xlabel: string, text describing the X-axis of the plot
13106:
13107: =item $ylabel: string, text describing the Y-axis of the plot
13108:
13109: =item $colors: Array ref containing the hex color codes for the data to be
13110: plotted in. If undefined, default values will be used.
13111:
13112: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13113:
13114: =item $Ydata1: The first data set
13115:
13116: =item $Min1: The minimum value of the left Y-axis
13117:
13118: =item $Max1: The maximum value of the left Y-axis
13119:
13120: =item $Ydata2: The second data set
13121:
13122: =item $Min2: The minimum value of the right Y-axis
13123:
13124: =item $Max2: The maximum value of the left Y-axis
13125:
13126: =item %Values: hash indicating or overriding any default values which are
13127: passed to graph.png.
13128: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13129:
13130: =back
13131:
13132: Returns:
13133:
13134: An <img> tag which references graph.png and the appropriate identifying
13135: information for the plot.
13136:
13137: =cut
13138:
13139: ############################################################
13140: ############################################################
13141: sub DrawXYYGraph {
13142: my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13143: $Ydata2,$Min2,$Max2,%Values)=@_;
13144: #
13145: # Create the identifier for the graph
13146: my $identifier = &get_cgi_id();
13147: my $id = 'cgi.'.$identifier;
13148: #
13149: $Title = '' if (! defined($Title));
13150: $xlabel = '' if (! defined($xlabel));
13151: $ylabel = '' if (! defined($ylabel));
13152: my %ValuesHash =
13153: (
13154: $id.'.title' => &escape($Title),
13155: $id.'.xlabel' => &escape($xlabel),
13156: $id.'.ylabel' => &escape($ylabel),
13157: $id.'.labels' => join(',',@$Xlabels),
13158: $id.'.PlotType' => 'XY',
13159: $id.'.NumSets' => 2,
13160: $id.'.two_axes' => 1,
13161: $id.'.y1_max_value' => $Max1,
13162: $id.'.y1_min_value' => $Min1,
13163: $id.'.y2_max_value' => $Max2,
13164: $id.'.y2_min_value' => $Min2,
13165: );
13166: #
13167: if (defined($colors) && ref($colors) eq 'ARRAY') {
13168: $ValuesHash{$id.'.Colors'} = join(',',@{$colors});
13169: }
13170: #
13171: if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13172: ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13173: return '';
13174: }
13175: my $NumSets=1;
13176: foreach my $array ($Ydata1,$Ydata2){
13177: next if (! ref($array));
13178: $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13179: }
13180: #
13181: # Deal with other parameters
13182: while (my ($key,$value) = each(%Values)) {
13183: $ValuesHash{$id.'.'.$key} = $value;
13184: }
13185: #
13186: &Apache::lonnet::appenv(\%ValuesHash);
13187: return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13188: }
13189:
13190: ############################################################
13191: ############################################################
13192:
13193: =pod
13194:
13195: =back
13196:
13197: =head1 Statistics helper routines?
13198:
13199: Bad place for them but what the hell.
13200:
13201: =over 4
13202:
13203: =item * &chartlink()
13204:
13205: Returns a link to the chart for a specific student.
13206:
13207: Inputs:
13208:
13209: =over 4
13210:
13211: =item $linktext: The text of the link
13212:
13213: =item $sname: The students username
13214:
13215: =item $sdomain: The students domain
13216:
13217: =back
13218:
13219: =back
13220:
13221: =cut
13222:
13223: ############################################################
13224: ############################################################
13225: sub chartlink {
13226: my ($linktext, $sname, $sdomain) = @_;
13227: my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13228: '&SelectedStudent='.&escape($sname.':'.$sdomain).
13229: '&chartoutputmode='.HTML::Entities::encode('html, with all links').
13230: '">'.$linktext.'</a>';
13231: }
13232:
13233: #######################################################
13234: #######################################################
13235:
13236: =pod
13237:
13238: =head1 Course Environment Routines
13239:
13240: =over 4
13241:
13242: =item * &restore_course_settings()
13243:
13244: =item * &store_course_settings()
13245:
13246: Restores/Store indicated form parameters from the course environment.
13247: Will not overwrite existing values of the form parameters.
13248:
13249: Inputs:
13250: a scalar describing the data (e.g. 'chart', 'problem_analysis')
13251:
13252: a hash ref describing the data to be stored. For example:
13253:
13254: %Save_Parameters = ('Status' => 'scalar',
13255: 'chartoutputmode' => 'scalar',
13256: 'chartoutputdata' => 'scalar',
13257: 'Section' => 'array',
13258: 'Group' => 'array',
13259: 'StudentData' => 'array',
13260: 'Maps' => 'array');
13261:
13262: Returns: both routines return nothing
13263:
13264: =back
13265:
13266: =cut
13267:
13268: #######################################################
13269: #######################################################
13270: sub store_course_settings {
13271: return &store_settings($env{'request.course.id'},@_);
13272: }
13273:
13274: sub store_settings {
13275: # save to the environment
13276: # appenv the same items, just to be safe
13277: my $udom = $env{'user.domain'};
13278: my $uname = $env{'user.name'};
13279: my ($context,$prefix,$Settings) = @_;
13280: my %SaveHash;
13281: my %AppHash;
13282: while (my ($setting,$type) = each(%$Settings)) {
13283: my $basename = join('.','internal',$context,$prefix,$setting);
13284: my $envname = 'environment.'.$basename;
13285: if (exists($env{'form.'.$setting})) {
13286: # Save this value away
13287: if ($type eq 'scalar' &&
13288: (! exists($env{$envname}) ||
13289: $env{$envname} ne $env{'form.'.$setting})) {
13290: $SaveHash{$basename} = $env{'form.'.$setting};
13291: $AppHash{$envname} = $env{'form.'.$setting};
13292: } elsif ($type eq 'array') {
13293: my $stored_form;
13294: if (ref($env{'form.'.$setting})) {
13295: $stored_form = join(',',
13296: map {
13297: &escape($_);
13298: } sort(@{$env{'form.'.$setting}}));
13299: } else {
13300: $stored_form =
13301: &escape($env{'form.'.$setting});
13302: }
13303: # Determine if the array contents are the same.
13304: if ($stored_form ne $env{$envname}) {
13305: $SaveHash{$basename} = $stored_form;
13306: $AppHash{$envname} = $stored_form;
13307: }
13308: }
13309: }
13310: }
13311: my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
13312: $udom,$uname);
13313: if ($put_result !~ /^(ok|delayed)/) {
13314: &Apache::lonnet::logthis('unable to save form parameters, '.
13315: 'got error:'.$put_result);
13316: }
13317: # Make sure these settings stick around in this session, too
13318: &Apache::lonnet::appenv(\%AppHash);
13319: return;
13320: }
13321:
13322: sub restore_course_settings {
13323: return &restore_settings($env{'request.course.id'},@_);
13324: }
13325:
13326: sub restore_settings {
13327: my ($context,$prefix,$Settings) = @_;
13328: while (my ($setting,$type) = each(%$Settings)) {
13329: next if (exists($env{'form.'.$setting}));
13330: my $envname = 'environment.internal.'.$context.'.'.$prefix.
13331: '.'.$setting;
13332: if (exists($env{$envname})) {
13333: if ($type eq 'scalar') {
13334: $env{'form.'.$setting} = $env{$envname};
13335: } elsif ($type eq 'array') {
13336: $env{'form.'.$setting} = [
13337: map {
13338: &unescape($_);
13339: } split(',',$env{$envname})
13340: ];
13341: }
13342: }
13343: }
13344: }
13345:
13346: #######################################################
13347: #######################################################
13348:
13349: =pod
13350:
13351: =head1 Domain E-mail Routines
13352:
13353: =over 4
13354:
13355: =item * &build_recipient_list()
13356:
13357: Build recipient lists for following types of e-mail:
13358: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
13359: (d) Help requests, (e) Course requests needing approval, (f) loncapa
13360: module change checking, student/employee ID conflict checks, as
13361: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
13362: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
13363:
13364: Inputs:
13365: defmail (scalar - email address of default recipient),
13366: mailing type (scalar: errormail, packagesmail, helpdeskmail,
13367: requestsmail, updatesmail, or idconflictsmail).
13368:
13369: defdom (domain for which to retrieve configuration settings),
13370:
13371: origmail (scalar - email address of recipient from loncapa.conf,
13372: i.e., predates configuration by DC via domainprefs.pm
13373:
13374: Returns: comma separated list of addresses to which to send e-mail.
13375:
13376: =back
13377:
13378: =cut
13379:
13380: ############################################################
13381: ############################################################
13382: sub build_recipient_list {
13383: my ($defmail,$mailing,$defdom,$origmail) = @_;
13384: my @recipients;
13385: my $otheremails;
13386: my %domconfig =
13387: &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
13388: if (ref($domconfig{'contacts'}) eq 'HASH') {
13389: if (exists($domconfig{'contacts'}{$mailing})) {
13390: if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
13391: my @contacts = ('adminemail','supportemail');
13392: foreach my $item (@contacts) {
13393: if ($domconfig{'contacts'}{$mailing}{$item}) {
13394: my $addr = $domconfig{'contacts'}{$item};
13395: if (!grep(/^\Q$addr\E$/,@recipients)) {
13396: push(@recipients,$addr);
13397: }
13398: }
13399: $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
13400: }
13401: }
13402: } elsif ($origmail ne '') {
13403: push(@recipients,$origmail);
13404: }
13405: } elsif ($origmail ne '') {
13406: push(@recipients,$origmail);
13407: }
13408: if (defined($defmail)) {
13409: if ($defmail ne '') {
13410: push(@recipients,$defmail);
13411: }
13412: }
13413: if ($otheremails) {
13414: my @others;
13415: if ($otheremails =~ /,/) {
13416: @others = split(/,/,$otheremails);
13417: } else {
13418: push(@others,$otheremails);
13419: }
13420: foreach my $addr (@others) {
13421: if (!grep(/^\Q$addr\E$/,@recipients)) {
13422: push(@recipients,$addr);
13423: }
13424: }
13425: }
13426: my $recipientlist = join(',',@recipients);
13427: return $recipientlist;
13428: }
13429:
13430: ############################################################
13431: ############################################################
13432:
13433: =pod
13434:
13435: =head1 Course Catalog Routines
13436:
13437: =over 4
13438:
13439: =item * &gather_categories()
13440:
13441: Converts category definitions - keys of categories hash stored in
13442: coursecategories in configuration.db on the primary library server in a
13443: domain - to an array. Also generates javascript and idx hash used to
13444: generate Domain Coordinator interface for editing Course Categories.
13445:
13446: Inputs:
13447:
13448: categories (reference to hash of category definitions).
13449:
13450: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13451: categories and subcategories).
13452:
13453: idx (reference to hash of counters used in Domain Coordinator interface for
13454: editing Course Categories).
13455:
13456: jsarray (reference to array of categories used to create Javascript arrays for
13457: Domain Coordinator interface for editing Course Categories).
13458:
13459: Returns: nothing
13460:
13461: Side effects: populates cats, idx and jsarray.
13462:
13463: =cut
13464:
13465: sub gather_categories {
13466: my ($categories,$cats,$idx,$jsarray) = @_;
13467: my %counters;
13468: my $num = 0;
13469: foreach my $item (keys(%{$categories})) {
13470: my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
13471: if ($container eq '' && $depth == 0) {
13472: $cats->[$depth][$categories->{$item}] = $cat;
13473: } else {
13474: $cats->[$depth]{$container}[$categories->{$item}] = $cat;
13475: }
13476: my ($escitem,$tail) = split(/:/,$item,2);
13477: if ($counters{$tail} eq '') {
13478: $counters{$tail} = $num;
13479: $num ++;
13480: }
13481: if (ref($idx) eq 'HASH') {
13482: $idx->{$item} = $counters{$tail};
13483: }
13484: if (ref($jsarray) eq 'ARRAY') {
13485: push(@{$jsarray->[$counters{$tail}]},$item);
13486: }
13487: }
13488: return;
13489: }
13490:
13491: =pod
13492:
13493: =item * &extract_categories()
13494:
13495: Used to generate breadcrumb trails for course categories.
13496:
13497: Inputs:
13498:
13499: categories (reference to hash of category definitions).
13500:
13501: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13502: categories and subcategories).
13503:
13504: trails (reference to array of breacrumb trails for each category).
13505:
13506: allitems (reference to hash - key is category key
13507: (format: escaped(name):escaped(parent category):depth in hierarchy).
13508:
13509: idx (reference to hash of counters used in Domain Coordinator interface for
13510: editing Course Categories).
13511:
13512: jsarray (reference to array of categories used to create Javascript arrays for
13513: Domain Coordinator interface for editing Course Categories).
13514:
13515: subcats (reference to hash of arrays containing all subcategories within each
13516: category, -recursive)
13517:
13518: Returns: nothing
13519:
13520: Side effects: populates trails and allitems hash references.
13521:
13522: =cut
13523:
13524: sub extract_categories {
13525: my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
13526: if (ref($categories) eq 'HASH') {
13527: &gather_categories($categories,$cats,$idx,$jsarray);
13528: if (ref($cats->[0]) eq 'ARRAY') {
13529: for (my $i=0; $i<@{$cats->[0]}; $i++) {
13530: my $name = $cats->[0][$i];
13531: my $item = &escape($name).'::0';
13532: my $trailstr;
13533: if ($name eq 'instcode') {
13534: $trailstr = &mt('Official courses (with institutional codes)');
13535: } elsif ($name eq 'communities') {
13536: $trailstr = &mt('Communities');
13537: } else {
13538: $trailstr = $name;
13539: }
13540: if ($allitems->{$item} eq '') {
13541: push(@{$trails},$trailstr);
13542: $allitems->{$item} = scalar(@{$trails})-1;
13543: }
13544: my @parents = ($name);
13545: if (ref($cats->[1]{$name}) eq 'ARRAY') {
13546: for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
13547: my $category = $cats->[1]{$name}[$j];
13548: if (ref($subcats) eq 'HASH') {
13549: push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
13550: }
13551: &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
13552: }
13553: } else {
13554: if (ref($subcats) eq 'HASH') {
13555: $subcats->{$item} = [];
13556: }
13557: }
13558: }
13559: }
13560: }
13561: return;
13562: }
13563:
13564: =pod
13565:
13566: =item * &recurse_categories()
13567:
13568: Recursively used to generate breadcrumb trails for course categories.
13569:
13570: Inputs:
13571:
13572: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13573: categories and subcategories).
13574:
13575: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
13576:
13577: category (current course category, for which breadcrumb trail is being generated).
13578:
13579: trails (reference to array of breadcrumb trails for each category).
13580:
13581: allitems (reference to hash - key is category key
13582: (format: escaped(name):escaped(parent category):depth in hierarchy).
13583:
13584: parents (array containing containers directories for current category,
13585: back to top level).
13586:
13587: Returns: nothing
13588:
13589: Side effects: populates trails and allitems hash references
13590:
13591: =cut
13592:
13593: sub recurse_categories {
13594: my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
13595: my $shallower = $depth - 1;
13596: if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
13597: for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
13598: my $name = $cats->[$depth]{$category}[$k];
13599: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13600: my $trailstr = join(' -> ',(@{$parents},$category));
13601: if ($allitems->{$item} eq '') {
13602: push(@{$trails},$trailstr);
13603: $allitems->{$item} = scalar(@{$trails})-1;
13604: }
13605: my $deeper = $depth+1;
13606: push(@{$parents},$category);
13607: if (ref($subcats) eq 'HASH') {
13608: my $subcat = &escape($name).':'.$category.':'.$depth;
13609: for (my $j=@{$parents}; $j>=0; $j--) {
13610: my $higher;
13611: if ($j > 0) {
13612: $higher = &escape($parents->[$j]).':'.
13613: &escape($parents->[$j-1]).':'.$j;
13614: } else {
13615: $higher = &escape($parents->[$j]).'::'.$j;
13616: }
13617: push(@{$subcats->{$higher}},$subcat);
13618: }
13619: }
13620: &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
13621: $subcats);
13622: pop(@{$parents});
13623: }
13624: } else {
13625: my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13626: my $trailstr = join(' -> ',(@{$parents},$category));
13627: if ($allitems->{$item} eq '') {
13628: push(@{$trails},$trailstr);
13629: $allitems->{$item} = scalar(@{$trails})-1;
13630: }
13631: }
13632: return;
13633: }
13634:
13635: =pod
13636:
13637: =item * &assign_categories_table()
13638:
13639: Create a datatable for display of hierarchical categories in a domain,
13640: with checkboxes to allow a course to be categorized.
13641:
13642: Inputs:
13643:
13644: cathash - reference to hash of categories defined for the domain (from
13645: configuration.db)
13646:
13647: currcat - scalar with an & separated list of categories assigned to a course.
13648:
13649: type - scalar contains course type (Course or Community).
13650:
13651: Returns: $output (markup to be displayed)
13652:
13653: =cut
13654:
13655: sub assign_categories_table {
13656: my ($cathash,$currcat,$type) = @_;
13657: my $output;
13658: if (ref($cathash) eq 'HASH') {
13659: my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
13660: &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
13661: $maxdepth = scalar(@cats);
13662: if (@cats > 0) {
13663: my $itemcount = 0;
13664: if (ref($cats[0]) eq 'ARRAY') {
13665: my @currcategories;
13666: if ($currcat ne '') {
13667: @currcategories = split('&',$currcat);
13668: }
13669: my $table;
13670: for (my $i=0; $i<@{$cats[0]}; $i++) {
13671: my $parent = $cats[0][$i];
13672: next if ($parent eq 'instcode');
13673: if ($type eq 'Community') {
13674: next unless ($parent eq 'communities');
13675: } else {
13676: next if ($parent eq 'communities');
13677: }
13678: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13679: my $item = &escape($parent).'::0';
13680: my $checked = '';
13681: if (@currcategories > 0) {
13682: if (grep(/^\Q$item\E$/,@currcategories)) {
13683: $checked = ' checked="checked"';
13684: }
13685: }
13686: my $parent_title = $parent;
13687: if ($parent eq 'communities') {
13688: $parent_title = &mt('Communities');
13689: }
13690: $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
13691: '<input type="checkbox" name="usecategory" value="'.
13692: $item.'"'.$checked.' />'.$parent_title.'</span>'.
13693: '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
13694: my $depth = 1;
13695: push(@path,$parent);
13696: $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
13697: pop(@path);
13698: $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
13699: $itemcount ++;
13700: }
13701: if ($itemcount) {
13702: $output = &Apache::loncommon::start_data_table().
13703: $table.
13704: &Apache::loncommon::end_data_table();
13705: }
13706: }
13707: }
13708: }
13709: return $output;
13710: }
13711:
13712: =pod
13713:
13714: =item * &assign_category_rows()
13715:
13716: Create a datatable row for display of nested categories in a domain,
13717: with checkboxes to allow a course to be categorized,called recursively.
13718:
13719: Inputs:
13720:
13721: itemcount - track row number for alternating colors
13722:
13723: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13724: categories and subcategories.
13725:
13726: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13727:
13728: parent - parent of current category item
13729:
13730: path - Array containing all categories back up through the hierarchy from the
13731: current category to the top level.
13732:
13733: currcategories - reference to array of current categories assigned to the course
13734:
13735: Returns: $output (markup to be displayed).
13736:
13737: =cut
13738:
13739: sub assign_category_rows {
13740: my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13741: my ($text,$name,$item,$chgstr);
13742: if (ref($cats) eq 'ARRAY') {
13743: my $maxdepth = scalar(@{$cats});
13744: if (ref($cats->[$depth]) eq 'HASH') {
13745: if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13746: my $numchildren = @{$cats->[$depth]{$parent}};
13747: my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13748: $text .= '<td><table class="LC_data_table">';
13749: for (my $j=0; $j<$numchildren; $j++) {
13750: $name = $cats->[$depth]{$parent}[$j];
13751: $item = &escape($name).':'.&escape($parent).':'.$depth;
13752: my $deeper = $depth+1;
13753: my $checked = '';
13754: if (ref($currcategories) eq 'ARRAY') {
13755: if (@{$currcategories} > 0) {
13756: if (grep(/^\Q$item\E$/,@{$currcategories})) {
13757: $checked = ' checked="checked"';
13758: }
13759: }
13760: }
13761: $text .= '<tr><td><span class="LC_nobreak"><label>'.
13762: '<input type="checkbox" name="usecategory" value="'.
13763: $item.'"'.$checked.' />'.$name.'</label></span>'.
13764: '<input type="hidden" name="catname" value="'.$name.'" />'.
13765: '</td><td>';
13766: if (ref($path) eq 'ARRAY') {
13767: push(@{$path},$name);
13768: $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13769: pop(@{$path});
13770: }
13771: $text .= '</td></tr>';
13772: }
13773: $text .= '</table></td>';
13774: }
13775: }
13776: }
13777: return $text;
13778: }
13779:
13780: =pod
13781:
13782: =back
13783:
13784: =cut
13785:
13786: ############################################################
13787: ############################################################
13788:
13789:
13790: sub commit_customrole {
13791: my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
13792: my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
13793: ($start?', '.&mt('starting').' '.localtime($start):'').
13794: ($end?', ending '.localtime($end):'').': <b>'.
13795: &Apache::lonnet::assigncustomrole(
13796: $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
13797: '</b><br />';
13798: return $output;
13799: }
13800:
13801: sub commit_standardrole {
13802: my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
13803: my ($output,$logmsg,$linefeed);
13804: if ($context eq 'auto') {
13805: $linefeed = "\n";
13806: } else {
13807: $linefeed = "<br />\n";
13808: }
13809: if ($three eq 'st') {
13810: my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
13811: $one,$two,$sec,$context,$credits);
13812: if (($result =~ /^error/) || ($result eq 'not_in_class') ||
13813: ($result eq 'unknown_course') || ($result eq 'refused')) {
13814: $output = $logmsg.' '.&mt('Error: ').$result."\n";
13815: } else {
13816: $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
13817: ($start?', '.&mt('starting').' '.localtime($start):'').
13818: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13819: if ($context eq 'auto') {
13820: $output .= $result.$linefeed.&mt('Add to classlist').': ok';
13821: } else {
13822: $output .= '<b>'.$result.'</b>'.$linefeed.
13823: &mt('Add to classlist').': <b>ok</b>';
13824: }
13825: $output .= $linefeed;
13826: }
13827: } else {
13828: $output = &mt('Assigning').' '.$three.' in '.$url.
13829: ($start?', '.&mt('starting').' '.localtime($start):'').
13830: ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13831: my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
13832: if ($context eq 'auto') {
13833: $output .= $result.$linefeed;
13834: } else {
13835: $output .= '<b>'.$result.'</b>'.$linefeed;
13836: }
13837: }
13838: return $output;
13839: }
13840:
13841: sub commit_studentrole {
13842: my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
13843: $credits) = @_;
13844: my ($result,$linefeed,$oldsecurl,$newsecurl);
13845: if ($context eq 'auto') {
13846: $linefeed = "\n";
13847: } else {
13848: $linefeed = '<br />'."\n";
13849: }
13850: if (defined($one) && defined($two)) {
13851: my $cid=$one.'_'.$two;
13852: my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
13853: my $secchange = 0;
13854: my $expire_role_result;
13855: my $modify_section_result;
13856: if ($oldsec ne '-1') {
13857: if ($oldsec ne $sec) {
13858: $secchange = 1;
13859: my $now = time;
13860: my $uurl='/'.$cid;
13861: $uurl=~s/\_/\//g;
13862: if ($oldsec) {
13863: $uurl.='/'.$oldsec;
13864: }
13865: $oldsecurl = $uurl;
13866: $expire_role_result =
13867: &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
13868: if ($env{'request.course.sec'} ne '') {
13869: if ($expire_role_result eq 'refused') {
13870: my @roles = ('st');
13871: my @statuses = ('previous');
13872: my @roledoms = ($one);
13873: my $withsec = 1;
13874: my %roleshash =
13875: &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
13876: \@statuses,\@roles,\@roledoms,$withsec);
13877: if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
13878: my ($oldstart,$oldend) =
13879: split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
13880: if ($oldend > 0 && $oldend <= $now) {
13881: $expire_role_result = 'ok';
13882: }
13883: }
13884: }
13885: }
13886: $result = $expire_role_result;
13887: }
13888: }
13889: if (($expire_role_result eq 'ok') || ($secchange == 0)) {
13890: $modify_section_result =
13891: &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
13892: undef,undef,undef,$sec,
13893: $end,$start,'','',$cid,
13894: '',$context,$credits);
13895: if ($modify_section_result =~ /^ok/) {
13896: if ($secchange == 1) {
13897: if ($sec eq '') {
13898: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
13899: } else {
13900: $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
13901: }
13902: } elsif ($oldsec eq '-1') {
13903: if ($sec eq '') {
13904: $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
13905: } else {
13906: $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13907: }
13908: } else {
13909: if ($sec eq '') {
13910: $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
13911: } else {
13912: $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13913: }
13914: }
13915: } else {
13916: if ($secchange) {
13917: $$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;
13918: } else {
13919: $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
13920: }
13921: }
13922: $result = $modify_section_result;
13923: } elsif ($secchange == 1) {
13924: if ($oldsec eq '') {
13925: $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
13926: } else {
13927: $$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;
13928: }
13929: if ($expire_role_result eq 'refused') {
13930: my $newsecurl = '/'.$cid;
13931: $newsecurl =~ s/\_/\//g;
13932: if ($sec ne '') {
13933: $newsecurl.='/'.$sec;
13934: }
13935: if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
13936: if ($sec eq '') {
13937: $$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;
13938: } else {
13939: $$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;
13940: }
13941: }
13942: }
13943: }
13944: } else {
13945: $$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;
13946: $result = "error: incomplete course id\n";
13947: }
13948: return $result;
13949: }
13950:
13951: sub show_role_extent {
13952: my ($scope,$context,$role) = @_;
13953: $scope =~ s{^/}{};
13954: my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
13955: push(@courseroles,'co');
13956: my @authorroles = &Apache::lonuserutils::roles_by_context('author');
13957: if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
13958: $scope =~ s{/}{_};
13959: return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
13960: } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
13961: my ($audom,$auname) = split(/\//,$scope);
13962: return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
13963: &Apache::loncommon::plainname($auname,$audom).'</span>');
13964: } else {
13965: $scope =~ s{/$}{};
13966: return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
13967: &Apache::lonnet::domain($scope,'description').'</span>');
13968: }
13969: }
13970:
13971: ############################################################
13972: ############################################################
13973:
13974: sub check_clone {
13975: my ($args,$linefeed) = @_;
13976: my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
13977: my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
13978: my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
13979: my $clonemsg;
13980: my $can_clone = 0;
13981: my $lctype = lc($args->{'crstype'});
13982: if ($lctype ne 'community') {
13983: $lctype = 'course';
13984: }
13985: if ($clonehome eq 'no_host') {
13986: if ($args->{'crstype'} eq 'Community') {
13987: $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'});
13988: } else {
13989: $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'});
13990: }
13991: } else {
13992: my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
13993: if ($args->{'crstype'} eq 'Community') {
13994: if ($clonedesc{'type'} ne 'Community') {
13995: $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'});
13996: return ($can_clone, $clonemsg, $cloneid, $clonehome);
13997: }
13998: }
13999: if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
14000: (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
14001: $can_clone = 1;
14002: } else {
14003: my %clonehash = &Apache::lonnet::get('environment',['cloners'],
14004: $args->{'clonedomain'},$args->{'clonecourse'});
14005: my @cloners = split(/,/,$clonehash{'cloners'});
14006: if (grep(/^\*$/,@cloners)) {
14007: $can_clone = 1;
14008: } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14009: $can_clone = 1;
14010: } else {
14011: my $ccrole = 'cc';
14012: if ($args->{'crstype'} eq 'Community') {
14013: $ccrole = 'co';
14014: }
14015: my %roleshash =
14016: &Apache::lonnet::get_my_roles($args->{'ccuname'},
14017: $args->{'ccdomain'},
14018: 'userroles',['active'],[$ccrole],
14019: [$args->{'clonedomain'}]);
14020: if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
14021: $can_clone = 1;
14022: } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
14023: $can_clone = 1;
14024: } else {
14025: if ($args->{'crstype'} eq 'Community') {
14026: $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'});
14027: } else {
14028: $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'});
14029: }
14030: }
14031: }
14032: }
14033: }
14034: return ($can_clone, $clonemsg, $cloneid, $clonehome);
14035: }
14036:
14037: sub construct_course {
14038: my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
14039: my $outcome;
14040: my $linefeed = '<br />'."\n";
14041: if ($context eq 'auto') {
14042: $linefeed = "\n";
14043: }
14044:
14045: #
14046: # Are we cloning?
14047: #
14048: my ($can_clone, $clonemsg, $cloneid, $clonehome);
14049: if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
14050: ($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
14051: if ($context ne 'auto') {
14052: if ($clonemsg ne '') {
14053: $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
14054: }
14055: }
14056: $outcome .= $clonemsg.$linefeed;
14057:
14058: if (!$can_clone) {
14059: return (0,$outcome);
14060: }
14061: }
14062:
14063: #
14064: # Open course
14065: #
14066: my $crstype = lc($args->{'crstype'});
14067: my %cenv=();
14068: $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
14069: $args->{'cdescr'},
14070: $args->{'curl'},
14071: $args->{'course_home'},
14072: $args->{'nonstandard'},
14073: $args->{'crscode'},
14074: $args->{'ccuname'}.':'.
14075: $args->{'ccdomain'},
14076: $args->{'crstype'},
14077: $cnum,$context,$category);
14078:
14079: # Note: The testing routines depend on this being output; see
14080: # Utils::Course. This needs to at least be output as a comment
14081: # if anyone ever decides to not show this, and Utils::Course::new
14082: # will need to be suitably modified.
14083: $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
14084: if ($$courseid =~ /^error:/) {
14085: return (0,$outcome);
14086: }
14087:
14088: #
14089: # Check if created correctly
14090: #
14091: ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
14092: my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
14093: if ($crsuhome eq 'no_host') {
14094: $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
14095: return (0,$outcome);
14096: }
14097: $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
14098:
14099: #
14100: # Do the cloning
14101: #
14102: if ($can_clone && $cloneid) {
14103: $clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
14104: if ($context ne 'auto') {
14105: $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
14106: }
14107: $outcome .= $clonemsg.$linefeed;
14108: my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
14109: # Copy all files
14110: &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
14111: # Restore URL
14112: $cenv{'url'}=$oldcenv{'url'};
14113: # Restore title
14114: $cenv{'description'}=$oldcenv{'description'};
14115: # Restore creation date, creator and creation context.
14116: $cenv{'internal.created'}=$oldcenv{'internal.created'};
14117: $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
14118: $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
14119: # Mark as cloned
14120: $cenv{'clonedfrom'}=$cloneid;
14121: # Need to clone grading mode
14122: my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
14123: $cenv{'grading'}=$newenv{'grading'};
14124: # Do not clone these environment entries
14125: &Apache::lonnet::del('environment',
14126: ['default_enrollment_start_date',
14127: 'default_enrollment_end_date',
14128: 'question.email',
14129: 'policy.email',
14130: 'comment.email',
14131: 'pch.users.denied',
14132: 'plc.users.denied',
14133: 'hidefromcat',
14134: 'checkforpriv',
14135: 'categories',
14136: 'internal.uniquecode'],
14137: $$crsudom,$$crsunum);
14138: if ($args->{'textbook'}) {
14139: $cenv{'internal.textbook'} = $args->{'textbook'};
14140: }
14141: }
14142:
14143: #
14144: # Set environment (will override cloned, if existing)
14145: #
14146: my @sections = ();
14147: my @xlists = ();
14148: if ($args->{'crstype'}) {
14149: $cenv{'type'}=$args->{'crstype'};
14150: }
14151: if ($args->{'crsid'}) {
14152: $cenv{'courseid'}=$args->{'crsid'};
14153: }
14154: if ($args->{'crscode'}) {
14155: $cenv{'internal.coursecode'}=$args->{'crscode'};
14156: }
14157: if ($args->{'crsquota'} ne '') {
14158: $cenv{'internal.coursequota'}=$args->{'crsquota'};
14159: } else {
14160: $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
14161: }
14162: if ($args->{'ccuname'}) {
14163: $cenv{'internal.courseowner'} = $args->{'ccuname'}.
14164: ':'.$args->{'ccdomain'};
14165: } else {
14166: $cenv{'internal.courseowner'} = $args->{'curruser'};
14167: }
14168: if ($args->{'defaultcredits'}) {
14169: $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
14170: }
14171: my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
14172: if ($args->{'crssections'}) {
14173: $cenv{'internal.sectionnums'} = '';
14174: if ($args->{'crssections'} =~ m/,/) {
14175: @sections = split/,/,$args->{'crssections'};
14176: } else {
14177: $sections[0] = $args->{'crssections'};
14178: }
14179: if (@sections > 0) {
14180: foreach my $item (@sections) {
14181: my ($sec,$gp) = split/:/,$item;
14182: my $class = $args->{'crscode'}.$sec;
14183: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
14184: $cenv{'internal.sectionnums'} .= $item.',';
14185: unless ($addcheck eq 'ok') {
14186: push @badclasses, $class;
14187: }
14188: }
14189: $cenv{'internal.sectionnums'} =~ s/,$//;
14190: }
14191: }
14192: # do not hide course coordinator from staff listing,
14193: # even if privileged
14194: $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14195: # add course coordinator's domain to domains to check for privileged users
14196: # if different to course domain
14197: if ($$crsudom ne $args->{'ccdomain'}) {
14198: $cenv{'checkforpriv'} = $args->{'ccdomain'};
14199: }
14200: # add crosslistings
14201: if ($args->{'crsxlist'}) {
14202: $cenv{'internal.crosslistings'}='';
14203: if ($args->{'crsxlist'} =~ m/,/) {
14204: @xlists = split/,/,$args->{'crsxlist'};
14205: } else {
14206: $xlists[0] = $args->{'crsxlist'};
14207: }
14208: if (@xlists > 0) {
14209: foreach my $item (@xlists) {
14210: my ($xl,$gp) = split/:/,$item;
14211: my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
14212: $cenv{'internal.crosslistings'} .= $item.',';
14213: unless ($addcheck eq 'ok') {
14214: push @badclasses, $xl;
14215: }
14216: }
14217: $cenv{'internal.crosslistings'} =~ s/,$//;
14218: }
14219: }
14220: if ($args->{'autoadds'}) {
14221: $cenv{'internal.autoadds'}=$args->{'autoadds'};
14222: }
14223: if ($args->{'autodrops'}) {
14224: $cenv{'internal.autodrops'}=$args->{'autodrops'};
14225: }
14226: # check for notification of enrollment changes
14227: my @notified = ();
14228: if ($args->{'notify_owner'}) {
14229: if ($args->{'ccuname'} ne '') {
14230: push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
14231: }
14232: }
14233: if ($args->{'notify_dc'}) {
14234: if ($uname ne '') {
14235: push(@notified,$uname.':'.$udom);
14236: }
14237: }
14238: if (@notified > 0) {
14239: my $notifylist;
14240: if (@notified > 1) {
14241: $notifylist = join(',',@notified);
14242: } else {
14243: $notifylist = $notified[0];
14244: }
14245: $cenv{'internal.notifylist'} = $notifylist;
14246: }
14247: if (@badclasses > 0) {
14248: my %lt=&Apache::lonlocal::texthash(
14249: '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',
14250: 'dnhr' => 'does not have rights to access enrollment in these classes',
14251: 'adby' => 'as determined by the policies of your institution on access to official classlists'
14252: );
14253: my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
14254: ' ('.$lt{'adby'}.')';
14255: if ($context eq 'auto') {
14256: $outcome .= $badclass_msg.$linefeed;
14257: $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
14258: foreach my $item (@badclasses) {
14259: if ($context eq 'auto') {
14260: $outcome .= " - $item\n";
14261: } else {
14262: $outcome .= "<li>$item</li>\n";
14263: }
14264: }
14265: if ($context eq 'auto') {
14266: $outcome .= $linefeed;
14267: } else {
14268: $outcome .= "</ul><br /><br /></div>\n";
14269: }
14270: }
14271: }
14272: if ($args->{'no_end_date'}) {
14273: $args->{'endaccess'} = 0;
14274: }
14275: $cenv{'internal.autostart'}=$args->{'enrollstart'};
14276: $cenv{'internal.autoend'}=$args->{'enrollend'};
14277: $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
14278: $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
14279: if ($args->{'showphotos'}) {
14280: $cenv{'internal.showphotos'}=$args->{'showphotos'};
14281: }
14282: $cenv{'internal.authtype'} = $args->{'authtype'};
14283: $cenv{'internal.autharg'} = $args->{'autharg'};
14284: if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
14285: if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'} eq '') {
14286: 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');
14287: if ($context eq 'auto') {
14288: $outcome .= $krb_msg;
14289: } else {
14290: $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
14291: }
14292: $outcome .= $linefeed;
14293: }
14294: }
14295: if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
14296: if ($args->{'setpolicy'}) {
14297: $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14298: }
14299: if ($args->{'setcontent'}) {
14300: $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14301: }
14302: }
14303: if ($args->{'reshome'}) {
14304: $cenv{'reshome'}=$args->{'reshome'}.'/';
14305: $cenv{'reshome'}=~s/\/+$/\//;
14306: }
14307: #
14308: # course has keyed access
14309: #
14310: if ($args->{'setkeys'}) {
14311: $cenv{'keyaccess'}='yes';
14312: }
14313: # if specified, key authority is not course, but user
14314: # only active if keyaccess is yes
14315: if ($args->{'keyauth'}) {
14316: my ($user,$domain) = split(':',$args->{'keyauth'});
14317: $user = &LONCAPA::clean_username($user);
14318: $domain = &LONCAPA::clean_username($domain);
14319: if ($user ne '' && $domain ne '') {
14320: $cenv{'keyauth'}=$user.':'.$domain;
14321: }
14322: }
14323:
14324: #
14325: # generate and store uniquecode (available to course requester), if course should have one.
14326: #
14327: if ($args->{'uniquecode'}) {
14328: my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
14329: if ($code) {
14330: $cenv{'internal.uniquecode'} = $code;
14331: my %crsinfo =
14332: &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
14333: if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
14334: $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
14335: my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
14336: }
14337: if (ref($coderef)) {
14338: $$coderef = $code;
14339: }
14340: }
14341: }
14342:
14343: if ($args->{'disresdis'}) {
14344: $cenv{'pch.roles.denied'}='st';
14345: }
14346: if ($args->{'disablechat'}) {
14347: $cenv{'plc.roles.denied'}='st';
14348: }
14349:
14350: # Record we've not yet viewed the Course Initialization Helper for this
14351: # course
14352: $cenv{'course.helper.not.run'} = 1;
14353: #
14354: # Use new Randomseed
14355: #
14356: $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
14357: $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
14358: #
14359: # The encryption code and receipt prefix for this course
14360: #
14361: $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
14362: $cenv{'internal.encpref'}=100+int(9*rand(99));
14363: #
14364: # By default, use standard grading
14365: if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
14366:
14367: $outcome .= $linefeed.&mt('Setting environment').': '.
14368: &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
14369: #
14370: # Open all assignments
14371: #
14372: if ($args->{'openall'}) {
14373: my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
14374: my %storecontent = ($storeunder => time,
14375: $storeunder.'.type' => 'date_start');
14376:
14377: $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
14378: ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
14379: }
14380: #
14381: # Set first page
14382: #
14383: unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
14384: || ($cloneid)) {
14385: use LONCAPA::map;
14386: $outcome .= &mt('Setting first resource').': ';
14387:
14388: my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
14389: my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
14390:
14391: $outcome .= ($fatal?$errtext:'read ok').' - ';
14392: my $title; my $url;
14393: if ($args->{'firstres'} eq 'syl') {
14394: $title=&mt('Syllabus');
14395: $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
14396: } else {
14397: $title=&mt('Table of Contents');
14398: $url='/adm/navmaps';
14399: }
14400:
14401: $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
14402: (my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
14403:
14404: if ($errtext) { $fatal=2; }
14405: $outcome .= ($fatal?$errtext:'write ok').$linefeed;
14406: }
14407:
14408: return (1,$outcome);
14409: }
14410:
14411: sub make_unique_code {
14412: my ($cdom,$cnum) = @_;
14413: # get lock on uniquecodes db
14414: my $lockhash = {
14415: $cnum."\0".'uniquecodes' => $env{'user.name'}.
14416: ':'.$env{'user.domain'},
14417: };
14418: my $tries = 0;
14419: my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14420: my ($code,$error);
14421:
14422: while (($gotlock ne 'ok') && ($tries<3)) {
14423: $tries ++;
14424: sleep 1;
14425: $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14426: }
14427: if ($gotlock eq 'ok') {
14428: my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
14429: my $gotcode;
14430: my $attempts = 0;
14431: while ((!$gotcode) && ($attempts < 100)) {
14432: $code = &generate_code();
14433: if (!exists($currcodes{$code})) {
14434: $gotcode = 1;
14435: unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
14436: $error = 'nostore';
14437: }
14438: }
14439: $attempts ++;
14440: }
14441: my @del_lock = ($cnum."\0".'uniquecodes');
14442: my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
14443: } else {
14444: $error = 'nolock';
14445: }
14446: return ($code,$error);
14447: }
14448:
14449: sub generate_code {
14450: my $code;
14451: my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
14452: for (my $i=0; $i<6; $i++) {
14453: my $lettnum = int (rand 2);
14454: my $item = '';
14455: if ($lettnum) {
14456: $item = $letts[int( rand(18) )];
14457: } else {
14458: $item = 1+int( rand(8) );
14459: }
14460: $code .= $item;
14461: }
14462: return $code;
14463: }
14464:
14465: ############################################################
14466: ############################################################
14467:
14468: #SD
14469: # only Community and Course, or anything else?
14470: sub course_type {
14471: my ($cid) = @_;
14472: if (!defined($cid)) {
14473: $cid = $env{'request.course.id'};
14474: }
14475: if (defined($env{'course.'.$cid.'.type'})) {
14476: return $env{'course.'.$cid.'.type'};
14477: } else {
14478: return 'Course';
14479: }
14480: }
14481:
14482: sub group_term {
14483: my $crstype = &course_type();
14484: my %names = (
14485: 'Course' => 'group',
14486: 'Community' => 'group',
14487: );
14488: return $names{$crstype};
14489: }
14490:
14491: sub course_types {
14492: my @types = ('official','unofficial','community','textbook');
14493: my %typename = (
14494: official => 'Official course',
14495: unofficial => 'Unofficial course',
14496: community => 'Community',
14497: textbook => 'Textbook course',
14498: );
14499: return (\@types,\%typename);
14500: }
14501:
14502: sub icon {
14503: my ($file)=@_;
14504: my $curfext = lc((split(/\./,$file))[-1]);
14505: my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
14506: my $embstyle = &Apache::loncommon::fileembstyle($curfext);
14507: if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
14508: if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
14509: $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14510: $curfext.".gif") {
14511: $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14512: $curfext.".gif";
14513: }
14514: }
14515: return &lonhttpdurl($iconname);
14516: }
14517:
14518: sub lonhttpdurl {
14519: #
14520: # Had been used for "small fry" static images on separate port 8080.
14521: # Modify here if lightweight http functionality desired again.
14522: # Currently eliminated due to increasing firewall issues.
14523: #
14524: my ($url)=@_;
14525: return $url;
14526: }
14527:
14528: sub connection_aborted {
14529: my ($r)=@_;
14530: $r->print(" ");$r->rflush();
14531: my $c = $r->connection;
14532: return $c->aborted();
14533: }
14534:
14535: # Escapes strings that may have embedded 's that will be put into
14536: # strings as 'strings'.
14537: sub escape_single {
14538: my ($input) = @_;
14539: $input =~ s/\\/\\\\/g; # Escape the \'s..(must be first)>
14540: $input =~ s/\'/\\\'/g; # Esacpe the 's....
14541: return $input;
14542: }
14543:
14544: # Same as escape_single, but escape's "'s This
14545: # can be used for "strings"
14546: sub escape_double {
14547: my ($input) = @_;
14548: $input =~ s/\\/\\\\/g; # Escape the /'s..(must be first)>
14549: $input =~ s/\"/\\\"/g; # Esacpe the "s....
14550: return $input;
14551: }
14552:
14553: # Escapes the last element of a full URL.
14554: sub escape_url {
14555: my ($url) = @_;
14556: my @urlslices = split(/\//, $url,-1);
14557: my $lastitem = &escape(pop(@urlslices));
14558: return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
14559: }
14560:
14561: sub compare_arrays {
14562: my ($arrayref1,$arrayref2) = @_;
14563: my (@difference,%count);
14564: @difference = ();
14565: %count = ();
14566: if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
14567: foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
14568: foreach my $element (keys(%count)) {
14569: if ($count{$element} == 1) {
14570: push(@difference,$element);
14571: }
14572: }
14573: }
14574: return @difference;
14575: }
14576:
14577: # -------------------------------------------------------- Initialize user login
14578: sub init_user_environment {
14579: my ($r, $username, $domain, $authhost, $form, $args) = @_;
14580: my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
14581:
14582: my $public=($username eq 'public' && $domain eq 'public');
14583:
14584: # See if old ID present, if so, remove
14585:
14586: my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
14587: my $now=time;
14588:
14589: if ($public) {
14590: my $max_public=100;
14591: my $oldest;
14592: my $oldest_time=0;
14593: for(my $next=1;$next<=$max_public;$next++) {
14594: if (-e $lonids."/publicuser_$next.id") {
14595: my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
14596: if ($mtime<$oldest_time || !$oldest_time) {
14597: $oldest_time=$mtime;
14598: $oldest=$next;
14599: }
14600: } else {
14601: $cookie="publicuser_$next";
14602: last;
14603: }
14604: }
14605: if (!$cookie) { $cookie="publicuser_$oldest"; }
14606: } else {
14607: # if this isn't a robot, kill any existing non-robot sessions
14608: if (!$args->{'robot'}) {
14609: opendir(DIR,$lonids);
14610: while ($filename=readdir(DIR)) {
14611: if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
14612: unlink($lonids.'/'.$filename);
14613: }
14614: }
14615: closedir(DIR);
14616: }
14617: # Give them a new cookie
14618: my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
14619: : $now.$$.int(rand(10000)));
14620: $cookie="$username\_$id\_$domain\_$authhost";
14621:
14622: # Initialize roles
14623:
14624: ($userroles,$firstaccenv,$timerintenv) =
14625: &Apache::lonnet::rolesinit($domain,$username,$authhost);
14626: }
14627: # ------------------------------------ Check browser type and MathML capability
14628:
14629: my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
14630: $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
14631:
14632: # ------------------------------------------------------------- Get environment
14633:
14634: my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
14635: my ($tmp) = keys(%userenv);
14636: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14637: } else {
14638: undef(%userenv);
14639: }
14640: if (($userenv{'interface'}) && (!$form->{'interface'})) {
14641: $form->{'interface'}=$userenv{'interface'};
14642: }
14643: if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
14644:
14645: # --------------- Do not trust query string to be put directly into environment
14646: foreach my $option ('interface','localpath','localres') {
14647: $form->{$option}=~s/[\n\r\=]//gs;
14648: }
14649: # --------------------------------------------------------- Write first profile
14650:
14651: {
14652: my %initial_env =
14653: ("user.name" => $username,
14654: "user.domain" => $domain,
14655: "user.home" => $authhost,
14656: "browser.type" => $clientbrowser,
14657: "browser.version" => $clientversion,
14658: "browser.mathml" => $clientmathml,
14659: "browser.unicode" => $clientunicode,
14660: "browser.os" => $clientos,
14661: "browser.mobile" => $clientmobile,
14662: "browser.info" => $clientinfo,
14663: "browser.osversion" => $clientosversion,
14664: "server.domain" => $Apache::lonnet::perlvar{'lonDefDomain'},
14665: "request.course.fn" => '',
14666: "request.course.uri" => '',
14667: "request.course.sec" => '',
14668: "request.role" => 'cm',
14669: "request.role.adv" => $env{'user.adv'},
14670: "request.host" => $ENV{'REMOTE_ADDR'},);
14671:
14672: if ($form->{'localpath'}) {
14673: $initial_env{"browser.localpath"} = $form->{'localpath'};
14674: $initial_env{"browser.localres"} = $form->{'localres'};
14675: }
14676:
14677: if ($form->{'interface'}) {
14678: $form->{'interface'}=~s/\W//gs;
14679: $initial_env{"browser.interface"} = $form->{'interface'};
14680: $env{'browser.interface'}=$form->{'interface'};
14681: }
14682:
14683: if ($form->{'iptoken'}) {
14684: my $lonhost = $r->dir_config('lonHostID');
14685: $initial_env{"user.noloadbalance"} = $lonhost;
14686: $env{'user.noloadbalance'} = $lonhost;
14687: }
14688:
14689: my %is_adv = ( is_adv => $env{'user.adv'} );
14690: my %domdef;
14691: unless ($domain eq 'public') {
14692: %domdef = &Apache::lonnet::get_domain_defaults($domain);
14693: }
14694:
14695: foreach my $tool ('aboutme','blog','webdav','portfolio') {
14696: $userenv{'availabletools.'.$tool} =
14697: &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
14698: undef,\%userenv,\%domdef,\%is_adv);
14699: }
14700:
14701: foreach my $crstype ('official','unofficial','community','textbook') {
14702: $userenv{'canrequest.'.$crstype} =
14703: &Apache::lonnet::usertools_access($username,$domain,$crstype,
14704: 'reload','requestcourses',
14705: \%userenv,\%domdef,\%is_adv);
14706: }
14707:
14708: $userenv{'canrequest.author'} =
14709: &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
14710: 'reload','requestauthor',
14711: \%userenv,\%domdef,\%is_adv);
14712: my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
14713: $domain,$username);
14714: my $reqstatus = $reqauthor{'author_status'};
14715: if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
14716: if (ref($reqauthor{'author'}) eq 'HASH') {
14717: $userenv{'requestauthorqueued'} = $reqstatus.':'.
14718: $reqauthor{'author'}{'timestamp'};
14719: }
14720: }
14721:
14722: $env{'user.environment'} = "$lonids/$cookie.id";
14723:
14724: if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
14725: &GDBM_WRCREAT(),0640)) {
14726: &_add_to_env(\%disk_env,\%initial_env);
14727: &_add_to_env(\%disk_env,\%userenv,'environment.');
14728: &_add_to_env(\%disk_env,$userroles);
14729: if (ref($firstaccenv) eq 'HASH') {
14730: &_add_to_env(\%disk_env,$firstaccenv);
14731: }
14732: if (ref($timerintenv) eq 'HASH') {
14733: &_add_to_env(\%disk_env,$timerintenv);
14734: }
14735: if (ref($args->{'extra_env'})) {
14736: &_add_to_env(\%disk_env,$args->{'extra_env'});
14737: }
14738: untie(%disk_env);
14739: } else {
14740: &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
14741: 'Could not create environment storage in lonauth: '.$!.'</span>');
14742: return 'error: '.$!;
14743: }
14744: }
14745: $env{'request.role'}='cm';
14746: $env{'request.role.adv'}=$env{'user.adv'};
14747: $env{'browser.type'}=$clientbrowser;
14748:
14749: return $cookie;
14750:
14751: }
14752:
14753: sub _add_to_env {
14754: my ($idf,$env_data,$prefix) = @_;
14755: if (ref($env_data) eq 'HASH') {
14756: while (my ($key,$value) = each(%$env_data)) {
14757: $idf->{$prefix.$key} = $value;
14758: $env{$prefix.$key} = $value;
14759: }
14760: }
14761: }
14762:
14763: # --- Get the symbolic name of a problem and the url
14764: sub get_symb {
14765: my ($request,$silent) = @_;
14766: (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
14767: my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
14768: if ($symb eq '') {
14769: if (!$silent) {
14770: if (ref($request)) {
14771: $request->print("Unable to handle ambiguous references:$url:.");
14772: }
14773: return ();
14774: }
14775: }
14776: &Apache::lonenc::check_decrypt(\$symb);
14777: return ($symb);
14778: }
14779:
14780: # --------------------------------------------------------------Get annotation
14781:
14782: sub get_annotation {
14783: my ($symb,$enc) = @_;
14784:
14785: my $key = $symb;
14786: if (!$enc) {
14787: $key =
14788: &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
14789: }
14790: my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
14791: return $annotation{$key};
14792: }
14793:
14794: sub clean_symb {
14795: my ($symb,$delete_enc) = @_;
14796:
14797: &Apache::lonenc::check_decrypt(\$symb);
14798: my $enc = $env{'request.enc'};
14799: if ($delete_enc) {
14800: delete($env{'request.enc'});
14801: }
14802:
14803: return ($symb,$enc);
14804: }
14805:
14806: ############################################################
14807: ############################################################
14808:
14809: =pod
14810:
14811: =head1 Routines for building display used to search for courses
14812:
14813:
14814: =over 4
14815:
14816: =item * &build_filters()
14817:
14818: Create markup for a table used to set filters to use when selecting
14819: courses in a domain. Used by lonpickcourse.pm, lonmodifycourse.pm
14820: and quotacheck.pl
14821:
14822:
14823: Inputs:
14824:
14825: filterlist - anonymous array of fields to include as potential filters
14826:
14827: crstype - course type
14828:
14829: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
14830: to pop-open a course selector (will contain "extra element").
14831:
14832: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
14833:
14834: filter - anonymous hash of criteria and their values
14835:
14836: action - form action
14837:
14838: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
14839:
14840: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
14841:
14842: cloneruname - username of owner of new course who wants to clone
14843:
14844: clonerudom - domain of owner of new course who wants to clone
14845:
14846: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
14847:
14848: codetitlesref - reference to array of titles of components in institutional codes (official courses)
14849:
14850: codedom - domain
14851:
14852: formname - value of form element named "form".
14853:
14854: fixeddom - domain, if fixed.
14855:
14856: prevphase - value to assign to form element named "phase" when going back to the previous screen
14857:
14858: cnameelement - name of form element in form on opener page which will receive title of selected course
14859:
14860: cnumelement - name of form element in form on opener page which will receive courseID of selected course
14861:
14862: cdomelement - name of form element in form on opener page which will receive domain of selected course
14863:
14864: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
14865:
14866: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
14867:
14868: clonewarning - warning message about missing information for intended course owner when DC creates a course
14869:
14870:
14871: Returns: $output - HTML for display of search criteria, and hidden form elements.
14872:
14873:
14874: Side Effects: None
14875:
14876: =cut
14877:
14878: # ---------------------------------------------- search for courses based on last activity etc.
14879:
14880: sub build_filters {
14881: my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
14882: $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
14883: $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
14884: $cnameelement,$cnumelement,$cdomelement,$setroles,
14885: $clonetext,$clonewarning) = @_;
14886: my ($list,$jscript);
14887: my $onchange = 'javascript:updateFilters(this)';
14888: my ($domainselectform,$sincefilterform,$createdfilterform,
14889: $ownerdomselectform,$persondomselectform,$instcodeform,
14890: $typeselectform,$instcodetitle);
14891: if ($formname eq '') {
14892: $formname = $caller;
14893: }
14894: foreach my $item (@{$filterlist}) {
14895: unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
14896: ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
14897: if ($item eq 'domainfilter') {
14898: $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
14899: } elsif ($item eq 'coursefilter') {
14900: $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
14901: } elsif ($item eq 'ownerfilter') {
14902: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
14903: } elsif ($item eq 'ownerdomfilter') {
14904: $filter->{'ownerdomfilter'} =
14905: &LONCAPA::clean_domain($filter->{$item});
14906: $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
14907: 'ownerdomfilter',1);
14908: } elsif ($item eq 'personfilter') {
14909: $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
14910: } elsif ($item eq 'persondomfilter') {
14911: $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
14912: 'persondomfilter',1);
14913: } else {
14914: $filter->{$item} =~ s/\W//g;
14915: }
14916: if (!$filter->{$item}) {
14917: $filter->{$item} = '';
14918: }
14919: }
14920: if ($item eq 'domainfilter') {
14921: my $allow_blank = 1;
14922: if ($formname eq 'portform') {
14923: $allow_blank=0;
14924: } elsif ($formname eq 'studentform') {
14925: $allow_blank=0;
14926: }
14927: if ($fixeddom) {
14928: $domainselectform = '<input type="hidden" name="domainfilter"'.
14929: ' value="'.$codedom.'" />'.
14930: &Apache::lonnet::domain($codedom,'description');
14931: } else {
14932: $domainselectform = &select_dom_form($filter->{$item},
14933: 'domainfilter',
14934: $allow_blank,'',$onchange);
14935: }
14936: } else {
14937: $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
14938: }
14939: }
14940:
14941: # last course activity filter and selection
14942: $sincefilterform = &timebased_select_form('sincefilter',$filter);
14943:
14944: # course created filter and selection
14945: if (exists($filter->{'createdfilter'})) {
14946: $createdfilterform = &timebased_select_form('createdfilter',$filter);
14947: }
14948:
14949: my %lt = &Apache::lonlocal::texthash(
14950: 'cac' => "$crstype Activity",
14951: 'ccr' => "$crstype Created",
14952: 'cde' => "$crstype Title",
14953: 'cdo' => "$crstype Domain",
14954: 'ins' => 'Institutional Code',
14955: 'inc' => 'Institutional Categorization',
14956: 'cow' => "$crstype Owner/Co-owner",
14957: 'cop' => "$crstype Personnel Includes",
14958: 'cog' => 'Type',
14959: );
14960:
14961: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
14962: my $typeval = 'Course';
14963: if ($crstype eq 'Community') {
14964: $typeval = 'Community';
14965: }
14966: $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
14967: } else {
14968: $typeselectform = '<select name="type" size="1"';
14969: if ($onchange) {
14970: $typeselectform .= ' onchange="'.$onchange.'"';
14971: }
14972: $typeselectform .= '>'."\n";
14973: foreach my $posstype ('Course','Community') {
14974: $typeselectform.='<option value="'.$posstype.'"'.
14975: ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
14976: }
14977: $typeselectform.="</select>";
14978: }
14979:
14980: my ($cloneableonlyform,$cloneabletitle);
14981: if (exists($filter->{'cloneableonly'})) {
14982: my $cloneableon = '';
14983: my $cloneableoff = ' checked="checked"';
14984: if ($filter->{'cloneableonly'}) {
14985: $cloneableon = $cloneableoff;
14986: $cloneableoff = '';
14987: }
14988: $cloneableonlyform = '<span class="LC_nobreak"><label><input type="radio" name="cloneableonly" value="1" '.$cloneableon.'/> '.&mt('Required').'</label>'.(' 'x3).'<label><input type="radio" name="cloneableonly" value="" '.$cloneableoff.' /> '.&mt('No restriction').'</label></span>';
14989: if ($formname eq 'ccrs') {
14990: $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
14991: } else {
14992: $cloneabletitle = &mt('Cloneable by you');
14993: }
14994: }
14995: my $officialjs;
14996: if ($crstype eq 'Course') {
14997: if (exists($filter->{'instcodefilter'})) {
14998: # if (($fixeddom) || ($formname eq 'requestcrs') ||
14999: # ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
15000: if ($codedom) {
15001: $officialjs = 1;
15002: ($instcodeform,$jscript,$$numtitlesref) =
15003: &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
15004: $officialjs,$codetitlesref);
15005: if ($jscript) {
15006: $jscript = '<script type="text/javascript">'."\n".
15007: '// <![CDATA['."\n".
15008: $jscript."\n".
15009: '// ]]>'."\n".
15010: '</script>'."\n";
15011: }
15012: }
15013: if ($instcodeform eq '') {
15014: $instcodeform =
15015: '<input type="text" name="instcodefilter" size="10" value="'.
15016: $list->{'instcodefilter'}.'" />';
15017: $instcodetitle = $lt{'ins'};
15018: } else {
15019: $instcodetitle = $lt{'inc'};
15020: }
15021: if ($fixeddom) {
15022: $instcodetitle .= '<br />('.$codedom.')';
15023: }
15024: }
15025: }
15026: my $output = qq|
15027: <form method="post" name="filterpicker" action="$action">
15028: <input type="hidden" name="form" value="$formname" />
15029: |;
15030: if ($formname eq 'modifycourse') {
15031: $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
15032: '<input type="hidden" name="prevphase" value="'.
15033: $prevphase.'" />'."\n";
15034: } elsif ($formname eq 'quotacheck') {
15035: $output .= qq|
15036: <input type="hidden" name="sortby" value="" />
15037: <input type="hidden" name="sortorder" value="" />
15038: |;
15039: } else {
15040: my $name_input;
15041: if ($cnameelement ne '') {
15042: $name_input = '<input type="hidden" name="cnameelement" value="'.
15043: $cnameelement.'" />';
15044: }
15045: $output .= qq|
15046: <input type="hidden" name="cnumelement" value="$cnumelement" />
15047: <input type="hidden" name="cdomelement" value="$cdomelement" />
15048: $name_input
15049: $roleelement
15050: $multelement
15051: $typeelement
15052: |;
15053: if ($formname eq 'portform') {
15054: $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
15055: }
15056: }
15057: if ($fixeddom) {
15058: $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
15059: }
15060: $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
15061: if ($sincefilterform) {
15062: $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
15063: .$sincefilterform
15064: .&Apache::lonhtmlcommon::row_closure();
15065: }
15066: if ($createdfilterform) {
15067: $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
15068: .$createdfilterform
15069: .&Apache::lonhtmlcommon::row_closure();
15070: }
15071: if ($domainselectform) {
15072: $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
15073: .$domainselectform
15074: .&Apache::lonhtmlcommon::row_closure();
15075: }
15076: if ($typeselectform) {
15077: if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15078: $output .= $typeselectform;
15079: } else {
15080: $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
15081: .$typeselectform
15082: .&Apache::lonhtmlcommon::row_closure();
15083: }
15084: }
15085: if ($instcodeform) {
15086: $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
15087: .$instcodeform
15088: .&Apache::lonhtmlcommon::row_closure();
15089: }
15090: if (exists($filter->{'ownerfilter'})) {
15091: $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
15092: '<table><tr><td>'.&mt('Username').'<br />'.
15093: '<input type="text" name="ownerfilter" size="20" value="'.
15094: $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
15095: $ownerdomselectform.'</td></tr></table>'.
15096: &Apache::lonhtmlcommon::row_closure();
15097: }
15098: if (exists($filter->{'personfilter'})) {
15099: $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
15100: '<table><tr><td>'.&mt('Username').'<br />'.
15101: '<input type="text" name="personfilter" size="20" value="'.
15102: $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
15103: $persondomselectform.'</td></tr></table>'.
15104: &Apache::lonhtmlcommon::row_closure();
15105: }
15106: if (exists($filter->{'coursefilter'})) {
15107: $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
15108: .'<input type="text" name="coursefilter" size="25" value="'
15109: .$list->{'coursefilter'}.'" />'
15110: .&Apache::lonhtmlcommon::row_closure();
15111: }
15112: if ($cloneableonlyform) {
15113: $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
15114: $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
15115: }
15116: if (exists($filter->{'descriptfilter'})) {
15117: $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
15118: .'<input type="text" name="descriptfilter" size="40" value="'
15119: .$list->{'descriptfilter'}.'" />'
15120: .&Apache::lonhtmlcommon::row_closure(1);
15121: }
15122: $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
15123: '<input type="hidden" name="updater" value="" />'."\n".
15124: '<input type="submit" name="gosearch" value="'.
15125: &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
15126: return $jscript.$clonewarning.$output;
15127: }
15128:
15129: =pod
15130:
15131: =item * &timebased_select_form()
15132:
15133: Create markup for a dropdown list used to select a time-based
15134: filter e.g., Course Activity, Course Created, when searching for courses
15135: or communities
15136:
15137: Inputs:
15138:
15139: item - name of form element (sincefilter or createdfilter)
15140:
15141: filter - anonymous hash of criteria and their values
15142:
15143: Returns: HTML for a select box contained a blank, then six time selections,
15144: with value set in incoming form variables currently selected.
15145:
15146: Side Effects: None
15147:
15148: =cut
15149:
15150: sub timebased_select_form {
15151: my ($item,$filter) = @_;
15152: if (ref($filter) eq 'HASH') {
15153: $filter->{$item} =~ s/[^\d-]//g;
15154: if (!$filter->{$item}) { $filter->{$item}=-1; }
15155: return &select_form(
15156: $filter->{$item},
15157: $item,
15158: { '-1' => '',
15159: '86400' => &mt('today'),
15160: '604800' => &mt('last week'),
15161: '2592000' => &mt('last month'),
15162: '7776000' => &mt('last three months'),
15163: '15552000' => &mt('last six months'),
15164: '31104000' => &mt('last year'),
15165: 'select_form_order' =>
15166: ['-1','86400','604800','2592000','7776000',
15167: '15552000','31104000']});
15168: }
15169: }
15170:
15171: =pod
15172:
15173: =item * &js_changer()
15174:
15175: Create script tag containing Javascript used to submit course search form
15176: when course type or domain is changed, and also to hide 'Searching ...' on
15177: page load completion for page showing search result.
15178:
15179: Inputs: None
15180:
15181: Returns: markup containing updateFilters() and hideSearching() javascript functions.
15182:
15183: Side Effects: None
15184:
15185: =cut
15186:
15187: sub js_changer {
15188: return <<ENDJS;
15189: <script type="text/javascript">
15190: // <![CDATA[
15191: function updateFilters(caller) {
15192: if (typeof(caller) != "undefined") {
15193: document.filterpicker.updater.value = caller.name;
15194: }
15195: document.filterpicker.submit();
15196: }
15197:
15198: function hideSearching() {
15199: if (document.getElementById('searching')) {
15200: document.getElementById('searching').style.display = 'none';
15201: }
15202: return;
15203: }
15204:
15205: // ]]>
15206: </script>
15207:
15208: ENDJS
15209: }
15210:
15211: =pod
15212:
15213: =item * &search_courses()
15214:
15215: Process selected filters form course search form and pass to lonnet::courseiddump
15216: to retrieve a hash for which keys are courseIDs which match the selected filters.
15217:
15218: Inputs:
15219:
15220: dom - domain being searched
15221:
15222: type - course type ('Course' or 'Community' or '.' if any).
15223:
15224: filter - anonymous hash of criteria and their values
15225:
15226: numtitles - for institutional codes - number of categories
15227:
15228: cloneruname - optional username of new course owner
15229:
15230: clonerudom - optional domain of new course owner
15231:
15232: domcloner - Optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
15233: (used when DC is using course creation form)
15234:
15235: codetitles - reference to array of titles of components in institutional codes (official courses).
15236:
15237:
15238: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
15239:
15240:
15241: Side Effects: None
15242:
15243: =cut
15244:
15245:
15246: sub search_courses {
15247: my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles) = @_;
15248: my (%courses,%showcourses,$cloner);
15249: if (($filter->{'ownerfilter'} ne '') ||
15250: ($filter->{'ownerdomfilter'} ne '')) {
15251: $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
15252: $filter->{'ownerdomfilter'};
15253: }
15254: foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
15255: if (!$filter->{$item}) {
15256: $filter->{$item}='.';
15257: }
15258: }
15259: my $now = time;
15260: my $timefilter =
15261: ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
15262: my ($createdbefore,$createdafter);
15263: if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
15264: $createdbefore = $now;
15265: $createdafter = $now-$filter->{'createdfilter'};
15266: }
15267: my ($instcodefilter,$regexpok);
15268: if ($numtitles) {
15269: if ($env{'form.official'} eq 'on') {
15270: $instcodefilter =
15271: &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
15272: $regexpok = 1;
15273: } elsif ($env{'form.official'} eq 'off') {
15274: $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
15275: unless ($instcodefilter eq '') {
15276: $regexpok = -1;
15277: }
15278: }
15279: } else {
15280: $instcodefilter = $filter->{'instcodefilter'};
15281: }
15282: if ($instcodefilter eq '') { $instcodefilter = '.'; }
15283: if ($type eq '') { $type = '.'; }
15284:
15285: if (($clonerudom ne '') && ($cloneruname ne '')) {
15286: $cloner = $cloneruname.':'.$clonerudom;
15287: }
15288: %courses = &Apache::lonnet::courseiddump($dom,
15289: $filter->{'descriptfilter'},
15290: $timefilter,
15291: $instcodefilter,
15292: $filter->{'combownerfilter'},
15293: $filter->{'coursefilter'},
15294: undef,undef,$type,$regexpok,undef,undef,
15295: undef,undef,$cloner,$env{'form.cc_clone'},
15296: $filter->{'cloneableonly'},
15297: $createdbefore,$createdafter,undef,
15298: $domcloner);
15299: if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
15300: my $ccrole;
15301: if ($type eq 'Community') {
15302: $ccrole = 'co';
15303: } else {
15304: $ccrole = 'cc';
15305: }
15306: my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
15307: $filter->{'persondomfilter'},
15308: 'userroles',undef,
15309: [$ccrole,'in','ad','ep','ta','cr'],
15310: $dom);
15311: foreach my $role (keys(%rolehash)) {
15312: my ($cnum,$cdom,$courserole) = split(':',$role);
15313: my $cid = $cdom.'_'.$cnum;
15314: if (exists($courses{$cid})) {
15315: if (ref($courses{$cid}) eq 'HASH') {
15316: if (ref($courses{$cid}{roles}) eq 'ARRAY') {
15317: if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
15318: push (@{$courses{$cid}{roles}},$courserole);
15319: }
15320: } else {
15321: $courses{$cid}{roles} = [$courserole];
15322: }
15323: $showcourses{$cid} = $courses{$cid};
15324: }
15325: }
15326: }
15327: %courses = %showcourses;
15328: }
15329: return %courses;
15330: }
15331:
15332: =pod
15333:
15334: =back
15335:
15336: =cut
15337:
15338:
15339: sub update_content_constraints {
15340: my ($cdom,$cnum,$chome,$cid) = @_;
15341: my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
15342: my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
15343: my %checkresponsetypes;
15344: foreach my $key (keys(%Apache::lonnet::needsrelease)) {
15345: my ($item,$name,$value) = split(/:/,$key);
15346: if ($item eq 'resourcetag') {
15347: if ($name eq 'responsetype') {
15348: $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
15349: }
15350: }
15351: }
15352: my $navmap = Apache::lonnavmaps::navmap->new();
15353: if (defined($navmap)) {
15354: my %allresponses;
15355: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
15356: my %responses = $res->responseTypes();
15357: foreach my $key (keys(%responses)) {
15358: next unless(exists($checkresponsetypes{$key}));
15359: $allresponses{$key} += $responses{$key};
15360: }
15361: }
15362: foreach my $key (keys(%allresponses)) {
15363: my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
15364: if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
15365: ($reqdmajor,$reqdminor) = ($major,$minor);
15366: }
15367: }
15368: undef($navmap);
15369: }
15370: unless (($reqdmajor eq '') && ($reqdminor eq '')) {
15371: &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
15372: }
15373: return;
15374: }
15375:
15376: sub allmaps_incourse {
15377: my ($cdom,$cnum,$chome,$cid) = @_;
15378: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
15379: $cid = $env{'request.course.id'};
15380: $cdom = $env{'course.'.$cid.'.domain'};
15381: $cnum = $env{'course.'.$cid.'.num'};
15382: $chome = $env{'course.'.$cid.'.home'};
15383: }
15384: my %allmaps = ();
15385: my $lastchange =
15386: &Apache::lonnet::get_coursechange($cdom,$cnum);
15387: if ($lastchange > $env{'request.course.tied'}) {
15388: my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
15389: unless ($ferr) {
15390: &update_content_constraints($cdom,$cnum,$chome,$cid);
15391: }
15392: }
15393: my $navmap = Apache::lonnavmaps::navmap->new();
15394: if (defined($navmap)) {
15395: foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
15396: $allmaps{$res->src()} = 1;
15397: }
15398: }
15399: return \%allmaps;
15400: }
15401:
15402: sub parse_supplemental_title {
15403: my ($title) = @_;
15404:
15405: my ($foldertitle,$renametitle);
15406: if ($title =~ /&&&/) {
15407: $title = &HTML::Entites::decode($title);
15408: }
15409: if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
15410: $renametitle=$4;
15411: my ($time,$uname,$udom) = ($1,$2,$3);
15412: $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
15413: my $name = &plainname($uname,$udom);
15414: $name = &HTML::Entities::encode($name,'"<>&\'');
15415: $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
15416: $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
15417: $name.': <br />'.$foldertitle;
15418: }
15419: if (wantarray) {
15420: return ($title,$foldertitle,$renametitle);
15421: }
15422: return $title;
15423: }
15424:
15425: sub recurse_supplemental {
15426: my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
15427: if ($suppmap) {
15428: my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
15429: if ($fatal) {
15430: $errors ++;
15431: } else {
15432: if ($#LONCAPA::map::resources > 0) {
15433: foreach my $res (@LONCAPA::map::resources) {
15434: my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
15435: if (($src ne '') && ($status eq 'res')) {
15436: if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
15437: ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
15438: } else {
15439: $numfiles ++;
15440: }
15441: }
15442: }
15443: }
15444: }
15445: }
15446: return ($numfiles,$errors);
15447: }
15448:
15449: sub symb_to_docspath {
15450: my ($symb) = @_;
15451: return unless ($symb);
15452: my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
15453: if ($resurl=~/\.(sequence|page)$/) {
15454: $mapurl=$resurl;
15455: } elsif ($resurl eq 'adm/navmaps') {
15456: $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
15457: }
15458: my $mapresobj;
15459: my $navmap = Apache::lonnavmaps::navmap->new();
15460: if (ref($navmap)) {
15461: $mapresobj = $navmap->getResourceByUrl($mapurl);
15462: }
15463: $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
15464: my $type=$2;
15465: my $path;
15466: if (ref($mapresobj)) {
15467: my $pcslist = $mapresobj->map_hierarchy();
15468: if ($pcslist ne '') {
15469: foreach my $pc (split(/,/,$pcslist)) {
15470: next if ($pc <= 1);
15471: my $res = $navmap->getByMapPc($pc);
15472: if (ref($res)) {
15473: my $thisurl = $res->src();
15474: $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
15475: my $thistitle = $res->title();
15476: $path .= '&'.
15477: &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
15478: &escape($thistitle).
15479: ':'.$res->randompick().
15480: ':'.$res->randomout().
15481: ':'.$res->encrypted().
15482: ':'.$res->randomorder().
15483: ':'.$res->is_page();
15484: }
15485: }
15486: }
15487: $path =~ s/^\&//;
15488: my $maptitle = $mapresobj->title();
15489: if ($mapurl eq 'default') {
15490: $maptitle = 'Main Content';
15491: }
15492: $path .= (($path ne '')? '&' : '').
15493: &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
15494: &escape($maptitle).
15495: ':'.$mapresobj->randompick().
15496: ':'.$mapresobj->randomout().
15497: ':'.$mapresobj->encrypted().
15498: ':'.$mapresobj->randomorder().
15499: ':'.$mapresobj->is_page();
15500: } else {
15501: my $maptitle = &Apache::lonnet::gettitle($mapurl);
15502: my $ispage = (($type eq 'page')? 1 : '');
15503: if ($mapurl eq 'default') {
15504: $maptitle = 'Main Content';
15505: }
15506: $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
15507: &escape($maptitle).':::::'.$ispage;
15508: }
15509: unless ($mapurl eq 'default') {
15510: $path = 'default&'.
15511: &escape('Main Content').
15512: ':::::&'.$path;
15513: }
15514: return $path;
15515: }
15516:
15517: sub captcha_display {
15518: my ($context,$lonhost) = @_;
15519: my ($output,$error);
15520: my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
15521: if ($captcha eq 'original') {
15522: $output = &create_captcha();
15523: unless ($output) {
15524: $error = 'captcha';
15525: }
15526: } elsif ($captcha eq 'recaptcha') {
15527: $output = &create_recaptcha($pubkey);
15528: unless ($output) {
15529: $error = 'recaptcha';
15530: }
15531: }
15532: return ($output,$error,$captcha);
15533: }
15534:
15535: sub captcha_response {
15536: my ($context,$lonhost) = @_;
15537: my ($captcha_chk,$captcha_error);
15538: my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
15539: if ($captcha eq 'original') {
15540: ($captcha_chk,$captcha_error) = &check_captcha();
15541: } elsif ($captcha eq 'recaptcha') {
15542: $captcha_chk = &check_recaptcha($privkey);
15543: } else {
15544: $captcha_chk = 1;
15545: }
15546: return ($captcha_chk,$captcha_error);
15547: }
15548:
15549: sub get_captcha_config {
15550: my ($context,$lonhost) = @_;
15551: my ($captcha,$pubkey,$privkey,$hashtocheck);
15552: my $hostname = &Apache::lonnet::hostname($lonhost);
15553: my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
15554: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
15555: if ($context eq 'usercreation') {
15556: my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
15557: if (ref($domconfig{$context}) eq 'HASH') {
15558: $hashtocheck = $domconfig{$context}{'cancreate'};
15559: if (ref($hashtocheck) eq 'HASH') {
15560: if ($hashtocheck->{'captcha'} eq 'recaptcha') {
15561: if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
15562: $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
15563: $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
15564: }
15565: if ($privkey && $pubkey) {
15566: $captcha = 'recaptcha';
15567: } else {
15568: $captcha = 'original';
15569: }
15570: } elsif ($hashtocheck->{'captcha'} ne 'notused') {
15571: $captcha = 'original';
15572: }
15573: }
15574: } else {
15575: $captcha = 'captcha';
15576: }
15577: } elsif ($context eq 'login') {
15578: my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
15579: if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
15580: $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
15581: $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
15582: if ($privkey && $pubkey) {
15583: $captcha = 'recaptcha';
15584: } else {
15585: $captcha = 'original';
15586: }
15587: } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
15588: $captcha = 'original';
15589: }
15590: }
15591: return ($captcha,$pubkey,$privkey);
15592: }
15593:
15594: sub create_captcha {
15595: my %captcha_params = &captcha_settings();
15596: my ($output,$maxtries,$tries) = ('',10,0);
15597: while ($tries < $maxtries) {
15598: $tries ++;
15599: my $captcha = Authen::Captcha->new (
15600: output_folder => $captcha_params{'output_dir'},
15601: data_folder => $captcha_params{'db_dir'},
15602: );
15603: my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
15604:
15605: if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
15606: $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
15607: &mt('Type in the letters/numbers shown below').' '.
15608: '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
15609: '<br />'.
15610: '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
15611: last;
15612: }
15613: }
15614: return $output;
15615: }
15616:
15617: sub captcha_settings {
15618: my %captcha_params = (
15619: output_dir => $Apache::lonnet::perlvar{'lonCaptchaDir'},
15620: www_output_dir => "/captchaspool",
15621: db_dir => $Apache::lonnet::perlvar{'lonCaptchaDb'},
15622: numchars => '5',
15623: );
15624: return %captcha_params;
15625: }
15626:
15627: sub check_captcha {
15628: my ($captcha_chk,$captcha_error);
15629: my $code = $env{'form.code'};
15630: my $md5sum = $env{'form.crypt'};
15631: my %captcha_params = &captcha_settings();
15632: my $captcha = Authen::Captcha->new(
15633: output_folder => $captcha_params{'output_dir'},
15634: data_folder => $captcha_params{'db_dir'},
15635: );
15636: $captcha_chk = $captcha->check_code($code,$md5sum);
15637: my %captcha_hash = (
15638: 0 => 'Code not checked (file error)',
15639: -1 => 'Failed: code expired',
15640: -2 => 'Failed: invalid code (not in database)',
15641: -3 => 'Failed: invalid code (code does not match crypt)',
15642: );
15643: if ($captcha_chk != 1) {
15644: $captcha_error = $captcha_hash{$captcha_chk}
15645: }
15646: return ($captcha_chk,$captcha_error);
15647: }
15648:
15649: sub create_recaptcha {
15650: my ($pubkey) = @_;
15651: my $use_ssl;
15652: if ($ENV{'SERVER_PORT'} == 443) {
15653: $use_ssl = 1;
15654: }
15655: my $captcha = Captcha::reCAPTCHA->new;
15656: return $captcha->get_options_setter({theme => 'white'})."\n".
15657: $captcha->get_html($pubkey,undef,$use_ssl).
15658: &mt('If either word is hard to read, [_1] will replace them.',
15659: '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
15660: '<br /><br />';
15661: }
15662:
15663: sub check_recaptcha {
15664: my ($privkey) = @_;
15665: my $captcha_chk;
15666: my $captcha = Captcha::reCAPTCHA->new;
15667: my $captcha_result =
15668: $captcha->check_answer(
15669: $privkey,
15670: $ENV{'REMOTE_ADDR'},
15671: $env{'form.recaptcha_challenge_field'},
15672: $env{'form.recaptcha_response_field'},
15673: );
15674: if ($captcha_result->{is_valid}) {
15675: $captcha_chk = 1;
15676: }
15677: return $captcha_chk;
15678: }
15679:
15680: sub emailusername_info {
15681: my @fields = ('firstname','lastname','institution','web','location','officialemail');
15682: my %titles = &Apache::lonlocal::texthash (
15683: lastname => 'Last Name',
15684: firstname => 'First Name',
15685: institution => 'School/college/university',
15686: location => "School's city, state/province, country",
15687: web => "School's web address",
15688: officialemail => 'E-mail address at institution (if different)',
15689: );
15690: return (\@fields,\%titles);
15691: }
15692:
15693: sub cleanup_html {
15694: my ($incoming) = @_;
15695: my $outgoing;
15696: if ($incoming ne '') {
15697: $outgoing = $incoming;
15698: $outgoing =~ s/;/;/g;
15699: $outgoing =~ s/\#/#/g;
15700: $outgoing =~ s/\&/&/g;
15701: $outgoing =~ s/</</g;
15702: $outgoing =~ s/>/>/g;
15703: $outgoing =~ s/\(/(/g;
15704: $outgoing =~ s/\)/)/g;
15705: $outgoing =~ s/"/"/g;
15706: $outgoing =~ s/'/'/g;
15707: $outgoing =~ s/\$/$/g;
15708: $outgoing =~ s{/}{/}g;
15709: $outgoing =~ s/=/=/g;
15710: $outgoing =~ s/\\/\/g
15711: }
15712: return $outgoing;
15713: }
15714:
15715: # Checks for critical messages and returns a redirect url if one exists.
15716: # $interval indicates how often to check for messages.
15717: sub critical_redirect {
15718: my ($interval) = @_;
15719: if ((time-$env{'user.criticalcheck.time'})>$interval) {
15720: my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
15721: $env{'user.name'});
15722: &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
15723: my $redirecturl;
15724: if ($what[0]) {
15725: if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
15726: $redirecturl='/adm/email?critical=display';
15727: my $url=&Apache::lonnet::absolute_url().$redirecturl;
15728: return (1, $url);
15729: }
15730: }
15731: }
15732: return ();
15733: }
15734:
15735: # Use:
15736: # my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
15737: #
15738: ##################################################
15739: # password associated functions #
15740: ##################################################
15741: sub des_keys {
15742: # Make a new key for DES encryption.
15743: # Each key has two parts which are returned separately.
15744: # Please note: Each key must be passed through the &hex function
15745: # before it is output to the web browser. The hex versions cannot
15746: # be used to decrypt.
15747: my @hexstr=('0','1','2','3','4','5','6','7',
15748: '8','9','a','b','c','d','e','f');
15749: my $lkey='';
15750: for (0..7) {
15751: $lkey.=$hexstr[rand(15)];
15752: }
15753: my $ukey='';
15754: for (0..7) {
15755: $ukey.=$hexstr[rand(15)];
15756: }
15757: return ($lkey,$ukey);
15758: }
15759:
15760: sub des_decrypt {
15761: my ($key,$cyphertext) = @_;
15762: my $keybin=pack("H16",$key);
15763: my $cypher;
15764: if ($Crypt::DES::VERSION>=2.03) {
15765: $cypher=new Crypt::DES $keybin;
15766: } else {
15767: $cypher=new DES $keybin;
15768: }
15769: my $plaintext=
15770: $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,0,16))));
15771: $plaintext.=
15772: $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,16,16))));
15773: $plaintext=substr($plaintext,1,ord(substr($plaintext,0,1)) );
15774: return $plaintext;
15775: }
15776:
15777: 1;
15778: __END__;
15779:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>