1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1261 2014/05/29 12:45:05 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:
30: =pod
31:
32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
71: package Apache::lonnet;
72:
73: use strict;
74: use LWP::UserAgent();
75: use HTTP::Date;
76: use Image::Magick;
77:
78:
79: use Encode;
80:
81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
88: %courseownerbuf, %coursetypebuf,$locknum);
89:
90: use IO::Socket;
91: use GDBM_File;
92: use HTML::LCParser;
93: use Fcntl qw(:flock);
94: use Storable qw(thaw nfreeze);
95: use Time::HiRes qw( gettimeofday tv_interval );
96: use Cache::Memcached;
97: use Digest::MD5;
98: use Math::Random;
99: use File::MMagic;
100: use LONCAPA qw(:DEFAULT :match);
101: use LONCAPA::Configuration;
102: use LONCAPA::lonmetadata;
103: use LONCAPA::Lond;
104:
105: use File::Copy;
106:
107: my $readit;
108: my $max_connection_retries = 10; # Or some such value.
109:
110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
115:
116: # ------------------------------------ Logging (parameters, docs, slots, roles)
117: {
118: my $logid;
119: sub write_log {
120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
126: }
127: $logid ++;
128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
143: }
144: }
145:
146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
164: close($fh);
165: }
166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
178: return 1;
179: }
180:
181: sub create_connection {
182: my ($hostname,$lonid) = @_;
183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
208:
209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
232: sub get_server_loncaparev {
233: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
234: if (defined($lonhost)) {
235: if (!defined(&hostname($lonhost))) {
236: undef($lonhost);
237: }
238: }
239: if (!defined($lonhost)) {
240: if (defined(&domain($dom,'primary'))) {
241: $lonhost=&domain($dom,'primary');
242: if ($lonhost eq 'no_host') {
243: undef($lonhost);
244: }
245: }
246: }
247: if (defined($lonhost)) {
248: my $cachetime = 12*3600;
249: if (!$ignore_cache) {
250: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
251: if (defined($cached)) {
252: return $loncaparev;
253: }
254: }
255: my ($answer,$loncaparev);
256: my @ids=¤t_machine_ids();
257: if (grep(/^\Q$lonhost\E$/,@ids)) {
258: $answer = $perlvar{'lonVersion'};
259: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
260: $loncaparev = $1;
261: }
262: } else {
263: $answer = &reply('serverloncaparev',$lonhost);
264: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
265: if ($caller eq 'loncron') {
266: my $ua=new LWP::UserAgent;
267: $ua->timeout(4);
268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
270: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
283: $loncaparev = $1;
284: }
285: }
286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
287: }
288: }
289:
290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
324: my ($response,$cached);
325: unless ($ignore_cache) {
326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
327: }
328: if (defined($cached)) {
329: $returnhash{$what} = $response;
330: } else {
331: $whatneeded{$what} = 1;
332: }
333: }
334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
344: my @pairs=split(/\&/,$rep);
345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
351: }
352: }
353: }
354: }
355: return ($result,\%returnhash);
356: }
357:
358: sub remote_devalidate_cache {
359: my ($lonhost,$cachekeys) = @_;
360: my $items;
361: return unless (ref($cachekeys) eq 'ARRAY');
362: my $cachestr = join('&',@{$cachekeys});
363: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
364: return $response;
365: }
366:
367: # -------------------------------------------------- Non-critical communication
368: sub subreply {
369: my ($cmd,$server)=@_;
370: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
371: #
372: # With loncnew process trimming, there's a timing hole between lonc server
373: # process exit and the master server picking up the listen on the AF_UNIX
374: # socket. In that time interval, a lock file will exist:
375:
376: my $lockfile=$peerfile.".lock";
377: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
378: sleep(1);
379: }
380: # At this point, either a loncnew parent is listening or an old lonc
381: # or loncnew child is listening so we can connect or everything's dead.
382: #
383: # We'll give the connection a few tries before abandoning it. If
384: # connection is not possible, we'll con_lost back to the client.
385: #
386: my $client;
387: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
388: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
389: Type => SOCK_STREAM,
390: Timeout => 10);
391: if ($client) {
392: last; # Connected!
393: } else {
394: &create_connection(&hostname($server),$server);
395: }
396: sleep(1); # Try again later if failed connection.
397: }
398: my $answer;
399: if ($client) {
400: print $client "sethost:$server:$cmd\n";
401: $answer=<$client>;
402: if (!$answer) { $answer="con_lost"; }
403: chomp($answer);
404: } else {
405: $answer = 'con_lost'; # Failed connection.
406: }
407: return $answer;
408: }
409:
410: sub reply {
411: my ($cmd,$server)=@_;
412: unless (defined(&hostname($server))) { return 'no_such_host'; }
413: my $answer=subreply($cmd,$server);
414: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
415: &logthis("<font color=\"blue\">WARNING:".
416: " $cmd to $server returned $answer</font>");
417: }
418: return $answer;
419: }
420:
421: # ----------------------------------------------------------- Send USR1 to lonc
422:
423: sub reconlonc {
424: my ($lonid) = @_;
425: my $hostname = &hostname($lonid);
426: if ($lonid) {
427: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
428: if ($hostname && -e $peerfile) {
429: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
430: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
431: Type => SOCK_STREAM,
432: Timeout => 10);
433: if ($client) {
434: print $client ("reset_retries\n");
435: my $answer=<$client>;
436: #reset just this one.
437: }
438: }
439: return;
440: }
441:
442: &logthis("Trying to reconnect lonc");
443: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
444: if (open(my $fh,"<$loncfile")) {
445: my $loncpid=<$fh>;
446: chomp($loncpid);
447: if (kill 0 => $loncpid) {
448: &logthis("lonc at pid $loncpid responding, sending USR1");
449: kill USR1 => $loncpid;
450: sleep 1;
451: } else {
452: &logthis(
453: "<font color=\"blue\">WARNING:".
454: " lonc at pid $loncpid not responding, giving up</font>");
455: }
456: } else {
457: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
458: }
459: }
460:
461: # ------------------------------------------------------ Critical communication
462:
463: sub critical {
464: my ($cmd,$server)=@_;
465: unless (&hostname($server)) {
466: &logthis("<font color=\"blue\">WARNING:".
467: " Critical message to unknown server ($server)</font>");
468: return 'no_such_host';
469: }
470: my $answer=reply($cmd,$server);
471: if ($answer eq 'con_lost') {
472: &reconlonc("$perlvar{'lonSockDir'}/$server");
473: my $answer=reply($cmd,$server);
474: if ($answer eq 'con_lost') {
475: my $now=time;
476: my $middlename=$cmd;
477: $middlename=substr($middlename,0,16);
478: $middlename=~s/\W//g;
479: my $dfilename=
480: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
481: $dumpcount++;
482: {
483: my $dfh;
484: if (open($dfh,">$dfilename")) {
485: print $dfh "$cmd\n";
486: close($dfh);
487: }
488: }
489: sleep 2;
490: my $wcmd='';
491: {
492: my $dfh;
493: if (open($dfh,"<$dfilename")) {
494: $wcmd=<$dfh>;
495: close($dfh);
496: }
497: }
498: chomp($wcmd);
499: if ($wcmd eq $cmd) {
500: &logthis("<font color=\"blue\">WARNING: ".
501: "Connection buffer $dfilename: $cmd</font>");
502: &logperm("D:$server:$cmd");
503: return 'con_delayed';
504: } else {
505: &logthis("<font color=\"red\">CRITICAL:"
506: ." Critical connection failed: $server $cmd</font>");
507: &logperm("F:$server:$cmd");
508: return 'con_failed';
509: }
510: }
511: }
512: return $answer;
513: }
514:
515: # ------------------------------------------- check if return value is an error
516:
517: sub error {
518: my ($result) = @_;
519: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
520: if ($2 == 2) { return undef; }
521: return $1;
522: }
523: return undef;
524: }
525:
526: sub convert_and_load_session_env {
527: my ($lonidsdir,$handle)=@_;
528: my @profile;
529: {
530: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
531: if (!$opened) {
532: return 0;
533: }
534: flock($idf,LOCK_SH);
535: @profile=<$idf>;
536: close($idf);
537: }
538: my %temp_env;
539: foreach my $line (@profile) {
540: if ($line !~ m/=/) {
541: return 0;
542: }
543: chomp($line);
544: my ($envname,$envvalue)=split(/=/,$line,2);
545: $temp_env{&unescape($envname)} = &unescape($envvalue);
546: }
547: unlink("$lonidsdir/$handle.id");
548: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
549: 0640)) {
550: %disk_env = %temp_env;
551: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
552: untie(%disk_env);
553: }
554: return 1;
555: }
556:
557: # ------------------------------------------- Transfer profile into environment
558: my $env_loaded;
559: sub transfer_profile_to_env {
560: my ($lonidsdir,$handle,$force_transfer) = @_;
561: if (!$force_transfer && $env_loaded) { return; }
562:
563: if (!defined($lonidsdir)) {
564: $lonidsdir = $perlvar{'lonIDsDir'};
565: }
566: if (!defined($handle)) {
567: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
568: }
569:
570: my $convert;
571: {
572: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
573: if (!$opened) {
574: return;
575: }
576: flock($idf,LOCK_SH);
577: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
578: &GDBM_READER(),0640)) {
579: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
580: untie(%disk_env);
581: } else {
582: $convert = 1;
583: }
584: }
585: if ($convert) {
586: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
587: &logthis("Failed to load session, or convert session.");
588: }
589: }
590:
591: my %remove;
592: while ( my $envname = each(%env) ) {
593: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
594: if ($time < time-300) {
595: $remove{$key}++;
596: }
597: }
598: }
599:
600: $env{'user.environment'} = "$lonidsdir/$handle.id";
601: $env_loaded=1;
602: foreach my $expired_key (keys(%remove)) {
603: &delenv($expired_key);
604: }
605: }
606:
607: # ---------------------------------------------------- Check for valid session
608: sub check_for_valid_session {
609: my ($r,$name,$userhashref) = @_;
610: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
611: if ($name eq '') {
612: $name = 'lonID';
613: }
614: my $lonid=$cookies{$name};
615: return undef if (!$lonid);
616:
617: my $handle=&LONCAPA::clean_handle($lonid->value);
618: my $lonidsdir;
619: if ($name eq 'lonDAV') {
620: $lonidsdir=$r->dir_config('lonDAVsessDir');
621: } else {
622: $lonidsdir=$r->dir_config('lonIDsDir');
623: }
624: return undef if (!-e "$lonidsdir/$handle.id");
625:
626: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
627: return undef if (!$opened);
628:
629: flock($idf,LOCK_SH);
630: my %disk_env;
631: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
632: &GDBM_READER(),0640)) {
633: return undef;
634: }
635:
636: if (!defined($disk_env{'user.name'})
637: || !defined($disk_env{'user.domain'})) {
638: return undef;
639: }
640:
641: if (ref($userhashref) eq 'HASH') {
642: $userhashref->{'name'} = $disk_env{'user.name'};
643: $userhashref->{'domain'} = $disk_env{'user.domain'};
644: }
645:
646: return $handle;
647: }
648:
649: sub timed_flock {
650: my ($file,$lock_type) = @_;
651: my $failed=0;
652: eval {
653: local $SIG{__DIE__}='DEFAULT';
654: local $SIG{ALRM}=sub {
655: $failed=1;
656: die("failed lock");
657: };
658: alarm(13);
659: flock($file,$lock_type);
660: alarm(0);
661: };
662: if ($failed) {
663: return undef;
664: } else {
665: return 1;
666: }
667: }
668:
669: # ---------------------------------------------------------- Append Environment
670:
671: sub appenv {
672: my ($newenv,$roles) = @_;
673: if (ref($newenv) eq 'HASH') {
674: foreach my $key (keys(%{$newenv})) {
675: my $refused = 0;
676: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
677: $refused = 1;
678: if (ref($roles) eq 'ARRAY') {
679: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
680: if (grep(/^\Q$role\E$/,@{$roles})) {
681: $refused = 0;
682: }
683: }
684: }
685: if ($refused) {
686: &logthis("<font color=\"blue\">WARNING: ".
687: "Attempt to modify environment ".$key." to ".$newenv->{$key}
688: .'</font>');
689: delete($newenv->{$key});
690: } else {
691: $env{$key}=$newenv->{$key};
692: }
693: }
694: my $opened = open(my $env_file,'+<',$env{'user.environment'});
695: if ($opened
696: && &timed_flock($env_file,LOCK_EX)
697: &&
698: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
699: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
700: while (my ($key,$value) = each(%{$newenv})) {
701: $disk_env{$key} = $value;
702: }
703: untie(%disk_env);
704: }
705: }
706: return 'ok';
707: }
708: # ----------------------------------------------------- Delete from Environment
709:
710: sub delenv {
711: my ($delthis,$regexp,$roles) = @_;
712: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
713: my $refused = 1;
714: if (ref($roles) eq 'ARRAY') {
715: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
716: if (grep(/^\Q$role\E$/,@{$roles})) {
717: $refused = 0;
718: }
719: }
720: if ($refused) {
721: &logthis("<font color=\"blue\">WARNING: ".
722: "Attempt to delete from environment ".$delthis);
723: return 'error';
724: }
725: }
726: my $opened = open(my $env_file,'+<',$env{'user.environment'});
727: if ($opened
728: && &timed_flock($env_file,LOCK_EX)
729: &&
730: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
731: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
732: foreach my $key (keys(%disk_env)) {
733: if ($regexp) {
734: if ($key=~/^$delthis/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: } else {
739: if ($key=~/^\Q$delthis\E/) {
740: delete($env{$key});
741: delete($disk_env{$key});
742: }
743: }
744: }
745: untie(%disk_env);
746: }
747: return 'ok';
748: }
749:
750: sub get_env_multiple {
751: my ($name) = @_;
752: my @values;
753: if (defined($env{$name})) {
754: # exists is it an array
755: if (ref($env{$name})) {
756: @values=@{ $env{$name} };
757: } else {
758: $values[0]=$env{$name};
759: }
760: }
761: return(@values);
762: }
763:
764: # ------------------------------------------------------------------- Locking
765:
766: sub set_lock {
767: my ($text)=@_;
768: $locknum++;
769: my $id=$$.'-'.$locknum;
770: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
771: 'session.lock.'.$id => $text});
772: return $id;
773: }
774:
775: sub get_locks {
776: my $num=0;
777: my %texts=();
778: foreach my $lock (split(/\,/,$env{'session.locks'})) {
779: if ($lock=~/\w/) {
780: $num++;
781: $texts{$lock}=$env{'session.lock.'.$lock};
782: }
783: }
784: return ($num,%texts);
785: }
786:
787: sub remove_lock {
788: my ($id)=@_;
789: my $newlocks='';
790: foreach my $lock (split(/\,/,$env{'session.locks'})) {
791: if (($lock=~/\w/) && ($lock ne $id)) {
792: $newlocks.=','.$lock;
793: }
794: }
795: &appenv({'session.locks' => $newlocks});
796: &delenv('session.lock.'.$id);
797: }
798:
799: sub remove_all_locks {
800: my $activelocks=$env{'session.locks'};
801: foreach my $lock (split(/\,/,$env{'session.locks'})) {
802: if ($lock=~/\w/) {
803: &remove_lock($lock);
804: }
805: }
806: }
807:
808:
809: # ------------------------------------------ Find out current server userload
810: sub userload {
811: my $numusers=0;
812: {
813: opendir(LONIDS,$perlvar{'lonIDsDir'});
814: my $filename;
815: my $curtime=time;
816: while ($filename=readdir(LONIDS)) {
817: next if ($filename eq '.' || $filename eq '..');
818: next if ($filename =~ /publicuser_\d+\.id/);
819: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
820: if ($curtime-$mtime < 1800) { $numusers++; }
821: }
822: closedir(LONIDS);
823: }
824: my $userloadpercent=0;
825: my $maxuserload=$perlvar{'lonUserLoadLim'};
826: if ($maxuserload) {
827: $userloadpercent=100*$numusers/$maxuserload;
828: }
829: $userloadpercent=sprintf("%.2f",$userloadpercent);
830: return $userloadpercent;
831: }
832:
833: # ------------------------------ Find server with least workload from spare.tab
834:
835: sub spareserver {
836: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
837: my $spare_server;
838: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
839: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
840: : $userloadpercent;
841: my ($uint_dom,$remotesessions);
842: if (($udom ne '') && (&domain($udom) ne '')) {
843: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
844: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
845: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
846: $remotesessions = $udomdefaults{'remotesessions'};
847: }
848: my $spareshash = &this_host_spares($udom);
849: if (ref($spareshash) eq 'HASH') {
850: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
851: foreach my $try_server (@{ $spareshash->{'primary'} }) {
852: if ($uint_dom) {
853: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
854: $try_server));
855: }
856: ($spare_server, $lowest_load) =
857: &compare_server_load($try_server, $spare_server, $lowest_load);
858: }
859: }
860:
861: my $found_server = ($spare_server ne '' && $lowest_load < 100);
862:
863: if (!$found_server) {
864: if (ref($spareshash->{'default'}) eq 'ARRAY') {
865: foreach my $try_server (@{ $spareshash->{'default'} }) {
866: if ($uint_dom) {
867: next unless (&spare_can_host($udom,$uint_dom,
868: $remotesessions,$try_server));
869: }
870: ($spare_server, $lowest_load) =
871: &compare_server_load($try_server, $spare_server, $lowest_load);
872: }
873: }
874: }
875: }
876:
877: if (!$want_server_name) {
878: my $protocol = 'http';
879: if ($protocol{$spare_server} eq 'https') {
880: $protocol = $protocol{$spare_server};
881: }
882: if (defined($spare_server)) {
883: my $hostname = &hostname($spare_server);
884: if (defined($hostname)) {
885: $spare_server = $protocol.'://'.$hostname;
886: }
887: }
888: }
889: return $spare_server;
890: }
891:
892: sub compare_server_load {
893: my ($try_server, $spare_server, $lowest_load, $required) = @_;
894:
895: if ($required) {
896: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
897: my $remoterev = &get_server_loncaparev(undef,$try_server);
898: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
899: if (($major eq '' && $minor eq '') ||
900: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
901: return ($spare_server,$lowest_load);
902: }
903: }
904:
905: my $loadans = &reply('load', $try_server);
906: my $userloadans = &reply('userload',$try_server);
907:
908: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
909: return ($spare_server, $lowest_load); #didn't get a number from the server
910: }
911:
912: my $load;
913: if ($loadans =~ /\d/) {
914: if ($userloadans =~ /\d/) {
915: #both are numbers, pick the bigger one
916: $load = ($loadans > $userloadans) ? $loadans
917: : $userloadans;
918: } else {
919: $load = $loadans;
920: }
921: } else {
922: $load = $userloadans;
923: }
924:
925: if (($load =~ /\d/) && ($load < $lowest_load)) {
926: $spare_server = $try_server;
927: $lowest_load = $load;
928: }
929: return ($spare_server,$lowest_load);
930: }
931:
932: # --------------------------- ask offload servers if user already has a session
933: sub find_existing_session {
934: my ($udom,$uname) = @_;
935: my $spareshash = &this_host_spares($udom);
936: if (ref($spareshash) eq 'HASH') {
937: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
938: foreach my $try_server (@{ $spareshash->{'primary'} }) {
939: return $try_server if (&has_user_session($try_server, $udom, $uname));
940: }
941: }
942: if (ref($spareshash->{'default'}) eq 'ARRAY') {
943: foreach my $try_server (@{ $spareshash->{'default'} }) {
944: return $try_server if (&has_user_session($try_server, $udom, $uname));
945: }
946: }
947: }
948: return;
949: }
950:
951: # -------------------------------- ask if server already has a session for user
952: sub has_user_session {
953: my ($lonid,$udom,$uname) = @_;
954: my $result = &reply(join(':','userhassession',
955: map {&escape($_)} ($udom,$uname)),$lonid);
956: return 1 if ($result eq 'ok');
957:
958: return 0;
959: }
960:
961: # --------- determine least loaded server in a user's domain which allows login
962:
963: sub choose_server {
964: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
965: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
966: my %servers = &get_servers($udom);
967: my $lowest_load = 30000;
968: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
969: if ($skiploadbal) {
970: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
971: unless (defined($cached)) {
972: my $cachetime = 60*60*24;
973: my %domconfig =
974: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
975: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
976: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
977: $cachetime);
978: }
979: }
980: }
981: foreach my $lonhost (keys(%servers)) {
982: if ($skiploadbal) {
983: if (ref($balancers) eq 'HASH') {
984: next if (exists($balancers->{$lonhost}));
985: }
986: }
987: my $loginvia;
988: if ($checkloginvia) {
989: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
990: if ($loginvia) {
991: my ($server,$path) = split(/:/,$loginvia);
992: ($login_host, $lowest_load) =
993: &compare_server_load($server, $login_host, $lowest_load, $required);
994: if ($login_host eq $server) {
995: $portal_path = $path;
996: $isredirect = 1;
997: }
998: } else {
999: ($login_host, $lowest_load) =
1000: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1001: if ($login_host eq $lonhost) {
1002: $portal_path = '';
1003: $isredirect = '';
1004: }
1005: }
1006: } else {
1007: ($login_host, $lowest_load) =
1008: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1009: }
1010: }
1011: if ($login_host ne '') {
1012: $hostname = &hostname($login_host);
1013: }
1014: return ($login_host,$hostname,$portal_path,$isredirect);
1015: }
1016:
1017: # --------------------------------------------- Try to change a user's password
1018:
1019: sub changepass {
1020: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1021: $currentpass = &escape($currentpass);
1022: $newpass = &escape($newpass);
1023: my $lonhost = $perlvar{'lonHostID'};
1024: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1025: $server);
1026: if (! $answer) {
1027: &logthis("No reply on password change request to $server ".
1028: "by $uname in domain $udom.");
1029: } elsif ($answer =~ "^ok") {
1030: &logthis("$uname in $udom successfully changed their password ".
1031: "on $server.");
1032: } elsif ($answer =~ "^pwchange_failure") {
1033: &logthis("$uname in $udom was unable to change their password ".
1034: "on $server. The action was blocked by either lcpasswd ".
1035: "or pwchange");
1036: } elsif ($answer =~ "^non_authorized") {
1037: &logthis("$uname in $udom did not get their password correct when ".
1038: "attempting to change it on $server.");
1039: } elsif ($answer =~ "^auth_mode_error") {
1040: &logthis("$uname in $udom attempted to change their password despite ".
1041: "not being locally or internally authenticated on $server.");
1042: } elsif ($answer =~ "^unknown_user") {
1043: &logthis("$uname in $udom attempted to change their password ".
1044: "on $server but were unable to because $server is not ".
1045: "their home server.");
1046: } elsif ($answer =~ "^refused") {
1047: &logthis("$server refused to change $uname in $udom password because ".
1048: "it was sent an unencrypted request to change the password.");
1049: } elsif ($answer =~ "invalid_client") {
1050: &logthis("$server refused to change $uname in $udom password because ".
1051: "it was a reset by e-mail originating from an invalid server.");
1052: }
1053: return $answer;
1054: }
1055:
1056: # ----------------------- Try to determine user's current authentication scheme
1057:
1058: sub queryauthenticate {
1059: my ($uname,$udom)=@_;
1060: my $uhome=&homeserver($uname,$udom);
1061: if (!$uhome) {
1062: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1063: return 'no_host';
1064: }
1065: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1066: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1067: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1068: }
1069: return $answer;
1070: }
1071:
1072: # --------- Try to authenticate user from domain's lib servers (first this one)
1073:
1074: sub authenticate {
1075: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1076: $upass=&escape($upass);
1077: $uname= &LONCAPA::clean_username($uname);
1078: my $uhome=&homeserver($uname,$udom,1);
1079: my $newhome;
1080: if ((!$uhome) || ($uhome eq 'no_host')) {
1081: # Maybe the machine was offline and only re-appeared again recently?
1082: &reconlonc();
1083: # One more
1084: $uhome=&homeserver($uname,$udom,1);
1085: if (($uhome eq 'no_host') && $checkdefauth) {
1086: if (defined(&domain($udom,'primary'))) {
1087: $newhome=&domain($udom,'primary');
1088: }
1089: if ($newhome ne '') {
1090: $uhome = $newhome;
1091: }
1092: }
1093: if ((!$uhome) || ($uhome eq 'no_host')) {
1094: &logthis("User $uname at $udom is unknown in authenticate");
1095: return 'no_host';
1096: }
1097: }
1098: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1099: if ($answer eq 'authorized') {
1100: if ($newhome) {
1101: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1102: return 'no_account_on_host';
1103: } else {
1104: &logthis("User $uname at $udom authorized by $uhome");
1105: return $uhome;
1106: }
1107: }
1108: if ($answer eq 'non_authorized') {
1109: &logthis("User $uname at $udom rejected by $uhome");
1110: return 'no_host';
1111: }
1112: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1113: return 'no_host';
1114: }
1115:
1116: sub can_host_session {
1117: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1118: my $canhost = 1;
1119: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1120: if (ref($remotesessions) eq 'HASH') {
1121: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1122: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1123: $canhost = 0;
1124: } else {
1125: $canhost = 1;
1126: }
1127: }
1128: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1129: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1130: $canhost = 1;
1131: } else {
1132: $canhost = 0;
1133: }
1134: }
1135: if ($canhost) {
1136: if ($remotesessions->{'version'} ne '') {
1137: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1138: if ($reqmajor ne '' && $reqminor ne '') {
1139: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1140: my $major = $1;
1141: my $minor = $2;
1142: if (($major < $reqmajor ) ||
1143: (($major == $reqmajor) && ($minor < $reqminor))) {
1144: $canhost = 0;
1145: }
1146: } else {
1147: $canhost = 0;
1148: }
1149: }
1150: }
1151: }
1152: }
1153: if ($canhost) {
1154: if (ref($hostedsessions) eq 'HASH') {
1155: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1156: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1157: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1158: if (($uint_dom ne '') &&
1159: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1160: $canhost = 0;
1161: } else {
1162: $canhost = 1;
1163: }
1164: }
1165: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1166: if (($uint_dom ne '') &&
1167: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1168: $canhost = 1;
1169: } else {
1170: $canhost = 0;
1171: }
1172: }
1173: }
1174: }
1175: return $canhost;
1176: }
1177:
1178: sub spare_can_host {
1179: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1180: my $canhost=1;
1181: my @intdoms;
1182: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1183: if (ref($internet_names) eq 'ARRAY') {
1184: @intdoms = @{$internet_names};
1185: }
1186: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1187: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1188: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1189: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1190: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1191: $canhost = &can_host_session($udom,$try_server,$remoterev,
1192: $remotesessions,
1193: $defdomdefaults{'hostedsessions'});
1194: }
1195: return $canhost;
1196: }
1197:
1198: sub this_host_spares {
1199: my ($dom) = @_;
1200: my ($dom_in_use,$lonhost_in_use,$result);
1201: my @hosts = ¤t_machine_ids();
1202: foreach my $lonhost (@hosts) {
1203: if (&host_domain($lonhost) eq $dom) {
1204: $dom_in_use = $dom;
1205: $lonhost_in_use = $lonhost;
1206: last;
1207: }
1208: }
1209: if ($dom_in_use ne '') {
1210: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1211: }
1212: if (ref($result) ne 'HASH') {
1213: $lonhost_in_use = $perlvar{'lonHostID'};
1214: $dom_in_use = &host_domain($lonhost_in_use);
1215: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1216: if (ref($result) ne 'HASH') {
1217: $result = \%spareid;
1218: }
1219: }
1220: return $result;
1221: }
1222:
1223: sub spares_for_offload {
1224: my ($dom_in_use,$lonhost_in_use) = @_;
1225: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1226: if (defined($cached)) {
1227: return $result;
1228: } else {
1229: my $cachetime = 60*60*24;
1230: my %domconfig =
1231: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1232: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1233: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1234: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1235: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1236: }
1237: }
1238: }
1239: }
1240: return;
1241: }
1242:
1243: sub get_lonbalancer_config {
1244: my ($servers) = @_;
1245: my ($currbalancer,$currtargets);
1246: if (ref($servers) eq 'HASH') {
1247: foreach my $server (keys(%{$servers})) {
1248: my %what = (
1249: spareid => 1,
1250: perlvar => 1,
1251: );
1252: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1253: if ($result eq 'ok') {
1254: if (ref($returnhash) eq 'HASH') {
1255: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1256: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1257: $currbalancer = $server;
1258: $currtargets = {};
1259: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1260: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1261: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1262: }
1263: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1264: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1265: }
1266: }
1267: last;
1268: }
1269: }
1270: }
1271: }
1272: }
1273: }
1274: return ($currbalancer,$currtargets);
1275: }
1276:
1277: sub check_loadbalancing {
1278: my ($uname,$udom) = @_;
1279: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1280: $rule_in_effect,$offloadto,$otherserver);
1281: my $lonhost = $perlvar{'lonHostID'};
1282: my @hosts = ¤t_machine_ids();
1283: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1284: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1285: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1286: my $serverhomedom = &host_domain($lonhost);
1287:
1288: my $cachetime = 60*60*24;
1289:
1290: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1291: $dom_in_use = $udom;
1292: $homeintdom = 1;
1293: } else {
1294: $dom_in_use = $serverhomedom;
1295: }
1296: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1297: unless (defined($cached)) {
1298: my %domconfig =
1299: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1300: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1301: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1302: }
1303: }
1304: if (ref($result) eq 'HASH') {
1305: ($is_balancer,$currtargets,$currrules) =
1306: &check_balancer_result($result,@hosts);
1307: if ($is_balancer) {
1308: if (ref($currrules) eq 'HASH') {
1309: if ($homeintdom) {
1310: if ($uname ne '') {
1311: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1312: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1313: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1314: $rule_in_effect = $currrules->{'_LC_author'};
1315: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1316: $rule_in_effect = $currrules->{'_LC_adv'}
1317: }
1318: }
1319: if ($rule_in_effect eq '') {
1320: my %userenv = &userenvironment($udom,$uname,'inststatus');
1321: if ($userenv{'inststatus'} ne '') {
1322: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1323: my ($othertitle,$usertypes,$types) =
1324: &Apache::loncommon::sorted_inst_types($udom);
1325: if (ref($types) eq 'ARRAY') {
1326: foreach my $type (@{$types}) {
1327: if (grep(/^\Q$type\E$/,@statuses)) {
1328: if (exists($currrules->{$type})) {
1329: $rule_in_effect = $currrules->{$type};
1330: }
1331: }
1332: }
1333: }
1334: } else {
1335: if (exists($currrules->{'default'})) {
1336: $rule_in_effect = $currrules->{'default'};
1337: }
1338: }
1339: }
1340: } else {
1341: if (exists($currrules->{'default'})) {
1342: $rule_in_effect = $currrules->{'default'};
1343: }
1344: }
1345: } else {
1346: if ($currrules->{'_LC_external'} ne '') {
1347: $rule_in_effect = $currrules->{'_LC_external'};
1348: }
1349: }
1350: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1351: $uname,$udom);
1352: }
1353: }
1354: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1355: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1356: unless (defined($cached)) {
1357: my %domconfig =
1358: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1359: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1360: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1361: }
1362: }
1363: if (ref($result) eq 'HASH') {
1364: ($is_balancer,$currtargets,$currrules) =
1365: &check_balancer_result($result,@hosts);
1366: if ($is_balancer) {
1367: if (ref($currrules) eq 'HASH') {
1368: if ($currrules->{'_LC_internetdom'} ne '') {
1369: $rule_in_effect = $currrules->{'_LC_internetdom'};
1370: }
1371: }
1372: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1373: $uname,$udom);
1374: }
1375: } else {
1376: if ($perlvar{'lonBalancer'} eq 'yes') {
1377: $is_balancer = 1;
1378: $offloadto = &this_host_spares($dom_in_use);
1379: }
1380: }
1381: } else {
1382: if ($perlvar{'lonBalancer'} eq 'yes') {
1383: $is_balancer = 1;
1384: $offloadto = &this_host_spares($dom_in_use);
1385: }
1386: }
1387: if ($is_balancer) {
1388: my $lowest_load = 30000;
1389: if (ref($offloadto) eq 'HASH') {
1390: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1391: foreach my $try_server (@{$offloadto->{'primary'}}) {
1392: ($otherserver,$lowest_load) =
1393: &compare_server_load($try_server,$otherserver,$lowest_load);
1394: }
1395: }
1396: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1397:
1398: if (!$found_server) {
1399: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1400: foreach my $try_server (@{$offloadto->{'default'}}) {
1401: ($otherserver,$lowest_load) =
1402: &compare_server_load($try_server,$otherserver,$lowest_load);
1403: }
1404: }
1405: }
1406: } elsif (ref($offloadto) eq 'ARRAY') {
1407: if (@{$offloadto} == 1) {
1408: $otherserver = $offloadto->[0];
1409: } elsif (@{$offloadto} > 1) {
1410: foreach my $try_server (@{$offloadto}) {
1411: ($otherserver,$lowest_load) =
1412: &compare_server_load($try_server,$otherserver,$lowest_load);
1413: }
1414: }
1415: }
1416: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1417: $is_balancer = 0;
1418: if ($uname ne '' && $udom ne '') {
1419: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1420:
1421: &appenv({'user.loadbalexempt' => $lonhost,
1422: 'user.loadbalcheck.time' => time});
1423: }
1424: }
1425: }
1426: }
1427: return ($is_balancer,$otherserver);
1428: }
1429:
1430: sub check_balancer_result {
1431: my ($result,@hosts) = @_;
1432: my ($is_balancer,$currtargets,$currrules);
1433: if (ref($result) eq 'HASH') {
1434: if ($result->{'lonhost'} ne '') {
1435: my $currbalancer = $result->{'lonhost'};
1436: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1437: $is_balancer = 1;
1438: $currtargets = $result->{'targets'};
1439: $currrules = $result->{'rules'};
1440: }
1441: } else {
1442: foreach my $key (keys(%{$result})) {
1443: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1444: (ref($result->{$key}) eq 'HASH')) {
1445: $is_balancer = 1;
1446: $currrules = $result->{$key}{'rules'};
1447: $currtargets = $result->{$key}{'targets'};
1448: last;
1449: }
1450: }
1451: }
1452: }
1453: return ($is_balancer,$currtargets,$currrules);
1454: }
1455:
1456: sub get_loadbalancer_targets {
1457: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1458: my $offloadto;
1459: if ($rule_in_effect eq 'none') {
1460: return [$perlvar{'lonHostID'}];
1461: } elsif ($rule_in_effect eq '') {
1462: $offloadto = $currtargets;
1463: } else {
1464: if ($rule_in_effect eq 'homeserver') {
1465: my $homeserver = &homeserver($uname,$udom);
1466: if ($homeserver ne 'no_host') {
1467: $offloadto = [$homeserver];
1468: }
1469: } elsif ($rule_in_effect eq 'externalbalancer') {
1470: my %domconfig =
1471: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1472: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1473: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1474: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1475: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1476: }
1477: }
1478: } else {
1479: my %servers = &internet_dom_servers($udom);
1480: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1481: if (&hostname($remotebalancer) ne '') {
1482: $offloadto = [$remotebalancer];
1483: }
1484: }
1485: } elsif (&hostname($rule_in_effect) ne '') {
1486: $offloadto = [$rule_in_effect];
1487: }
1488: }
1489: return $offloadto;
1490: }
1491:
1492: sub internet_dom_servers {
1493: my ($dom) = @_;
1494: my (%uniqservers,%servers);
1495: my $primaryserver = &hostname(&domain($dom,'primary'));
1496: my @machinedoms = &machine_domains($primaryserver);
1497: foreach my $mdom (@machinedoms) {
1498: my %currservers = %servers;
1499: my %server = &get_servers($mdom);
1500: %servers = (%currservers,%server);
1501: }
1502: my %by_hostname;
1503: foreach my $id (keys(%servers)) {
1504: push(@{$by_hostname{$servers{$id}}},$id);
1505: }
1506: foreach my $hostname (sort(keys(%by_hostname))) {
1507: if (@{$by_hostname{$hostname}} > 1) {
1508: my $match = 0;
1509: foreach my $id (@{$by_hostname{$hostname}}) {
1510: if (&host_domain($id) eq $dom) {
1511: $uniqservers{$id} = $hostname;
1512: $match = 1;
1513: }
1514: }
1515: unless ($match) {
1516: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1517: }
1518: } else {
1519: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1520: }
1521: }
1522: return %uniqservers;
1523: }
1524:
1525: # ---------------------- Find the homebase for a user from domain's lib servers
1526:
1527: my %homecache;
1528: sub homeserver {
1529: my ($uname,$udom,$ignoreBadCache)=@_;
1530: my $index="$uname:$udom";
1531:
1532: if (exists($homecache{$index})) { return $homecache{$index}; }
1533:
1534: my %servers = &get_servers($udom,'library');
1535: foreach my $tryserver (keys(%servers)) {
1536: next if ($ignoreBadCache ne 'true' &&
1537: exists($badServerCache{$tryserver}));
1538:
1539: my $answer=reply("home:$udom:$uname",$tryserver);
1540: if ($answer eq 'found') {
1541: delete($badServerCache{$tryserver});
1542: return $homecache{$index}=$tryserver;
1543: } elsif ($answer eq 'no_host') {
1544: $badServerCache{$tryserver}=1;
1545: }
1546: }
1547: return 'no_host';
1548: }
1549:
1550: # ------------------------------------- Find the usernames behind a list of IDs
1551:
1552: sub idget {
1553: my ($udom,@ids)=@_;
1554: my %returnhash=();
1555:
1556: my %servers = &get_servers($udom,'library');
1557: foreach my $tryserver (keys(%servers)) {
1558: my $idlist=join('&',@ids);
1559: $idlist=~tr/A-Z/a-z/;
1560: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1561: my @answer=();
1562: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1563: @answer=split(/\&/,$reply);
1564: } ;
1565: my $i;
1566: for ($i=0;$i<=$#ids;$i++) {
1567: if ($answer[$i]) {
1568: $returnhash{$ids[$i]}=$answer[$i];
1569: }
1570: }
1571: }
1572: return %returnhash;
1573: }
1574:
1575: # ------------------------------------- Find the IDs behind a list of usernames
1576:
1577: sub idrget {
1578: my ($udom,@unames)=@_;
1579: my %returnhash=();
1580: foreach my $uname (@unames) {
1581: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1582: }
1583: return %returnhash;
1584: }
1585:
1586: # ------------------------------- Store away a list of names and associated IDs
1587:
1588: sub idput {
1589: my ($udom,%ids)=@_;
1590: my %servers=();
1591: foreach my $uname (keys(%ids)) {
1592: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1593: my $uhom=&homeserver($uname,$udom);
1594: if ($uhom ne 'no_host') {
1595: my $id=&escape($ids{$uname});
1596: $id=~tr/A-Z/a-z/;
1597: my $esc_unam=&escape($uname);
1598: if ($servers{$uhom}) {
1599: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1600: } else {
1601: $servers{$uhom}=$id.'='.$esc_unam;
1602: }
1603: }
1604: }
1605: foreach my $server (keys(%servers)) {
1606: &critical('idput:'.$udom.':'.$servers{$server},$server);
1607: }
1608: }
1609:
1610: # ---------------------------------------- Delete unwanted IDs from ids.db file
1611:
1612: sub iddel {
1613: my ($udom,$idshashref,$uhome)=@_;
1614: my %result=();
1615: unless (ref($idshashref) eq 'HASH') {
1616: return %result;
1617: }
1618: my %servers=();
1619: while (my ($id,$uname) = each(%{$idshashref})) {
1620: my $uhom;
1621: if ($uhome) {
1622: $uhom = $uhome;
1623: } else {
1624: $uhom=&homeserver($uname,$udom);
1625: }
1626: if ($uhom ne 'no_host') {
1627: if ($servers{$uhom}) {
1628: $servers{$uhom}.='&'.&escape($id);
1629: } else {
1630: $servers{$uhom}=&escape($id);
1631: }
1632: }
1633: }
1634: foreach my $server (keys(%servers)) {
1635: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1636: }
1637: return %result;
1638: }
1639:
1640: # ------------------------------dump from db file owned by domainconfig user
1641: sub dump_dom {
1642: my ($namespace, $udom, $regexp) = @_;
1643:
1644: $udom ||= $env{'user.domain'};
1645:
1646: return () unless $udom;
1647:
1648: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1649: }
1650:
1651: # ------------------------------------------ get items from domain db files
1652:
1653: sub get_dom {
1654: my ($namespace,$storearr,$udom,$uhome)=@_;
1655: my $items='';
1656: foreach my $item (@$storearr) {
1657: $items.=&escape($item).'&';
1658: }
1659: $items=~s/\&$//;
1660: if (!$udom) {
1661: $udom=$env{'user.domain'};
1662: if (defined(&domain($udom,'primary'))) {
1663: $uhome=&domain($udom,'primary');
1664: } else {
1665: undef($uhome);
1666: }
1667: } else {
1668: if (!$uhome) {
1669: if (defined(&domain($udom,'primary'))) {
1670: $uhome=&domain($udom,'primary');
1671: }
1672: }
1673: }
1674: if ($udom && $uhome && ($uhome ne 'no_host')) {
1675: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1676: my %returnhash;
1677: if ($rep eq '' || $rep =~ /^error: 2 /) {
1678: return %returnhash;
1679: }
1680: my @pairs=split(/\&/,$rep);
1681: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1682: return @pairs;
1683: }
1684: my $i=0;
1685: foreach my $item (@$storearr) {
1686: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1687: $i++;
1688: }
1689: return %returnhash;
1690: } else {
1691: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1692: }
1693: }
1694:
1695: # -------------------------------------------- put items in domain db files
1696:
1697: sub put_dom {
1698: my ($namespace,$storehash,$udom,$uhome)=@_;
1699: if (!$udom) {
1700: $udom=$env{'user.domain'};
1701: if (defined(&domain($udom,'primary'))) {
1702: $uhome=&domain($udom,'primary');
1703: } else {
1704: undef($uhome);
1705: }
1706: } else {
1707: if (!$uhome) {
1708: if (defined(&domain($udom,'primary'))) {
1709: $uhome=&domain($udom,'primary');
1710: }
1711: }
1712: }
1713: if ($udom && $uhome && ($uhome ne 'no_host')) {
1714: my $items='';
1715: foreach my $item (keys(%$storehash)) {
1716: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1717: }
1718: $items=~s/\&$//;
1719: return &reply("putdom:$udom:$namespace:$items",$uhome);
1720: } else {
1721: &logthis("put_dom failed - no homeserver and/or domain");
1722: }
1723: }
1724:
1725: # --------------------- newput for items in db file owned by domainconfig user
1726: sub newput_dom {
1727: my ($namespace,$storehash,$udom) = @_;
1728: my $result;
1729: if (!$udom) {
1730: $udom=$env{'user.domain'};
1731: }
1732: if ($udom) {
1733: my $uname = &get_domainconfiguser($udom);
1734: $result = &newput($namespace,$storehash,$udom,$uname);
1735: }
1736: return $result;
1737: }
1738:
1739: # --------------------- delete for items in db file owned by domainconfig user
1740: sub del_dom {
1741: my ($namespace,$storearr,$udom)=@_;
1742: if (ref($storearr) eq 'ARRAY') {
1743: if (!$udom) {
1744: $udom=$env{'user.domain'};
1745: }
1746: if ($udom) {
1747: my $uname = &get_domainconfiguser($udom);
1748: return &del($namespace,$storearr,$udom,$uname);
1749: }
1750: }
1751: }
1752:
1753: # ----------------------------------construct domainconfig user for a domain
1754: sub get_domainconfiguser {
1755: my ($udom) = @_;
1756: return $udom.'-domainconfig';
1757: }
1758:
1759: sub retrieve_inst_usertypes {
1760: my ($udom) = @_;
1761: my (%returnhash,@order);
1762: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1763: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1764: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1765: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1766: } else {
1767: if (defined(&domain($udom,'primary'))) {
1768: my $uhome=&domain($udom,'primary');
1769: my $rep=&reply("inst_usertypes:$udom",$uhome);
1770: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1771: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1772: return (\%returnhash,\@order);
1773: }
1774: my ($hashitems,$orderitems) = split(/:/,$rep);
1775: my @pairs=split(/\&/,$hashitems);
1776: foreach my $item (@pairs) {
1777: my ($key,$value)=split(/=/,$item,2);
1778: $key = &unescape($key);
1779: next if ($key =~ /^error: 2 /);
1780: $returnhash{$key}=&thaw_unescape($value);
1781: }
1782: my @esc_order = split(/\&/,$orderitems);
1783: foreach my $item (@esc_order) {
1784: push(@order,&unescape($item));
1785: }
1786: } else {
1787: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1788: }
1789: return (\%returnhash,\@order);
1790: }
1791: }
1792:
1793: sub is_domainimage {
1794: my ($url) = @_;
1795: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1796: if (&domain($1) ne '') {
1797: return '1';
1798: }
1799: }
1800: return;
1801: }
1802:
1803: sub inst_directory_query {
1804: my ($srch) = @_;
1805: my $udom = $srch->{'srchdomain'};
1806: my %results;
1807: my $homeserver = &domain($udom,'primary');
1808: my $outcome;
1809: if ($homeserver ne '') {
1810: my $queryid=&reply("querysend:instdirsearch:".
1811: &escape($srch->{'srchby'}).':'.
1812: &escape($srch->{'srchterm'}).':'.
1813: &escape($srch->{'srchtype'}),$homeserver);
1814: my $host=&hostname($homeserver);
1815: if ($queryid !~/^\Q$host\E\_/) {
1816: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1817: return;
1818: }
1819: my $response = &get_query_reply($queryid);
1820: my $maxtries = 5;
1821: my $tries = 1;
1822: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1823: $response = &get_query_reply($queryid);
1824: $tries ++;
1825: }
1826:
1827: if (!&error($response) && $response ne 'refused') {
1828: if ($response eq 'unavailable') {
1829: $outcome = $response;
1830: } else {
1831: $outcome = 'ok';
1832: my @matches = split(/\n/,$response);
1833: foreach my $match (@matches) {
1834: my ($key,$value) = split(/=/,$match);
1835: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1836: }
1837: }
1838: }
1839: }
1840: return ($outcome,%results);
1841: }
1842:
1843: sub usersearch {
1844: my ($srch) = @_;
1845: my $dom = $srch->{'srchdomain'};
1846: my %results;
1847: my %libserv = &all_library();
1848: my $query = 'usersearch';
1849: foreach my $tryserver (keys(%libserv)) {
1850: if (&host_domain($tryserver) eq $dom) {
1851: my $host=&hostname($tryserver);
1852: my $queryid=
1853: &reply("querysend:".&escape($query).':'.
1854: &escape($srch->{'srchby'}).':'.
1855: &escape($srch->{'srchtype'}).':'.
1856: &escape($srch->{'srchterm'}),$tryserver);
1857: if ($queryid !~/^\Q$host\E\_/) {
1858: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1859: next;
1860: }
1861: my $reply = &get_query_reply($queryid);
1862: my $maxtries = 1;
1863: my $tries = 1;
1864: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1865: $reply = &get_query_reply($queryid);
1866: $tries ++;
1867: }
1868: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1869: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1870: } else {
1871: my @matches;
1872: if ($reply =~ /\n/) {
1873: @matches = split(/\n/,$reply);
1874: } else {
1875: @matches = split(/\&/,$reply);
1876: }
1877: foreach my $match (@matches) {
1878: my ($uname,$udom,%userhash);
1879: foreach my $entry (split(/:/,$match)) {
1880: my ($key,$value) =
1881: map {&unescape($_);} split(/=/,$entry);
1882: $userhash{$key} = $value;
1883: if ($key eq 'username') {
1884: $uname = $value;
1885: } elsif ($key eq 'domain') {
1886: $udom = $value;
1887: }
1888: }
1889: $results{$uname.':'.$udom} = \%userhash;
1890: }
1891: }
1892: }
1893: }
1894: return %results;
1895: }
1896:
1897: sub get_instuser {
1898: my ($udom,$uname,$id) = @_;
1899: my $homeserver = &domain($udom,'primary');
1900: my ($outcome,%results);
1901: if ($homeserver ne '') {
1902: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1903: &escape($id).':'.&escape($udom),$homeserver);
1904: my $host=&hostname($homeserver);
1905: if ($queryid !~/^\Q$host\E\_/) {
1906: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1907: return;
1908: }
1909: my $response = &get_query_reply($queryid);
1910: my $maxtries = 5;
1911: my $tries = 1;
1912: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1913: $response = &get_query_reply($queryid);
1914: $tries ++;
1915: }
1916: if (!&error($response) && $response ne 'refused') {
1917: if ($response eq 'unavailable') {
1918: $outcome = $response;
1919: } else {
1920: $outcome = 'ok';
1921: my @matches = split(/\n/,$response);
1922: foreach my $match (@matches) {
1923: my ($key,$value) = split(/=/,$match);
1924: $results{&unescape($key)} = &thaw_unescape($value);
1925: }
1926: }
1927: }
1928: }
1929: my %userinfo;
1930: if (ref($results{$uname}) eq 'HASH') {
1931: %userinfo = %{$results{$uname}};
1932: }
1933: return ($outcome,%userinfo);
1934: }
1935:
1936: sub inst_rulecheck {
1937: my ($udom,$uname,$id,$item,$rules) = @_;
1938: my %returnhash;
1939: if ($udom ne '') {
1940: if (ref($rules) eq 'ARRAY') {
1941: @{$rules} = map {&escape($_);} (@{$rules});
1942: my $rulestr = join(':',@{$rules});
1943: my $homeserver=&domain($udom,'primary');
1944: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1945: my $response;
1946: if ($item eq 'username') {
1947: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1948: ':'.&escape($uname).':'.$rulestr,
1949: $homeserver));
1950: } elsif ($item eq 'id') {
1951: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1952: ':'.&escape($id).':'.$rulestr,
1953: $homeserver));
1954: } elsif ($item eq 'selfcreate') {
1955: $response=&unescape(&reply('instselfcreatecheck:'.
1956: &escape($udom).':'.&escape($uname).
1957: ':'.$rulestr,$homeserver));
1958: }
1959: if ($response ne 'refused') {
1960: my @pairs=split(/\&/,$response);
1961: foreach my $item (@pairs) {
1962: my ($key,$value)=split(/=/,$item,2);
1963: $key = &unescape($key);
1964: next if ($key =~ /^error: 2 /);
1965: $returnhash{$key}=&thaw_unescape($value);
1966: }
1967: }
1968: }
1969: }
1970: }
1971: return %returnhash;
1972: }
1973:
1974: sub inst_userrules {
1975: my ($udom,$check) = @_;
1976: my (%ruleshash,@ruleorder);
1977: if ($udom ne '') {
1978: my $homeserver=&domain($udom,'primary');
1979: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1980: my $response;
1981: if ($check eq 'id') {
1982: $response=&reply('instidrules:'.&escape($udom),
1983: $homeserver);
1984: } elsif ($check eq 'email') {
1985: $response=&reply('instemailrules:'.&escape($udom),
1986: $homeserver);
1987: } else {
1988: $response=&reply('instuserrules:'.&escape($udom),
1989: $homeserver);
1990: }
1991: if (($response ne 'refused') && ($response ne 'error') &&
1992: ($response ne 'unknown_cmd') &&
1993: ($response ne 'no_such_host')) {
1994: my ($hashitems,$orderitems) = split(/:/,$response);
1995: my @pairs=split(/\&/,$hashitems);
1996: foreach my $item (@pairs) {
1997: my ($key,$value)=split(/=/,$item,2);
1998: $key = &unescape($key);
1999: next if ($key =~ /^error: 2 /);
2000: $ruleshash{$key}=&thaw_unescape($value);
2001: }
2002: my @esc_order = split(/\&/,$orderitems);
2003: foreach my $item (@esc_order) {
2004: push(@ruleorder,&unescape($item));
2005: }
2006: }
2007: }
2008: }
2009: return (\%ruleshash,\@ruleorder);
2010: }
2011:
2012: # ------------- Get Authentication, Language and User Tools Defaults for Domain
2013:
2014: sub get_domain_defaults {
2015: my ($domain,$ignore_cache) = @_;
2016: return if (($domain eq '') || ($domain eq 'public'));
2017: my $cachetime = 60*60*24;
2018: unless ($ignore_cache) {
2019: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2020: if (defined($cached)) {
2021: if (ref($result) eq 'HASH') {
2022: return %{$result};
2023: }
2024: }
2025: }
2026: my %domdefaults;
2027: my %domconfig =
2028: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
2029: 'requestcourses','inststatus',
2030: 'coursedefaults','usersessions',
2031: 'requestauthor','selfenrollment',
2032: 'coursecategories'],$domain);
2033: my @coursetypes = ('official','unofficial','community','textbook');
2034: if (ref($domconfig{'defaults'}) eq 'HASH') {
2035: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2036: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2037: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
2038: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
2039: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
2040: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
2041: } else {
2042: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2043: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2044: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2045: }
2046: if (ref($domconfig{'quotas'}) eq 'HASH') {
2047: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2048: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2049: } else {
2050: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
2051: }
2052: my @usertools = ('aboutme','blog','webdav','portfolio');
2053: foreach my $item (@usertools) {
2054: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2055: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2056: }
2057: }
2058: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2059: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2060: }
2061: }
2062: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
2063: foreach my $item ('official','unofficial','community','textbook') {
2064: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2065: }
2066: }
2067: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2068: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2069: }
2070: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2071: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
2072: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2073: }
2074: }
2075: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
2076: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
2077: foreach my $type (@coursetypes) {
2078: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2079: unless ($type eq 'community') {
2080: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2081: }
2082: }
2083: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2084: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2085: }
2086: }
2087: }
2088: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2089: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2090: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2091: }
2092: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2093: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2094: }
2095: }
2096: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2097: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2098: my @settings = ('types','registered','enroll_dates','access_dates','section',
2099: 'approval','limit');
2100: foreach my $type (@coursetypes) {
2101: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2102: my @mgrdc = ();
2103: foreach my $item (@settings) {
2104: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2105: push(@mgrdc,$item);
2106: }
2107: }
2108: if (@mgrdc) {
2109: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2110: }
2111: }
2112: }
2113: }
2114: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2115: foreach my $type (@coursetypes) {
2116: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2117: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2118: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2119: }
2120: }
2121: }
2122: }
2123: }
2124: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2125: $domdefaults{'catauth'} = 'std';
2126: $domdefaults{'catunauth'} = 'std';
2127: if ($domconfig{'coursecategories'}{'auth'}) {
2128: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2129: }
2130: if ($domconfig{'coursecategories'}{'unauth'}) {
2131: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2132: }
2133: }
2134: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
2135: return %domdefaults;
2136: }
2137:
2138: # --------------------------------------------------- Assign a key to a student
2139:
2140: sub assign_access_key {
2141: #
2142: # a valid key looks like uname:udom#comments
2143: # comments are being appended
2144: #
2145: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2146: $kdom=
2147: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
2148: $knum=
2149: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
2150: $cdom=
2151: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2152: $cnum=
2153: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2154: $udom=$env{'user.name'} unless (defined($udom));
2155: $uname=$env{'user.domain'} unless (defined($uname));
2156: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
2157: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
2158: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2159: # assigned to this person
2160: # - this should not happen,
2161: # unless something went wrong
2162: # the first time around
2163: # ready to assign
2164: $logentry=$1.'; '.$logentry;
2165: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2166: $kdom,$knum) eq 'ok') {
2167: # key now belongs to user
2168: my $envkey='key.'.$cdom.'_'.$cnum;
2169: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2170: &appenv({'environment.'.$envkey => $ckey});
2171: return 'ok';
2172: } else {
2173: return
2174: 'error: Count not permanently assign key, will need to be re-entered later.';
2175: }
2176: } else {
2177: return 'error: Could not assign key, try again later.';
2178: }
2179: } elsif (!$existing{$ckey}) {
2180: # the key does not exist
2181: return 'error: The key does not exist';
2182: } else {
2183: # the key is somebody else's
2184: return 'error: The key is already in use';
2185: }
2186: }
2187:
2188: # ------------------------------------------ put an additional comment on a key
2189:
2190: sub comment_access_key {
2191: #
2192: # a valid key looks like uname:udom#comments
2193: # comments are being appended
2194: #
2195: my ($ckey,$cdom,$cnum,$logentry)=@_;
2196: $cdom=
2197: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2198: $cnum=
2199: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2200: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2201: if ($existing{$ckey}) {
2202: $existing{$ckey}.='; '.$logentry;
2203: # ready to assign
2204: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2205: $cdom,$cnum) eq 'ok') {
2206: return 'ok';
2207: } else {
2208: return 'error: Count not store comment.';
2209: }
2210: } else {
2211: # the key does not exist
2212: return 'error: The key does not exist';
2213: }
2214: }
2215:
2216: # ------------------------------------------------------ Generate a set of keys
2217:
2218: sub generate_access_keys {
2219: my ($number,$cdom,$cnum,$logentry)=@_;
2220: $cdom=
2221: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2222: $cnum=
2223: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2224: unless (&allowed('mky',$cdom)) { return 0; }
2225: unless (($cdom) && ($cnum)) { return 0; }
2226: if ($number>10000) { return 0; }
2227: sleep(2); # make sure don't get same seed twice
2228: srand(time()^($$+($$<<15))); # from "Programming Perl"
2229: my $total=0;
2230: for (my $i=1;$i<=$number;$i++) {
2231: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2232: sprintf("%lx",int(100000*rand)).'-'.
2233: sprintf("%lx",int(100000*rand));
2234: $newkey=~s/1/g/g; # folks mix up 1 and l
2235: $newkey=~s/0/h/g; # and also 0 and O
2236: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2237: if ($existing{$newkey}) {
2238: $i--;
2239: } else {
2240: if (&put('accesskeys',
2241: { $newkey => '# generated '.localtime().
2242: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2243: '; '.$logentry },
2244: $cdom,$cnum) eq 'ok') {
2245: $total++;
2246: }
2247: }
2248: }
2249: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2250: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2251: return $total;
2252: }
2253:
2254: # ------------------------------------------------------- Validate an accesskey
2255:
2256: sub validate_access_key {
2257: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2258: $cdom=
2259: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2260: $cnum=
2261: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2262: $udom=$env{'user.domain'} unless (defined($udom));
2263: $uname=$env{'user.name'} unless (defined($uname));
2264: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2265: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2266: }
2267:
2268: # ------------------------------------- Find the section of student in a course
2269: sub devalidate_getsection_cache {
2270: my ($udom,$unam,$courseid)=@_;
2271: my $hashid="$udom:$unam:$courseid";
2272: &devalidate_cache_new('getsection',$hashid);
2273: }
2274:
2275: sub courseid_to_courseurl {
2276: my ($courseid) = @_;
2277: #already url style courseid
2278: return $courseid if ($courseid =~ m{^/});
2279:
2280: if (exists($env{'course.'.$courseid.'.num'})) {
2281: my $cnum = $env{'course.'.$courseid.'.num'};
2282: my $cdom = $env{'course.'.$courseid.'.domain'};
2283: return "/$cdom/$cnum";
2284: }
2285:
2286: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2287: if (exists($courseinfo{'num'})) {
2288: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2289: }
2290:
2291: return undef;
2292: }
2293:
2294: sub getsection {
2295: my ($udom,$unam,$courseid)=@_;
2296: my $cachetime=1800;
2297:
2298: my $hashid="$udom:$unam:$courseid";
2299: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2300: if (defined($cached)) { return $result; }
2301:
2302: my %Pending;
2303: my %Expired;
2304: #
2305: # Each role can either have not started yet (pending), be active,
2306: # or have expired.
2307: #
2308: # If there is an active role, we are done.
2309: #
2310: # If there is more than one role which has not started yet,
2311: # choose the one which will start sooner
2312: # If there is one role which has not started yet, return it.
2313: #
2314: # If there is more than one expired role, choose the one which ended last.
2315: # If there is a role which has expired, return it.
2316: #
2317: $courseid = &courseid_to_courseurl($courseid);
2318: my %roleshash = &dump('roles',$udom,$unam,$courseid);
2319: foreach my $key (keys(%roleshash)) {
2320: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2321: my $section=$1;
2322: if ($key eq $courseid.'_st') { $section=''; }
2323: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2324: my $now=time;
2325: if (defined($end) && $end && ($now > $end)) {
2326: $Expired{$end}=$section;
2327: next;
2328: }
2329: if (defined($start) && $start && ($now < $start)) {
2330: $Pending{$start}=$section;
2331: next;
2332: }
2333: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2334: }
2335: #
2336: # Presumedly there will be few matching roles from the above
2337: # loop and the sorting time will be negligible.
2338: if (scalar(keys(%Pending))) {
2339: my ($time) = sort {$a <=> $b} keys(%Pending);
2340: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2341: }
2342: if (scalar(keys(%Expired))) {
2343: my @sorted = sort {$a <=> $b} keys(%Expired);
2344: my $time = pop(@sorted);
2345: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2346: }
2347: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2348: }
2349:
2350: sub save_cache {
2351: &purge_remembered();
2352: #&Apache::loncommon::validate_page();
2353: undef(%env);
2354: undef($env_loaded);
2355: }
2356:
2357: my $to_remember=-1;
2358: my %remembered;
2359: my %accessed;
2360: my $kicks=0;
2361: my $hits=0;
2362: sub make_key {
2363: my ($name,$id) = @_;
2364: if (length($id) > 65
2365: && length(&escape($id)) > 200) {
2366: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2367: }
2368: return &escape($name.':'.$id);
2369: }
2370:
2371: sub devalidate_cache_new {
2372: my ($name,$id,$debug) = @_;
2373: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2374: $id=&make_key($name,$id);
2375: $memcache->delete($id);
2376: delete($remembered{$id});
2377: delete($accessed{$id});
2378: }
2379:
2380: sub is_cached_new {
2381: my ($name,$id,$debug) = @_;
2382: $id=&make_key($name,$id);
2383: if (exists($remembered{$id})) {
2384: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
2385: $accessed{$id}=[&gettimeofday()];
2386: $hits++;
2387: return ($remembered{$id},1);
2388: }
2389: my $value = $memcache->get($id);
2390: if (!(defined($value))) {
2391: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2392: return (undef,undef);
2393: }
2394: if ($value eq '__undef__') {
2395: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2396: $value=undef;
2397: }
2398: &make_room($id,$value,$debug);
2399: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2400: return ($value,1);
2401: }
2402:
2403: sub do_cache_new {
2404: my ($name,$id,$value,$time,$debug) = @_;
2405: $id=&make_key($name,$id);
2406: my $setvalue=$value;
2407: if (!defined($setvalue)) {
2408: $setvalue='__undef__';
2409: }
2410: if (!defined($time) ) {
2411: $time=600;
2412: }
2413: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2414: my $result = $memcache->set($id,$setvalue,$time);
2415: if (! $result) {
2416: &logthis("caching of id -> $id failed");
2417: $memcache->disconnect_all();
2418: }
2419: # need to make a copy of $value
2420: &make_room($id,$value,$debug);
2421: return $value;
2422: }
2423:
2424: sub make_room {
2425: my ($id,$value,$debug)=@_;
2426:
2427: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2428: : $value;
2429: if ($to_remember<0) { return; }
2430: $accessed{$id}=[&gettimeofday()];
2431: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2432: my $to_kick;
2433: my $max_time=0;
2434: foreach my $other (keys(%accessed)) {
2435: if (&tv_interval($accessed{$other}) > $max_time) {
2436: $to_kick=$other;
2437: $max_time=&tv_interval($accessed{$other});
2438: }
2439: }
2440: delete($remembered{$to_kick});
2441: delete($accessed{$to_kick});
2442: $kicks++;
2443: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2444: return;
2445: }
2446:
2447: sub purge_remembered {
2448: #&logthis("Tossing ".scalar(keys(%remembered)));
2449: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2450: undef(%remembered);
2451: undef(%accessed);
2452: }
2453: # ------------------------------------- Read an entry from a user's environment
2454:
2455: sub userenvironment {
2456: my ($udom,$unam,@what)=@_;
2457: my $items;
2458: foreach my $item (@what) {
2459: $items.=&escape($item).'&';
2460: }
2461: $items=~s/\&$//;
2462: my %returnhash=();
2463: my $uhome = &homeserver($unam,$udom);
2464: unless ($uhome eq 'no_host') {
2465: my @answer=split(/\&/,
2466: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2467: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2468: return %returnhash;
2469: }
2470: my $i;
2471: for ($i=0;$i<=$#what;$i++) {
2472: $returnhash{$what[$i]}=&unescape($answer[$i]);
2473: }
2474: }
2475: return %returnhash;
2476: }
2477:
2478: # ---------------------------------------------------------- Get a studentphoto
2479: sub studentphoto {
2480: my ($udom,$unam,$ext) = @_;
2481: my $home=&Apache::lonnet::homeserver($unam,$udom);
2482: if (defined($env{'request.course.id'})) {
2483: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2484: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2485: return(&retrievestudentphoto($udom,$unam,$ext));
2486: } else {
2487: my ($result,$perm_reqd)=
2488: &Apache::lonnet::auto_photo_permission($unam,$udom);
2489: if ($result eq 'ok') {
2490: if (!($perm_reqd eq 'yes')) {
2491: return(&retrievestudentphoto($udom,$unam,$ext));
2492: }
2493: }
2494: }
2495: }
2496: } else {
2497: my ($result,$perm_reqd) =
2498: &Apache::lonnet::auto_photo_permission($unam,$udom);
2499: if ($result eq 'ok') {
2500: if (!($perm_reqd eq 'yes')) {
2501: return(&retrievestudentphoto($udom,$unam,$ext));
2502: }
2503: }
2504: }
2505: return '/adm/lonKaputt/lonlogo_broken.gif';
2506: }
2507:
2508: sub retrievestudentphoto {
2509: my ($udom,$unam,$ext,$type) = @_;
2510: my $home=&Apache::lonnet::homeserver($unam,$udom);
2511: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2512: if ($ret eq 'ok') {
2513: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2514: if ($type eq 'thumbnail') {
2515: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2516: }
2517: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2518: return $tokenurl;
2519: } else {
2520: if ($type eq 'thumbnail') {
2521: return '/adm/lonKaputt/genericstudent_tn.gif';
2522: } else {
2523: return '/adm/lonKaputt/lonlogo_broken.gif';
2524: }
2525: }
2526: }
2527:
2528: # -------------------------------------------------------------------- New chat
2529:
2530: sub chatsend {
2531: my ($newentry,$anon,$group)=@_;
2532: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2533: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2534: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2535: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2536: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2537: &escape($newentry)).':'.$group,$chome);
2538: }
2539:
2540: # ------------------------------------------ Find current version of a resource
2541:
2542: sub getversion {
2543: my $fname=&clutter(shift);
2544: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
2545: return ¤tversion(&filelocation('',$fname));
2546: }
2547:
2548: sub currentversion {
2549: my $fname=shift;
2550: my $author=$fname;
2551: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2552: my ($udom,$uname)=split(/\//,$author);
2553: my $home=&homeserver($uname,$udom);
2554: if ($home eq 'no_host') {
2555: return -1;
2556: }
2557: my $answer=&reply("currentversion:$fname",$home);
2558: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2559: return -1;
2560: }
2561: return $answer;
2562: }
2563:
2564: #
2565: # Return special version number of resource if set by override, empty otherwise
2566: #
2567: sub usedversion {
2568: my $fname=shift;
2569: unless ($fname) { $fname=$env{'request.uri'}; }
2570: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2571: if ($urlversion) { return $urlversion; }
2572: return '';
2573: }
2574:
2575: # ----------------------------- Subscribe to a resource, return URL if possible
2576:
2577: sub subscribe {
2578: my $fname=shift;
2579: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2580: $fname=~s/[\n\r]//g;
2581: my $author=$fname;
2582: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2583: my ($udom,$uname)=split(/\//,$author);
2584: my $home=homeserver($uname,$udom);
2585: if ($home eq 'no_host') {
2586: return 'not_found';
2587: }
2588: my $answer=reply("sub:$fname",$home);
2589: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2590: $answer.=' by '.$home;
2591: }
2592: return $answer;
2593: }
2594:
2595: # -------------------------------------------------------------- Replicate file
2596:
2597: sub repcopy {
2598: my $filename=shift;
2599: $filename=~s/\/+/\//g;
2600: my $londocroot = $perlvar{'lonDocRoot'};
2601: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
2602: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
2603: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2604: $filename=~m{^/*(uploaded|editupload)/}) {
2605: return &repcopy_userfile($filename);
2606: }
2607: $filename=~s/[\n\r]//g;
2608: my $transname="$filename.in.transfer";
2609: # FIXME: this should flock
2610: if ((-e $filename) || (-e $transname)) { return 'ok'; }
2611: my $remoteurl=subscribe($filename);
2612: if ($remoteurl =~ /^con_lost by/) {
2613: &logthis("Subscribe returned $remoteurl: $filename");
2614: return 'unavailable';
2615: } elsif ($remoteurl eq 'not_found') {
2616: #&logthis("Subscribe returned not_found: $filename");
2617: return 'not_found';
2618: } elsif ($remoteurl =~ /^rejected by/) {
2619: &logthis("Subscribe returned $remoteurl: $filename");
2620: return 'forbidden';
2621: } elsif ($remoteurl eq 'directory') {
2622: return 'ok';
2623: } else {
2624: my $author=$filename;
2625: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2626: my ($udom,$uname)=split(/\//,$author);
2627: my $home=homeserver($uname,$udom);
2628: unless ($home eq $perlvar{'lonHostID'}) {
2629: my @parts=split(/\//,$filename);
2630: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2631: if ($path ne "$londocroot/res") {
2632: &logthis("Malconfiguration for replication: $filename");
2633: return 'bad_request';
2634: }
2635: my $count;
2636: for ($count=5;$count<$#parts;$count++) {
2637: $path.="/$parts[$count]";
2638: if ((-e $path)!=1) {
2639: mkdir($path,0777);
2640: }
2641: }
2642: my $ua=new LWP::UserAgent;
2643: my $request=new HTTP::Request('GET',"$remoteurl");
2644: my $response=$ua->request($request,$transname);
2645: if ($response->is_error()) {
2646: unlink($transname);
2647: my $message=$response->status_line;
2648: &logthis("<font color=\"blue\">WARNING:"
2649: ." LWP get: $message: $filename</font>");
2650: return 'unavailable';
2651: } else {
2652: if ($remoteurl!~/\.meta$/) {
2653: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2654: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2655: if ($mresponse->is_error()) {
2656: unlink($filename.'.meta');
2657: &logthis(
2658: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
2659: }
2660: }
2661: rename($transname,$filename);
2662: return 'ok';
2663: }
2664: }
2665: }
2666: }
2667:
2668: # ------------------------------------------------ Get server side include body
2669: sub ssi_body {
2670: my ($filelink,%form)=@_;
2671: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2672: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2673: }
2674: my $output='';
2675: my $response;
2676: if ($filelink=~/^https?\:/) {
2677: ($output,$response)=&externalssi($filelink);
2678: } else {
2679: $filelink .= $filelink=~/\?/ ? '&' : '?';
2680: $filelink .= 'inhibitmenu=yes';
2681: ($output,$response)=&ssi($filelink,%form);
2682: }
2683: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
2684: $output=~s/^.*?\<body[^\>]*\>//si;
2685: $output=~s/\<\/body\s*\>.*?$//si;
2686: if (wantarray) {
2687: return ($output, $response);
2688: } else {
2689: return $output;
2690: }
2691: }
2692:
2693: # --------------------------------------------------------- Server Side Include
2694:
2695: sub absolute_url {
2696: my ($host_name) = @_;
2697: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2698: if ($host_name eq '') {
2699: $host_name = $ENV{'SERVER_NAME'};
2700: }
2701: return $protocol.$host_name;
2702: }
2703:
2704: #
2705: # Server side include.
2706: # Parameters:
2707: # fn Possibly encrypted resource name/id.
2708: # form Hash that describes how the rendering should be done
2709: # and other things.
2710: # Returns:
2711: # Scalar context: The content of the response.
2712: # Array context: 2 element list of the content and the full response object.
2713: #
2714: sub ssi {
2715:
2716: my ($fn,%form)=@_;
2717: my $ua=new LWP::UserAgent;
2718: my $request;
2719:
2720: $form{'no_update_last_known'}=1;
2721: &Apache::lonenc::check_encrypt(\$fn);
2722: if (%form) {
2723: $request=new HTTP::Request('POST',&absolute_url().$fn);
2724: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
2725: } else {
2726: $request=new HTTP::Request('GET',&absolute_url().$fn);
2727: }
2728:
2729: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2730: my $response= $ua->request($request);
2731: my $content = $response->content;
2732:
2733:
2734: if (wantarray) {
2735: return ($content, $response);
2736: } else {
2737: return $content;
2738: }
2739: }
2740:
2741: sub externalssi {
2742: my ($url)=@_;
2743: my $ua=new LWP::UserAgent;
2744: my $request=new HTTP::Request('GET',$url);
2745: my $response=$ua->request($request);
2746: if (wantarray) {
2747: return ($response->content, $response);
2748: } else {
2749: return $response->content;
2750: }
2751: }
2752:
2753: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2754:
2755: sub allowuploaded {
2756: my ($srcurl,$url)=@_;
2757: $url=&clutter(&declutter($url));
2758: my $dir=$url;
2759: $dir=~s/\/[^\/]+$//;
2760: my %httpref=();
2761: my $httpurl=&hreflocation('',$url);
2762: $httpref{'httpref.'.$httpurl}=$srcurl;
2763: &Apache::lonnet::appenv(\%httpref);
2764: }
2765:
2766: #
2767: # Determine if the current user should be able to edit a particular resource,
2768: # when viewing in course context.
2769: # (a) When viewing resource used to determine if "Edit" item is included in
2770: # Functions.
2771: # (b) When displaying folder contents in course editor, used to determine if
2772: # "Edit" link will be displayed alongside resource.
2773: #
2774: # input: six args -- filename (decluttered), course number, course domain,
2775: # url, symb (if registered) and group (if this is a group
2776: # item -- e.g., bulletin board, group page etc.).
2777: # output: array of five scalars --
2778: # $cfile -- url for file editing if editable on current server
2779: # $home -- homeserver of resource (i.e., for author if published,
2780: # or course if uploaded.).
2781: # $switchserver -- 1 if server switch will be needed.
2782: # $forceedit -- 1 if icon/link should be to go to edit mode
2783: # $forceview -- 1 if icon/link should be to go to view mode
2784: #
2785:
2786: sub can_edit_resource {
2787: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2788: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2789: #
2790: # For aboutme pages user can only edit his/her own.
2791: #
2792: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2793: my ($sdom,$sname) = ($1,$2);
2794: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2795: $home = $env{'user.home'};
2796: $cfile = $resurl;
2797: if ($env{'form.forceedit'}) {
2798: $forceview = 1;
2799: } else {
2800: $forceedit = 1;
2801: }
2802: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2803: } else {
2804: return;
2805: }
2806: }
2807:
2808: if ($env{'request.course.id'}) {
2809: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2810: if ($group ne '') {
2811: # if this is a group homepage or group bulletin board, check group privs
2812: my $allowed = 0;
2813: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2814: if ((&allowed('mdg',$env{'request.course.id'}.
2815: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2816: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2817: $allowed = 1;
2818: }
2819: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2820: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2821: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2822: $allowed = 1;
2823: }
2824: }
2825: if ($allowed) {
2826: $home=&homeserver($cnum,$cdom);
2827: if ($env{'form.forceedit'}) {
2828: $forceview = 1;
2829: } else {
2830: $forceedit = 1;
2831: }
2832: $cfile = $resurl;
2833: } else {
2834: return;
2835: }
2836: } else {
2837: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2838: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2839: return;
2840: }
2841: } elsif (!$crsedit) {
2842: #
2843: # No edit allowed where CC has switched to student role.
2844: #
2845: return;
2846: }
2847: }
2848: }
2849:
2850: if ($file ne '') {
2851: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2852: if (&is_course_upload($file,$cnum,$cdom)) {
2853: $uploaded = 1;
2854: $incourse = 1;
2855: if ($file =~/\.(htm|html|css|js|txt)$/) {
2856: $cfile = &hreflocation('',$file);
2857: if ($env{'form.forceedit'}) {
2858: $forceview = 1;
2859: } else {
2860: $forceedit = 1;
2861: }
2862: }
2863: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2864: $incourse = 1;
2865: if ($env{'form.forceedit'}) {
2866: $forceview = 1;
2867: } else {
2868: $forceedit = 1;
2869: }
2870: $cfile = $resurl;
2871: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2872: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2873: $incourse = 1;
2874: if ($env{'form.forceedit'}) {
2875: $forceview = 1;
2876: } else {
2877: $forceedit = 1;
2878: }
2879: $cfile = $resurl;
2880: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2881: $incourse = 1;
2882: $cfile = $resurl.'/smpedit';
2883: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2884: $incourse = 1;
2885: if ($env{'form.forceedit'}) {
2886: $forceview = 1;
2887: } else {
2888: $forceedit = 1;
2889: }
2890: $cfile = $resurl;
2891: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2892: $incourse = 1;
2893: if ($env{'form.forceedit'}) {
2894: $forceview = 1;
2895: } else {
2896: $forceedit = 1;
2897: }
2898: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
2899: }
2900: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2901: my $template = '/res/lib/templates/simpleproblem.problem';
2902: if (&is_on_map($template)) {
2903: $incourse = 1;
2904: $forceview = 1;
2905: $cfile = $template;
2906: }
2907: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2908: $incourse = 1;
2909: if ($env{'form.forceedit'}) {
2910: $forceview = 1;
2911: } else {
2912: $forceedit = 1;
2913: }
2914: $cfile = $resurl;
2915: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2916: $incourse = 1;
2917: $forceview = 1;
2918: if ($symb) {
2919: my ($map,$id,$res)=&decode_symb($symb);
2920: $env{'request.symb'} = $symb;
2921: $cfile = &clutter($res);
2922: } else {
2923: $cfile = $env{'form.suppurl'};
2924: $cfile =~ s{^http://}{};
2925: $cfile = '/adm/wrapper/ext/'.$cfile;
2926: }
2927: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2928: if ($env{'form.forceedit'}) {
2929: $forceview = 1;
2930: } else {
2931: $forceedit = 1;
2932: }
2933: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
2934: }
2935: }
2936: if ($uploaded || $incourse) {
2937: $home=&homeserver($cnum,$cdom);
2938: } elsif ($file !~ m{/$}) {
2939: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2940: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2941: # Check that the user has permission to edit this resource
2942: my $setpriv = 1;
2943: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2944: if (defined($cfudom)) {
2945: $home=&homeserver($cfuname,$cfudom);
2946: $cfile=$file;
2947: }
2948: }
2949: if (($cfile ne '') && (!$incourse || $uploaded) &&
2950: (($home ne '') && ($home ne 'no_host'))) {
2951: my @ids=¤t_machine_ids();
2952: unless (grep(/^\Q$home\E$/,@ids)) {
2953: $switchserver=1;
2954: }
2955: }
2956: }
2957: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2958: }
2959:
2960: sub is_course_upload {
2961: my ($file,$cnum,$cdom) = @_;
2962: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2963: $uploadpath =~ s{^\/}{};
2964: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2965: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2966: return 1;
2967: }
2968: return;
2969: }
2970:
2971: sub in_course {
2972: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2973: if ($hideprivileged) {
2974: my $skipuser;
2975: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2976: my @possdoms = ($cdom);
2977: if ($coursehash{'checkforpriv'}) {
2978: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2979: }
2980: if (&privileged($uname,$udom,\@possdoms)) {
2981: $skipuser = 1;
2982: if ($coursehash{'nothideprivileged'}) {
2983: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2984: my $user;
2985: if ($item =~ /:/) {
2986: $user = $item;
2987: } else {
2988: $user = join(':',split(/[\@]/,$item));
2989: }
2990: if ($user eq $uname.':'.$udom) {
2991: undef($skipuser);
2992: last;
2993: }
2994: }
2995: }
2996: if ($skipuser) {
2997: return 0;
2998: }
2999: }
3000: }
3001: $type ||= 'any';
3002: if (!defined($cdom) || !defined($cnum)) {
3003: my $cid = $env{'request.course.id'};
3004: $cdom = $env{'course.'.$cid.'.domain'};
3005: $cnum = $env{'course.'.$cid.'.num'};
3006: }
3007: my $typesref;
3008: if (($type eq 'any') || ($type eq 'all')) {
3009: $typesref = ['active','previous','future'];
3010: } elsif ($type eq 'previous' || $type eq 'future') {
3011: $typesref = [$type];
3012: }
3013: my %roles = &get_my_roles($uname,$udom,'userroles',
3014: $typesref,undef,[$cdom]);
3015: my ($tmp) = keys(%roles);
3016: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3017: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3018: if (@course_roles > 0) {
3019: return 1;
3020: }
3021: return 0;
3022: }
3023:
3024: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
3025: # input: action, courseID, current domain, intended
3026: # path to file, source of file, instruction to parse file for objects,
3027: # ref to hash for embedded objects,
3028: # ref to hash for codebase of java objects.
3029: # reference to scalar to accommodate mime type determined
3030: # from File::MMagic if $parser = parse.
3031: #
3032: # output: url to file (if action was uploaddoc),
3033: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
3034: #
3035: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3036: # course.
3037: #
3038: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3039: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3040: # course's home server.
3041: #
3042: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3043: # be copied from $source (current location) to
3044: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3045: # and will then be copied to
3046: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3047: # course's home server.
3048: #
3049: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3050: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
3051: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3052: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3053: # in course's home server.
3054: #
3055:
3056: sub process_coursefile {
3057: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3058: $mimetype)=@_;
3059: my $fetchresult;
3060: my $home=&homeserver($docuname,$docudom);
3061: if ($action eq 'propagate') {
3062: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3063: $home);
3064: } else {
3065: my $fpath = '';
3066: my $fname = $file;
3067: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3068: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3069: my $filepath = &build_filepath($fpath);
3070: if ($action eq 'copy') {
3071: if ($source eq '') {
3072: $fetchresult = 'no source file';
3073: return $fetchresult;
3074: } else {
3075: my $destination = $filepath.'/'.$fname;
3076: rename($source,$destination);
3077: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3078: $home);
3079: }
3080: } elsif ($action eq 'uploaddoc') {
3081: open(my $fh,'>'.$filepath.'/'.$fname);
3082: print $fh $env{'form.'.$source};
3083: close($fh);
3084: if ($parser eq 'parse') {
3085: my $mm = new File::MMagic;
3086: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3087: if ($type eq 'text/html') {
3088: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3089: unless ($parse_result eq 'ok') {
3090: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3091: }
3092: }
3093: if (ref($mimetype)) {
3094: $$mimetype = $type;
3095: }
3096: }
3097: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3098: $home);
3099: if ($fetchresult eq 'ok') {
3100: return '/uploaded/'.$fpath.'/'.$fname;
3101: } else {
3102: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3103: ' to host '.$home.': '.$fetchresult);
3104: return '/adm/notfound.html';
3105: }
3106: }
3107: }
3108: unless ( $fetchresult eq 'ok') {
3109: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3110: ' to host '.$home.': '.$fetchresult);
3111: }
3112: return $fetchresult;
3113: }
3114:
3115: sub build_filepath {
3116: my ($fpath) = @_;
3117: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3118: unless ($fpath eq '') {
3119: my @parts=split('/',$fpath);
3120: foreach my $part (@parts) {
3121: $filepath.= '/'.$part;
3122: if ((-e $filepath)!=1) {
3123: mkdir($filepath,0777);
3124: }
3125: }
3126: }
3127: return $filepath;
3128: }
3129:
3130: sub store_edited_file {
3131: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
3132: my $file = $primary_url;
3133: $file =~ s#^/uploaded/$docudom/$docuname/##;
3134: my $fpath = '';
3135: my $fname = $file;
3136: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3137: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3138: my $filepath = &build_filepath($fpath);
3139: open(my $fh,'>'.$filepath.'/'.$fname);
3140: print $fh $content;
3141: close($fh);
3142: my $home=&homeserver($docuname,$docudom);
3143: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3144: $home);
3145: if ($$fetchresult eq 'ok') {
3146: return '/uploaded/'.$fpath.'/'.$fname;
3147: } else {
3148: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3149: ' to host '.$home.': '.$$fetchresult);
3150: return '/adm/notfound.html';
3151: }
3152: }
3153:
3154: sub clean_filename {
3155: my ($fname,$args)=@_;
3156: # Replace Windows backslashes by forward slashes
3157: $fname=~s/\\/\//g;
3158: if (!$args->{'keep_path'}) {
3159: # Get rid of everything but the actual filename
3160: $fname=~s/^.*\/([^\/]+)$/$1/;
3161: }
3162: # Replace spaces by underscores
3163: $fname=~s/\s+/\_/g;
3164: # Replace all other weird characters by nothing
3165: $fname=~s{[^/\w\.\-]}{}g;
3166: # Replace all .\d. sequences with _\d. so they no longer look like version
3167: # numbers
3168: $fname=~s/\.(\d+)(?=\.)/_$1/g;
3169: return $fname;
3170: }
3171: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3172: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3173: # image with the same aspect ratio as the original, but with dimensions which do
3174: # not exceed $resizewidth and $resizeheight.
3175:
3176: sub resizeImage {
3177: my ($img_path,$resizewidth,$resizeheight) = @_;
3178: my $ima = Image::Magick->new;
3179: my $resized;
3180: if (-e $img_path) {
3181: $ima->Read($img_path);
3182: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3183: my $width = $ima->Get('width');
3184: my $height = $ima->Get('height');
3185: if ($width > $resizewidth) {
3186: my $factor = $width/$resizewidth;
3187: my $newheight = $height/$factor;
3188: $ima->Scale(width=>$resizewidth,height=>$newheight);
3189: $resized = 1;
3190: }
3191: }
3192: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3193: my $width = $ima->Get('width');
3194: my $height = $ima->Get('height');
3195: if ($height > $resizeheight) {
3196: my $factor = $height/$resizeheight;
3197: my $newwidth = $width/$factor;
3198: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3199: $resized = 1;
3200: }
3201: }
3202: if ($resized) {
3203: $ima->Write($img_path);
3204: }
3205: }
3206: return;
3207: }
3208:
3209: # --------------- Take an uploaded file and put it into the userfiles directory
3210: # input: $formname - the contents of the file are in $env{"form.$formname"}
3211: # the desired filename is in $env{"form.$formname.filename"}
3212: # $context - possible values: coursedoc, existingfile, overwrite,
3213: # canceloverwrite, or ''.
3214: # if 'coursedoc': upload to the current course
3215: # if 'existingfile': write file to tmp/overwrites directory
3216: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3217: # $context is passed as argument to &finishuserfileupload
3218: # $subdir - directory in userfile to store the file into
3219: # $parser - instruction to parse file for objects ($parser = parse)
3220: # $allfiles - reference to hash for embedded objects
3221: # $codebase - reference to hash for codebase of java objects
3222: # $desuname - username for permanent storage of uploaded file
3223: # $dsetudom - domain for permanaent storage of uploaded file
3224: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3225: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
3226: # $resizewidth - width (pixels) to which to resize uploaded image
3227: # $resizeheight - height (pixels) to which to resize uploaded image
3228: # $mimetype - reference to scalar to accommodate mime type determined
3229: # from File::MMagic.
3230: #
3231: # output: url of file in userspace, or error: <message>
3232: # or /adm/notfound.html if failure to upload occurse
3233:
3234: sub userfileupload {
3235: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
3236: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
3237: if (!defined($subdir)) { $subdir='unknown'; }
3238: my $fname=$env{'form.'.$formname.'.filename'};
3239: $fname=&clean_filename($fname);
3240: # See if there is anything left
3241: unless ($fname) { return 'error: no uploaded file'; }
3242: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3243: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3244: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3245: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3246: my $now = time;
3247: my $filepath;
3248: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
3249: $filepath = 'tmp/helprequests/'.$now;
3250: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3251: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3252: '_'.$env{'user.domain'}.'/pending';
3253: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3254: my ($docuname,$docudom);
3255: if ($destudom) {
3256: $docudom = $destudom;
3257: } else {
3258: $docudom = $env{'user.domain'};
3259: }
3260: if ($destuname) {
3261: $docuname = $destuname;
3262: } else {
3263: $docuname = $env{'user.name'};
3264: }
3265: if (exists($env{'form.group'})) {
3266: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3267: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3268: }
3269: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3270: if ($context eq 'canceloverwrite') {
3271: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3272: if (-e $tempfile) {
3273: my @info = stat($tempfile);
3274: if ($info[9] eq $env{'form.timestamp'}) {
3275: unlink($tempfile);
3276: }
3277: }
3278: return;
3279: }
3280: }
3281: # Create the directory if not present
3282: my @parts=split(/\//,$filepath);
3283: my $fullpath = $perlvar{'lonDaemons'};
3284: for (my $i=0;$i<@parts;$i++) {
3285: $fullpath .= '/'.$parts[$i];
3286: if ((-e $fullpath)!=1) {
3287: mkdir($fullpath,0777);
3288: }
3289: }
3290: open(my $fh,'>'.$fullpath.'/'.$fname);
3291: print $fh $env{'form.'.$formname};
3292: close($fh);
3293: if ($context eq 'existingfile') {
3294: my @info = stat($fullpath.'/'.$fname);
3295: return ($fullpath.'/'.$fname,$info[9]);
3296: } else {
3297: return $fullpath.'/'.$fname;
3298: }
3299: }
3300: if ($subdir eq 'scantron') {
3301: $fname = 'scantron_orig_'.$fname;
3302: } else {
3303: $fname="$subdir/$fname";
3304: }
3305: if ($context eq 'coursedoc') {
3306: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3307: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3308: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
3309: return &finishuserfileupload($docuname,$docudom,
3310: $formname,$fname,$parser,$allfiles,
3311: $codebase,$thumbwidth,$thumbheight,
3312: $resizewidth,$resizeheight,$context,$mimetype);
3313: } else {
3314: if ($env{'form.folder'}) {
3315: $fname=$env{'form.folder'}.'/'.$fname;
3316: }
3317: return &process_coursefile('uploaddoc',$docuname,$docudom,
3318: $fname,$formname,$parser,
3319: $allfiles,$codebase,$mimetype);
3320: }
3321: } elsif (defined($destuname)) {
3322: my $docuname=$destuname;
3323: my $docudom=$destudom;
3324: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3325: $parser,$allfiles,$codebase,
3326: $thumbwidth,$thumbheight,
3327: $resizewidth,$resizeheight,$context,$mimetype);
3328: } else {
3329: my $docuname=$env{'user.name'};
3330: my $docudom=$env{'user.domain'};
3331: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
3332: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3333: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3334: }
3335: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3336: $parser,$allfiles,$codebase,
3337: $thumbwidth,$thumbheight,
3338: $resizewidth,$resizeheight,$context,$mimetype);
3339: }
3340: }
3341:
3342: sub finishuserfileupload {
3343: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
3344: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
3345: my $path=$docudom.'/'.$docuname.'/';
3346: my $filepath=$perlvar{'lonDocRoot'};
3347:
3348: my ($fnamepath,$file,$fetchthumb);
3349: $file=$fname;
3350: if ($fname=~m|/|) {
3351: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3352: $path.=$fnamepath.'/';
3353: }
3354: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
3355: my $count;
3356: for ($count=4;$count<=$#parts;$count++) {
3357: $filepath.="/$parts[$count]";
3358: if ((-e $filepath)!=1) {
3359: mkdir($filepath,0777);
3360: }
3361: }
3362:
3363: # Save the file
3364: {
3365: if (!open(FH,'>'.$filepath.'/'.$file)) {
3366: &logthis('Failed to create '.$filepath.'/'.$file);
3367: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3368: return '/adm/notfound.html';
3369: }
3370: if ($context eq 'overwrite') {
3371: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
3372: my $target = $filepath.'/'.$file;
3373: if (-e $source) {
3374: my @info = stat($source);
3375: if ($info[9] eq $env{'form.timestamp'}) {
3376: unless (&File::Copy::move($source,$target)) {
3377: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3378: return "Moving from $source failed";
3379: }
3380: } else {
3381: return "Temporary file: $source had unexpected date/time for last modification";
3382: }
3383: } else {
3384: return "Temporary file: $source missing";
3385: }
3386: } elsif (!print FH ($env{'form.'.$formname})) {
3387: &logthis('Failed to write to '.$filepath.'/'.$file);
3388: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3389: return '/adm/notfound.html';
3390: }
3391: close(FH);
3392: if ($resizewidth && $resizeheight) {
3393: my $mm = new File::MMagic;
3394: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3395: if ($mime_type =~ m{^image/}) {
3396: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3397: }
3398: }
3399: }
3400: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3401: if (ref($mimetype)) {
3402: if ($$mimetype eq '') {
3403: my $mm = new File::MMagic;
3404: my $type = $mm->checktype_filename($filepath.'/'.$file);
3405: $$mimetype = $type;
3406: }
3407: }
3408: }
3409: if ($parser eq 'parse') {
3410: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
3411: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3412: $allfiles,$codebase);
3413: unless ($parse_result eq 'ok') {
3414: &logthis('Failed to parse '.$filepath.$file.
3415: ' for embedded media: '.$parse_result);
3416: }
3417: }
3418: }
3419: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3420: my $input = $filepath.'/'.$file;
3421: my $output = $filepath.'/'.'tn-'.$file;
3422: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3423: system("convert -sample $thumbsize $input $output");
3424: if (-e $filepath.'/'.'tn-'.$file) {
3425: $fetchthumb = 1;
3426: }
3427: }
3428:
3429: # Notify homeserver to grep it
3430: #
3431: my $docuhome=&homeserver($docuname,$docudom);
3432: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
3433: if ($fetchresult eq 'ok') {
3434: if ($fetchthumb) {
3435: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3436: if ($thumbresult ne 'ok') {
3437: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3438: $docuhome.': '.$thumbresult);
3439: }
3440: }
3441: #
3442: # Return the URL to it
3443: return '/uploaded/'.$path.$file;
3444: } else {
3445: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3446: ': '.$fetchresult);
3447: return '/adm/notfound.html';
3448: }
3449: }
3450:
3451: sub extract_embedded_items {
3452: my ($fullpath,$allfiles,$codebase,$content) = @_;
3453: my @state = ();
3454: my (%lastids,%related,%shockwave,%flashvars);
3455: my %javafiles = (
3456: codebase => '',
3457: code => '',
3458: archive => ''
3459: );
3460: my %mediafiles = (
3461: src => '',
3462: movie => '',
3463: );
3464: my $p;
3465: if ($content) {
3466: $p = HTML::LCParser->new($content);
3467: } else {
3468: $p = HTML::LCParser->new($fullpath);
3469: }
3470: while (my $t=$p->get_token()) {
3471: if ($t->[0] eq 'S') {
3472: my ($tagname, $attr) = ($t->[1],$t->[2]);
3473: push(@state, $tagname);
3474: if (lc($tagname) eq 'allow') {
3475: &add_filetype($allfiles,$attr->{'src'},'src');
3476: }
3477: if (lc($tagname) eq 'img') {
3478: &add_filetype($allfiles,$attr->{'src'},'src');
3479: }
3480: if (lc($tagname) eq 'a') {
3481: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3482: &add_filetype($allfiles,$attr->{'href'},'href');
3483: }
3484: }
3485: if (lc($tagname) eq 'script') {
3486: my $src;
3487: if ($attr->{'archive'} =~ /\.jar$/i) {
3488: &add_filetype($allfiles,$attr->{'archive'},'archive');
3489: } else {
3490: if ($attr->{'src'} ne '') {
3491: $src = $attr->{'src'};
3492: &add_filetype($allfiles,$src,'src');
3493: }
3494: }
3495: my $text = $p->get_trimmed_text();
3496: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3497: my @swfargs = split(/,/,$1);
3498: foreach my $item (@swfargs) {
3499: $item =~ s/["']//g;
3500: $item =~ s/^\s+//;
3501: $item =~ s/\s+$//;
3502: }
3503: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3504: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3505: push(@{$related{$swfargs[0]}},$swfargs[2]);
3506: } else {
3507: $related{$swfargs[0]} = [$swfargs[2]];
3508: }
3509: }
3510: }
3511: }
3512: if (lc($tagname) eq 'link') {
3513: if (lc($attr->{'rel'}) eq 'stylesheet') {
3514: &add_filetype($allfiles,$attr->{'href'},'href');
3515: }
3516: }
3517: if (lc($tagname) eq 'object' ||
3518: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3519: foreach my $item (keys(%javafiles)) {
3520: $javafiles{$item} = '';
3521: }
3522: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3523: $lastids{lc($tagname)} = $attr->{'id'};
3524: }
3525: }
3526: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3527: my $name = lc($attr->{'name'});
3528: foreach my $item (keys(%javafiles)) {
3529: if ($name eq $item) {
3530: $javafiles{$item} = $attr->{'value'};
3531: last;
3532: }
3533: }
3534: my $pathfrom;
3535: foreach my $item (keys(%mediafiles)) {
3536: if ($name eq $item) {
3537: $pathfrom = $attr->{'value'};
3538: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3539: &add_filetype($allfiles,$pathfrom,$name);
3540: last;
3541: }
3542: }
3543: if ($name eq 'flashvars') {
3544: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3545: }
3546: if ($pathfrom ne '') {
3547: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3548: $pathfrom);
3549: }
3550: }
3551: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3552: foreach my $item (keys(%javafiles)) {
3553: if ($attr->{$item}) {
3554: $javafiles{$item} = $attr->{$item};
3555: last;
3556: }
3557: }
3558: foreach my $item (keys(%mediafiles)) {
3559: if ($attr->{$item}) {
3560: &add_filetype($allfiles,$attr->{$item},$item);
3561: last;
3562: }
3563: }
3564: if (lc($tagname) eq 'embed') {
3565: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3566: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3567: $attr->{'src'});
3568: }
3569: }
3570: }
3571: if (lc($tagname) eq 'iframe') {
3572: my $src = $attr->{'src'} ;
3573: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3574: &add_filetype($allfiles,$src,'src');
3575: } elsif ($src =~ m{^/}) {
3576: if ($env{'request.course.id'}) {
3577: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3578: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3579: my $url = &hreflocation('',$fullpath);
3580: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3581: my $relpath = $1;
3582: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3583: &add_filetype($allfiles,$1,'src');
3584: }
3585: }
3586: }
3587: }
3588: }
3589: if ($t->[4] =~ m{/>$}) {
3590: pop(@state);
3591: }
3592: } elsif ($t->[0] eq 'E') {
3593: my ($tagname) = ($t->[1]);
3594: if ($javafiles{'codebase'} ne '') {
3595: $javafiles{'codebase'} .= '/';
3596: }
3597: if (lc($tagname) eq 'applet' ||
3598: lc($tagname) eq 'object' ||
3599: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3600: ) {
3601: foreach my $item (keys(%javafiles)) {
3602: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3603: my $file=$javafiles{'codebase'}.$javafiles{$item};
3604: &add_filetype($allfiles,$file,$item);
3605: }
3606: }
3607: }
3608: pop @state;
3609: }
3610: }
3611: foreach my $id (sort(keys(%flashvars))) {
3612: if ($shockwave{$id} ne '') {
3613: my @pairs = split(/\&/,$flashvars{$id});
3614: foreach my $pair (@pairs) {
3615: my ($key,$value) = split(/\=/,$pair);
3616: if ($key eq 'thumb') {
3617: &add_filetype($allfiles,$value,$key);
3618: } elsif ($key eq 'content') {
3619: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3620: my ($ext) = ($value =~ /\.([^.]+)$/);
3621: if ($ext ne '') {
3622: &add_filetype($allfiles,$path.$value,$ext);
3623: }
3624: }
3625: }
3626: }
3627: }
3628: return 'ok';
3629: }
3630:
3631: sub add_filetype {
3632: my ($allfiles,$file,$type)=@_;
3633: if (exists($allfiles->{$file})) {
3634: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3635: push(@{$allfiles->{$file}}, &escape($type));
3636: }
3637: } else {
3638: @{$allfiles->{$file}} = (&escape($type));
3639: }
3640: }
3641:
3642: sub embedded_dependency {
3643: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3644: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3645: if (($identifier ne '') &&
3646: (ref($related->{$identifier}) eq 'ARRAY') &&
3647: ($pathfrom ne '')) {
3648: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3649: foreach my $dep (@{$related->{$identifier}}) {
3650: &add_filetype($allfiles,$path.$dep,'object');
3651: }
3652: }
3653: }
3654: return;
3655: }
3656:
3657: sub removeuploadedurl {
3658: my ($url)=@_;
3659: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
3660: return &removeuserfile($uname,$udom,$fname);
3661: }
3662:
3663: sub removeuserfile {
3664: my ($docuname,$docudom,$fname)=@_;
3665: my $home=&homeserver($docuname,$docudom);
3666: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
3667: if ($result eq 'ok') {
3668: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3669: my $metafile = $fname.'.meta';
3670: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
3671: my $url = "/uploaded/$docudom/$docuname/$fname";
3672: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3673: my $sqlresult =
3674: &update_portfolio_table($docuname,$docudom,$file,
3675: 'portfolio_metadata',$group,
3676: 'delete');
3677: }
3678: }
3679: return $result;
3680: }
3681:
3682: sub mkdiruserfile {
3683: my ($docuname,$docudom,$dir)=@_;
3684: my $home=&homeserver($docuname,$docudom);
3685: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3686: }
3687:
3688: sub renameuserfile {
3689: my ($docuname,$docudom,$old,$new)=@_;
3690: my $home=&homeserver($docuname,$docudom);
3691: my $result = &reply("renameuserfile:$docudom:$docuname:".
3692: &escape("$old").':'.&escape("$new"),$home);
3693: if ($result eq 'ok') {
3694: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3695: my $oldmeta = $old.'.meta';
3696: my $newmeta = $new.'.meta';
3697: my $metaresult =
3698: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
3699: my $url = "/uploaded/$docudom/$docuname/$old";
3700: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3701: my $sqlresult =
3702: &update_portfolio_table($docuname,$docudom,$file,
3703: 'portfolio_metadata',$group,
3704: 'delete');
3705: }
3706: }
3707: return $result;
3708: }
3709:
3710: # ------------------------------------------------------------------------- Log
3711:
3712: sub log {
3713: my ($dom,$nam,$hom,$what)=@_;
3714: return critical("log:$dom:$nam:$what",$hom);
3715: }
3716:
3717: # ------------------------------------------------------------------ Course Log
3718: #
3719: # This routine flushes several buffers of non-mission-critical nature
3720: #
3721:
3722: sub flushcourselogs {
3723: &logthis('Flushing log buffers');
3724: #
3725: # course logs
3726: # This is a log of all transactions in a course, which can be used
3727: # for data mining purposes
3728: #
3729: # It also collects the courseid database, which lists last transaction
3730: # times and course titles for all courseids
3731: #
3732: my %courseidbuffer=();
3733: foreach my $crsid (keys(%courselogs)) {
3734: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
3735: &escape($courselogs{$crsid}),
3736: $coursehombuf{$crsid}) eq 'ok') {
3737: delete $courselogs{$crsid};
3738: } else {
3739: &logthis('Failed to flush log buffer for '.$crsid);
3740: if (length($courselogs{$crsid})>40000) {
3741: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
3742: " exceeded maximum size, deleting.</font>");
3743: delete $courselogs{$crsid};
3744: }
3745: }
3746: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
3747: 'description' => $coursedescrbuf{$crsid},
3748: 'inst_code' => $courseinstcodebuf{$crsid},
3749: 'type' => $coursetypebuf{$crsid},
3750: 'owner' => $courseownerbuf{$crsid},
3751: };
3752: }
3753: #
3754: # Write course id database (reverse lookup) to homeserver of courses
3755: # Is used in pickcourse
3756: #
3757: foreach my $crs_home (keys(%courseidbuffer)) {
3758: my $response = &courseidput(&host_domain($crs_home),
3759: $courseidbuffer{$crs_home},
3760: $crs_home,'timeonly');
3761: }
3762: #
3763: # File accesses
3764: # Writes to the dynamic metadata of resources to get hit counts, etc.
3765: #
3766: foreach my $entry (keys(%accesshash)) {
3767: if ($entry =~ /___count$/) {
3768: my ($dom,$name);
3769: ($dom,$name,undef)=
3770: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
3771: if (! defined($dom) || $dom eq '' ||
3772: ! defined($name) || $name eq '') {
3773: my $cid = $env{'request.course.id'};
3774: $dom = $env{'request.'.$cid.'.domain'};
3775: $name = $env{'request.'.$cid.'.num'};
3776: }
3777: my $value = $accesshash{$entry};
3778: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3779: my %temphash=($url => $value);
3780: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3781: if ($result eq 'ok') {
3782: delete $accesshash{$entry};
3783: }
3784: } else {
3785: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
3786: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
3787: my %temphash=($entry => $accesshash{$entry});
3788: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3789: delete $accesshash{$entry};
3790: }
3791: }
3792: }
3793: #
3794: # Roles
3795: # Reverse lookup of user roles for course faculty/staff and co-authorship
3796: #
3797: foreach my $entry (keys(%userrolehash)) {
3798: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
3799: split(/\:/,$entry);
3800: if (&Apache::lonnet::put('nohist_userroles',
3801: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
3802: $rudom,$runame) eq 'ok') {
3803: delete $userrolehash{$entry};
3804: }
3805: }
3806: #
3807: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3808: #
3809: my %domrolebuffer = ();
3810: foreach my $entry (keys(%domainrolehash)) {
3811: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
3812: if ($domrolebuffer{$rudom}) {
3813: $domrolebuffer{$rudom}.='&'.&escape($entry).
3814: '='.&escape($domainrolehash{$entry});
3815: } else {
3816: $domrolebuffer{$rudom}.=&escape($entry).
3817: '='.&escape($domainrolehash{$entry});
3818: }
3819: delete $domainrolehash{$entry};
3820: }
3821: foreach my $dom (keys(%domrolebuffer)) {
3822: my %servers = &get_servers($dom,'library');
3823: foreach my $tryserver (keys(%servers)) {
3824: unless (&reply('domroleput:'.$dom.':'.
3825: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3826: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3827: }
3828: }
3829: }
3830: $dumpcount++;
3831: }
3832:
3833: sub courselog {
3834: my $what=shift;
3835: $what=time.':'.$what;
3836: unless ($env{'request.course.id'}) { return ''; }
3837: $coursedombuf{$env{'request.course.id'}}=
3838: $env{'course.'.$env{'request.course.id'}.'.domain'};
3839: $coursenumbuf{$env{'request.course.id'}}=
3840: $env{'course.'.$env{'request.course.id'}.'.num'};
3841: $coursehombuf{$env{'request.course.id'}}=
3842: $env{'course.'.$env{'request.course.id'}.'.home'};
3843: $coursedescrbuf{$env{'request.course.id'}}=
3844: $env{'course.'.$env{'request.course.id'}.'.description'};
3845: $courseinstcodebuf{$env{'request.course.id'}}=
3846: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3847: $courseownerbuf{$env{'request.course.id'}}=
3848: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
3849: $coursetypebuf{$env{'request.course.id'}}=
3850: $env{'course.'.$env{'request.course.id'}.'.type'};
3851: if (defined $courselogs{$env{'request.course.id'}}) {
3852: $courselogs{$env{'request.course.id'}}.='&'.$what;
3853: } else {
3854: $courselogs{$env{'request.course.id'}}.=$what;
3855: }
3856: if (length($courselogs{$env{'request.course.id'}})>4048) {
3857: &flushcourselogs();
3858: }
3859: }
3860:
3861: sub courseacclog {
3862: my $fnsymb=shift;
3863: unless ($env{'request.course.id'}) { return ''; }
3864: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
3865: if ($fnsymb=~/$LONCAPA::assess_re/) {
3866: $what.=':POST';
3867: # FIXME: Probably ought to escape things....
3868: foreach my $key (keys(%env)) {
3869: if ($key=~/^form\.(.*)/) {
3870: my $formitem = $1;
3871: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3872: $what.=':'.$formitem.'='.$env{$key};
3873: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3874: $what.=':'.$formitem.'='.$env{$key};
3875: }
3876: }
3877: }
3878: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3879: # FIXME: We should not be depending on a form parameter that someone
3880: # editing lonsearchcat.pm might change in the future.
3881: if ($env{'form.phase'} eq 'course_search') {
3882: $what.= ':POST';
3883: # FIXME: Probably ought to escape things....
3884: foreach my $element ('courseexp','crsfulltext','crsrelated',
3885: 'crsdiscuss') {
3886: $what.=':'.$element.'='.$env{'form.'.$element};
3887: }
3888: }
3889: }
3890: &courselog($what);
3891: }
3892:
3893: sub countacc {
3894: my $url=&declutter(shift);
3895: return if (! defined($url) || $url eq '');
3896: unless ($env{'request.course.id'}) { return ''; }
3897: #
3898: # Mark that this url was used in this course
3899: #
3900: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
3901: #
3902: # Increase the access count for this resource in this child process
3903: #
3904: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
3905: $accesshash{$key}++;
3906: }
3907:
3908: sub linklog {
3909: my ($from,$to)=@_;
3910: $from=&declutter($from);
3911: $to=&declutter($to);
3912: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3913: $accesshash{$to.'___'.$from.'___goto'}=1;
3914: }
3915:
3916: sub statslog {
3917: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3918: if ($users<2) { return; }
3919: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3920: 'course' => $env{'request.course.id'},
3921: 'sections' => '"all"',
3922: 'num_students' => $users,
3923: 'part' => $part,
3924: 'symb' => $symb,
3925: 'mean_tries' => $av_attempts,
3926: 'deg_of_diff' => $degdiff});
3927: foreach my $key (keys(%dynstore)) {
3928: $accesshash{$key}=$dynstore{$key};
3929: }
3930: }
3931:
3932: sub userrolelog {
3933: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
3934: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
3935: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3936: $userrolehash
3937: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3938: =$tend.':'.$tstart;
3939: }
3940: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
3941: $userrolehash
3942: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3943: =$tend.':'.$tstart;
3944: }
3945: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
3946: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3947: $domainrolehash
3948: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3949: = $tend.':'.$tstart;
3950: }
3951: }
3952:
3953: sub courserolelog {
3954: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3955: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3956: my $cdom = $1;
3957: my $cnum = $2;
3958: my $sec = $3;
3959: my $namespace = 'rolelog';
3960: my %storehash = (
3961: role => $trole,
3962: start => $tstart,
3963: end => $tend,
3964: selfenroll => $selfenroll,
3965: context => $context,
3966: );
3967: if ($trole eq 'gr') {
3968: $namespace = 'groupslog';
3969: $storehash{'group'} = $sec;
3970: } else {
3971: $storehash{'section'} = $sec;
3972: }
3973: &write_log('course',$namespace,\%storehash,$delflag,$username,
3974: $domain,$cnum,$cdom);
3975: if (($trole ne 'st') || ($sec ne '')) {
3976: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3977: }
3978: }
3979: return;
3980: }
3981:
3982: sub domainrolelog {
3983: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
3984: if ($area =~ m{^/($match_domain)/$}) {
3985: my $cdom = $1;
3986: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
3987: my $namespace = 'rolelog';
3988: my %storehash = (
3989: role => $trole,
3990: start => $tstart,
3991: end => $tend,
3992: context => $context,
3993: );
3994: &write_log('domain',$namespace,\%storehash,$delflag,$username,
3995: $domain,$domconfiguser,$cdom);
3996: }
3997: return;
3998:
3999: }
4000:
4001: sub coauthorrolelog {
4002: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4003: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4004: my $audom = $1;
4005: my $auname = $2;
4006: my $namespace = 'rolelog';
4007: my %storehash = (
4008: role => $trole,
4009: start => $tstart,
4010: end => $tend,
4011: context => $context,
4012: );
4013: &write_log('author',$namespace,\%storehash,$delflag,$username,
4014: $domain,$auname,$audom);
4015: }
4016: return;
4017: }
4018:
4019: sub get_course_adv_roles {
4020: my ($cid,$codes) = @_;
4021: $cid=$env{'request.course.id'} unless (defined($cid));
4022: my %coursehash=&coursedescription($cid);
4023: my $crstype = &Apache::loncommon::course_type($cid);
4024: my %nothide=();
4025: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4026: if ($user !~ /:/) {
4027: $nothide{join(':',split(/[\@]/,$user))}=1;
4028: } else {
4029: $nothide{$user}=1;
4030: }
4031: }
4032: my @possdoms = ($coursehash{'domain'});
4033: if ($coursehash{'checkforpriv'}) {
4034: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4035: }
4036: my %returnhash=();
4037: my %dumphash=
4038: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4039: my $now=time;
4040: my %privileged;
4041: foreach my $entry (keys(%dumphash)) {
4042: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4043: if (($tstart) && ($tstart<0)) { next; }
4044: if (($tend) && ($tend<$now)) { next; }
4045: if (($tstart) && ($now<$tstart)) { next; }
4046: my ($role,$username,$domain,$section)=split(/\:/,$entry);
4047: if ($username eq '' || $domain eq '') { next; }
4048: if ((&privileged($username,$domain,\@possdoms)) &&
4049: (!$nothide{$username.':'.$domain})) { next; }
4050: if ($role eq 'cr') { next; }
4051: if ($codes) {
4052: if ($section) { $role .= ':'.$section; }
4053: if ($returnhash{$role}) {
4054: $returnhash{$role}.=','.$username.':'.$domain;
4055: } else {
4056: $returnhash{$role}=$username.':'.$domain;
4057: }
4058: } else {
4059: my $key=&plaintext($role,$crstype);
4060: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
4061: if ($returnhash{$key}) {
4062: $returnhash{$key}.=','.$username.':'.$domain;
4063: } else {
4064: $returnhash{$key}=$username.':'.$domain;
4065: }
4066: }
4067: }
4068: return %returnhash;
4069: }
4070:
4071: sub get_my_roles {
4072: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
4073: unless (defined($uname)) { $uname=$env{'user.name'}; }
4074: unless (defined($udom)) { $udom=$env{'user.domain'}; }
4075: my (%dumphash,%nothide);
4076: if ($context eq 'userroles') {
4077: %dumphash = &dump('roles',$udom,$uname);
4078: } else {
4079: %dumphash = &dump('nohist_userroles',$udom,$uname);
4080: if ($hidepriv) {
4081: my %coursehash=&coursedescription($udom.'_'.$uname);
4082: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4083: if ($user !~ /:/) {
4084: $nothide{join(':',split(/[\@]/,$user))} = 1;
4085: } else {
4086: $nothide{$user} = 1;
4087: }
4088: }
4089: }
4090: }
4091: my %returnhash=();
4092: my $now=time;
4093: my %privileged;
4094: foreach my $entry (keys(%dumphash)) {
4095: my ($role,$tend,$tstart);
4096: if ($context eq 'userroles') {
4097: next if ($entry =~ /^rolesdef/);
4098: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4099: } else {
4100: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4101: }
4102: if (($tstart) && ($tstart<0)) { next; }
4103: my $status = 'active';
4104: if (($tend) && ($tend<=$now)) {
4105: $status = 'previous';
4106: }
4107: if (($tstart) && ($now<$tstart)) {
4108: $status = 'future';
4109: }
4110: if (ref($types) eq 'ARRAY') {
4111: if (!grep(/^\Q$status\E$/,@{$types})) {
4112: next;
4113: }
4114: } else {
4115: if ($status ne 'active') {
4116: next;
4117: }
4118: }
4119: my ($rolecode,$username,$domain,$section,$area);
4120: if ($context eq 'userroles') {
4121: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
4122: (undef,$domain,$username,$section) = split(/\//,$area);
4123: } else {
4124: ($role,$username,$domain,$section) = split(/\:/,$entry);
4125: }
4126: if (ref($roledoms) eq 'ARRAY') {
4127: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4128: next;
4129: }
4130: }
4131: if (ref($roles) eq 'ARRAY') {
4132: if (!grep(/^\Q$role\E$/,@{$roles})) {
4133: if ($role =~ /^cr\//) {
4134: if (!grep(/^cr$/,@{$roles})) {
4135: next;
4136: }
4137: } elsif ($role =~ /^gr\//) {
4138: if (!grep(/^gr$/,@{$roles})) {
4139: next;
4140: }
4141: } else {
4142: next;
4143: }
4144: }
4145: }
4146: if ($hidepriv) {
4147: my @privroles = ('dc','su');
4148: if ($context eq 'userroles') {
4149: next if (grep(/^\Q$role\E$/,@privroles));
4150: } else {
4151: my $possdoms = [$domain];
4152: if (ref($roledoms) eq 'ARRAY') {
4153: push(@{$possdoms},@{$roledoms});
4154: }
4155: if (&privileged($username,$domain,$possdoms,\@privroles)) {
4156: if (!$nothide{$username.':'.$domain}) {
4157: next;
4158: }
4159: }
4160: }
4161: }
4162: if ($withsec) {
4163: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4164: $tstart.':'.$tend;
4165: } else {
4166: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4167: }
4168: }
4169: return %returnhash;
4170: }
4171:
4172: # ----------------------------------------------------- Frontpage Announcements
4173: #
4174: #
4175:
4176: sub postannounce {
4177: my ($server,$text)=@_;
4178: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
4179: unless ($text=~/\w/) { $text=''; }
4180: return &reply('setannounce:'.&escape($text),$server);
4181: }
4182:
4183: sub getannounce {
4184:
4185: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
4186: my $announcement='';
4187: while (my $line = <$fh>) { $announcement .= $line; }
4188: close($fh);
4189: if ($announcement=~/\w/) {
4190: return
4191: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
4192: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
4193: } else {
4194: return '';
4195: }
4196: } else {
4197: return '';
4198: }
4199: }
4200:
4201: # ---------------------------------------------------------- Course ID routines
4202: # Deal with domain's nohist_courseid.db files
4203: #
4204:
4205: sub courseidput {
4206: my ($domain,$storehash,$coursehome,$caller) = @_;
4207: return unless (ref($storehash) eq 'HASH');
4208: my $outcome;
4209: if ($caller eq 'timeonly') {
4210: my $cids = '';
4211: foreach my $item (keys(%$storehash)) {
4212: $cids.=&escape($item).'&';
4213: }
4214: $cids=~s/\&$//;
4215: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4216: $coursehome);
4217: } else {
4218: my $items = '';
4219: foreach my $item (keys(%$storehash)) {
4220: $items.= &escape($item).'='.
4221: &freeze_escape($$storehash{$item}).'&';
4222: }
4223: $items=~s/\&$//;
4224: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4225: $coursehome);
4226: }
4227: if ($outcome eq 'unknown_cmd') {
4228: my $what;
4229: foreach my $cid (keys(%$storehash)) {
4230: $what .= &escape($cid).'=';
4231: foreach my $item ('description','inst_code','owner','type') {
4232: $what .= &escape($storehash->{$cid}{$item}).':';
4233: }
4234: $what =~ s/\:$/&/;
4235: }
4236: $what =~ s/\&$//;
4237: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4238: } else {
4239: return $outcome;
4240: }
4241: }
4242:
4243: sub courseiddump {
4244: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
4245: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
4246: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
4247: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4248: $hasuniquecode)=@_;
4249: my $as_hash = 1;
4250: my %returnhash;
4251: if (!$domfilter) { $domfilter=''; }
4252: my %libserv = &all_library();
4253: foreach my $tryserver (keys(%libserv)) {
4254: if ( ( $hostidflag == 1
4255: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4256: || (!defined($hostidflag)) ) {
4257:
4258: if (($domfilter eq '') ||
4259: (&host_domain($tryserver) eq $domfilter)) {
4260: my $rep;
4261: if (grep { $_ eq $tryserver } current_machine_ids()) {
4262: $rep = LONCAPA::Lond::dump_course_id_handler(
4263: join(":", (&host_domain($tryserver), $sincefilter,
4264: &escape($descfilter), &escape($instcodefilter),
4265: &escape($ownerfilter), &escape($coursefilter),
4266: &escape($typefilter), &escape($regexp_ok),
4267: $as_hash, &escape($selfenrollonly),
4268: &escape($catfilter), $showhidden, $caller,
4269: &escape($cloner), &escape($cc_clone), $cloneonly,
4270: &escape($createdbefore), &escape($createdafter),
4271: &escape($creationcontext), $domcloner, $hasuniquecode)));
4272: } else {
4273: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4274: $sincefilter.':'.&escape($descfilter).':'.
4275: &escape($instcodefilter).':'.&escape($ownerfilter).
4276: ':'.&escape($coursefilter).':'.&escape($typefilter).
4277: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4278: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4279: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4280: &escape($cc_clone).':'.$cloneonly.':'.
4281: &escape($createdbefore).':'.&escape($createdafter).':'.
4282: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
4283: $tryserver);
4284: }
4285:
4286: my @pairs=split(/\&/,$rep);
4287: foreach my $item (@pairs) {
4288: my ($key,$value)=split(/\=/,$item,2);
4289: $key = &unescape($key);
4290: next if ($key =~ /^error: 2 /);
4291: my $result = &thaw_unescape($value);
4292: if (ref($result) eq 'HASH') {
4293: $returnhash{$key}=$result;
4294: } else {
4295: my @responses = split(/:/,$value);
4296: my @items = ('description','inst_code','owner','type');
4297: for (my $i=0; $i<@responses; $i++) {
4298: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
4299: }
4300: }
4301: }
4302: }
4303: }
4304: }
4305: return %returnhash;
4306: }
4307:
4308: sub courselastaccess {
4309: my ($cdom,$cnum,$hostidref) = @_;
4310: my %returnhash;
4311: if ($cdom && $cnum) {
4312: my $chome = &homeserver($cnum,$cdom);
4313: if ($chome ne 'no_host') {
4314: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4315: &extract_lastaccess(\%returnhash,$rep);
4316: }
4317: } else {
4318: if (!$cdom) { $cdom=''; }
4319: my %libserv = &all_library();
4320: foreach my $tryserver (keys(%libserv)) {
4321: if (ref($hostidref) eq 'ARRAY') {
4322: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4323: }
4324: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4325: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4326: &extract_lastaccess(\%returnhash,$rep);
4327: }
4328: }
4329: }
4330: return %returnhash;
4331: }
4332:
4333: sub extract_lastaccess {
4334: my ($returnhash,$rep) = @_;
4335: if (ref($returnhash) eq 'HASH') {
4336: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4337: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4338: $rep eq '') {
4339: my @pairs=split(/\&/,$rep);
4340: foreach my $item (@pairs) {
4341: my ($key,$value)=split(/\=/,$item,2);
4342: $key = &unescape($key);
4343: next if ($key =~ /^error: 2 /);
4344: $returnhash->{$key} = &thaw_unescape($value);
4345: }
4346: }
4347: }
4348: return;
4349: }
4350:
4351: # ---------------------------------------------------------- DC e-mail
4352:
4353: sub dcmailput {
4354: my ($domain,$msgid,$message,$server)=@_;
4355: my $status = &Apache::lonnet::critical(
4356: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4357: &escape($message),$server);
4358: return $status;
4359: }
4360:
4361: sub dcmaildump {
4362: my ($dom,$startdate,$enddate,$senders) = @_;
4363: my %returnhash=();
4364:
4365: if (defined(&domain($dom,'primary'))) {
4366: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4367: &escape($enddate).':';
4368: my @esc_senders=map { &escape($_)} @$senders;
4369: $cmd.=&escape(join('&',@esc_senders));
4370: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
4371: my ($key,$value) = split(/\=/,$line,2);
4372: if (($key) && ($value)) {
4373: $returnhash{&unescape($key)} = &unescape($value);
4374: }
4375: }
4376: }
4377: return %returnhash;
4378: }
4379: # ---------------------------------------------------------- Domain roles
4380:
4381: sub get_domain_roles {
4382: my ($dom,$roles,$startdate,$enddate)=@_;
4383: if ((!defined($startdate)) || ($startdate eq '')) {
4384: $startdate = '.';
4385: }
4386: if ((!defined($enddate)) || ($enddate eq '')) {
4387: $enddate = '.';
4388: }
4389: my $rolelist;
4390: if (ref($roles) eq 'ARRAY') {
4391: $rolelist = join('&',@{$roles});
4392: }
4393: my %personnel = ();
4394:
4395: my %servers = &get_servers($dom,'library');
4396: foreach my $tryserver (keys(%servers)) {
4397: %{$personnel{$tryserver}}=();
4398: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4399: &escape($startdate).':'.
4400: &escape($enddate).':'.
4401: &escape($rolelist), $tryserver))) {
4402: my ($key,$value) = split(/\=/,$line,2);
4403: if (($key) && ($value)) {
4404: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4405: }
4406: }
4407: }
4408: return %personnel;
4409: }
4410:
4411: # ----------------------------------------------------------- Interval timing
4412:
4413: {
4414: # Caches needed for speedup of navmaps
4415: # We don't want to cache this for very long at all (5 seconds at most)
4416: #
4417: # The user for whom we cache
4418: my $cachedkey='';
4419: # The cached times for this user
4420: my %cachedtimes=();
4421: # When this was last done
4422: my $cachedtime=();
4423:
4424: sub load_all_first_access {
4425: my ($uname,$udom)=@_;
4426: if (($cachedkey eq $uname.':'.$udom) &&
4427: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
4428: return;
4429: }
4430: $cachedtime=time;
4431: $cachedkey=$uname.':'.$udom;
4432: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
4433: }
4434:
4435: sub get_first_access {
4436: my ($type,$argsymb,$argmap)=@_;
4437: my ($symb,$courseid,$udom,$uname)=&whichuser();
4438: if ($argsymb) { $symb=$argsymb; }
4439: my ($map,$id,$res)=&decode_symb($symb);
4440: if ($argmap) { $map = $argmap; }
4441: if ($type eq 'course') {
4442: $res='course';
4443: } elsif ($type eq 'map') {
4444: $res=&symbread($map);
4445: } else {
4446: $res=$symb;
4447: }
4448: &load_all_first_access($uname,$udom);
4449: return $cachedtimes{"$courseid\0$res"};
4450: }
4451:
4452: sub set_first_access {
4453: my ($type,$interval)=@_;
4454: my ($symb,$courseid,$udom,$uname)=&whichuser();
4455: my ($map,$id,$res)=&decode_symb($symb);
4456: if ($type eq 'course') {
4457: $res='course';
4458: } elsif ($type eq 'map') {
4459: $res=&symbread($map);
4460: } else {
4461: $res=$symb;
4462: }
4463: $cachedkey='';
4464: my $firstaccess=&get_first_access($type,$symb,$map);
4465: if (!$firstaccess) {
4466: my $start = time;
4467: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4468: $udom,$uname);
4469: if ($putres eq 'ok') {
4470: &put('timerinterval',{"$courseid\0$res"=>$interval},
4471: $udom,$uname);
4472: &appenv(
4473: {
4474: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4475: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4476: }
4477: );
4478: }
4479: return $putres;
4480: }
4481: return 'already_set';
4482: }
4483: }
4484: # --------------------------------------------- Set Expire Date for Spreadsheet
4485:
4486: sub expirespread {
4487: my ($uname,$udom,$stype,$usymb)=@_;
4488: my $cid=$env{'request.course.id'};
4489: if ($cid) {
4490: my $now=time;
4491: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
4492: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4493: $env{'course.'.$cid.'.num'}.
4494: ':nohist_expirationdates:'.
4495: &escape($key).'='.$now,
4496: $env{'course.'.$cid.'.home'})
4497: }
4498: return 'ok';
4499: }
4500:
4501: # ----------------------------------------------------- Devalidate Spreadsheets
4502:
4503: sub devalidate {
4504: my ($symb,$uname,$udom)=@_;
4505: my $cid=$env{'request.course.id'};
4506: if ($cid) {
4507: # delete the stored spreadsheets for
4508: # - the student level sheet of this user in course's homespace
4509: # - the assessment level sheet for this resource
4510: # for this user in user's homespace
4511: # - current conditional state info
4512: my $key=$uname.':'.$udom.':';
4513: my $status=
4514: &del('nohist_calculatedsheets',
4515: [$key.'studentcalc:'],
4516: $env{'course.'.$cid.'.domain'},
4517: $env{'course.'.$cid.'.num'})
4518: .' '.
4519: &del('nohist_calculatedsheets_'.$cid,
4520: [$key.'assesscalc:'.$symb],$udom,$uname);
4521: unless ($status eq 'ok ok') {
4522: &logthis('Could not devalidate spreadsheet '.
4523: $uname.' at '.$udom.' for '.
4524: $symb.': '.$status);
4525: }
4526: &delenv('user.state.'.$cid);
4527: }
4528: }
4529:
4530: sub get_scalar {
4531: my ($string,$end) = @_;
4532: my $value;
4533: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4534: $value = $1;
4535: } elsif ($$string =~ s/^([^&]*?)&//) {
4536: $value = $1;
4537: }
4538: return &unescape($value);
4539: }
4540:
4541: sub array2str {
4542: my (@array) = @_;
4543: my $result=&arrayref2str(\@array);
4544: $result=~s/^__ARRAY_REF__//;
4545: $result=~s/__END_ARRAY_REF__$//;
4546: return $result;
4547: }
4548:
4549: sub arrayref2str {
4550: my ($arrayref) = @_;
4551: my $result='__ARRAY_REF__';
4552: foreach my $elem (@$arrayref) {
4553: if(ref($elem) eq 'ARRAY') {
4554: $result.=&arrayref2str($elem).'&';
4555: } elsif(ref($elem) eq 'HASH') {
4556: $result.=&hashref2str($elem).'&';
4557: } elsif(ref($elem)) {
4558: #print("Got a ref of ".(ref($elem))." skipping.");
4559: } else {
4560: $result.=&escape($elem).'&';
4561: }
4562: }
4563: $result=~s/\&$//;
4564: $result .= '__END_ARRAY_REF__';
4565: return $result;
4566: }
4567:
4568: sub hash2str {
4569: my (%hash) = @_;
4570: my $result=&hashref2str(\%hash);
4571: $result=~s/^__HASH_REF__//;
4572: $result=~s/__END_HASH_REF__$//;
4573: return $result;
4574: }
4575:
4576: sub hashref2str {
4577: my ($hashref)=@_;
4578: my $result='__HASH_REF__';
4579: foreach my $key (sort(keys(%$hashref))) {
4580: if (ref($key) eq 'ARRAY') {
4581: $result.=&arrayref2str($key).'=';
4582: } elsif (ref($key) eq 'HASH') {
4583: $result.=&hashref2str($key).'=';
4584: } elsif (ref($key)) {
4585: $result.='=';
4586: #print("Got a ref of ".(ref($key))." skipping.");
4587: } else {
4588: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
4589: }
4590:
4591: if(ref($hashref->{$key}) eq 'ARRAY') {
4592: $result.=&arrayref2str($hashref->{$key}).'&';
4593: } elsif(ref($hashref->{$key}) eq 'HASH') {
4594: $result.=&hashref2str($hashref->{$key}).'&';
4595: } elsif(ref($hashref->{$key})) {
4596: $result.='&';
4597: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
4598: } else {
4599: $result.=&escape($hashref->{$key}).'&';
4600: }
4601: }
4602: $result=~s/\&$//;
4603: $result .= '__END_HASH_REF__';
4604: return $result;
4605: }
4606:
4607: sub str2hash {
4608: my ($string)=@_;
4609: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4610: return %$hash;
4611: }
4612:
4613: sub str2hashref {
4614: my ($string) = @_;
4615:
4616: my %hash;
4617:
4618: if($string !~ /^__HASH_REF__/) {
4619: if (! ($string eq '' || !defined($string))) {
4620: $hash{'error'}='Not hash reference';
4621: }
4622: return (\%hash, $string);
4623: }
4624:
4625: $string =~ s/^__HASH_REF__//;
4626:
4627: while($string !~ /^__END_HASH_REF__/) {
4628: #key
4629: my $key='';
4630: if($string =~ /^__HASH_REF__/) {
4631: ($key, $string)=&str2hashref($string);
4632: if(defined($key->{'error'})) {
4633: $hash{'error'}='Bad data';
4634: return (\%hash, $string);
4635: }
4636: } elsif($string =~ /^__ARRAY_REF__/) {
4637: ($key, $string)=&str2arrayref($string);
4638: if($key->[0] eq 'Array reference error') {
4639: $hash{'error'}='Bad data';
4640: return (\%hash, $string);
4641: }
4642: } else {
4643: $string =~ s/^(.*?)=//;
4644: $key=&unescape($1);
4645: }
4646: $string =~ s/^=//;
4647:
4648: #value
4649: my $value='';
4650: if($string =~ /^__HASH_REF__/) {
4651: ($value, $string)=&str2hashref($string);
4652: if(defined($value->{'error'})) {
4653: $hash{'error'}='Bad data';
4654: return (\%hash, $string);
4655: }
4656: } elsif($string =~ /^__ARRAY_REF__/) {
4657: ($value, $string)=&str2arrayref($string);
4658: if($value->[0] eq 'Array reference error') {
4659: $hash{'error'}='Bad data';
4660: return (\%hash, $string);
4661: }
4662: } else {
4663: $value=&get_scalar(\$string,'__END_HASH_REF__');
4664: }
4665: $string =~ s/^&//;
4666:
4667: $hash{$key}=$value;
4668: }
4669:
4670: $string =~ s/^__END_HASH_REF__//;
4671:
4672: return (\%hash, $string);
4673: }
4674:
4675: sub str2array {
4676: my ($string)=@_;
4677: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4678: return @$array;
4679: }
4680:
4681: sub str2arrayref {
4682: my ($string) = @_;
4683: my @array;
4684:
4685: if($string !~ /^__ARRAY_REF__/) {
4686: if (! ($string eq '' || !defined($string))) {
4687: $array[0]='Array reference error';
4688: }
4689: return (\@array, $string);
4690: }
4691:
4692: $string =~ s/^__ARRAY_REF__//;
4693:
4694: while($string !~ /^__END_ARRAY_REF__/) {
4695: my $value='';
4696: if($string =~ /^__HASH_REF__/) {
4697: ($value, $string)=&str2hashref($string);
4698: if(defined($value->{'error'})) {
4699: $array[0] ='Array reference error';
4700: return (\@array, $string);
4701: }
4702: } elsif($string =~ /^__ARRAY_REF__/) {
4703: ($value, $string)=&str2arrayref($string);
4704: if($value->[0] eq 'Array reference error') {
4705: $array[0] ='Array reference error';
4706: return (\@array, $string);
4707: }
4708: } else {
4709: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4710: }
4711: $string =~ s/^&//;
4712:
4713: push(@array, $value);
4714: }
4715:
4716: $string =~ s/^__END_ARRAY_REF__//;
4717:
4718: return (\@array, $string);
4719: }
4720:
4721: # -------------------------------------------------------------------Temp Store
4722:
4723: sub tmpreset {
4724: my ($symb,$namespace,$domain,$stuname) = @_;
4725: if (!$symb) {
4726: $symb=&symbread();
4727: if (!$symb) { $symb= $env{'request.url'}; }
4728: }
4729: $symb=escape($symb);
4730:
4731: if (!$namespace) { $namespace=$env{'request.state'}; }
4732: $namespace=~s/\//\_/g;
4733: $namespace=~s/\W//g;
4734:
4735: if (!$domain) { $domain=$env{'user.domain'}; }
4736: if (!$stuname) { $stuname=$env{'user.name'}; }
4737: if ($domain eq 'public' && $stuname eq 'public') {
4738: $stuname=$ENV{'REMOTE_ADDR'};
4739: }
4740: my $path=LONCAPA::tempdir();
4741: my %hash;
4742: if (tie(%hash,'GDBM_File',
4743: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4744: &GDBM_WRCREAT(),0640)) {
4745: foreach my $key (keys(%hash)) {
4746: if ($key=~ /:$symb/) {
4747: delete($hash{$key});
4748: }
4749: }
4750: }
4751: }
4752:
4753: sub tmpstore {
4754: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4755:
4756: if (!$symb) {
4757: $symb=&symbread();
4758: if (!$symb) { $symb= $env{'request.url'}; }
4759: }
4760: $symb=escape($symb);
4761:
4762: if (!$namespace) {
4763: # I don't think we would ever want to store this for a course.
4764: # it seems this will only be used if we don't have a course.
4765: #$namespace=$env{'request.course.id'};
4766: #if (!$namespace) {
4767: $namespace=$env{'request.state'};
4768: #}
4769: }
4770: $namespace=~s/\//\_/g;
4771: $namespace=~s/\W//g;
4772: if (!$domain) { $domain=$env{'user.domain'}; }
4773: if (!$stuname) { $stuname=$env{'user.name'}; }
4774: if ($domain eq 'public' && $stuname eq 'public') {
4775: $stuname=$ENV{'REMOTE_ADDR'};
4776: }
4777: my $now=time;
4778: my %hash;
4779: my $path=LONCAPA::tempdir();
4780: if (tie(%hash,'GDBM_File',
4781: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4782: &GDBM_WRCREAT(),0640)) {
4783: $hash{"version:$symb"}++;
4784: my $version=$hash{"version:$symb"};
4785: my $allkeys='';
4786: foreach my $key (keys(%$storehash)) {
4787: $allkeys.=$key.':';
4788: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
4789: }
4790: $hash{"$version:$symb:timestamp"}=$now;
4791: $allkeys.='timestamp';
4792: $hash{"$version:keys:$symb"}=$allkeys;
4793: if (untie(%hash)) {
4794: return 'ok';
4795: } else {
4796: return "error:$!";
4797: }
4798: } else {
4799: return "error:$!";
4800: }
4801: }
4802:
4803: # -----------------------------------------------------------------Temp Restore
4804:
4805: sub tmprestore {
4806: my ($symb,$namespace,$domain,$stuname) = @_;
4807:
4808: if (!$symb) {
4809: $symb=&symbread();
4810: if (!$symb) { $symb= $env{'request.url'}; }
4811: }
4812: $symb=escape($symb);
4813:
4814: if (!$namespace) { $namespace=$env{'request.state'}; }
4815:
4816: if (!$domain) { $domain=$env{'user.domain'}; }
4817: if (!$stuname) { $stuname=$env{'user.name'}; }
4818: if ($domain eq 'public' && $stuname eq 'public') {
4819: $stuname=$ENV{'REMOTE_ADDR'};
4820: }
4821: my %returnhash;
4822: $namespace=~s/\//\_/g;
4823: $namespace=~s/\W//g;
4824: my %hash;
4825: my $path=LONCAPA::tempdir();
4826: if (tie(%hash,'GDBM_File',
4827: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4828: &GDBM_READER(),0640)) {
4829: my $version=$hash{"version:$symb"};
4830: $returnhash{'version'}=$version;
4831: my $scope;
4832: for ($scope=1;$scope<=$version;$scope++) {
4833: my $vkeys=$hash{"$scope:keys:$symb"};
4834: my @keys=split(/:/,$vkeys);
4835: my $key;
4836: $returnhash{"$scope:keys"}=$vkeys;
4837: foreach $key (@keys) {
4838: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4839: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4840: }
4841: }
4842: if (!(untie(%hash))) {
4843: return "error:$!";
4844: }
4845: } else {
4846: return "error:$!";
4847: }
4848: return %returnhash;
4849: }
4850:
4851: # ----------------------------------------------------------------------- Store
4852:
4853: sub store {
4854: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4855: my $home='';
4856:
4857: if ($stuname) { $home=&homeserver($stuname,$domain); }
4858:
4859: $symb=&symbclean($symb);
4860: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4861:
4862: if (!$domain) { $domain=$env{'user.domain'}; }
4863: if (!$stuname) { $stuname=$env{'user.name'}; }
4864:
4865: &devalidate($symb,$stuname,$domain);
4866:
4867: $symb=escape($symb);
4868: if (!$namespace) {
4869: unless ($namespace=$env{'request.course.id'}) {
4870: return '';
4871: }
4872: }
4873: if (!$home) { $home=$env{'user.home'}; }
4874:
4875: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4876: $$storehash{'host'}=$perlvar{'lonHostID'};
4877:
4878: my $namevalue='';
4879: foreach my $key (keys(%$storehash)) {
4880: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4881: }
4882: $namevalue=~s/\&$//;
4883: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
4884: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4885: }
4886:
4887: # -------------------------------------------------------------- Critical Store
4888:
4889: sub cstore {
4890: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4891: my $home='';
4892:
4893: if ($stuname) { $home=&homeserver($stuname,$domain); }
4894:
4895: $symb=&symbclean($symb);
4896: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4897:
4898: if (!$domain) { $domain=$env{'user.domain'}; }
4899: if (!$stuname) { $stuname=$env{'user.name'}; }
4900:
4901: &devalidate($symb,$stuname,$domain);
4902:
4903: $symb=escape($symb);
4904: if (!$namespace) {
4905: unless ($namespace=$env{'request.course.id'}) {
4906: return '';
4907: }
4908: }
4909: if (!$home) { $home=$env{'user.home'}; }
4910:
4911: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4912: $$storehash{'host'}=$perlvar{'lonHostID'};
4913:
4914: my $namevalue='';
4915: foreach my $key (keys(%$storehash)) {
4916: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4917: }
4918: $namevalue=~s/\&$//;
4919: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
4920: return critical
4921: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4922: }
4923:
4924: # --------------------------------------------------------------------- Restore
4925:
4926: sub restore {
4927: my ($symb,$namespace,$domain,$stuname) = @_;
4928: my $home='';
4929:
4930: if ($stuname) { $home=&homeserver($stuname,$domain); }
4931:
4932: if (!$symb) {
4933: return if ($namespace eq 'courserequests');
4934: unless ($symb=escape(&symbread())) { return ''; }
4935: } else {
4936: unless ($namespace eq 'courserequests') {
4937: $symb=&escape(&symbclean($symb));
4938: }
4939: }
4940: if (!$namespace) {
4941: unless ($namespace=$env{'request.course.id'}) {
4942: return '';
4943: }
4944: }
4945: if (!$domain) { $domain=$env{'user.domain'}; }
4946: if (!$stuname) { $stuname=$env{'user.name'}; }
4947: if (!$home) { $home=$env{'user.home'}; }
4948: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4949:
4950: my %returnhash=();
4951: foreach my $line (split(/\&/,$answer)) {
4952: my ($name,$value)=split(/\=/,$line);
4953: $returnhash{&unescape($name)}=&thaw_unescape($value);
4954: }
4955: my $version;
4956: for ($version=1;$version<=$returnhash{'version'};$version++) {
4957: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4958: $returnhash{$item}=$returnhash{$version.':'.$item};
4959: }
4960: }
4961: return %returnhash;
4962: }
4963:
4964: # ---------------------------------------------------------- Course Description
4965: #
4966: #
4967:
4968: sub coursedescription {
4969: my ($courseid,$args)=@_;
4970: $courseid=~s/^\///;
4971: $courseid=~s/\_/\//g;
4972: my ($cdomain,$cnum)=split(/\//,$courseid);
4973: my $chome=&homeserver($cnum,$cdomain);
4974: my $normalid=$cdomain.'_'.$cnum;
4975: # need to always cache even if we get errors otherwise we keep
4976: # trying and trying and trying to get the course description.
4977: my %envhash=();
4978: my %returnhash=();
4979:
4980: my $expiretime=600;
4981: if ($env{'request.course.id'} eq $normalid) {
4982: $expiretime=120;
4983: }
4984:
4985: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4986: if (!$args->{'freshen_cache'}
4987: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4988: foreach my $key (keys(%env)) {
4989: next if ($key !~ /^\Q$prefix\E(.*)/);
4990: my ($setting) = $1;
4991: $returnhash{$setting} = $env{$key};
4992: }
4993: return %returnhash;
4994: }
4995:
4996: # get the data again
4997:
4998: if (!$args->{'one_time'}) {
4999: $envhash{'course.'.$normalid.'.last_cache'}=time;
5000: }
5001:
5002: if ($chome ne 'no_host') {
5003: %returnhash=&dump('environment',$cdomain,$cnum);
5004: if (!exists($returnhash{'con_lost'})) {
5005: my $username = $env{'user.name'}; # Defult username
5006: if(defined $args->{'user'}) {
5007: $username = $args->{'user'};
5008: }
5009: $returnhash{'home'}= $chome;
5010: $returnhash{'domain'} = $cdomain;
5011: $returnhash{'num'} = $cnum;
5012: if (!defined($returnhash{'type'})) {
5013: $returnhash{'type'} = 'Course';
5014: }
5015: while (my ($name,$value) = each %returnhash) {
5016: $envhash{'course.'.$normalid.'.'.$name}=$value;
5017: }
5018: $returnhash{'url'}=&clutter($returnhash{'url'});
5019: $returnhash{'fn'}=LONCAPA::tempdir() .
5020: $username.'_'.$cdomain.'_'.$cnum;
5021: $envhash{'course.'.$normalid.'.home'}=$chome;
5022: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5023: $envhash{'course.'.$normalid.'.num'}=$cnum;
5024: }
5025: }
5026: if (!$args->{'one_time'}) {
5027: &appenv(\%envhash);
5028: }
5029: return %returnhash;
5030: }
5031:
5032: sub update_released_required {
5033: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5034: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5035: $cid = $env{'request.course.id'};
5036: $cdom = $env{'course.'.$cid.'.domain'};
5037: $cnum = $env{'course.'.$cid.'.num'};
5038: $chome = $env{'course.'.$cid.'.home'};
5039: }
5040: if ($needsrelease) {
5041: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5042: my $needsupdate;
5043: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5044: $needsupdate = 1;
5045: } else {
5046: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5047: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5048: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5049: $needsupdate = 1;
5050: }
5051: }
5052: if ($needsupdate) {
5053: my %needshash = (
5054: 'internal.releaserequired' => $needsrelease,
5055: );
5056: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5057: if ($putresult eq 'ok') {
5058: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5059: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5060: if (ref($crsinfo{$cid}) eq 'HASH') {
5061: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5062: &courseidput($cdom,\%crsinfo,$chome,'notime');
5063: }
5064: }
5065: }
5066: }
5067: return;
5068: }
5069:
5070: # -------------------------------------------------See if a user is privileged
5071:
5072: sub privileged {
5073: my ($username,$domain,$possdomains,$possroles)=@_;
5074: my $now = time;
5075: my $roles;
5076: if (ref($possroles) eq 'ARRAY') {
5077: $roles = $possroles;
5078: } else {
5079: $roles = ['dc','su'];
5080: }
5081: if (ref($possdomains) eq 'ARRAY') {
5082: my %privileged = &privileged_by_domain($possdomains,$roles);
5083: foreach my $dom (@{$possdomains}) {
5084: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5085: (ref($privileged{$dom}) eq 'HASH')) {
5086: foreach my $role (@{$roles}) {
5087: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5088: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5089: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5090: return 1 unless (($end && $end < $now) ||
5091: ($start && $start > $now));
5092: }
5093: }
5094: }
5095: }
5096: }
5097: } else {
5098: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5099: my $now = time;
5100:
5101: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
5102: my ($trole, $tend, $tstart) = split(/_/, $role);
5103: if (grep(/^\Q$trole\E$/,@{$roles})) {
5104: return 1 unless ($tend && $tend < $now)
5105: or ($tstart && $tstart > $now);
5106: }
5107: }
5108: }
5109: return 0;
5110: }
5111:
5112: sub privileged_by_domain {
5113: my ($domains,$roles) = @_;
5114: my %privileged = ();
5115: my $cachetime = 60*60*24;
5116: my $now = time;
5117: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5118: return %privileged;
5119: }
5120: foreach my $dom (@{$domains}) {
5121: next if (ref($privileged{$dom}) eq 'HASH');
5122: my $needroles;
5123: foreach my $role (@{$roles}) {
5124: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5125: if (defined($cached)) {
5126: if (ref($result) eq 'HASH') {
5127: $privileged{$dom}{$role} = $result;
5128: }
5129: } else {
5130: $needroles = 1;
5131: }
5132: }
5133: if ($needroles) {
5134: my %dompersonnel = &get_domain_roles($dom,$roles);
5135: $privileged{$dom} = {};
5136: foreach my $server (keys(%dompersonnel)) {
5137: if (ref($dompersonnel{$server}) eq 'HASH') {
5138: foreach my $item (keys(%{$dompersonnel{$server}})) {
5139: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5140: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5141: next if ($end && $end < $now);
5142: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5143: $dompersonnel{$server}{$item};
5144: }
5145: }
5146: }
5147: if (ref($privileged{$dom}) eq 'HASH') {
5148: foreach my $role (@{$roles}) {
5149: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5150: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5151: } else {
5152: my %hash = ();
5153: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5154: }
5155: }
5156: }
5157: }
5158: }
5159: return %privileged;
5160: }
5161:
5162: # -------------------------------------------------------- Get user privileges
5163:
5164: sub rolesinit {
5165: my ($domain, $username) = @_;
5166: my %userroles = ('user.login.time' => time);
5167: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5168:
5169: # firstaccess and timerinterval are related to timed maps/resources.
5170: # also, blocking can be triggered by an activating timer
5171: # it's saved in the user's %env.
5172: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5173: my %timerinterval = &dump('timerinterval', $domain, $username);
5174: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5175: %timerintchk, %timerintenv);
5176:
5177: foreach my $key (keys(%firstaccess)) {
5178: my ($cid, $rest) = split(/\0/, $key);
5179: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5180: }
5181:
5182: foreach my $key (keys(%timerinterval)) {
5183: my ($cid,$rest) = split(/\0/,$key);
5184: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5185: }
5186:
5187: my %allroles=();
5188: my %allgroups=();
5189:
5190: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
5191: my $role = $rolesdump{$area};
5192: $area =~ s/\_\w\w$//;
5193:
5194: my ($trole, $tend, $tstart, $group_privs);
5195:
5196: if ($role =~ /^cr/) {
5197: # Custom role, defined by a user
5198: # e.g., user.role.cr/msu/smith/mynewrole
5199: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5200: $trole = $1;
5201: ($tend, $tstart) = split('_', $2);
5202: } else {
5203: $trole = $role;
5204: }
5205: } elsif ($role =~ m|^gr/|) {
5206: # Role of member in a group, defined within a course/community
5207: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5208: ($trole, $tend, $tstart) = split(/_/, $role);
5209: next if $tstart eq '-1';
5210: ($trole, $group_privs) = split(/\//, $trole);
5211: $group_privs = &unescape($group_privs);
5212: } else {
5213: # Just a normal role, defined in roles.tab
5214: ($trole, $tend, $tstart) = split(/_/,$role);
5215: }
5216:
5217: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5218: $username);
5219: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5220:
5221: # role expired or not available yet?
5222: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5223: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5224:
5225: next if $area eq '' or $trole eq '';
5226:
5227: my $spec = "$trole.$area";
5228: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5229:
5230: if ($trole =~ /^cr\//) {
5231: # Custom role, defined by a user
5232: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5233: } elsif ($trole eq 'gr') {
5234: # Role of a member in a group, defined within a course/community
5235: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5236: next;
5237: } else {
5238: # Normal role, defined in roles.tab
5239: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5240: }
5241:
5242: my $cid = $tdomain.'_'.$trest;
5243: unless ($firstaccchk{$cid}) {
5244: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5245: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5246: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5247: $coursetimerstarts{$cid}{$item};
5248: }
5249: }
5250: $firstaccchk{$cid} = 1;
5251: }
5252: unless ($timerintchk{$cid}) {
5253: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5254: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5255: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5256: $coursetimerintervals{$cid}{$item};
5257: }
5258: }
5259: $timerintchk{$cid} = 1;
5260: }
5261: }
5262:
5263: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5264: \%allroles, \%allgroups);
5265: $env{'user.adv'} = $userroles{'user.adv'};
5266:
5267: return (\%userroles,\%firstaccenv,\%timerintenv);
5268: }
5269:
5270: sub set_arearole {
5271: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5272: unless ($nolog) {
5273: # log the associated role with the area
5274: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5275: }
5276: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
5277: }
5278:
5279: sub custom_roleprivs {
5280: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5281: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
5282: my $homsvr = &homeserver($rauthor,$rdomain);
5283: if (&hostname($homsvr) ne '') {
5284: my ($rdummy,$roledef)=
5285: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5286: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5287: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5288: if (defined($syspriv)) {
5289: if ($trest =~ /^$match_community$/) {
5290: $syspriv =~ s/bre\&S//;
5291: }
5292: $$allroles{'cm./'}.=':'.$syspriv;
5293: $$allroles{$spec.'./'}.=':'.$syspriv;
5294: }
5295: if ($tdomain ne '') {
5296: if (defined($dompriv)) {
5297: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5298: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5299: }
5300: if (($trest ne '') && (defined($coursepriv))) {
5301: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5302: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5303: }
5304: }
5305: }
5306: }
5307: }
5308:
5309: sub group_roleprivs {
5310: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5311: my $access = 1;
5312: my $now = time;
5313: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5314: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5315: if ($access) {
5316: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
5317: $$allgroups{$course}{$group} .=':'.$group_privs;
5318: }
5319: }
5320:
5321: sub standard_roleprivs {
5322: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5323: if (defined($pr{$trole.':s'})) {
5324: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5325: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5326: }
5327: if ($tdomain ne '') {
5328: if (defined($pr{$trole.':d'})) {
5329: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5330: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5331: }
5332: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5333: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5334: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5335: }
5336: }
5337: }
5338:
5339: sub set_userprivs {
5340: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
5341: my $author=0;
5342: my $adv=0;
5343: my %grouproles = ();
5344: if (keys(%{$allgroups}) > 0) {
5345: my @groupkeys;
5346: foreach my $role (keys(%{$allroles})) {
5347: push(@groupkeys,$role);
5348: }
5349: if (ref($groups_roles) eq 'HASH') {
5350: foreach my $key (keys(%{$groups_roles})) {
5351: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5352: push(@groupkeys,$key);
5353: }
5354: }
5355: }
5356: if (@groupkeys > 0) {
5357: foreach my $role (@groupkeys) {
5358: my ($trole,$area,$sec,$extendedarea);
5359: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5360: $trole = $1;
5361: $area = $2;
5362: $sec = $3;
5363: $extendedarea = $area.$sec;
5364: if (exists($$allgroups{$area})) {
5365: foreach my $group (keys(%{$$allgroups{$area}})) {
5366: my $spec = $trole.'.'.$extendedarea;
5367: $grouproles{$spec.'.'.$area.'/'.$group} =
5368: $$allgroups{$area}{$group};
5369: }
5370: }
5371: }
5372: }
5373: }
5374: }
5375: foreach my $group (keys(%grouproles)) {
5376: $$allroles{$group} = $grouproles{$group};
5377: }
5378: foreach my $role (keys(%{$allroles})) {
5379: my %thesepriv;
5380: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
5381: foreach my $item (split(/:/,$$allroles{$role})) {
5382: if ($item ne '') {
5383: my ($privilege,$restrictions)=split(/&/,$item);
5384: if ($restrictions eq '') {
5385: $thesepriv{$privilege}='F';
5386: } elsif ($thesepriv{$privilege} ne 'F') {
5387: $thesepriv{$privilege}.=$restrictions;
5388: }
5389: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5390: }
5391: }
5392: my $thesestr='';
5393: foreach my $priv (sort(keys(%thesepriv))) {
5394: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5395: }
5396: $userroles->{'user.priv.'.$role} = $thesestr;
5397: }
5398: return ($author,$adv);
5399: }
5400:
5401: sub role_status {
5402: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
5403: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
5404: my ($one,$two) = split(m{\./},$rolekey,2);
5405: (undef,undef,$$role) = split(/\./,$one,3);
5406: unless (!defined($$role) || $$role eq '') {
5407: $$where = '/'.$two;
5408: $$trolecode=$$role.'.'.$$where;
5409: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5410: $$tstatus='is';
5411: if ($$tstart && $$tstart>$update) {
5412: $$tstatus='future';
5413: if ($$tstart<$now) {
5414: if ($$tstart && $$tstart>$refresh) {
5415: if (($$where ne '') && ($$role ne '')) {
5416: my (%allroles,%allgroups,$group_privs,
5417: %groups_roles,@rolecodes);
5418: my %userroles = (
5419: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5420: );
5421: @rolecodes = ('cm');
5422: my $spec=$$role.'.'.$$where;
5423: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5424: if ($$role =~ /^cr\//) {
5425: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
5426: push(@rolecodes,'cr');
5427: } elsif ($$role eq 'gr') {
5428: push(@rolecodes,$$role);
5429: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5430: $env{'user.name'});
5431: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
5432: (undef,my $group_privs) = split(/\//,$trole);
5433: $group_privs = &unescape($group_privs);
5434: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
5435: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
5436: &get_groups_roles($tdomain,$trest,
5437: \%course_roles,\@rolecodes,
5438: \%groups_roles);
5439: } else {
5440: push(@rolecodes,$$role);
5441: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5442: }
5443: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5444: &appenv(\%userroles,\@rolecodes);
5445: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5446: }
5447: }
5448: $$tstatus = 'is';
5449: }
5450: }
5451: if ($$tend) {
5452: if ($$tend<$update) {
5453: $$tstatus='expired';
5454: } elsif ($$tend<$now) {
5455: $$tstatus='will_not';
5456: }
5457: }
5458: }
5459: }
5460: }
5461:
5462: sub get_groups_roles {
5463: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5464: return unless((ref($cdom_courseroles) eq 'HASH') &&
5465: (ref($rolecodes) eq 'ARRAY') &&
5466: (ref($groups_roles) eq 'HASH'));
5467: if (keys(%{$cdom_courseroles}) > 0) {
5468: my ($cnum) = ($rest =~ /^($match_courseid)/);
5469: if ($cdom ne '' && $cnum ne '') {
5470: foreach my $key (keys(%{$cdom_courseroles})) {
5471: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5472: my $crsrole = $1;
5473: my $crssec = $2;
5474: if ($crsrole =~ /^cr/) {
5475: unless (grep(/^cr$/,@{$rolecodes})) {
5476: push(@{$rolecodes},'cr');
5477: }
5478: } else {
5479: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5480: push(@{$rolecodes},$crsrole);
5481: }
5482: }
5483: my $rolekey = "$crsrole./$cdom/$cnum";
5484: if ($crssec ne '') {
5485: $rolekey .= "/$crssec";
5486: }
5487: $rolekey .= './';
5488: $groups_roles->{$rolekey} = $rolecodes;
5489: }
5490: }
5491: }
5492: }
5493: return;
5494: }
5495:
5496: sub delete_env_groupprivs {
5497: my ($where,$courseroles,$possroles) = @_;
5498: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5499: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5500: unless (ref($courseroles->{$udom}) eq 'HASH') {
5501: %{$courseroles->{$udom}} =
5502: &get_my_roles('','','userroles',['active'],
5503: $possroles,[$udom],1);
5504: }
5505: if (ref($courseroles->{$udom}) eq 'HASH') {
5506: foreach my $item (keys(%{$courseroles->{$udom}})) {
5507: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5508: my $area = '/'.$cdom.'/'.$cnum;
5509: my $privkey = "user.priv.$crsrole.$area";
5510: if ($crssec ne '') {
5511: $privkey .= '/'.$crssec;
5512: }
5513: $privkey .= ".$area/$group";
5514: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5515: }
5516: }
5517: return;
5518: }
5519:
5520: sub check_adhoc_privs {
5521: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
5522: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
5523: my $setprivs;
5524: if ($env{$cckey}) {
5525: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
5526: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
5527: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
5528: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
5529: $setprivs = 1;
5530: }
5531: } else {
5532: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
5533: $setprivs = 1;
5534: }
5535: return $setprivs;
5536: }
5537:
5538: sub set_adhoc_privileges {
5539: # role can be cc or ca
5540: my ($dcdom,$pickedcourse,$role,$caller) = @_;
5541: my $area = '/'.$dcdom.'/'.$pickedcourse;
5542: my $spec = $role.'.'.$area;
5543: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
5544: $env{'user.name'},1);
5545: my %ccrole = ();
5546: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5547: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5548: &appenv(\%userroles,[$role,'cm']);
5549: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5550: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5551: &appenv( {'request.role' => $spec,
5552: 'request.role.domain' => $dcdom,
5553: 'request.course.sec' => ''
5554: }
5555: );
5556: my $tadv=0;
5557: if (&allowed('adv') eq 'F') { $tadv=1; }
5558: &appenv({'request.role.adv' => $tadv});
5559: }
5560: }
5561:
5562: # --------------------------------------------------------------- get interface
5563:
5564: sub get {
5565: my ($namespace,$storearr,$udomain,$uname)=@_;
5566: my $items='';
5567: foreach my $item (@$storearr) {
5568: $items.=&escape($item).'&';
5569: }
5570: $items=~s/\&$//;
5571: if (!$udomain) { $udomain=$env{'user.domain'}; }
5572: if (!$uname) { $uname=$env{'user.name'}; }
5573: my $uhome=&homeserver($uname,$udomain);
5574:
5575: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
5576: my @pairs=split(/\&/,$rep);
5577: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5578: return @pairs;
5579: }
5580: my %returnhash=();
5581: my $i=0;
5582: foreach my $item (@$storearr) {
5583: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5584: $i++;
5585: }
5586: return %returnhash;
5587: }
5588:
5589: # --------------------------------------------------------------- del interface
5590:
5591: sub del {
5592: my ($namespace,$storearr,$udomain,$uname)=@_;
5593: my $items='';
5594: foreach my $item (@$storearr) {
5595: $items.=&escape($item).'&';
5596: }
5597:
5598: $items=~s/\&$//;
5599: if (!$udomain) { $udomain=$env{'user.domain'}; }
5600: if (!$uname) { $uname=$env{'user.name'}; }
5601: my $uhome=&homeserver($uname,$udomain);
5602: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
5603: }
5604:
5605: # -------------------------------------------------------------- dump interface
5606:
5607: sub unserialize {
5608: my ($rep, $escapedkeys) = @_;
5609:
5610: return {} if $rep =~ /^error/;
5611:
5612: my %returnhash=();
5613: foreach my $item (split(/\&/,$rep)) {
5614: my ($key, $value) = split(/=/, $item, 2);
5615: $key = unescape($key) unless $escapedkeys;
5616: next if $key =~ /^error: 2 /;
5617: $returnhash{$key} = &thaw_unescape($value);
5618: }
5619: #return %returnhash;
5620: return \%returnhash;
5621: }
5622:
5623: # see Lond::dump_with_regexp
5624: # if $escapedkeys hash keys won't get unescaped.
5625: sub dump {
5626: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
5627: if (!$udomain) { $udomain=$env{'user.domain'}; }
5628: if (!$uname) { $uname=$env{'user.name'}; }
5629: my $uhome=&homeserver($uname,$udomain);
5630:
5631: my $reply;
5632: if (grep { $_ eq $uhome } current_machine_ids()) {
5633: # user is hosted on this machine
5634: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
5635: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
5636: return %{unserialize($reply, $escapedkeys)};
5637: }
5638: if ($regexp) {
5639: $regexp=&escape($regexp);
5640: } else {
5641: $regexp='.';
5642: }
5643: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5644: my @pairs=split(/\&/,$rep);
5645: my %returnhash=();
5646: if (!($rep =~ /^error/ )) {
5647: foreach my $item (@pairs) {
5648: my ($key,$value)=split(/=/,$item,2);
5649: $key = unescape($key) unless $escapedkeys;
5650: #$key = &unescape($key);
5651: next if ($key =~ /^error: 2 /);
5652: $returnhash{$key}=&thaw_unescape($value);
5653: }
5654: }
5655: return %returnhash;
5656: }
5657:
5658:
5659: # --------------------------------------------------------- dumpstore interface
5660:
5661: sub dumpstore {
5662: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
5663: # same as dump but keys must be escaped. They may contain colon separated
5664: # lists of values that may themself contain colons (e.g. symbs).
5665: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
5666: }
5667:
5668: # -------------------------------------------------------------- keys interface
5669:
5670: sub getkeys {
5671: my ($namespace,$udomain,$uname)=@_;
5672: if (!$udomain) { $udomain=$env{'user.domain'}; }
5673: if (!$uname) { $uname=$env{'user.name'}; }
5674: my $uhome=&homeserver($uname,$udomain);
5675: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5676: my @keyarray=();
5677: foreach my $key (split(/\&/,$rep)) {
5678: next if ($key =~ /^error: 2 /);
5679: push(@keyarray,&unescape($key));
5680: }
5681: return @keyarray;
5682: }
5683:
5684: # --------------------------------------------------------------- currentdump
5685: sub currentdump {
5686: my ($courseid,$sdom,$sname)=@_;
5687: $courseid = $env{'request.course.id'} if (! defined($courseid));
5688: $sdom = $env{'user.domain'} if (! defined($sdom));
5689: $sname = $env{'user.name'} if (! defined($sname));
5690: my $uhome = &homeserver($sname,$sdom);
5691: my $rep;
5692:
5693: if (grep { $_ eq $uhome } current_machine_ids()) {
5694: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5695: $courseid)));
5696: } else {
5697: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5698: }
5699:
5700: return if ($rep =~ /^(error:|no_such_host)/);
5701: #
5702: my %returnhash=();
5703: #
5704: if ($rep eq "unknown_cmd") {
5705: # an old lond will not know currentdump
5706: # Do a dump and make it look like a currentdump
5707: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
5708: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5709: my %hash = @tmp;
5710: @tmp=();
5711: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
5712: } else {
5713: my @pairs=split(/\&/,$rep);
5714: foreach my $pair (@pairs) {
5715: my ($key,$value)=split(/=/,$pair,2);
5716: my ($symb,$param) = split(/:/,$key);
5717: $returnhash{&unescape($symb)}->{&unescape($param)} =
5718: &thaw_unescape($value);
5719: }
5720: }
5721: return %returnhash;
5722: }
5723:
5724: sub convert_dump_to_currentdump{
5725: my %hash = %{shift()};
5726: my %returnhash;
5727: # Code ripped from lond, essentially. The only difference
5728: # here is the unescaping done by lonnet::dump(). Conceivably
5729: # we might run in to problems with parameter names =~ /^v\./
5730: while (my ($key,$value) = each(%hash)) {
5731: my ($v,$symb,$param) = split(/:/,$key);
5732: $symb = &unescape($symb);
5733: $param = &unescape($param);
5734: next if ($v eq 'version' || $symb eq 'keys');
5735: next if (exists($returnhash{$symb}) &&
5736: exists($returnhash{$symb}->{$param}) &&
5737: $returnhash{$symb}->{'v.'.$param} > $v);
5738: $returnhash{$symb}->{$param}=$value;
5739: $returnhash{$symb}->{'v.'.$param}=$v;
5740: }
5741: #
5742: # Remove all of the keys in the hashes which keep track of
5743: # the version of the parameter.
5744: while (my ($symb,$param_hash) = each(%returnhash)) {
5745: # use a foreach because we are going to delete from the hash.
5746: foreach my $key (keys(%$param_hash)) {
5747: delete($param_hash->{$key}) if ($key =~ /^v\./);
5748: }
5749: }
5750: return \%returnhash;
5751: }
5752:
5753: # ------------------------------------------------------ critical inc interface
5754:
5755: sub cinc {
5756: return &inc(@_,'critical');
5757: }
5758:
5759: # --------------------------------------------------------------- inc interface
5760:
5761: sub inc {
5762: my ($namespace,$store,$udomain,$uname,$critical) = @_;
5763: if (!$udomain) { $udomain=$env{'user.domain'}; }
5764: if (!$uname) { $uname=$env{'user.name'}; }
5765: my $uhome=&homeserver($uname,$udomain);
5766: my $items='';
5767: if (! ref($store)) {
5768: # got a single value, so use that instead
5769: $items = &escape($store).'=&';
5770: } elsif (ref($store) eq 'SCALAR') {
5771: $items = &escape($$store).'=&';
5772: } elsif (ref($store) eq 'ARRAY') {
5773: $items = join('=&',map {&escape($_);} @{$store});
5774: } elsif (ref($store) eq 'HASH') {
5775: while (my($key,$value) = each(%{$store})) {
5776: $items.= &escape($key).'='.&escape($value).'&';
5777: }
5778: }
5779: $items=~s/\&$//;
5780: if ($critical) {
5781: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5782: } else {
5783: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5784: }
5785: }
5786:
5787: # --------------------------------------------------------------- put interface
5788:
5789: sub put {
5790: my ($namespace,$storehash,$udomain,$uname)=@_;
5791: if (!$udomain) { $udomain=$env{'user.domain'}; }
5792: if (!$uname) { $uname=$env{'user.name'}; }
5793: my $uhome=&homeserver($uname,$udomain);
5794: my $items='';
5795: foreach my $item (keys(%$storehash)) {
5796: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5797: }
5798: $items=~s/\&$//;
5799: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5800: }
5801:
5802: # ------------------------------------------------------------ newput interface
5803:
5804: sub newput {
5805: my ($namespace,$storehash,$udomain,$uname)=@_;
5806: if (!$udomain) { $udomain=$env{'user.domain'}; }
5807: if (!$uname) { $uname=$env{'user.name'}; }
5808: my $uhome=&homeserver($uname,$udomain);
5809: my $items='';
5810: foreach my $key (keys(%$storehash)) {
5811: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5812: }
5813: $items=~s/\&$//;
5814: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5815: }
5816:
5817: # --------------------------------------------------------- putstore interface
5818:
5819: sub putstore {
5820: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5821: if (!$udomain) { $udomain=$env{'user.domain'}; }
5822: if (!$uname) { $uname=$env{'user.name'}; }
5823: my $uhome=&homeserver($uname,$udomain);
5824: my $items='';
5825: foreach my $key (keys(%$storehash)) {
5826: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5827: }
5828: $items=~s/\&$//;
5829: my $esc_symb=&escape($symb);
5830: my $esc_v=&escape($version);
5831: my $reply =
5832: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
5833: $uhome);
5834: if ($reply eq 'unknown_cmd') {
5835: # gfall back to way things use to be done
5836: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5837: $uname);
5838: }
5839: return $reply;
5840: }
5841:
5842: sub old_putstore {
5843: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5844: if (!$udomain) { $udomain=$env{'user.domain'}; }
5845: if (!$uname) { $uname=$env{'user.name'}; }
5846: my $uhome=&homeserver($uname,$udomain);
5847: my %newstorehash;
5848: foreach my $item (keys(%$storehash)) {
5849: my $key = $version.':'.&escape($symb).':'.$item;
5850: $newstorehash{$key} = $storehash->{$item};
5851: }
5852: my $items='';
5853: my %allitems = ();
5854: foreach my $item (keys(%newstorehash)) {
5855: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
5856: my $key = $1.':keys:'.$2;
5857: $allitems{$key} .= $3.':';
5858: }
5859: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
5860: }
5861: foreach my $item (keys(%allitems)) {
5862: $allitems{$item} =~ s/\:$//;
5863: $items.= $item.'='.$allitems{$item}.'&';
5864: }
5865: $items=~s/\&$//;
5866: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5867: }
5868:
5869: # ------------------------------------------------------ critical put interface
5870:
5871: sub cput {
5872: my ($namespace,$storehash,$udomain,$uname)=@_;
5873: if (!$udomain) { $udomain=$env{'user.domain'}; }
5874: if (!$uname) { $uname=$env{'user.name'}; }
5875: my $uhome=&homeserver($uname,$udomain);
5876: my $items='';
5877: foreach my $item (keys(%$storehash)) {
5878: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5879: }
5880: $items=~s/\&$//;
5881: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
5882: }
5883:
5884: # -------------------------------------------------------------- eget interface
5885:
5886: sub eget {
5887: my ($namespace,$storearr,$udomain,$uname)=@_;
5888: my $items='';
5889: foreach my $item (@$storearr) {
5890: $items.=&escape($item).'&';
5891: }
5892: $items=~s/\&$//;
5893: if (!$udomain) { $udomain=$env{'user.domain'}; }
5894: if (!$uname) { $uname=$env{'user.name'}; }
5895: my $uhome=&homeserver($uname,$udomain);
5896: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
5897: my @pairs=split(/\&/,$rep);
5898: my %returnhash=();
5899: my $i=0;
5900: foreach my $item (@$storearr) {
5901: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5902: $i++;
5903: }
5904: return %returnhash;
5905: }
5906:
5907: # ------------------------------------------------------------ tmpput interface
5908: sub tmpput {
5909: my ($storehash,$server,$context)=@_;
5910: my $items='';
5911: foreach my $item (keys(%$storehash)) {
5912: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5913: }
5914: $items=~s/\&$//;
5915: if (defined($context)) {
5916: $items .= ':'.&escape($context);
5917: }
5918: return &reply("tmpput:$items",$server);
5919: }
5920:
5921: # ------------------------------------------------------------ tmpget interface
5922: sub tmpget {
5923: my ($token,$server)=@_;
5924: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5925: my $rep=&reply("tmpget:$token",$server);
5926: my %returnhash;
5927: foreach my $item (split(/\&/,$rep)) {
5928: my ($key,$value)=split(/=/,$item);
5929: next if ($key =~ /^error: 2 /);
5930: $returnhash{&unescape($key)}=&thaw_unescape($value);
5931: }
5932: return %returnhash;
5933: }
5934:
5935: # ------------------------------------------------------------ tmpdel interface
5936: sub tmpdel {
5937: my ($token,$server)=@_;
5938: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5939: return &reply("tmpdel:$token",$server);
5940: }
5941:
5942: # ------------------------------------------------------------ get_timebased_id
5943:
5944: sub get_timebased_id {
5945: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5946: $maxtries) = @_;
5947: my ($newid,$error,$dellock);
5948: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5949: return ('','ok','invalid call to get suffix');
5950: }
5951:
5952: # set defaults for any optional args for which values were not supplied
5953: if ($who eq '') {
5954: $who = $env{'user.name'}.':'.$env{'user.domain'};
5955: }
5956: if (!$locktries) {
5957: $locktries = 3;
5958: }
5959: if (!$maxtries) {
5960: $maxtries = 10;
5961: }
5962:
5963: if (($cdom eq '') || ($cnum eq '')) {
5964: if ($env{'request.course.id'}) {
5965: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5966: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5967: }
5968: if (($cdom eq '') || ($cnum eq '')) {
5969: return ('','ok','call to get suffix not in course context');
5970: }
5971: }
5972:
5973: # construct locking item
5974: my $lockhash = {
5975: $prefix."\0".'locked_'.$keyid => $who,
5976: };
5977: my $tries = 0;
5978:
5979: # attempt to get lock on nohist_$namespace file
5980: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5981: while (($gotlock ne 'ok') && $tries <$locktries) {
5982: $tries ++;
5983: sleep 1;
5984: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
5985: }
5986:
5987: # attempt to get unique identifier, based on current timestamp
5988: if ($gotlock eq 'ok') {
5989: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
5990: my $id = time;
5991: $newid = $id;
5992: my $idtries = 0;
5993: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
5994: if ($idtype eq 'concat') {
5995: $newid = $id.$idtries;
5996: } else {
5997: $newid ++;
5998: }
5999: $idtries ++;
6000: }
6001: if (!exists($inuse{$prefix."\0".$newid})) {
6002: my %new_item = (
6003: $prefix."\0".$newid => $who,
6004: );
6005: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6006: $cdom,$cnum);
6007: if ($putresult ne 'ok') {
6008: undef($newid);
6009: $error = 'error saving new item: '.$putresult;
6010: }
6011: } else {
6012: $error = ('error: no unique suffix available for the new item ');
6013: }
6014: # remove lock
6015: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6016: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6017: } else {
6018: $error = "error: could not obtain lockfile\n";
6019: $dellock = 'ok';
6020: }
6021: return ($newid,$dellock,$error);
6022: }
6023:
6024: # -------------------------------------------------- portfolio access checking
6025:
6026: sub portfolio_access {
6027: my ($requrl) = @_;
6028: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6029: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
6030: if ($result) {
6031: my %setters;
6032: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6033: my ($startblock,$endblock) =
6034: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6035: if ($startblock && $endblock) {
6036: return 'B';
6037: }
6038: } else {
6039: my ($startblock,$endblock) =
6040: &Apache::loncommon::blockcheck(\%setters,'port');
6041: if ($startblock && $endblock) {
6042: return 'B';
6043: }
6044: }
6045: }
6046: if ($result eq 'ok') {
6047: return 'F';
6048: } elsif ($result =~ /^[^:]+:guest_/) {
6049: return 'A';
6050: }
6051: return '';
6052: }
6053:
6054: sub get_portfolio_access {
6055: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
6056:
6057: if (!ref($access_hash)) {
6058: my $current_perms = &get_portfile_permissions($udom,$unum);
6059: my %access_controls = &get_access_controls($current_perms,$group,
6060: $file_name);
6061: $access_hash = $access_controls{$file_name};
6062: }
6063:
6064: my ($public,$guest,@domains,@users,@courses,@groups);
6065: my $now = time;
6066: if (ref($access_hash) eq 'HASH') {
6067: foreach my $key (keys(%{$access_hash})) {
6068: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6069: if ($start > $now) {
6070: next;
6071: }
6072: if ($end && $end<$now) {
6073: next;
6074: }
6075: if ($scope eq 'public') {
6076: $public = $key;
6077: last;
6078: } elsif ($scope eq 'guest') {
6079: $guest = $key;
6080: } elsif ($scope eq 'domains') {
6081: push(@domains,$key);
6082: } elsif ($scope eq 'users') {
6083: push(@users,$key);
6084: } elsif ($scope eq 'course') {
6085: push(@courses,$key);
6086: } elsif ($scope eq 'group') {
6087: push(@groups,$key);
6088: }
6089: }
6090: if ($public) {
6091: return 'ok';
6092: }
6093: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6094: if ($guest) {
6095: return $guest;
6096: }
6097: } else {
6098: if (@domains > 0) {
6099: foreach my $domkey (@domains) {
6100: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6101: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6102: return 'ok';
6103: }
6104: }
6105: }
6106: }
6107: if (@users > 0) {
6108: foreach my $userkey (@users) {
6109: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6110: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6111: if (ref($item) eq 'HASH') {
6112: if (($item->{'uname'} eq $env{'user.name'}) &&
6113: ($item->{'udom'} eq $env{'user.domain'})) {
6114: return 'ok';
6115: }
6116: }
6117: }
6118: }
6119: }
6120: }
6121: my %roleshash;
6122: my @courses_and_groups = @courses;
6123: push(@courses_and_groups,@groups);
6124: if (@courses_and_groups > 0) {
6125: my (%allgroups,%allroles);
6126: my ($start,$end,$role,$sec,$group);
6127: foreach my $envkey (%env) {
6128: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
6129: my $cid = $2.'_'.$3;
6130: if ($1 eq 'gr') {
6131: $group = $4;
6132: $allgroups{$cid}{$group} = $env{$envkey};
6133: } else {
6134: if ($4 eq '') {
6135: $sec = 'none';
6136: } else {
6137: $sec = $4;
6138: }
6139: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6140: }
6141: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
6142: my $cid = $2.'_'.$3;
6143: if ($4 eq '') {
6144: $sec = 'none';
6145: } else {
6146: $sec = $4;
6147: }
6148: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6149: }
6150: }
6151: if (keys(%allroles) == 0) {
6152: return;
6153: }
6154: foreach my $key (@courses_and_groups) {
6155: my %content = %{$$access_hash{$key}};
6156: my $cnum = $content{'number'};
6157: my $cdom = $content{'domain'};
6158: my $cid = $cdom.'_'.$cnum;
6159: if (!exists($allroles{$cid})) {
6160: next;
6161: }
6162: foreach my $role_id (keys(%{$content{'roles'}})) {
6163: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6164: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6165: my @status = @{$content{'roles'}{$role_id}{'access'}};
6166: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6167: foreach my $role (keys(%{$allroles{$cid}})) {
6168: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6169: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6170: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6171: if (grep/^all$/,@sections) {
6172: return 'ok';
6173: } else {
6174: if (grep/^$sec$/,@sections) {
6175: return 'ok';
6176: }
6177: }
6178: }
6179: }
6180: if (keys(%{$allgroups{$cid}}) == 0) {
6181: if (grep/^none$/,@groups) {
6182: return 'ok';
6183: }
6184: } else {
6185: if (grep/^all$/,@groups) {
6186: return 'ok';
6187: }
6188: foreach my $group (keys(%{$allgroups{$cid}})) {
6189: if (grep/^$group$/,@groups) {
6190: return 'ok';
6191: }
6192: }
6193: }
6194: }
6195: }
6196: }
6197: }
6198: }
6199: if ($guest) {
6200: return $guest;
6201: }
6202: }
6203: }
6204: return;
6205: }
6206:
6207: sub course_group_datechecker {
6208: my ($dates,$now,$status) = @_;
6209: my ($start,$end) = split(/\./,$dates);
6210: if (!$start && !$end) {
6211: return 'ok';
6212: }
6213: if (grep/^active$/,@{$status}) {
6214: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6215: return 'ok';
6216: }
6217: }
6218: if (grep/^previous$/,@{$status}) {
6219: if ($end > $now ) {
6220: return 'ok';
6221: }
6222: }
6223: if (grep/^future$/,@{$status}) {
6224: if ($start > $now) {
6225: return 'ok';
6226: }
6227: }
6228: return;
6229: }
6230:
6231: sub parse_portfolio_url {
6232: my ($url) = @_;
6233:
6234: my ($type,$udom,$unum,$group,$file_name);
6235:
6236: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
6237: $type = 1;
6238: $udom = $1;
6239: $unum = $2;
6240: $file_name = $3;
6241: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
6242: $type = 2;
6243: $udom = $1;
6244: $unum = $2;
6245: $group = $3;
6246: $file_name = $3.'/'.$4;
6247: }
6248: if (wantarray) {
6249: return ($type,$udom,$unum,$file_name,$group);
6250: }
6251: return $type;
6252: }
6253:
6254: sub is_portfolio_url {
6255: my ($url) = @_;
6256: return scalar(&parse_portfolio_url($url));
6257: }
6258:
6259: sub is_portfolio_file {
6260: my ($file) = @_;
6261: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
6262: return 1;
6263: }
6264: return;
6265: }
6266:
6267: sub usertools_access {
6268: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
6269: my ($access,%tools);
6270: if ($context eq '') {
6271: $context = 'tools';
6272: }
6273: if ($context eq 'requestcourses') {
6274: %tools = (
6275: official => 1,
6276: unofficial => 1,
6277: community => 1,
6278: textbook => 1,
6279: );
6280: } elsif ($context eq 'requestauthor') {
6281: %tools = (
6282: requestauthor => 1,
6283: );
6284: } else {
6285: %tools = (
6286: aboutme => 1,
6287: blog => 1,
6288: webdav => 1,
6289: portfolio => 1,
6290: );
6291: }
6292: return if (!defined($tools{$tool}));
6293:
6294: if (($udom eq '') || ($uname eq '')) {
6295: $udom = $env{'user.domain'};
6296: $uname = $env{'user.name'};
6297: }
6298:
6299: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6300: if ($action ne 'reload') {
6301: if ($context eq 'requestcourses') {
6302: return $env{'environment.canrequest.'.$tool};
6303: } elsif ($context eq 'requestauthor') {
6304: return $env{'environment.canrequest.author'};
6305: } else {
6306: return $env{'environment.availabletools.'.$tool};
6307: }
6308: }
6309: }
6310:
6311: my ($toolstatus,$inststatus,$envkey);
6312: if ($context eq 'requestauthor') {
6313: $envkey = $context;
6314: } else {
6315: $envkey = $context.'.'.$tool;
6316: }
6317:
6318: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6319: ($action ne 'reload')) {
6320: $toolstatus = $env{'environment.'.$envkey};
6321: $inststatus = $env{'environment.inststatus'};
6322: } else {
6323: if (ref($userenvref) eq 'HASH') {
6324: $toolstatus = $userenvref->{$envkey};
6325: $inststatus = $userenvref->{'inststatus'};
6326: } else {
6327: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6328: $toolstatus = $userenv{$envkey};
6329: $inststatus = $userenv{'inststatus'};
6330: }
6331: }
6332:
6333: if ($toolstatus ne '') {
6334: if ($toolstatus) {
6335: $access = 1;
6336: } else {
6337: $access = 0;
6338: }
6339: return $access;
6340: }
6341:
6342: my ($is_adv,%domdef);
6343: if (ref($is_advref) eq 'HASH') {
6344: $is_adv = $is_advref->{'is_adv'};
6345: } else {
6346: $is_adv = &is_advanced_user($udom,$uname);
6347: }
6348: if (ref($domdefref) eq 'HASH') {
6349: %domdef = %{$domdefref};
6350: } else {
6351: %domdef = &get_domain_defaults($udom);
6352: }
6353: if (ref($domdef{$tool}) eq 'HASH') {
6354: if ($is_adv) {
6355: if ($domdef{$tool}{'_LC_adv'} ne '') {
6356: if ($domdef{$tool}{'_LC_adv'}) {
6357: $access = 1;
6358: } else {
6359: $access = 0;
6360: }
6361: return $access;
6362: }
6363: }
6364: if ($inststatus ne '') {
6365: my ($hasaccess,$hasnoaccess);
6366: foreach my $affiliation (split(/:/,$inststatus)) {
6367: if ($domdef{$tool}{$affiliation} ne '') {
6368: if ($domdef{$tool}{$affiliation}) {
6369: $hasaccess = 1;
6370: } else {
6371: $hasnoaccess = 1;
6372: }
6373: }
6374: }
6375: if ($hasaccess || $hasnoaccess) {
6376: if ($hasaccess) {
6377: $access = 1;
6378: } elsif ($hasnoaccess) {
6379: $access = 0;
6380: }
6381: return $access;
6382: }
6383: } else {
6384: if ($domdef{$tool}{'default'} ne '') {
6385: if ($domdef{$tool}{'default'}) {
6386: $access = 1;
6387: } elsif ($domdef{$tool}{'default'} == 0) {
6388: $access = 0;
6389: }
6390: return $access;
6391: }
6392: }
6393: } else {
6394: if (($context eq 'tools') && ($tool ne 'webdav')) {
6395: $access = 1;
6396: } else {
6397: $access = 0;
6398: }
6399: return $access;
6400: }
6401: }
6402:
6403: sub is_course_owner {
6404: my ($cdom,$cnum,$udom,$uname) = @_;
6405: if (($udom eq '') || ($uname eq '')) {
6406: $udom = $env{'user.domain'};
6407: $uname = $env{'user.name'};
6408: }
6409: unless (($udom eq '') || ($uname eq '')) {
6410: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6411: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6412: return 1;
6413: } else {
6414: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6415: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6416: return 1;
6417: }
6418: }
6419: }
6420: }
6421: return;
6422: }
6423:
6424: sub is_advanced_user {
6425: my ($udom,$uname) = @_;
6426: if ($udom ne '' && $uname ne '') {
6427: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6428: if (wantarray) {
6429: return ($env{'user.adv'},$env{'user.author'});
6430: } else {
6431: return $env{'user.adv'};
6432: }
6433: }
6434: }
6435: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6436: my %allroles;
6437: my ($is_adv,$is_author);
6438: foreach my $role (keys(%roleshash)) {
6439: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6440: my $area = '/'.$tdomain.'/'.$trest;
6441: if ($sec ne '') {
6442: $area .= '/'.$sec;
6443: }
6444: if (($area ne '') && ($trole ne '')) {
6445: my $spec=$trole.'.'.$area;
6446: if ($trole =~ /^cr\//) {
6447: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6448: } elsif ($trole ne 'gr') {
6449: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6450: }
6451: if ($trole eq 'au') {
6452: $is_author = 1;
6453: }
6454: }
6455: }
6456: foreach my $role (keys(%allroles)) {
6457: last if ($is_adv);
6458: foreach my $item (split(/:/,$allroles{$role})) {
6459: if ($item ne '') {
6460: my ($privilege,$restrictions)=split(/&/,$item);
6461: if ($privilege eq 'adv') {
6462: $is_adv = 1;
6463: last;
6464: }
6465: }
6466: }
6467: }
6468: if (wantarray) {
6469: return ($is_adv,$is_author);
6470: }
6471: return $is_adv;
6472: }
6473:
6474: sub check_can_request {
6475: my ($dom,$can_request,$request_domains) = @_;
6476: my $canreq = 0;
6477: my ($types,$typename) = &Apache::loncommon::course_types();
6478: my @options = ('approval','validate','autolimit');
6479: my $optregex = join('|',@options);
6480: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6481: foreach my $type (@{$types}) {
6482: if (&usertools_access($env{'user.name'},
6483: $env{'user.domain'},
6484: $type,undef,'requestcourses')) {
6485: $canreq ++;
6486: if (ref($request_domains) eq 'HASH') {
6487: push(@{$request_domains->{$type}},$env{'user.domain'});
6488: }
6489: if ($dom eq $env{'user.domain'}) {
6490: $can_request->{$type} = 1;
6491: }
6492: }
6493: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6494: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6495: if (@curr > 0) {
6496: foreach my $item (@curr) {
6497: if (ref($request_domains) eq 'HASH') {
6498: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6499: if ($otherdom ne '') {
6500: if (ref($request_domains->{$type}) eq 'ARRAY') {
6501: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6502: push(@{$request_domains->{$type}},$otherdom);
6503: }
6504: } else {
6505: push(@{$request_domains->{$type}},$otherdom);
6506: }
6507: }
6508: }
6509: }
6510: unless($dom eq $env{'user.domain'}) {
6511: $canreq ++;
6512: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6513: $can_request->{$type} = 1;
6514: }
6515: }
6516: }
6517: }
6518: }
6519: }
6520: return $canreq;
6521: }
6522:
6523: # ---------------------------------------------- Custom access rule evaluation
6524:
6525: sub customaccess {
6526: my ($priv,$uri)=@_;
6527: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
6528: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
6529: $udom = &LONCAPA::clean_domain($udom);
6530: $ucrs = &LONCAPA::clean_username($ucrs);
6531: my $access=0;
6532: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
6533: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6534: if ($type eq 'user') {
6535: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6536: my ($tdom,$tuname)=split(m{/},$scope);
6537: if ($tdom) {
6538: if ($tdom ne $env{'user.domain'}) { next; }
6539: }
6540: if ($tuname) {
6541: if ($tuname ne $env{'user.name'}) { next; }
6542: }
6543: $access=($effect eq 'allow');
6544: last;
6545: }
6546: } else {
6547: if ($role) {
6548: if ($role ne $urole) { next; }
6549: }
6550: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6551: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6552: if ($tdom) {
6553: if ($tdom ne $udom) { next; }
6554: }
6555: if ($tcrs) {
6556: if ($tcrs ne $ucrs) { next; }
6557: }
6558: if ($tsec) {
6559: if ($tsec ne $usec) { next; }
6560: }
6561: $access=($effect eq 'allow');
6562: last;
6563: }
6564: if ($realm eq '' && $role eq '') {
6565: $access=($effect eq 'allow');
6566: }
6567: }
6568: }
6569: return $access;
6570: }
6571:
6572: # ------------------------------------------------- Check for a user privilege
6573:
6574: sub allowed {
6575: my ($priv,$uri,$symb,$role)=@_;
6576: my $ver_orguri=$uri;
6577: $uri=&deversion($uri);
6578: my $orguri=$uri;
6579: $uri=&declutter($uri);
6580:
6581: if ($priv eq 'evb') {
6582: # Evade communication block restrictions for specified role in a course
6583: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6584: return $1;
6585: } else {
6586: return;
6587: }
6588: }
6589:
6590: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
6591: # Free bre access to adm and meta resources
6592: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
6593: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6594: && ($priv eq 'bre')) {
6595: return 'F';
6596: }
6597:
6598: # Free bre access to user's own portfolio contents
6599: my ($space,$domain,$name,@dir)=split('/',$uri);
6600: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
6601: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
6602: my %setters;
6603: my ($startblock,$endblock) =
6604: &Apache::loncommon::blockcheck(\%setters,'port');
6605: if ($startblock && $endblock) {
6606: return 'B';
6607: } else {
6608: return 'F';
6609: }
6610: }
6611:
6612: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
6613: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6614: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6615: if (exists($env{'request.course.id'})) {
6616: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6617: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6618: if (($domain eq $cdom) && ($name eq $cnum)) {
6619: my $courseprivid=$env{'request.course.id'};
6620: $courseprivid=~s/\_/\//;
6621: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6622: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6623: return $1;
6624: } else {
6625: if ($env{'request.course.sec'}) {
6626: $courseprivid.='/'.$env{'request.course.sec'};
6627: }
6628: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6629: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6630: return $2;
6631: }
6632: }
6633: }
6634: }
6635: }
6636:
6637: # Free bre to public access
6638:
6639: if ($priv eq 'bre') {
6640: my $copyright=&metadata($uri,'copyright');
6641: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
6642: return 'F';
6643: }
6644: if ($copyright eq 'priv') {
6645: $uri=~/([^\/]+)\/([^\/]+)\//;
6646: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
6647: return '';
6648: }
6649: }
6650: if ($copyright eq 'domain') {
6651: $uri=~/([^\/]+)\/([^\/]+)\//;
6652: unless (($env{'user.domain'} eq $1) ||
6653: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
6654: return '';
6655: }
6656: }
6657: if ($env{'request.role'}=~ /li\.\//) {
6658: # Library role, so allow browsing of resources in this domain.
6659: return 'F';
6660: }
6661: if ($copyright eq 'custom') {
6662: unless (&customaccess($priv,$uri)) { return ''; }
6663: }
6664: }
6665: # Domain coordinator is trying to create a course
6666: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
6667: # uri is the requested domain in this case.
6668: # comparison to 'request.role.domain' shows if the user has selected
6669: # a role of dc for the domain in question.
6670: return 'F' if ($uri eq $env{'request.role.domain'});
6671: }
6672:
6673: my $thisallowed='';
6674: my $statecond=0;
6675: my $courseprivid='';
6676:
6677: my $ownaccess;
6678: # Community Coordinator or Assistant Co-author browsing resource space.
6679: if (($priv eq 'bro') && ($env{'user.author'})) {
6680: if ($uri eq '') {
6681: $ownaccess = 1;
6682: } else {
6683: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6684: my $udom = $env{'user.domain'};
6685: my $uname = $env{'user.name'};
6686: if ($uri =~ m{^\Q$udom\E/?$}) {
6687: $ownaccess = 1;
6688: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
6689: unless ($uri =~ m{\.\./}) {
6690: $ownaccess = 1;
6691: }
6692: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6693: my $now = time;
6694: if ($uri =~ m{^([^/]+)/?$}) {
6695: my $adom = $1;
6696: foreach my $key (keys(%env)) {
6697: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
6698: my ($start,$end) = split('.',$env{$key});
6699: if (($now >= $start) && (!$end || $end < $now)) {
6700: $ownaccess = 1;
6701: last;
6702: }
6703: }
6704: }
6705: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6706: my $adom = $1;
6707: my $aname = $2;
6708: foreach my $role ('ca','aa') {
6709: if ($env{"user.role.$role./$adom/$aname"}) {
6710: my ($start,$end) =
6711: split('.',$env{"user.role.$role./$adom/$aname"});
6712: if (($now >= $start) && (!$end || $end < $now)) {
6713: $ownaccess = 1;
6714: last;
6715: }
6716: }
6717: }
6718: }
6719: }
6720: }
6721: }
6722: }
6723:
6724: # Course
6725:
6726: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
6727: unless (($priv eq 'bro') && (!$ownaccess)) {
6728: $thisallowed.=$1;
6729: }
6730: }
6731:
6732: # Domain
6733:
6734: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
6735: =~/\Q$priv\E\&([^\:]*)/) {
6736: unless (($priv eq 'bro') && (!$ownaccess)) {
6737: $thisallowed.=$1;
6738: }
6739: }
6740:
6741: # User who is not author or co-author might still be able to edit
6742: # resource of an author in the domain (e.g., if Domain Coordinator).
6743: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6744: (&allowed('mdc',$env{'request.course.id'}))) {
6745: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6746: $thisallowed.=$1;
6747: }
6748: }
6749:
6750: # Course: uri itself is a course
6751: my $courseuri=$uri;
6752: $courseuri=~s/\_(\d)/\/$1/;
6753: $courseuri=~s/^([^\/])/\/$1/;
6754:
6755: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
6756: =~/\Q$priv\E\&([^\:]*)/) {
6757: unless (($priv eq 'bro') && (!$ownaccess)) {
6758: $thisallowed.=$1;
6759: }
6760: }
6761:
6762: # URI is an uploaded document for this course, default permissions don't matter
6763: # not allowing 'edit' access (editupload) to uploaded course docs
6764: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
6765: $thisallowed='';
6766: my ($match)=&is_on_map($uri);
6767: if ($match) {
6768: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6769: =~/\Q$priv\E\&([^\:]*)/) {
6770: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6771: if (@blockers > 0) {
6772: $thisallowed = 'B';
6773: } else {
6774: $thisallowed.=$1;
6775: }
6776: }
6777: } else {
6778: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
6779: if ($refuri) {
6780: if ($refuri =~ m|^/adm/|) {
6781: $thisallowed='F';
6782: } else {
6783: $refuri=&declutter($refuri);
6784: my ($match) = &is_on_map($refuri);
6785: if ($match) {
6786: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6787: if (@blockers > 0) {
6788: $thisallowed = 'B';
6789: } else {
6790: $thisallowed='F';
6791: }
6792: }
6793: }
6794: }
6795: }
6796: }
6797:
6798: if ($priv eq 'bre'
6799: && $thisallowed ne 'F'
6800: && $thisallowed ne '2'
6801: && &is_portfolio_url($uri)) {
6802: $thisallowed = &portfolio_access($uri);
6803: }
6804:
6805: # Full access at system, domain or course-wide level? Exit.
6806: if ($thisallowed=~/F/) {
6807: return 'F';
6808: }
6809:
6810: # If this is generating or modifying users, exit with special codes
6811:
6812: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6813: if (($priv eq 'cca') || ($priv eq 'caa')) {
6814: my ($audom,$auname)=split('/',$uri);
6815: # no author name given, so this just checks on the general right to make a co-author in this domain
6816: unless ($auname) { return $thisallowed; }
6817: # an author name is given, so we are about to actually make a co-author for a certain account
6818: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6819: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6820: ($audom ne $env{'request.role.domain'}))) { return ''; }
6821: }
6822: return $thisallowed;
6823: }
6824: #
6825: # Gathered so far: system, domain and course wide privileges
6826: #
6827: # Course: See if uri or referer is an individual resource that is part of
6828: # the course
6829:
6830: if ($env{'request.course.id'}) {
6831:
6832: $courseprivid=$env{'request.course.id'};
6833: if ($env{'request.course.sec'}) {
6834: $courseprivid.='/'.$env{'request.course.sec'};
6835: }
6836: $courseprivid=~s/\_/\//;
6837: my $checkreferer=1;
6838: my ($match,$cond)=&is_on_map($uri);
6839: if ($match) {
6840: $statecond=$cond;
6841: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6842: =~/\Q$priv\E\&([^\:]*)/) {
6843: my $value = $1;
6844: if ($priv eq 'bre') {
6845: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6846: if (@blockers > 0) {
6847: $thisallowed = 'B';
6848: } else {
6849: $thisallowed.=$value;
6850: }
6851: } else {
6852: $thisallowed.=$value;
6853: }
6854: $checkreferer=0;
6855: }
6856: }
6857:
6858: if ($checkreferer) {
6859: my $refuri=$env{'httpref.'.$orguri};
6860: unless ($refuri) {
6861: foreach my $key (keys(%env)) {
6862: if ($key=~/^httpref\..*\*/) {
6863: my $pattern=$key;
6864: $pattern=~s/^httpref\.\/res\///;
6865: $pattern=~s/\*/\[\^\/\]\+/g;
6866: $pattern=~s/\//\\\//g;
6867: if ($orguri=~/$pattern/) {
6868: $refuri=$env{$key};
6869: }
6870: }
6871: }
6872: }
6873:
6874: if ($refuri) {
6875: $refuri=&declutter($refuri);
6876: my ($match,$cond)=&is_on_map($refuri);
6877: if ($match) {
6878: my $refstatecond=$cond;
6879: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6880: =~/\Q$priv\E\&([^\:]*)/) {
6881: my $value = $1;
6882: if ($priv eq 'bre') {
6883: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6884: if (@blockers > 0) {
6885: $thisallowed = 'B';
6886: } else {
6887: $thisallowed.=$value;
6888: }
6889: } else {
6890: $thisallowed.=$value;
6891: }
6892: $uri=$refuri;
6893: $statecond=$refstatecond;
6894: }
6895: }
6896: }
6897: }
6898: }
6899:
6900: #
6901: # Gathered now: all privileges that could apply, and condition number
6902: #
6903: #
6904: # Full or no access?
6905: #
6906:
6907: if ($thisallowed=~/F/) {
6908: return 'F';
6909: }
6910:
6911: unless ($thisallowed) {
6912: return '';
6913: }
6914:
6915: # Restrictions exist, deal with them
6916: #
6917: # C:according to course preferences
6918: # R:according to resource settings
6919: # L:unless locked
6920: # X:according to user session state
6921: #
6922:
6923: # Possibly locked functionality, check all courses
6924: # Locks might take effect only after 10 minutes cache expiration for other
6925: # courses, and 2 minutes for current course
6926:
6927: my $envkey;
6928: if ($thisallowed=~/L/) {
6929: foreach $envkey (keys(%env)) {
6930: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6931: my $courseid=$2;
6932: my $roleid=$1.'.'.$2;
6933: $courseid=~s/^\///;
6934: my $expiretime=600;
6935: if ($env{'request.role'} eq $roleid) {
6936: $expiretime=120;
6937: }
6938: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6939: my $prefix='course.'.$cdom.'_'.$cnum.'.';
6940: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
6941: &coursedescription($courseid,{'freshen_cache' => 1});
6942: }
6943: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6944: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6945: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6946: &log($env{'user.domain'},$env{'user.name'},
6947: $env{'user.home'},
6948: 'Locked by res: '.$priv.' for '.$uri.' due to '.
6949: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6950: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6951: return '';
6952: }
6953: }
6954: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6955: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6956: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6957: &log($env{'user.domain'},$env{'user.name'},
6958: $env{'user.home'},
6959: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
6960: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6961: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6962: return '';
6963: }
6964: }
6965: }
6966: }
6967: }
6968:
6969: #
6970: # Rest of the restrictions depend on selected course
6971: #
6972:
6973: unless ($env{'request.course.id'}) {
6974: if ($thisallowed eq 'A') {
6975: return 'A';
6976: } elsif ($thisallowed eq 'B') {
6977: return 'B';
6978: } else {
6979: return '1';
6980: }
6981: }
6982:
6983: #
6984: # Now user is definitely in a course
6985: #
6986:
6987:
6988: # Course preferences
6989:
6990: if ($thisallowed=~/C/) {
6991: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6992: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6993: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
6994: =~/\Q$rolecode\E/) {
6995: if (($priv ne 'pch') && ($priv ne 'plc')) {
6996: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6997: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6998: $env{'request.course.id'});
6999: }
7000: return '';
7001: }
7002:
7003: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
7004: =~/\Q$unamedom\E/) {
7005: if (($priv ne 'pch') && ($priv ne 'plc')) {
7006: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7007: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7008: $env{'request.course.id'});
7009: }
7010: return '';
7011: }
7012: }
7013:
7014: # Resource preferences
7015:
7016: if ($thisallowed=~/R/) {
7017: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7018: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
7019: if (($priv ne 'pch') && ($priv ne 'plc')) {
7020: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7021: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7022: }
7023: return '';
7024: }
7025: }
7026:
7027: # Restricted by state or randomout?
7028:
7029: if ($thisallowed=~/X/) {
7030: if ($env{'acc.randomout'}) {
7031: if (!$symb) { $symb=&symbread($uri,1); }
7032: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
7033: return '';
7034: }
7035: }
7036: if (&condval($statecond)) {
7037: return '2';
7038: } else {
7039: return '';
7040: }
7041: }
7042:
7043: if ($thisallowed eq 'A') {
7044: return 'A';
7045: } elsif ($thisallowed eq 'B') {
7046: return 'B';
7047: }
7048: return 'F';
7049: }
7050:
7051: # ------------------------------------------- Check construction space access
7052:
7053: sub constructaccess {
7054: my ($url,$setpriv)=@_;
7055:
7056: # We do not allow editing of previous versions of files
7057: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7058:
7059: # Get username and domain from URL
7060: my ($ownername,$ownerdomain,$ownerhome);
7061:
7062: ($ownerdomain,$ownername) =
7063: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7064:
7065: # The URL does not really point to any authorspace, forget it
7066: unless (($ownername) && ($ownerdomain)) { return ''; }
7067:
7068: # Now we need to see if the user has access to the authorspace of
7069: # $ownername at $ownerdomain
7070:
7071: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7072: # Real author for this?
7073: $ownerhome = $env{'user.home'};
7074: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7075: return ($ownername,$ownerdomain,$ownerhome);
7076: }
7077: } else {
7078: # Co-author for this?
7079: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7080: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7081: $ownerhome = &homeserver($ownername,$ownerdomain);
7082: return ($ownername,$ownerdomain,$ownerhome);
7083: }
7084: }
7085:
7086: # We don't have any access right now. If we are not possibly going to do anything about this,
7087: # we might as well leave
7088: unless ($setpriv) { return ''; }
7089:
7090: # Backdoor access?
7091: my $allowed=&allowed('eco',$ownerdomain);
7092: # Nope
7093: unless ($allowed) { return ''; }
7094: # Looks like we may have access, but could be locked by the owner of the construction space
7095: if ($allowed eq 'U') {
7096: my %blocked=&get('environment',['domcoord.author'],
7097: $ownerdomain,$ownername);
7098: # Is blocked by owner
7099: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7100: }
7101: if (($allowed eq 'F') || ($allowed eq 'U')) {
7102: # Grant temporary access
7103: my $then=$env{'user.login.time'};
7104: my $update=$env{'user.update.time'};
7105: if (!$update) { $update = $then; }
7106: my $refresh=$env{'user.refresh.time'};
7107: if (!$refresh) { $refresh = $update; }
7108: my $now = time;
7109: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7110: $now,'ca','constructaccess');
7111: $ownerhome = &homeserver($ownername,$ownerdomain);
7112: return($ownername,$ownerdomain,$ownerhome);
7113: }
7114: # No business here
7115: return '';
7116: }
7117:
7118: sub get_comm_blocks {
7119: my ($cdom,$cnum) = @_;
7120: if ($cdom eq '' || $cnum eq '') {
7121: return unless ($env{'request.course.id'});
7122: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7123: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7124: }
7125: my %commblocks;
7126: my $hashid=$cdom.'_'.$cnum;
7127: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7128: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7129: %commblocks = %{$blocksref};
7130: } else {
7131: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7132: my $cachetime = 600;
7133: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7134: }
7135: return %commblocks;
7136: }
7137:
7138: sub has_comm_blocking {
7139: my ($priv,$symb,$uri,$blocks) = @_;
7140: return unless ($env{'request.course.id'});
7141: return unless ($priv eq 'bre');
7142: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7143: my %commblocks;
7144: if (ref($blocks) eq 'HASH') {
7145: %commblocks = %{$blocks};
7146: } else {
7147: %commblocks = &get_comm_blocks();
7148: }
7149: return unless (keys(%commblocks) > 0);
7150: if (!$symb) { $symb=&symbread($uri,1); }
7151: my ($map,$resid,undef)=&decode_symb($symb);
7152: my %tocheck = (
7153: maps => $map,
7154: resources => $symb,
7155: );
7156: my @blockers;
7157: my $now = time;
7158: my $navmap = Apache::lonnavmaps::navmap->new();
7159: foreach my $block (keys(%commblocks)) {
7160: if ($block =~ /^(\d+)____(\d+)$/) {
7161: my ($start,$end) = ($1,$2);
7162: if ($start <= $now && $end >= $now) {
7163: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7164: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7165: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7166: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7167: unless (grep(/^\Q$block\E$/,@blockers)) {
7168: push(@blockers,$block);
7169: }
7170: }
7171: }
7172: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7173: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7174: unless (grep(/^\Q$block\E$/,@blockers)) {
7175: push(@blockers,$block);
7176: }
7177: }
7178: }
7179: }
7180: }
7181: }
7182: } elsif ($block =~ /^firstaccess____(.+)$/) {
7183: my $item = $1;
7184: my @to_test;
7185: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7186: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7187: my $check_interval;
7188: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7189: my @interval;
7190: my $type = 'map';
7191: if ($item eq 'course') {
7192: $type = 'course';
7193: @interval=&EXT("resource.0.interval");
7194: } else {
7195: if ($item =~ /___\d+___/) {
7196: $type = 'resource';
7197: @interval=&EXT("resource.0.interval",$item);
7198: if (ref($navmap)) {
7199: my $res = $navmap->getBySymb($item);
7200: push(@to_test,$res);
7201: }
7202: } else {
7203: my $mapsymb = &symbread($item,1);
7204: if ($mapsymb) {
7205: if (ref($navmap)) {
7206: my $mapres = $navmap->getBySymb($mapsymb);
7207: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7208: foreach my $res (@to_test) {
7209: my $symb = $res->symb();
7210: next if ($symb eq $mapsymb);
7211: if ($symb ne '') {
7212: @interval=&EXT("resource.0.interval",$symb);
7213: last;
7214: }
7215: }
7216: }
7217: }
7218: }
7219: }
7220: if ($interval[0] =~ /\d+/) {
7221: my $first_access;
7222: if ($type eq 'resource') {
7223: $first_access=&get_first_access($interval[1],$item);
7224: } elsif ($type eq 'map') {
7225: $first_access=&get_first_access($interval[1],undef,$item);
7226: } else {
7227: $first_access=&get_first_access($interval[1]);
7228: }
7229: if ($first_access) {
7230: my $timesup = $first_access+$interval[0];
7231: if ($timesup > $now) {
7232: foreach my $res (@to_test) {
7233: if ($res->is_problem()) {
7234: if ($res->completable()) {
7235: unless (grep(/^\Q$block\E$/,@blockers)) {
7236: push(@blockers,$block);
7237: }
7238: last;
7239: }
7240: }
7241: }
7242: }
7243: }
7244: }
7245: }
7246: }
7247: }
7248: }
7249: }
7250: return @blockers;
7251: }
7252:
7253: sub check_docs_block {
7254: my ($docsblock,$tocheck) =@_;
7255: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7256: return;
7257: }
7258: if (ref($docsblock->{'maps'}) eq 'HASH') {
7259: if ($tocheck->{'maps'}) {
7260: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7261: return 1;
7262: }
7263: }
7264: }
7265: if (ref($docsblock->{'resources'}) eq 'HASH') {
7266: if ($tocheck->{'resources'}) {
7267: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7268: return 1;
7269: }
7270: }
7271: }
7272: return;
7273: }
7274:
7275: #
7276: # Removes the versino from a URI and
7277: # splits it in to its filename and path to the filename.
7278: # Seems like File::Basename could have done this more clearly.
7279: # Parameters:
7280: # $uri - input URI
7281: # Returns:
7282: # Two element list consisting of
7283: # $pathname - the URI up to and excluding the trailing /
7284: # $filename - The part of the URI following the last /
7285: # NOTE:
7286: # Another realization of this is simply:
7287: # use File::Basename;
7288: # ...
7289: # $uri = shift;
7290: # $filename = basename($uri);
7291: # $path = dirname($uri);
7292: # return ($filename, $path);
7293: #
7294: # The implementation below is probably faster however.
7295: #
7296: sub split_uri_for_cond {
7297: my $uri=&deversion(&declutter(shift));
7298: my @uriparts=split(/\//,$uri);
7299: my $filename=pop(@uriparts);
7300: my $pathname=join('/',@uriparts);
7301: return ($pathname,$filename);
7302: }
7303: # --------------------------------------------------- Is a resource on the map?
7304:
7305: sub is_on_map {
7306: my ($pathname,$filename) = &split_uri_for_cond(shift);
7307: #Trying to find the conditional for the file
7308: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
7309: /\&\Q$filename\E\:([\d\|]+)\&/);
7310: if ($match) {
7311: return (1,$1);
7312: } else {
7313: return (0,0);
7314: }
7315: }
7316:
7317: # --------------------------------------------------------- Get symb from alias
7318:
7319: sub get_symb_from_alias {
7320: my $symb=shift;
7321: my ($map,$resid,$url)=&decode_symb($symb);
7322: # Already is a symb
7323: if ($url) { return $symb; }
7324: # Must be an alias
7325: my $aliassymb='';
7326: my %bighash;
7327: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7328: &GDBM_READER(),0640)) {
7329: my $rid=$bighash{'mapalias_'.$symb};
7330: if ($rid) {
7331: my ($mapid,$resid)=split(/\./,$rid);
7332: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7333: $resid,$bighash{'src_'.$rid});
7334: }
7335: untie %bighash;
7336: }
7337: return $aliassymb;
7338: }
7339:
7340: # ----------------------------------------------------------------- Define Role
7341:
7342: sub definerole {
7343: if (allowed('mcr','/')) {
7344: my ($rolename,$sysrole,$domrole,$courole)=@_;
7345: foreach my $role (split(':',$sysrole)) {
7346: my ($crole,$cqual)=split(/\&/,$role);
7347: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7348: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7349: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
7350: return "refused:s:$crole&$cqual";
7351: }
7352: }
7353: }
7354: foreach my $role (split(':',$domrole)) {
7355: my ($crole,$cqual)=split(/\&/,$role);
7356: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7357: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7358: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
7359: return "refused:d:$crole&$cqual";
7360: }
7361: }
7362: }
7363: foreach my $role (split(':',$courole)) {
7364: my ($crole,$cqual)=split(/\&/,$role);
7365: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7366: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7367: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
7368: return "refused:c:$crole&$cqual";
7369: }
7370: }
7371: }
7372: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7373: "$env{'user.domain'}:$env{'user.name'}:".
7374: "rolesdef_$rolename=".
7375: escape($sysrole.'_'.$domrole.'_'.$courole);
7376: return reply($command,$env{'user.home'});
7377: } else {
7378: return 'refused';
7379: }
7380: }
7381:
7382: # ---------------- Make a metadata query against the network of library servers
7383:
7384: sub metadata_query {
7385: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
7386: my %rhash;
7387: my %libserv = &all_library();
7388: my @server_list = (defined($server_array) ? @$server_array
7389: : keys(%libserv) );
7390: for my $server (@server_list) {
7391: my $domains = '';
7392: if (ref($domains_hash) eq 'HASH') {
7393: $domains = $domains_hash->{$server};
7394: }
7395: unless ($custom or $customshow) {
7396: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
7397: $rhash{$server}=$reply;
7398: }
7399: else {
7400: my $reply=&reply("querysend:".&escape($query).':'.
7401: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
7402: $server);
7403: $rhash{$server}=$reply;
7404: }
7405: }
7406: return \%rhash;
7407: }
7408:
7409: # ----------------------------------------- Send log queries and wait for reply
7410:
7411: sub log_query {
7412: my ($uname,$udom,$query,%filters)=@_;
7413: my $uhome=&homeserver($uname,$udom);
7414: if ($uhome eq 'no_host') { return 'error: no_host'; }
7415: my $uhost=&hostname($uhome);
7416: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
7417: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7418: $uhome);
7419: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
7420: return get_query_reply($queryid);
7421: }
7422:
7423: # -------------------------- Update MySQL table for portfolio file
7424:
7425: sub update_portfolio_table {
7426: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
7427: if ($group ne '') {
7428: $file_name =~s /^\Q$group\E//;
7429: }
7430: my $homeserver = &homeserver($uname,$udom);
7431: my $queryid=
7432: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7433: ':'.&escape($file_name).':'.$action,$homeserver);
7434: my $reply = &get_query_reply($queryid);
7435: return $reply;
7436: }
7437:
7438: # -------------------------- Update MySQL allusers table
7439:
7440: sub update_allusers_table {
7441: my ($uname,$udom,$names) = @_;
7442: my $homeserver = &homeserver($uname,$udom);
7443: my $queryid=
7444: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7445: 'lastname='.&escape($names->{'lastname'}).'%%'.
7446: 'firstname='.&escape($names->{'firstname'}).'%%'.
7447: 'middlename='.&escape($names->{'middlename'}).'%%'.
7448: 'generation='.&escape($names->{'generation'}).'%%'.
7449: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7450: 'id='.&escape($names->{'id'}),$homeserver);
7451: return;
7452: }
7453:
7454: # ------- Request retrieval of institutional classlists for course(s)
7455:
7456: sub fetch_enrollment_query {
7457: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
7458: my $homeserver;
7459: my $maxtries = 1;
7460: if ($context eq 'automated') {
7461: $homeserver = $perlvar{'lonHostID'};
7462: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
7463: } else {
7464: $homeserver = &homeserver($cnum,$dom);
7465: }
7466: my $host=&hostname($homeserver);
7467: my $cmd = '';
7468: foreach my $affiliate (keys(%{$affiliatesref})) {
7469: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
7470: }
7471: $cmd =~ s/%%$//;
7472: $cmd = &escape($cmd);
7473: my $query = 'fetchenrollment';
7474: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
7475: unless ($queryid=~/^\Q$host\E\_/) {
7476: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7477: return 'error: '.$queryid;
7478: }
7479: my $reply = &get_query_reply($queryid);
7480: my $tries = 1;
7481: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7482: $reply = &get_query_reply($queryid);
7483: $tries ++;
7484: }
7485: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7486: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7487: } else {
7488: my @responses = split(/:/,$reply);
7489: if ($homeserver eq $perlvar{'lonHostID'}) {
7490: foreach my $line (@responses) {
7491: my ($key,$value) = split(/=/,$line,2);
7492: $$replyref{$key} = $value;
7493: }
7494: } else {
7495: my $pathname = LONCAPA::tempdir();
7496: foreach my $line (@responses) {
7497: my ($key,$value) = split(/=/,$line);
7498: $$replyref{$key} = $value;
7499: if ($value > 0) {
7500: foreach my $item (@{$$affiliatesref{$key}}) {
7501: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
7502: my $destname = $pathname.'/'.$filename;
7503: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
7504: if ($xml_classlist =~ /^error/) {
7505: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7506: } else {
7507: if ( open(FILE,">$destname") ) {
7508: print FILE &unescape($xml_classlist);
7509: close(FILE);
7510: } else {
7511: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
7512: }
7513: }
7514: }
7515: }
7516: }
7517: }
7518: return 'ok';
7519: }
7520: return 'error';
7521: }
7522:
7523: sub get_query_reply {
7524: my $queryid=shift;
7525: my $replyfile=LONCAPA::tempdir().$queryid;
7526: my $reply='';
7527: for (1..100) {
7528: sleep 2;
7529: if (-e $replyfile.'.end') {
7530: if (open(my $fh,$replyfile)) {
7531: $reply = join('',<$fh>);
7532: close($fh);
7533: } else { return 'error: reply_file_error'; }
7534: return &unescape($reply);
7535: }
7536: }
7537: return 'timeout:'.$queryid;
7538: }
7539:
7540: sub courselog_query {
7541: #
7542: # possible filters:
7543: # url: url or symb
7544: # username
7545: # domain
7546: # action: view, submit, grade
7547: # start: timestamp
7548: # end: timestamp
7549: #
7550: my (%filters)=@_;
7551: unless ($env{'request.course.id'}) { return 'no_course'; }
7552: if ($filters{'url'}) {
7553: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7554: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7555: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7556: }
7557: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7558: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7559: return &log_query($cname,$cdom,'courselog',%filters);
7560: }
7561:
7562: sub userlog_query {
7563: #
7564: # possible filters:
7565: # action: log check role
7566: # start: timestamp
7567: # end: timestamp
7568: #
7569: my ($uname,$udom,%filters)=@_;
7570: return &log_query($uname,$udom,'userlog',%filters);
7571: }
7572:
7573: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7574:
7575: sub auto_run {
7576: my ($cnum,$cdom) = @_;
7577: my $response = 0;
7578: my $settings;
7579: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7580: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7581: $settings = $domconfig{'autoenroll'};
7582: if ($settings->{'run'} eq '1') {
7583: $response = 1;
7584: }
7585: } else {
7586: my $homeserver;
7587: if (&is_course($cdom,$cnum)) {
7588: $homeserver = &homeserver($cnum,$cdom);
7589: } else {
7590: $homeserver = &domain($cdom,'primary');
7591: }
7592: if ($homeserver ne 'no_host') {
7593: $response = &reply('autorun:'.$cdom,$homeserver);
7594: }
7595: }
7596: return $response;
7597: }
7598:
7599: sub auto_get_sections {
7600: my ($cnum,$cdom,$inst_coursecode) = @_;
7601: my $homeserver;
7602: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7603: $homeserver = &homeserver($cnum,$cdom);
7604: }
7605: if (!defined($homeserver)) {
7606: if ($cdom =~ /^$match_domain$/) {
7607: $homeserver = &domain($cdom,'primary');
7608: }
7609: }
7610: my @secs;
7611: if (defined($homeserver)) {
7612: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7613: unless ($response eq 'refused') {
7614: @secs = split(/:/,$response);
7615: }
7616: }
7617: return @secs;
7618: }
7619:
7620: sub auto_new_course {
7621: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
7622: my $homeserver = &homeserver($cnum,$cdom);
7623: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
7624: return $response;
7625: }
7626:
7627: sub auto_validate_courseID {
7628: my ($cnum,$cdom,$inst_course_id) = @_;
7629: my $homeserver = &homeserver($cnum,$cdom);
7630: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
7631: return $response;
7632: }
7633:
7634: sub auto_validate_instcode {
7635: my ($cnum,$cdom,$instcode,$owner) = @_;
7636: my ($homeserver,$response);
7637: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7638: $homeserver = &homeserver($cnum,$cdom);
7639: }
7640: if (!defined($homeserver)) {
7641: if ($cdom =~ /^$match_domain$/) {
7642: $homeserver = &domain($cdom,'primary');
7643: }
7644: }
7645: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7646: &escape($instcode).':'.&escape($owner),$homeserver));
7647: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7648: return ($outcome,$description,$defaultcredits);
7649: }
7650:
7651: sub auto_create_password {
7652: my ($cnum,$cdom,$authparam,$udom) = @_;
7653: my ($homeserver,$response);
7654: my $create_passwd = 0;
7655: my $authchk = '';
7656: if ($udom =~ /^$match_domain$/) {
7657: $homeserver = &domain($udom,'primary');
7658: }
7659: if ($homeserver eq '') {
7660: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7661: $homeserver = &homeserver($cnum,$cdom);
7662: }
7663: }
7664: if ($homeserver eq '') {
7665: $authchk = 'nodomain';
7666: } else {
7667: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7668: if ($response eq 'refused') {
7669: $authchk = 'refused';
7670: } else {
7671: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
7672: }
7673: }
7674: return ($authparam,$create_passwd,$authchk);
7675: }
7676:
7677: sub auto_photo_permission {
7678: my ($cnum,$cdom,$students) = @_;
7679: my $homeserver = &homeserver($cnum,$cdom);
7680: my ($outcome,$perm_reqd,$conditions) =
7681: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
7682: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7683: return (undef,undef);
7684: }
7685: return ($outcome,$perm_reqd,$conditions);
7686: }
7687:
7688: sub auto_checkphotos {
7689: my ($uname,$udom,$pid) = @_;
7690: my $homeserver = &homeserver($uname,$udom);
7691: my ($result,$resulttype);
7692: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
7693: &escape($uname).':'.&escape($pid),
7694: $homeserver));
7695: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7696: return (undef,undef);
7697: }
7698: if ($outcome) {
7699: ($result,$resulttype) = split(/:/,$outcome);
7700: }
7701: return ($result,$resulttype);
7702: }
7703:
7704: sub auto_photochoice {
7705: my ($cnum,$cdom) = @_;
7706: my $homeserver = &homeserver($cnum,$cdom);
7707: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
7708: &escape($cdom),
7709: $homeserver)));
7710: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7711: return (undef,undef);
7712: }
7713: return ($update,$comment);
7714: }
7715:
7716: sub auto_photoupdate {
7717: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7718: my $homeserver = &homeserver($cnum,$dom);
7719: my $host=&hostname($homeserver);
7720: my $cmd = '';
7721: my $maxtries = 1;
7722: foreach my $affiliate (keys(%{$affiliatesref})) {
7723: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
7724: }
7725: $cmd =~ s/%%$//;
7726: $cmd = &escape($cmd);
7727: my $query = 'institutionalphotos';
7728: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7729: unless ($queryid=~/^\Q$host\E\_/) {
7730: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7731: return 'error: '.$queryid;
7732: }
7733: my $reply = &get_query_reply($queryid);
7734: my $tries = 1;
7735: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7736: $reply = &get_query_reply($queryid);
7737: $tries ++;
7738: }
7739: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7740: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7741: } else {
7742: my @responses = split(/:/,$reply);
7743: my $outcome = shift(@responses);
7744: foreach my $item (@responses) {
7745: my ($key,$value) = split(/=/,$item);
7746: $$photo{$key} = $value;
7747: }
7748: return $outcome;
7749: }
7750: return 'error';
7751: }
7752:
7753: sub auto_instcode_format {
7754: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7755: $cat_order) = @_;
7756: my $courses = '';
7757: my @homeservers;
7758: if ($caller eq 'global') {
7759: my %servers = &get_servers($codedom,'library');
7760: foreach my $tryserver (keys(%servers)) {
7761: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7762: push(@homeservers,$tryserver);
7763: }
7764: }
7765: } elsif ($caller eq 'requests') {
7766: if ($codedom =~ /^$match_domain$/) {
7767: my $chome = &domain($codedom,'primary');
7768: unless ($chome eq 'no_host') {
7769: push(@homeservers,$chome);
7770: }
7771: }
7772: } else {
7773: push(@homeservers,&homeserver($caller,$codedom));
7774: }
7775: foreach my $code (keys(%{$instcodes})) {
7776: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
7777: }
7778: chop($courses);
7779: my $ok_response = 0;
7780: my $response;
7781: while (@homeservers > 0 && $ok_response == 0) {
7782: my $server = shift(@homeservers);
7783: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7784: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7785: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
7786: split(/:/,$response);
7787: %{$codes} = (%{$codes},&str2hash($codes_str));
7788: push(@{$codetitles},&str2array($codetitles_str));
7789: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7790: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7791: $ok_response = 1;
7792: }
7793: }
7794: if ($ok_response) {
7795: return 'ok';
7796: } else {
7797: return $response;
7798: }
7799: }
7800:
7801: sub auto_instcode_defaults {
7802: my ($domain,$returnhash,$code_order) = @_;
7803: my @homeservers;
7804:
7805: my %servers = &get_servers($domain,'library');
7806: foreach my $tryserver (keys(%servers)) {
7807: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7808: push(@homeservers,$tryserver);
7809: }
7810: }
7811:
7812: my $response;
7813: foreach my $server (@homeservers) {
7814: $response=&reply('autoinstcodedefaults:'.$domain,$server);
7815: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7816:
7817: foreach my $pair (split(/\&/,$response)) {
7818: my ($name,$value)=split(/\=/,$pair);
7819: if ($name eq 'code_order') {
7820: @{$code_order} = split(/\&/,&unescape($value));
7821: } else {
7822: $returnhash->{&unescape($name)}=&unescape($value);
7823: }
7824: }
7825: return 'ok';
7826: }
7827:
7828: return $response;
7829: }
7830:
7831: sub auto_possible_instcodes {
7832: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7833: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7834: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7835: return;
7836: }
7837: my (@homeservers,$uhome);
7838: if (defined(&domain($domain,'primary'))) {
7839: $uhome=&domain($domain,'primary');
7840: push(@homeservers,&domain($domain,'primary'));
7841: } else {
7842: my %servers = &get_servers($domain,'library');
7843: foreach my $tryserver (keys(%servers)) {
7844: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7845: push(@homeservers,$tryserver);
7846: }
7847: }
7848: }
7849: my $response;
7850: foreach my $server (@homeservers) {
7851: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7852: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7853: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7854: split(':',$response);
7855: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7856: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
7857: foreach my $item (split('&',$cat_title)) {
7858: my ($name,$value)=split('=',$item);
7859: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
7860: }
7861: foreach my $item (split('&',$cat_order)) {
7862: my ($name,$value)=split('=',$item);
7863: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
7864: }
7865: return 'ok';
7866: }
7867: return $response;
7868: }
7869:
7870: sub auto_courserequest_checks {
7871: my ($dom) = @_;
7872: my ($homeserver,%validations);
7873: if ($dom =~ /^$match_domain$/) {
7874: $homeserver = &domain($dom,'primary');
7875: }
7876: unless ($homeserver eq 'no_host') {
7877: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7878: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7879: my @items = split(/&/,$response);
7880: foreach my $item (@items) {
7881: my ($key,$value) = split('=',$item);
7882: $validations{&unescape($key)} = &thaw_unescape($value);
7883: }
7884: }
7885: }
7886: return %validations;
7887: }
7888:
7889: sub auto_courserequest_validation {
7890: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
7891: my ($homeserver,$response);
7892: if ($dom =~ /^$match_domain$/) {
7893: $homeserver = &domain($dom,'primary');
7894: }
7895: unless ($homeserver eq 'no_host') {
7896: my $customdata;
7897: if (ref($custominfo) eq 'HASH') {
7898: $customdata = &freeze_escape($custominfo);
7899: }
7900: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
7901: ':'.&escape($crstype).':'.&escape($inststatuslist).
7902: ':'.&escape($instcode).':'.&escape($instseclist).':'.
7903: $customdata,$homeserver));
7904: }
7905: return $response;
7906: }
7907:
7908: sub auto_validate_class_sec {
7909: my ($cdom,$cnum,$owners,$inst_class) = @_;
7910: my $homeserver = &homeserver($cnum,$cdom);
7911: my $ownerlist;
7912: if (ref($owners) eq 'ARRAY') {
7913: $ownerlist = join(',',@{$owners});
7914: } else {
7915: $ownerlist = $owners;
7916: }
7917: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
7918: &escape($ownerlist).':'.$cdom,$homeserver);
7919: return $response;
7920: }
7921:
7922: sub auto_crsreq_update {
7923: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
7924: $code,$accessstart,$accessend,$inbound) = @_;
7925: my ($homeserver,%crsreqresponse);
7926: if ($cdom =~ /^$match_domain$/) {
7927: $homeserver = &domain($cdom,'primary');
7928: }
7929: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
7930: my $info;
7931: if (ref($inbound) eq 'HASH') {
7932: $info = &freeze_escape($inbound);
7933: }
7934: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
7935: ':'.&escape($action).':'.&escape($ownername).':'.
7936: &escape($ownerdomain).':'.&escape($fullname).':'.
7937: &escape($title).':'.&escape($code).':'.
7938: &escape($accessstart).':'.&escape($accessend).':'.$info,
7939: $homeserver);
7940: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7941: my @items = split(/&/,$response);
7942: foreach my $item (@items) {
7943: my ($key,$value) = split('=',$item);
7944: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
7945: }
7946: }
7947: }
7948: return \%crsreqresponse;
7949: }
7950:
7951: # ------------------------------------------------------- Course Group routines
7952:
7953: sub get_coursegroups {
7954: my ($cdom,$cnum,$group,$namespace) = @_;
7955: return(&dump($namespace,$cdom,$cnum,$group));
7956: }
7957:
7958: sub modify_coursegroup {
7959: my ($cdom,$cnum,$groupsettings) = @_;
7960: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7961: }
7962:
7963: sub toggle_coursegroup_status {
7964: my ($cdom,$cnum,$group,$action) = @_;
7965: my ($from_namespace,$to_namespace);
7966: if ($action eq 'delete') {
7967: $from_namespace = 'coursegroups';
7968: $to_namespace = 'deleted_groups';
7969: } else {
7970: $from_namespace = 'deleted_groups';
7971: $to_namespace = 'coursegroups';
7972: }
7973: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
7974: if (my $tmp = &error(%curr_group)) {
7975: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7976: return ('read error',$tmp);
7977: } else {
7978: my %savedsettings = %curr_group;
7979: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
7980: my $deloutcome;
7981: if ($result eq 'ok') {
7982: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
7983: } else {
7984: return ('write error',$result);
7985: }
7986: if ($deloutcome eq 'ok') {
7987: return 'ok';
7988: } else {
7989: return ('delete error',$deloutcome);
7990: }
7991: }
7992: }
7993:
7994: sub modify_group_roles {
7995: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
7996: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7997: my $role = 'gr/'.&escape($userprivs);
7998: my ($uname,$udom) = split(/:/,$user);
7999: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
8000: if ($result eq 'ok') {
8001: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8002: }
8003: return $result;
8004: }
8005:
8006: sub modify_coursegroup_membership {
8007: my ($cdom,$cnum,$membership) = @_;
8008: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8009: return $result;
8010: }
8011:
8012: sub get_active_groups {
8013: my ($udom,$uname,$cdom,$cnum) = @_;
8014: my $now = time;
8015: my %groups = ();
8016: foreach my $key (keys(%env)) {
8017: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
8018: my ($start,$end) = split(/\./,$env{$key});
8019: if (($end!=0) && ($end<$now)) { next; }
8020: if (($start!=0) && ($start>$now)) { next; }
8021: if ($1 eq $cdom && $2 eq $cnum) {
8022: $groups{$3} = $env{$key} ;
8023: }
8024: }
8025: }
8026: return %groups;
8027: }
8028:
8029: sub get_group_membership {
8030: my ($cdom,$cnum,$group) = @_;
8031: return(&dump('groupmembership',$cdom,$cnum,$group));
8032: }
8033:
8034: sub get_users_groups {
8035: my ($udom,$uname,$courseid) = @_;
8036: my @usersgroups;
8037: my $cachetime=1800;
8038:
8039: my $hashid="$udom:$uname:$courseid";
8040: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8041: if (defined($cached)) {
8042: @usersgroups = split(/:/,$grouplist);
8043: } else {
8044: $grouplist = '';
8045: my $courseurl = &courseid_to_courseurl($courseid);
8046: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
8047: my $access_end = $env{'course.'.$courseid.
8048: '.default_enrollment_end_date'};
8049: my $now = time;
8050: foreach my $key (keys(%roleshash)) {
8051: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8052: my $group = $1;
8053: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8054: my $start = $2;
8055: my $end = $1;
8056: if ($start == -1) { next; } # deleted from group
8057: if (($start!=0) && ($start>$now)) { next; }
8058: if (($end!=0) && ($end<$now)) {
8059: if ($access_end && $access_end < $now) {
8060: if ($access_end - $end < 86400) {
8061: push(@usersgroups,$group);
8062: }
8063: }
8064: next;
8065: }
8066: push(@usersgroups,$group);
8067: }
8068: }
8069: }
8070: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8071: $grouplist = join(':',@usersgroups);
8072: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
8073: }
8074: return @usersgroups;
8075: }
8076:
8077: sub devalidate_getgroups_cache {
8078: my ($udom,$uname,$cdom,$cnum)=@_;
8079: my $courseid = $cdom.'_'.$cnum;
8080:
8081: my $hashid="$udom:$uname:$courseid";
8082: &devalidate_cache_new('getgroups',$hashid);
8083: }
8084:
8085: # ------------------------------------------------------------------ Plain Text
8086:
8087: sub plaintext {
8088: my ($short,$type,$cid,$forcedefault) = @_;
8089: if ($short =~ m{^cr/}) {
8090: return (split('/',$short))[-1];
8091: }
8092: if (!defined($cid)) {
8093: $cid = $env{'request.course.id'};
8094: }
8095: my %rolenames = (
8096: Course => 'std',
8097: Community => 'alt1',
8098: );
8099: if ($cid ne '') {
8100: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8101: unless ($forcedefault) {
8102: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8103: &Apache::lonlocal::mt_escape(\$roletext);
8104: return &Apache::lonlocal::mt($roletext);
8105: }
8106: }
8107: }
8108: if ((defined($type)) && (defined($rolenames{$type})) &&
8109: (defined($rolenames{$type})) &&
8110: (defined($prp{$short}{$rolenames{$type}}))) {
8111: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
8112: } elsif ($cid ne '') {
8113: my $crstype = $env{'course.'.$cid.'.type'};
8114: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8115: (defined($prp{$short}{$rolenames{$crstype}}))) {
8116: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8117: }
8118: }
8119: return &Apache::lonlocal::mt($prp{$short}{'std'});
8120: }
8121:
8122: # ----------------------------------------------------------------- Assign Role
8123:
8124: sub assignrole {
8125: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8126: $context)=@_;
8127: my $mrole;
8128: if ($role =~ /^cr\//) {
8129: my $cwosec=$url;
8130: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
8131: unless (&allowed('ccr',$cwosec)) {
8132: my $refused = 1;
8133: if ($context eq 'requestcourses') {
8134: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8135: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8136: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8137: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8138: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8139: if ($crsenv{'internal.courseowner'} eq
8140: $env{'user.name'}.':'.$env{'user.domain'}) {
8141: $refused = '';
8142: }
8143: }
8144: }
8145: }
8146: }
8147: if ($refused) {
8148: &logthis('Refused custom assignrole: '.
8149: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8150: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8151: return 'refused';
8152: }
8153: }
8154: $mrole='cr';
8155: } elsif ($role =~ /^gr\//) {
8156: my $cwogrp=$url;
8157: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
8158: unless (&allowed('mdg',$cwogrp)) {
8159: &logthis('Refused group assignrole: '.
8160: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8161: $env{'user.name'}.' at '.$env{'user.domain'});
8162: return 'refused';
8163: }
8164: $mrole='gr';
8165: } else {
8166: my $cwosec=$url;
8167: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
8168: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8169: my $refused;
8170: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8171: if (!(&allowed('c'.$role,$url))) {
8172: $refused = 1;
8173: }
8174: } else {
8175: $refused = 1;
8176: }
8177: if ($refused) {
8178: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8179: if (!$selfenroll && $context eq 'course') {
8180: my %crsenv;
8181: if ($role eq 'cc' || $role eq 'co') {
8182: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8183: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8184: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8185: if ($crsenv{'internal.courseowner'} eq
8186: $env{'user.name'}.':'.$env{'user.domain'}) {
8187: $refused = '';
8188: }
8189: }
8190: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8191: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8192: if ($crsenv{'internal.courseowner'} eq
8193: $env{'user.name'}.':'.$env{'user.domain'}) {
8194: $refused = '';
8195: }
8196: }
8197: }
8198: }
8199: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
8200: $refused = '';
8201: } elsif ($context eq 'requestcourses') {
8202: my @possroles = ('st','ta','ep','in','cc','co');
8203: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
8204: my $wrongcc;
8205: if ($cnum =~ /^$match_community$/) {
8206: $wrongcc = 1 if ($role eq 'cc');
8207: } else {
8208: $wrongcc = 1 if ($role eq 'co');
8209: }
8210: unless ($wrongcc) {
8211: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8212: if ($crsenv{'internal.courseowner'} eq
8213: $env{'user.name'}.':'.$env{'user.domain'}) {
8214: $refused = '';
8215: }
8216: }
8217: }
8218: } elsif ($context eq 'requestauthor') {
8219: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8220: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8221: if ($env{'environment.requestauthor'} eq 'automatic') {
8222: $refused = '';
8223: } else {
8224: my %domdefaults = &get_domain_defaults($udom);
8225: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8226: my $checkbystatus;
8227: if ($env{'user.adv'}) {
8228: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8229: if ($disposition eq 'automatic') {
8230: $refused = '';
8231: } elsif ($disposition eq '') {
8232: $checkbystatus = 1;
8233: }
8234: } else {
8235: $checkbystatus = 1;
8236: }
8237: if ($checkbystatus) {
8238: if ($env{'environment.inststatus'}) {
8239: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8240: foreach my $type (@inststatuses) {
8241: if (($type ne '') &&
8242: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8243: $refused = '';
8244: }
8245: }
8246: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8247: $refused = '';
8248: }
8249: }
8250: }
8251: }
8252: }
8253: }
8254: if ($refused) {
8255: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8256: ' '.$role.' '.$end.' '.$start.' by '.
8257: $env{'user.name'}.' at '.$env{'user.domain'});
8258: return 'refused';
8259: }
8260: }
8261: } elsif ($role eq 'au') {
8262: if ($url ne '/'.$udom.'/') {
8263: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8264: ' to assign author role for '.$uname.':'.$udom.
8265: ' in domain: '.$url.' refused (wrong domain).');
8266: return 'refused';
8267: }
8268: }
8269: $mrole=$role;
8270: }
8271: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
8272: "$udom:$uname:$url".'_'."$mrole=$role";
8273: if ($end) { $command.='_'.$end; }
8274: if ($start) {
8275: if ($end) {
8276: $command.='_'.$start;
8277: } else {
8278: $command.='_0_'.$start;
8279: }
8280: }
8281: my $origstart = $start;
8282: my $origend = $end;
8283: my $delflag;
8284: # actually delete
8285: if ($deleteflag) {
8286: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
8287: # modify command to delete the role
8288: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
8289: "$udom:$uname:$url".'_'."$mrole";
8290: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
8291: # set start and finish to negative values for userrolelog
8292: $start=-1;
8293: $end=-1;
8294: $delflag = 1;
8295: }
8296: }
8297: # send command
8298: my $answer=&reply($command,&homeserver($uname,$udom));
8299: # log new user role if status is ok
8300: if ($answer eq 'ok') {
8301: &userrolelog($role,$uname,$udom,$url,$start,$end);
8302: if (($role eq 'cc') || ($role eq 'in') ||
8303: ($role eq 'ep') || ($role eq 'ad') ||
8304: ($role eq 'ta') || ($role eq 'st') ||
8305: ($role=~/^cr/) || ($role eq 'gr') ||
8306: ($role eq 'co')) {
8307: # for course roles, perform group memberships changes triggered by role change.
8308: unless ($role =~ /^gr/) {
8309: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8310: $origstart,$selfenroll,$context);
8311: }
8312: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8313: $selfenroll,$context);
8314: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8315: ($role eq 'au') || ($role eq 'dc')) {
8316: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8317: $context);
8318: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8319: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8320: $context);
8321: }
8322: if ($role eq 'cc') {
8323: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8324: }
8325: }
8326: return $answer;
8327: }
8328:
8329: sub autoupdate_coowners {
8330: my ($url,$end,$start,$uname,$udom) = @_;
8331: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8332: if (($cdom ne '') && ($cnum ne '')) {
8333: my $now = time;
8334: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8335: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8336: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8337: my $instcode = $coursehash{'internal.coursecode'};
8338: if ($instcode ne '') {
8339: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8340: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
8341: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
8342: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8343: if ($result eq 'valid') {
8344: if ($coursehash{'internal.co-owners'}) {
8345: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8346: push(@newcoowners,$coowner);
8347: }
8348: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8349: push(@newcoowners,$uname.':'.$udom);
8350: }
8351: @newcoowners = sort(@newcoowners);
8352: } else {
8353: push(@newcoowners,$uname.':'.$udom);
8354: }
8355: } else {
8356: if ($coursehash{'internal.co-owners'}) {
8357: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8358: unless ($coowner eq $uname.':'.$udom) {
8359: push(@newcoowners,$coowner);
8360: }
8361: }
8362: unless (@newcoowners > 0) {
8363: $delcoowners = 1;
8364: $coowners = '';
8365: }
8366: }
8367: }
8368: if (@newcoowners || $delcoowners) {
8369: &store_coowners($cdom,$cnum,$coursehash{'home'},
8370: $delcoowners,@newcoowners);
8371: }
8372: }
8373: }
8374: }
8375: }
8376: }
8377: }
8378:
8379: sub store_coowners {
8380: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8381: my $cid = $cdom.'_'.$cnum;
8382: my ($coowners,$delresult,$putresult);
8383: if (@newcoowners) {
8384: $coowners = join(',',@newcoowners);
8385: my %coownershash = (
8386: 'internal.co-owners' => $coowners,
8387: );
8388: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8389: if ($putresult eq 'ok') {
8390: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8391: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8392: }
8393: }
8394: }
8395: if ($delcoowners) {
8396: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8397: if ($delresult eq 'ok') {
8398: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8399: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8400: }
8401: }
8402: }
8403: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8404: my %crsinfo =
8405: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8406: if (ref($crsinfo{$cid}) eq 'HASH') {
8407: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8408: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8409: }
8410: }
8411: }
8412:
8413: # -------------------------------------------------- Modify user authentication
8414: # Overrides without validation
8415:
8416: sub modifyuserauth {
8417: my ($udom,$uname,$umode,$upass)=@_;
8418: my $uhome=&homeserver($uname,$udom);
8419: unless (&allowed('mau',$udom)) { return 'refused'; }
8420: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
8421: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8422: ' in domain '.$env{'request.role.domain'});
8423: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8424: &escape($upass),$uhome);
8425: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
8426: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8427: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8428: &log($udom,,$uname,$uhome,
8429: 'Authentication changed by '.$env{'user.domain'}.', '.
8430: $env{'user.name'}.', '.$umode.
8431: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8432: unless ($reply eq 'ok') {
8433: &logthis('Authentication mode error: '.$reply);
8434: return 'error: '.$reply;
8435: }
8436: return 'ok';
8437: }
8438:
8439: # --------------------------------------------------------------- Modify a user
8440:
8441: sub modifyuser {
8442: my ($udom, $uname, $uid,
8443: $umode, $upass, $first,
8444: $middle, $last, $gene,
8445: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
8446: $udom= &LONCAPA::clean_domain($udom);
8447: $uname=&LONCAPA::clean_username($uname);
8448: my $showcandelete = 'none';
8449: if (ref($candelete) eq 'ARRAY') {
8450: if (@{$candelete} > 0) {
8451: $showcandelete = join(', ',@{$candelete});
8452: }
8453: }
8454: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
8455: $umode.', '.$first.', '.$middle.', '.
8456: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
8457: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8458: ' desiredhome not specified').
8459: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8460: ' in domain '.$env{'request.role.domain'});
8461: my $uhome=&homeserver($uname,$udom,'true');
8462: my $newuser;
8463: if ($uhome eq 'no_host') {
8464: $newuser = 1;
8465: }
8466: # ----------------------------------------------------------------- Create User
8467: if (($uhome eq 'no_host') &&
8468: (($umode && $upass) || ($umode eq 'localauth'))) {
8469: my $unhome='';
8470: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
8471: $unhome = $desiredhome;
8472: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8473: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
8474: } else { # load balancing routine for determining $unhome
8475: my $loadm=10000000;
8476: my %servers = &get_servers($udom,'library');
8477: foreach my $tryserver (keys(%servers)) {
8478: my $answer=reply('load',$tryserver);
8479: if (($answer=~/\d+/) && ($answer<$loadm)) {
8480: $loadm=$answer;
8481: $unhome=$tryserver;
8482: }
8483: }
8484: }
8485: if (($unhome eq '') || ($unhome eq 'no_host')) {
8486: return 'error: unable to find a home server for '.$uname.
8487: ' in domain '.$udom;
8488: }
8489: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8490: &escape($upass),$unhome);
8491: unless ($reply eq 'ok') {
8492: return 'error: '.$reply;
8493: }
8494: $uhome=&homeserver($uname,$udom,'true');
8495: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
8496: return 'error: unable verify users home machine.';
8497: }
8498: } # End of creation of new user
8499: # ---------------------------------------------------------------------- Add ID
8500: if ($uid) {
8501: $uid=~tr/A-Z/a-z/;
8502: my %uidhash=&idrget($udom,$uname);
8503: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8504: && (!$forceid)) {
8505: unless ($uid eq $uidhash{$uname}) {
8506: return 'error: user id "'.$uid.'" does not match '.
8507: 'current user id "'.$uidhash{$uname}.'".';
8508: }
8509: } else {
8510: &idput($udom,($uname => $uid));
8511: }
8512: }
8513: # -------------------------------------------------------------- Add names, etc
8514: my @tmp=&get('environment',
8515: ['firstname','middlename','lastname','generation','id',
8516: 'permanentemail','inststatus'],
8517: $udom,$uname);
8518: my (%names,%oldnames);
8519: if ($tmp[0] =~ m/^error:.*/) {
8520: %names=();
8521: } else {
8522: %names = @tmp;
8523: %oldnames = %names;
8524: }
8525: #
8526: # If name, email and/or uid are blank (e.g., because an uploaded file
8527: # of users did not contain them), do not overwrite existing values
8528: # unless field is in $candelete array ref.
8529: #
8530:
8531: my @fields = ('firstname','middlename','lastname','generation',
8532: 'permanentemail','id');
8533: my %newvalues;
8534: if (ref($candelete) eq 'ARRAY') {
8535: foreach my $field (@fields) {
8536: if (grep(/^\Q$field\E$/,@{$candelete})) {
8537: if ($field eq 'firstname') {
8538: $names{$field} = $first;
8539: } elsif ($field eq 'middlename') {
8540: $names{$field} = $middle;
8541: } elsif ($field eq 'lastname') {
8542: $names{$field} = $last;
8543: } elsif ($field eq 'generation') {
8544: $names{$field} = $gene;
8545: } elsif ($field eq 'permanentemail') {
8546: $names{$field} = $email;
8547: } elsif ($field eq 'id') {
8548: $names{$field} = $uid;
8549: }
8550: }
8551: }
8552: }
8553: if ($first) { $names{'firstname'} = $first; }
8554: if (defined($middle)) { $names{'middlename'} = $middle; }
8555: if ($last) { $names{'lastname'} = $last; }
8556: if (defined($gene)) { $names{'generation'} = $gene; }
8557: if ($email) {
8558: $email=~s/[^\w\@\.\-\,]//gs;
8559: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
8560: }
8561: if ($uid) { $names{'id'} = $uid; }
8562: if (defined($inststatus)) {
8563: $names{'inststatus'} = '';
8564: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8565: if (ref($usertypes) eq 'HASH') {
8566: my @okstatuses;
8567: foreach my $item (split(/:/,$inststatus)) {
8568: if (defined($usertypes->{$item})) {
8569: push(@okstatuses,$item);
8570: }
8571: }
8572: if (@okstatuses) {
8573: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8574: }
8575: }
8576: }
8577: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
8578: $umode.', '.$first.', '.$middle.', '.
8579: $last.', '.$gene.', '.$email.', '.$inststatus;
8580: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8581: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8582: } else {
8583: $logmsg .= ' during self creation';
8584: }
8585: my $changed;
8586: if ($newuser) {
8587: $changed = 1;
8588: } else {
8589: foreach my $field (@fields) {
8590: if ($names{$field} ne $oldnames{$field}) {
8591: $changed = 1;
8592: last;
8593: }
8594: }
8595: }
8596: unless ($changed) {
8597: $logmsg = 'No changes in user information needed for: '.$logmsg;
8598: &logthis($logmsg);
8599: return 'ok';
8600: }
8601: my $reply = &put('environment', \%names, $udom,$uname);
8602: if ($reply ne 'ok') {
8603: return 'error: '.$reply;
8604: }
8605: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8606: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8607: }
8608: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8609: &devalidate_cache_new('namescache',$uname.':'.$udom);
8610: $logmsg = 'Success modifying user '.$logmsg;
8611: &logthis($logmsg);
8612: return 'ok';
8613: }
8614:
8615: # -------------------------------------------------------------- Modify student
8616:
8617: sub modifystudent {
8618: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
8619: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
8620: $selfenroll,$context,$inststatus,$credits)=@_;
8621: if (!$cid) {
8622: unless ($cid=$env{'request.course.id'}) {
8623: return 'not_in_class';
8624: }
8625: }
8626: # --------------------------------------------------------------- Make the user
8627: my $reply=&modifyuser
8628: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
8629: $desiredhome,$email,$inststatus);
8630: unless ($reply eq 'ok') { return $reply; }
8631: # This will cause &modify_student_enrollment to get the uid from the
8632: # student's environment
8633: $uid = undef if (!$forceid);
8634: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
8635: $gene,$usec,$end,$start,$type,$locktype,
8636: $cid,$selfenroll,$context,$credits);
8637: return $reply;
8638: }
8639:
8640: sub modify_student_enrollment {
8641: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8642: $locktype,$cid,$selfenroll,$context,$credits) = @_;
8643: my ($cdom,$cnum,$chome);
8644: if (!$cid) {
8645: unless ($cid=$env{'request.course.id'}) {
8646: return 'not_in_class';
8647: }
8648: $cdom=$env{'course.'.$cid.'.domain'};
8649: $cnum=$env{'course.'.$cid.'.num'};
8650: } else {
8651: ($cdom,$cnum)=split(/_/,$cid);
8652: }
8653: $chome=$env{'course.'.$cid.'.home'};
8654: if (!$chome) {
8655: $chome=&homeserver($cnum,$cdom);
8656: }
8657: if (!$chome) { return 'unknown_course'; }
8658: # Make sure the user exists
8659: my $uhome=&homeserver($uname,$udom);
8660: if (($uhome eq '') || ($uhome eq 'no_host')) {
8661: return 'error: no such user';
8662: }
8663: # Get student data if we were not given enough information
8664: if (!defined($first) || $first eq '' ||
8665: !defined($last) || $last eq '' ||
8666: !defined($uid) || $uid eq '' ||
8667: !defined($middle) || $middle eq '' ||
8668: !defined($gene) || $gene eq '') {
8669: # They did not supply us with enough data to enroll the student, so
8670: # we need to pick up more information.
8671: my %tmp = &get('environment',
8672: ['firstname','middlename','lastname', 'generation','id']
8673: ,$udom,$uname);
8674:
8675: #foreach my $key (keys(%tmp)) {
8676: # &logthis("key $key = ".$tmp{$key});
8677: #}
8678: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8679: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8680: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
8681: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
8682: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8683: }
8684: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
8685: my $user = "$uname:$udom";
8686: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
8687: my $reply=cput('classlist',
8688: {$user =>
8689: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
8690: $cdom,$cnum);
8691: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8692: &devalidate_getsection_cache($udom,$uname,$cid);
8693: } else {
8694: return 'error: '.$reply;
8695: }
8696: # Add student role to user
8697: my $uurl='/'.$cid;
8698: $uurl=~s/\_/\//g;
8699: if ($usec) {
8700: $uurl.='/'.$usec;
8701: }
8702: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8703: $selfenroll,$context);
8704: if ($result ne 'ok') {
8705: if ($old_entry{$user} ne '') {
8706: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8707: } else {
8708: $reply = &del('classlist',[$user],$cdom,$cnum);
8709: }
8710: }
8711: return $result;
8712: }
8713:
8714: sub format_name {
8715: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8716: my $name;
8717: if ($first ne 'lastname') {
8718: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8719: } else {
8720: if ($lastname=~/\S/) {
8721: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8722: $name=~s/\s+,/,/;
8723: } else {
8724: $name.= $firstname.' '.$middlename.' '.$generation;
8725: }
8726: }
8727: $name=~s/^\s+//;
8728: $name=~s/\s+$//;
8729: $name=~s/\s+/ /g;
8730: return $name;
8731: }
8732:
8733: # ------------------------------------------------- Write to course preferences
8734:
8735: sub writecoursepref {
8736: my ($courseid,%prefs)=@_;
8737: $courseid=~s/^\///;
8738: $courseid=~s/\_/\//g;
8739: my ($cdomain,$cnum)=split(/\//,$courseid);
8740: my $chome=homeserver($cnum,$cdomain);
8741: if (($chome eq '') || ($chome eq 'no_host')) {
8742: return 'error: no such course';
8743: }
8744: my $cstring='';
8745: foreach my $pref (keys(%prefs)) {
8746: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
8747: }
8748: $cstring=~s/\&$//;
8749: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8750: }
8751:
8752: # ---------------------------------------------------------- Make/modify course
8753:
8754: sub createcourse {
8755: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
8756: $course_owner,$crstype,$cnum,$context,$category)=@_;
8757: $url=&declutter($url);
8758: my $cid='';
8759: if ($context eq 'requestcourses') {
8760: my $can_create = 0;
8761: my ($ownername,$ownerdom) = split(':',$course_owner);
8762: if ($udom eq $ownerdom) {
8763: if (&usertools_access($ownername,$ownerdom,$category,undef,
8764: $context)) {
8765: $can_create = 1;
8766: }
8767: } else {
8768: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8769: $category);
8770: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8771: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8772: if (@curr > 0) {
8773: my @options = qw(approval validate autolimit);
8774: my $optregex = join('|',@options);
8775: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8776: $can_create = 1;
8777: }
8778: }
8779: }
8780: }
8781: if ($can_create) {
8782: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8783: unless (&allowed('ccc',$udom)) {
8784: return 'refused';
8785: }
8786: }
8787: } else {
8788: return 'refused';
8789: }
8790: } elsif (!&allowed('ccc',$udom)) {
8791: return 'refused';
8792: }
8793: # --------------------------------------------------------------- Get Unique ID
8794: my $uname;
8795: if ($cnum =~ /^$match_courseid$/) {
8796: my $chome=&homeserver($cnum,$udom,'true');
8797: if (($chome eq '') || ($chome eq 'no_host')) {
8798: $uname = $cnum;
8799: } else {
8800: $uname = &generate_coursenum($udom,$crstype);
8801: }
8802: } else {
8803: $uname = &generate_coursenum($udom,$crstype);
8804: }
8805: return $uname if ($uname =~ /^error/);
8806: # -------------------------------------------------- Check supplied server name
8807: if (!defined($course_server)) {
8808: if (defined(&domain($udom,'primary'))) {
8809: $course_server = &domain($udom,'primary');
8810: } else {
8811: $course_server = $env{'user.home'};
8812: }
8813: }
8814: my %host_servers =
8815: &Apache::lonnet::get_servers($udom,'library');
8816: unless ($host_servers{$course_server}) {
8817: return 'error: invalid home server for course: '.$course_server;
8818: }
8819: # ------------------------------------------------------------- Make the course
8820: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
8821: $course_server);
8822: unless ($reply eq 'ok') { return 'error: '.$reply; }
8823: my $uhome=&homeserver($uname,$udom,'true');
8824: if (($uhome eq '') || ($uhome eq 'no_host')) {
8825: return 'error: no such course';
8826: }
8827: # ----------------------------------------------------------------- Course made
8828: # log existence
8829: my $now = time;
8830: my $newcourse = {
8831: $udom.'_'.$uname => {
8832: description => $description,
8833: inst_code => $inst_code,
8834: owner => $course_owner,
8835: type => $crstype,
8836: creator => $env{'user.name'}.':'.
8837: $env{'user.domain'},
8838: created => $now,
8839: context => $context,
8840: },
8841: };
8842: &courseidput($udom,$newcourse,$uhome,'notime');
8843: # set toplevel url
8844: my $topurl=$url;
8845: unless ($nonstandard) {
8846: # ------------------------------------------ For standard courses, make top url
8847: my $mapurl=&clutter($url);
8848: if ($mapurl eq '/res/') { $mapurl=''; }
8849: $env{'form.initmap'}=(<<ENDINITMAP);
8850: <map>
8851: <resource id="1" type="start"></resource>
8852: <resource id="2" src="$mapurl"></resource>
8853: <resource id="3" type="finish"></resource>
8854: <link index="1" from="1" to="2"></link>
8855: <link index="2" from="2" to="3"></link>
8856: </map>
8857: ENDINITMAP
8858: $topurl=&declutter(
8859: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
8860: );
8861: }
8862: # ----------------------------------------------------------- Write preferences
8863: &writecoursepref($udom.'_'.$uname,
8864: ('description' => $description,
8865: 'url' => $topurl,
8866: 'internal.creator' => $env{'user.name'}.':'.
8867: $env{'user.domain'},
8868: 'internal.created' => $now,
8869: 'internal.creationcontext' => $context)
8870: );
8871: return '/'.$udom.'/'.$uname;
8872: }
8873:
8874: # ------------------------------------------------------------------- Create ID
8875: sub generate_coursenum {
8876: my ($udom,$crstype) = @_;
8877: my $domdesc = &domain($udom);
8878: return 'error: invalid domain' if ($domdesc eq '');
8879: my $first;
8880: if ($crstype eq 'Community') {
8881: $first = '0';
8882: } else {
8883: $first = int(1+rand(9));
8884: }
8885: my $uname=$first.
8886: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8887: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8888: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8889: # ----------------------------------------------- Make sure that does not exist
8890: my $uhome=&homeserver($uname,$udom,'true');
8891: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8892: if ($crstype eq 'Community') {
8893: $first = '0';
8894: } else {
8895: $first = int(1+rand(9));
8896: }
8897: $uname=$first.
8898: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8899: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8900: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8901: $uhome=&homeserver($uname,$udom,'true');
8902: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8903: return 'error: unable to generate unique course-ID';
8904: }
8905: }
8906: return $uname;
8907: }
8908:
8909: sub is_course {
8910: my ($cdom, $cnum) = scalar(@_) == 1 ?
8911: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8912:
8913: return unless $cdom and $cnum;
8914:
8915: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8916: '.');
8917:
8918: return unless(exists($courses{$cdom.'_'.$cnum}));
8919: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
8920: }
8921:
8922: sub store_userdata {
8923: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
8924: my $result;
8925: if ($datakey ne '') {
8926: if (ref($storehash) eq 'HASH') {
8927: if ($udom eq '' || $uname eq '') {
8928: $udom = $env{'user.domain'};
8929: $uname = $env{'user.name'};
8930: }
8931: my $uhome=&homeserver($uname,$udom);
8932: if (($uhome eq '') || ($uhome eq 'no_host')) {
8933: $result = 'error: no_host';
8934: } else {
8935: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8936: $storehash->{'host'} = $perlvar{'lonHostID'};
8937:
8938: my $namevalue='';
8939: foreach my $key (keys(%{$storehash})) {
8940: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8941: }
8942: $namevalue=~s/\&$//;
8943: unless ($namespace eq 'courserequests') {
8944: $datakey = &escape($datakey);
8945: }
8946: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8947: $namevalue,$uhome);
8948: }
8949: } else {
8950: $result = 'error: data to store was not a hash reference';
8951: }
8952: } else {
8953: $result= 'error: invalid requestkey';
8954: }
8955: return $result;
8956: }
8957:
8958: # ---------------------------------------------------------- Assign Custom Role
8959:
8960: sub assigncustomrole {
8961: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
8962: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
8963: $end,$start,$deleteflag,$selfenroll,$context);
8964: }
8965:
8966: # ----------------------------------------------------------------- Revoke Role
8967:
8968: sub revokerole {
8969: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
8970: my $now=time;
8971: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
8972: }
8973:
8974: # ---------------------------------------------------------- Revoke Custom Role
8975:
8976: sub revokecustomrole {
8977: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
8978: my $now=time;
8979: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
8980: $deleteflag,$selfenroll,$context);
8981: }
8982:
8983: # ------------------------------------------------------------ Disk usage
8984: sub diskusage {
8985: my ($udom,$uname,$directorypath,$getpropath)=@_;
8986: $directorypath =~ s/\/$//;
8987: my $listing=&reply('du2:'.&escape($directorypath).':'
8988: .&escape($getpropath).':'.&escape($uname).':'
8989: .&escape($udom),homeserver($uname,$udom));
8990: if ($listing eq 'unknown_cmd') {
8991: if ($getpropath) {
8992: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8993: }
8994: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8995: }
8996: return $listing;
8997: }
8998:
8999: sub is_locked {
9000: my ($file_name, $domain, $user, $which) = @_;
9001: my @check;
9002: my $is_locked;
9003: push (@check,$file_name);
9004: my %locked = &get('file_permissions',\@check,
9005: $env{'user.domain'},$env{'user.name'});
9006: my ($tmp)=keys(%locked);
9007: if ($tmp=~/^error:/) { undef(%locked); }
9008:
9009: if (ref($locked{$file_name}) eq 'ARRAY') {
9010: $is_locked = 'false';
9011: foreach my $entry (@{$locked{$file_name}}) {
9012: if (ref($entry) eq 'ARRAY') {
9013: $is_locked = 'true';
9014: if (ref($which) eq 'ARRAY') {
9015: push(@{$which},$entry);
9016: } else {
9017: last;
9018: }
9019: }
9020: }
9021: } else {
9022: $is_locked = 'false';
9023: }
9024: return $is_locked;
9025: }
9026:
9027: sub declutter_portfile {
9028: my ($file) = @_;
9029: $file =~ s{^(/portfolio/|portfolio/)}{/};
9030: return $file;
9031: }
9032:
9033: # ------------------------------------------------------------- Mark as Read Only
9034:
9035: sub mark_as_readonly {
9036: my ($domain,$user,$files,$what) = @_;
9037: my %current_permissions = &dump('file_permissions',$domain,$user);
9038: my ($tmp)=keys(%current_permissions);
9039: if ($tmp=~/^error:/) { undef(%current_permissions); }
9040: foreach my $file (@{$files}) {
9041: $file = &declutter_portfile($file);
9042: push(@{$current_permissions{$file}},$what);
9043: }
9044: &put('file_permissions',\%current_permissions,$domain,$user);
9045: return;
9046: }
9047:
9048: # ------------------------------------------------------------Save Selected Files
9049:
9050: sub save_selected_files {
9051: my ($user, $path, @files) = @_;
9052: my $filename = $user."savedfiles";
9053: my @other_files = &files_not_in_path($user, $path);
9054: open (OUT, '>'.$tmpdir.$filename);
9055: foreach my $file (@files) {
9056: print (OUT $env{'form.currentpath'}.$file."\n");
9057: }
9058: foreach my $file (@other_files) {
9059: print (OUT $file."\n");
9060: }
9061: close (OUT);
9062: return 'ok';
9063: }
9064:
9065: sub clear_selected_files {
9066: my ($user) = @_;
9067: my $filename = $user."savedfiles";
9068: open (OUT, '>'.LONCAPA::tempdir().$filename);
9069: print (OUT undef);
9070: close (OUT);
9071: return ("ok");
9072: }
9073:
9074: sub files_in_path {
9075: my ($user, $path) = @_;
9076: my $filename = $user."savedfiles";
9077: my %return_files;
9078: open (IN, '<'.LONCAPA::tempdir().$filename);
9079: while (my $line_in = <IN>) {
9080: chomp ($line_in);
9081: my @paths_and_file = split (m!/!, $line_in);
9082: my $file_part = pop (@paths_and_file);
9083: my $path_part = join ('/', @paths_and_file);
9084: $path_part.='/';
9085: my $path_and_file = $path_part.$file_part;
9086: if ($path_part eq $path) {
9087: $return_files{$file_part}= 'selected';
9088: }
9089: }
9090: close (IN);
9091: return (\%return_files);
9092: }
9093:
9094: # called in portfolio select mode, to show files selected NOT in current directory
9095: sub files_not_in_path {
9096: my ($user, $path) = @_;
9097: my $filename = $user."savedfiles";
9098: my @return_files;
9099: my $path_part;
9100: open(IN, '<'.LONCAPA::.$filename);
9101: while (my $line = <IN>) {
9102: #ok, I know it's clunky, but I want it to work
9103: my @paths_and_file = split(m|/|, $line);
9104: my $file_part = pop(@paths_and_file);
9105: chomp($file_part);
9106: my $path_part = join('/', @paths_and_file);
9107: $path_part .= '/';
9108: my $path_and_file = $path_part.$file_part;
9109: if ($path_part ne $path) {
9110: push(@return_files, ($path_and_file));
9111: }
9112: }
9113: close(OUT);
9114: return (@return_files);
9115: }
9116:
9117: #----------------------------------------------Get portfolio file permissions
9118:
9119: sub get_portfile_permissions {
9120: my ($domain,$user) = @_;
9121: my %current_permissions = &dump('file_permissions',$domain,$user);
9122: my ($tmp)=keys(%current_permissions);
9123: if ($tmp=~/^error:/) { undef(%current_permissions); }
9124: return \%current_permissions;
9125: }
9126:
9127: #---------------------------------------------Get portfolio file access controls
9128:
9129: sub get_access_controls {
9130: my ($current_permissions,$group,$file) = @_;
9131: my %access;
9132: my $real_file = $file;
9133: $file =~ s/\.meta$//;
9134: if (defined($file)) {
9135: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9136: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
9137: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
9138: }
9139: }
9140: } else {
9141: foreach my $key (keys(%{$current_permissions})) {
9142: if ($key =~ /\0accesscontrol$/) {
9143: if (defined($group)) {
9144: if ($key !~ m-^\Q$group\E/-) {
9145: next;
9146: }
9147: }
9148: my ($fullpath) = split(/\0/,$key);
9149: if (ref($$current_permissions{$key}) eq 'HASH') {
9150: foreach my $control (keys(%{$$current_permissions{$key}})) {
9151: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9152: }
9153: }
9154: }
9155: }
9156: }
9157: return %access;
9158: }
9159:
9160: sub modify_access_controls {
9161: my ($file_name,$changes,$domain,$user)=@_;
9162: my ($outcome,$deloutcome);
9163: my %store_permissions;
9164: my %new_values;
9165: my %new_control;
9166: my %translation;
9167: my @deletions = ();
9168: my $now = time;
9169: if (exists($$changes{'activate'})) {
9170: if (ref($$changes{'activate'}) eq 'HASH') {
9171: my @newitems = sort(keys(%{$$changes{'activate'}}));
9172: my $numnew = scalar(@newitems);
9173: for (my $i=0; $i<$numnew; $i++) {
9174: my $newkey = $newitems[$i];
9175: my $newid = &Apache::loncommon::get_cgi_id();
9176: if ($newkey =~ /^\d+:/) {
9177: $newkey =~ s/^(\d+)/$newid/;
9178: $translation{$1} = $newid;
9179: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9180: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9181: $translation{$1} = $newid;
9182: }
9183: $new_values{$file_name."\0".$newkey} =
9184: $$changes{'activate'}{$newitems[$i]};
9185: $new_control{$newkey} = $now;
9186: }
9187: }
9188: }
9189: my %todelete;
9190: my %changed_items;
9191: foreach my $action ('delete','update') {
9192: if (exists($$changes{$action})) {
9193: if (ref($$changes{$action}) eq 'HASH') {
9194: foreach my $key (keys(%{$$changes{$action}})) {
9195: my ($itemnum) = ($key =~ /^([^:]+):/);
9196: if ($action eq 'delete') {
9197: $todelete{$itemnum} = 1;
9198: } else {
9199: $changed_items{$itemnum} = $key;
9200: }
9201: }
9202: }
9203: }
9204: }
9205: # get lock on access controls for file.
9206: my $lockhash = {
9207: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9208: ':'.$env{'user.domain'},
9209: };
9210: my $tries = 0;
9211: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9212:
9213: while (($gotlock ne 'ok') && $tries <3) {
9214: $tries ++;
9215: sleep 1;
9216: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9217: }
9218: if ($gotlock eq 'ok') {
9219: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9220: my ($tmp)=keys(%curr_permissions);
9221: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9222: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9223: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9224: if (ref($curr_controls) eq 'HASH') {
9225: foreach my $control_item (keys(%{$curr_controls})) {
9226: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9227: if (defined($todelete{$itemnum})) {
9228: push(@deletions,$file_name."\0".$control_item);
9229: } else {
9230: if (defined($changed_items{$itemnum})) {
9231: $new_control{$changed_items{$itemnum}} = $now;
9232: push(@deletions,$file_name."\0".$control_item);
9233: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9234: } else {
9235: $new_control{$control_item} = $$curr_controls{$control_item};
9236: }
9237: }
9238: }
9239: }
9240: }
9241: my ($group);
9242: if (&is_course($domain,$user)) {
9243: ($group,my $file) = split(/\//,$file_name,2);
9244: }
9245: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9246: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9247: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9248: # remove lock
9249: my @del_lock = ($file_name."\0".'locked_access_records');
9250: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
9251: my $sqlresult =
9252: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
9253: $group);
9254: } else {
9255: $outcome = "error: could not obtain lockfile\n";
9256: }
9257: return ($outcome,$deloutcome,\%new_values,\%translation);
9258: }
9259:
9260: sub make_public_indefinitely {
9261: my ($requrl) = @_;
9262: my $now = time;
9263: my $action = 'activate';
9264: my $aclnum = 0;
9265: if (&is_portfolio_url($requrl)) {
9266: my (undef,$udom,$unum,$file_name,$group) =
9267: &parse_portfolio_url($requrl);
9268: my $current_perms = &get_portfile_permissions($udom,$unum);
9269: my %access_controls = &get_access_controls($current_perms,
9270: $group,$file_name);
9271: foreach my $key (keys(%{$access_controls{$file_name}})) {
9272: my ($num,$scope,$end,$start) =
9273: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9274: if ($scope eq 'public') {
9275: if ($start <= $now && $end == 0) {
9276: $action = 'none';
9277: } else {
9278: $action = 'update';
9279: $aclnum = $num;
9280: }
9281: last;
9282: }
9283: }
9284: if ($action eq 'none') {
9285: return 'ok';
9286: } else {
9287: my %changes;
9288: my $newend = 0;
9289: my $newstart = $now;
9290: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
9291: $changes{$action}{$newkey} = {
9292: type => 'public',
9293: time => {
9294: start => $newstart,
9295: end => $newend,
9296: },
9297: };
9298: my ($outcome,$deloutcome,$new_values,$translation) =
9299: &modify_access_controls($file_name,\%changes,$udom,$unum);
9300: return $outcome;
9301: }
9302: } else {
9303: return 'invalid';
9304: }
9305: }
9306:
9307: #------------------------------------------------------Get Marked as Read Only
9308:
9309: sub get_marked_as_readonly {
9310: my ($domain,$user,$what,$group) = @_;
9311: my $current_permissions = &get_portfile_permissions($domain,$user);
9312: my @readonly_files;
9313: my $cmp1=$what;
9314: if (ref($what)) { $cmp1=join('',@{$what}) };
9315: while (my ($file_name,$value) = each(%{$current_permissions})) {
9316: if (defined($group)) {
9317: if ($file_name !~ m-^\Q$group\E/-) {
9318: next;
9319: }
9320: }
9321: if (ref($value) eq "ARRAY"){
9322: foreach my $stored_what (@{$value}) {
9323: my $cmp2=$stored_what;
9324: if (ref($stored_what) eq 'ARRAY') {
9325: $cmp2=join('',@{$stored_what});
9326: }
9327: if ($cmp1 eq $cmp2) {
9328: push(@readonly_files, $file_name);
9329: last;
9330: } elsif (!defined($what)) {
9331: push(@readonly_files, $file_name);
9332: last;
9333: }
9334: }
9335: }
9336: }
9337: return @readonly_files;
9338: }
9339: #-----------------------------------------------------------Get Marked as Read Only Hash
9340:
9341: sub get_marked_as_readonly_hash {
9342: my ($current_permissions,$group,$what) = @_;
9343: my %readonly_files;
9344: while (my ($file_name,$value) = each(%{$current_permissions})) {
9345: if (defined($group)) {
9346: if ($file_name !~ m-^\Q$group\E/-) {
9347: next;
9348: }
9349: }
9350: if (ref($value) eq "ARRAY"){
9351: foreach my $stored_what (@{$value}) {
9352: if (ref($stored_what) eq 'ARRAY') {
9353: foreach my $lock_descriptor(@{$stored_what}) {
9354: if ($lock_descriptor eq 'graded') {
9355: $readonly_files{$file_name} = 'graded';
9356: } elsif ($lock_descriptor eq 'handback') {
9357: $readonly_files{$file_name} = 'handback';
9358: } else {
9359: if (!exists($readonly_files{$file_name})) {
9360: $readonly_files{$file_name} = 'locked';
9361: }
9362: }
9363: }
9364: }
9365: }
9366: }
9367: }
9368: return %readonly_files;
9369: }
9370: # ------------------------------------------------------------ Unmark as Read Only
9371:
9372: sub unmark_as_readonly {
9373: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9374: # for portfolio submissions, $what contains [$symb,$crsid]
9375: my ($domain,$user,$what,$file_name,$group) = @_;
9376: $file_name = &declutter_portfile($file_name);
9377: my $symb_crs = $what;
9378: if (ref($what)) { $symb_crs=join('',@$what); }
9379: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
9380: my ($tmp)=keys(%current_permissions);
9381: if ($tmp=~/^error:/) { undef(%current_permissions); }
9382: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
9383: foreach my $file (@readonly_files) {
9384: my $clean_file = &declutter_portfile($file);
9385: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
9386: my $current_locks = $current_permissions{$file};
9387: my @new_locks;
9388: my @del_keys;
9389: if (ref($current_locks) eq "ARRAY"){
9390: foreach my $locker (@{$current_locks}) {
9391: my $compare=$locker;
9392: if (ref($locker) eq 'ARRAY') {
9393: $compare=join('',@{$locker});
9394: if ($compare ne $symb_crs) {
9395: push(@new_locks, $locker);
9396: }
9397: }
9398: }
9399: if (scalar(@new_locks) > 0) {
9400: $current_permissions{$file} = \@new_locks;
9401: } else {
9402: push(@del_keys, $file);
9403: &del('file_permissions',\@del_keys, $domain, $user);
9404: delete($current_permissions{$file});
9405: }
9406: }
9407: }
9408: &put('file_permissions',\%current_permissions,$domain,$user);
9409: return;
9410: }
9411:
9412: # ------------------------------------------------------------ Directory lister
9413:
9414: sub dirlist {
9415: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
9416: $uri=~s/^\///;
9417: $uri=~s/\/$//;
9418: my ($udom, $uname);
9419: if ($getuserdir) {
9420: $udom = $userdomain;
9421: $uname = $username;
9422: } else {
9423: (undef,$udom,$uname)=split(/\//,$uri);
9424: if(defined($userdomain)) {
9425: $udom = $userdomain;
9426: }
9427: if(defined($username)) {
9428: $uname = $username;
9429: }
9430: }
9431: my ($dirRoot,$listing,@listing_results);
9432:
9433: $dirRoot = $perlvar{'lonDocRoot'};
9434: if (defined($getpropath)) {
9435: $dirRoot = &propath($udom,$uname);
9436: $dirRoot =~ s/\/$//;
9437: } elsif (defined($getuserdir)) {
9438: my $subdir=$uname.'__';
9439: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9440: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9441: ."/$udom/$subdir/$uname";
9442: } elsif (defined($alternateRoot)) {
9443: $dirRoot = $alternateRoot;
9444: }
9445:
9446: if($udom) {
9447: if($uname) {
9448: my $uhome = &homeserver($uname,$udom);
9449: if ($uhome eq 'no_host') {
9450: return ([],'no_host');
9451: }
9452: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
9453: .$getuserdir.':'.&escape($dirRoot)
9454: .':'.&escape($uname).':'.&escape($udom),$uhome);
9455: if ($listing eq 'unknown_cmd') {
9456: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
9457: } else {
9458: @listing_results = map { &unescape($_); } split(/:/,$listing);
9459: }
9460: if ($listing eq 'unknown_cmd') {
9461: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
9462: @listing_results = split(/:/,$listing);
9463: } else {
9464: @listing_results = map { &unescape($_); } split(/:/,$listing);
9465: }
9466: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9467: ($listing eq 'rejected') || ($listing eq 'refused') ||
9468: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9469: return ([],$listing);
9470: } else {
9471: return (\@listing_results);
9472: }
9473: } elsif(!$alternateRoot) {
9474: my (%allusers,%listerror);
9475: my %servers = &get_servers($udom,'library');
9476: foreach my $tryserver (keys(%servers)) {
9477: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9478: &escape($udom),$tryserver);
9479: if ($listing eq 'unknown_cmd') {
9480: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9481: $udom, $tryserver);
9482: } else {
9483: @listing_results = map { &unescape($_); } split(/:/,$listing);
9484: }
9485: if ($listing eq 'unknown_cmd') {
9486: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9487: $udom, $tryserver);
9488: @listing_results = split(/:/,$listing);
9489: } else {
9490: @listing_results =
9491: map { &unescape($_); } split(/:/,$listing);
9492: }
9493: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9494: ($listing eq 'rejected') || ($listing eq 'refused') ||
9495: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9496: $listerror{$tryserver} = $listing;
9497: } else {
9498: foreach my $line (@listing_results) {
9499: my ($entry) = split(/&/,$line,2);
9500: $allusers{$entry} = 1;
9501: }
9502: }
9503: }
9504: my @alluserslist=();
9505: foreach my $user (sort(keys(%allusers))) {
9506: push(@alluserslist,$user.'&user');
9507: }
9508: return (\@alluserslist);
9509: } else {
9510: return ([],'missing username');
9511: }
9512: } elsif(!defined($getpropath)) {
9513: my $path = $perlvar{'lonDocRoot'}.'/res/';
9514: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9515: return (\@all_domains);
9516: } else {
9517: return ([],'missing domain');
9518: }
9519: }
9520:
9521: # --------------------------------------------- GetFileTimestamp
9522: # This function utilizes dirlist and returns the date stamp for
9523: # when it was last modified. It will also return an error of -1
9524: # if an error occurs
9525:
9526: sub GetFileTimestamp {
9527: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
9528: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9529: $studentName = &LONCAPA::clean_username($studentName);
9530: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9531: undef,$getuserdir);
9532: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9533: return -1;
9534: }
9535: if (ref($fileref) eq 'ARRAY') {
9536: my @stats = split('&',$fileref->[0]);
9537: # @stats contains first the filename, then the stat output
9538: return $stats[10]; # so this is 10 instead of 9.
9539: } else {
9540: return -1;
9541: }
9542: }
9543:
9544: sub stat_file {
9545: my ($uri) = @_;
9546: $uri = &clutter_with_no_wrapper($uri);
9547:
9548: my ($udom,$uname,$file);
9549: if ($uri =~ m-^/(uploaded|editupload)/-) {
9550: ($udom,$uname,$file) =
9551: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
9552: $file = 'userfiles/'.$file;
9553: }
9554: if ($uri =~ m-^/res/-) {
9555: ($udom,$uname) =
9556: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
9557: $file = $uri;
9558: }
9559:
9560: if (!$udom || !$uname || !$file) {
9561: # unable to handle the uri
9562: return ();
9563: }
9564: my $getpropath;
9565: if ($file =~ /^userfiles\//) {
9566: $getpropath = 1;
9567: }
9568: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9569: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9570: return ();
9571: } else {
9572: if (ref($listref) eq 'ARRAY') {
9573: my @stats = split('&',$listref->[0]);
9574: shift(@stats); #filename is first
9575: return @stats;
9576: }
9577: }
9578: return ();
9579: }
9580:
9581: # -------------------------------------------------------- Value of a Condition
9582:
9583: # gets the value of a specific preevaluated condition
9584: # stored in the string $env{user.state.<cid>}
9585: # or looks up a condition reference in the bighash and if if hasn't
9586: # already been evaluated recurses into docondval to get the value of
9587: # the condition, then memoizing it to
9588: # $env{user.state.<cid>.<condition>}
9589: sub directcondval {
9590: my $number=shift;
9591: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
9592: &Apache::lonuserstate::evalstate();
9593: }
9594: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9595: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9596: } elsif ($number =~ /^_/) {
9597: my $sub_condition;
9598: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9599: &GDBM_READER(),0640)) {
9600: $sub_condition=$bighash{'conditions'.$number};
9601: untie(%bighash);
9602: }
9603: my $value = &docondval($sub_condition);
9604: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
9605: return $value;
9606: }
9607: if ($env{'user.state.'.$env{'request.course.id'}}) {
9608: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
9609: } else {
9610: return 2;
9611: }
9612: }
9613:
9614: # get the collection of conditions for this resource
9615: sub condval {
9616: my $condidx=shift;
9617: my $allpathcond='';
9618: foreach my $cond (split(/\|/,$condidx)) {
9619: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9620: $allpathcond.=
9621: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9622: }
9623: }
9624: $allpathcond=~s/\|$//;
9625: return &docondval($allpathcond);
9626: }
9627:
9628: #evaluates an expression of conditions
9629: sub docondval {
9630: my ($allpathcond) = @_;
9631: my $result=0;
9632: if ($env{'request.course.id'}
9633: && defined($allpathcond)) {
9634: my $operand='|';
9635: my @stack;
9636: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9637: if ($chunk eq '(') {
9638: push @stack,($operand,$result);
9639: } elsif ($chunk eq ')') {
9640: my $before=pop @stack;
9641: if (pop @stack eq '&') {
9642: $result=$result>$before?$before:$result;
9643: } else {
9644: $result=$result>$before?$result:$before;
9645: }
9646: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9647: $operand=$chunk;
9648: } else {
9649: my $new=directcondval($chunk);
9650: if ($operand eq '&') {
9651: $result=$result>$new?$new:$result;
9652: } else {
9653: $result=$result>$new?$result:$new;
9654: }
9655: }
9656: }
9657: }
9658: return $result;
9659: }
9660:
9661: # ---------------------------------------------------- Devalidate courseresdata
9662:
9663: sub devalidatecourseresdata {
9664: my ($coursenum,$coursedomain)=@_;
9665: my $hashid=$coursenum.':'.$coursedomain;
9666: &devalidate_cache_new('courseres',$hashid);
9667: }
9668:
9669:
9670: # --------------------------------------------------- Course Resourcedata Query
9671: #
9672: # Parameters:
9673: # $coursenum - Number of the course.
9674: # $coursedomain - Domain at which the course was created.
9675: # Returns:
9676: # A hash of the course parameters along (I think) with timestamps
9677: # and version info.
9678:
9679: sub get_courseresdata {
9680: my ($coursenum,$coursedomain)=@_;
9681: my $coursehom=&homeserver($coursenum,$coursedomain);
9682: my $hashid=$coursenum.':'.$coursedomain;
9683: my ($result,$cached)=&is_cached_new('courseres',$hashid);
9684: my %dumpreply;
9685: unless (defined($cached)) {
9686: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
9687: $result=\%dumpreply;
9688: my ($tmp) = keys(%dumpreply);
9689: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9690: &do_cache_new('courseres',$hashid,$result,600);
9691: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9692: return $tmp;
9693: } elsif ($tmp =~ /^(error)/) {
9694: $result=undef;
9695: &do_cache_new('courseres',$hashid,$result,600);
9696: }
9697: }
9698: return $result;
9699: }
9700:
9701: sub devalidateuserresdata {
9702: my ($uname,$udom)=@_;
9703: my $hashid="$udom:$uname";
9704: &devalidate_cache_new('userres',$hashid);
9705: }
9706:
9707: sub get_userresdata {
9708: my ($uname,$udom)=@_;
9709: #most student don\'t have any data set, check if there is some data
9710: if (&EXT_cache_status($udom,$uname)) { return undef; }
9711:
9712: my $hashid="$udom:$uname";
9713: my ($result,$cached)=&is_cached_new('userres',$hashid);
9714: if (!defined($cached)) {
9715: my %resourcedata=&dump('resourcedata',$udom,$uname);
9716: $result=\%resourcedata;
9717: &do_cache_new('userres',$hashid,$result,600);
9718: }
9719: my ($tmp)=keys(%$result);
9720: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9721: return $result;
9722: }
9723: #error 2 occurs when the .db doesn't exist
9724: if ($tmp!~/error: 2 /) {
9725: &logthis("<font color=\"blue\">WARNING:".
9726: " Trying to get resource data for ".
9727: $uname." at ".$udom.": ".
9728: $tmp."</font>");
9729: } elsif ($tmp=~/error: 2 /) {
9730: #&EXT_cache_set($udom,$uname);
9731: &do_cache_new('userres',$hashid,undef,600);
9732: undef($tmp); # not really an error so don't send it back
9733: }
9734: return $tmp;
9735: }
9736: #----------------------------------------------- resdata - return resource data
9737: # Purpose:
9738: # Return resource data for either users or for a course.
9739: # Parameters:
9740: # $name - Course/user name.
9741: # $domain - Name of the domain the user/course is registered on.
9742: # $type - Type of thing $name is (must be 'course' or 'user'
9743: # @which - Array of names of resources desired.
9744: # Returns:
9745: # The value of the first reasource in @which that is found in the
9746: # resource hash.
9747: # Exceptional Conditions:
9748: # If the $type passed in is not valid (not the string 'course' or
9749: # 'user', an undefined reference is returned.
9750: # If none of the resources are found, an undef is returned
9751: sub resdata {
9752: my ($name,$domain,$type,@which)=@_;
9753: my $result;
9754: if ($type eq 'course') {
9755: $result=&get_courseresdata($name,$domain);
9756: } elsif ($type eq 'user') {
9757: $result=&get_userresdata($name,$domain);
9758: }
9759: if (!ref($result)) { return $result; }
9760: foreach my $item (@which) {
9761: if (defined($result->{$item->[0]})) {
9762: return [$result->{$item->[0]},$item->[1]];
9763: }
9764: }
9765: return undef;
9766: }
9767:
9768: sub get_numsuppfiles {
9769: my ($cnum,$cdom,$ignorecache)=@_;
9770: my $hashid=$cnum.':'.$cdom;
9771: my ($suppcount,$cached);
9772: unless ($ignorecache) {
9773: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
9774: }
9775: unless (defined($cached)) {
9776: my $chome=&homeserver($cnum,$cdom);
9777: unless ($chome eq 'no_host') {
9778: ($suppcount,my $errors) = (0,0);
9779: my $suppmap = 'supplemental.sequence';
9780: ($suppcount,$errors) =
9781: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
9782: }
9783: &do_cache_new('suppcount',$hashid,$suppcount,600);
9784: }
9785: return $suppcount;
9786: }
9787:
9788: #
9789: # EXT resource caching routines
9790: #
9791:
9792: sub clear_EXT_cache_status {
9793: &delenv('cache.EXT.');
9794: }
9795:
9796: sub EXT_cache_status {
9797: my ($target_domain,$target_user) = @_;
9798: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
9799: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
9800: # We know already the user has no data
9801: return 1;
9802: } else {
9803: return 0;
9804: }
9805: }
9806:
9807: sub EXT_cache_set {
9808: my ($target_domain,$target_user) = @_;
9809: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
9810: #&appenv({$cachename => time});
9811: }
9812:
9813: # --------------------------------------------------------- Value of a Variable
9814: sub EXT {
9815:
9816: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
9817: unless ($varname) { return ''; }
9818: #get real user name/domain, courseid and symb
9819: my $courseid;
9820: my $publicuser;
9821: if ($symbparm) {
9822: $symbparm=&get_symb_from_alias($symbparm);
9823: }
9824: if (!($uname && $udom)) {
9825: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
9826: if (!$symbparm) { $symbparm=$cursymb; }
9827: } else {
9828: $courseid=$env{'request.course.id'};
9829: }
9830: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9831: my $rest;
9832: if (defined($therest[0])) {
9833: $rest=join('.',@therest);
9834: } else {
9835: $rest='';
9836: }
9837:
9838: my $qualifierrest=$qualifier;
9839: if ($rest) { $qualifierrest.='.'.$rest; }
9840: my $spacequalifierrest=$space;
9841: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
9842: if ($realm eq 'user') {
9843: # --------------------------------------------------------------- user.resource
9844: if ($space eq 'resource') {
9845: if ( (defined($Apache::lonhomework::parsing_a_problem)
9846: || defined($Apache::lonhomework::parsing_a_task))
9847: &&
9848: ($symbparm eq &symbread()) ) {
9849: # if we are in the middle of processing the resource the
9850: # get the value we are planning on committing
9851: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9852: return $Apache::lonhomework::results{$qualifierrest};
9853: } else {
9854: return $Apache::lonhomework::history{$qualifierrest};
9855: }
9856: } else {
9857: my %restored;
9858: if ($publicuser || $env{'request.state'} eq 'construct') {
9859: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9860: } else {
9861: %restored=&restore($symbparm,$courseid,$udom,$uname);
9862: }
9863: return $restored{$qualifierrest};
9864: }
9865: # ----------------------------------------------------------------- user.access
9866: } elsif ($space eq 'access') {
9867: # FIXME - not supporting calls for a specific user
9868: return &allowed($qualifier,$rest);
9869: # ------------------------------------------ user.preferences, user.environment
9870: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
9871: if (($uname eq $env{'user.name'}) &&
9872: ($udom eq $env{'user.domain'})) {
9873: return $env{join('.',('environment',$qualifierrest))};
9874: } else {
9875: my %returnhash;
9876: if (!$publicuser) {
9877: %returnhash=&userenvironment($udom,$uname,
9878: $qualifierrest);
9879: }
9880: return $returnhash{$qualifierrest};
9881: }
9882: # ----------------------------------------------------------------- user.course
9883: } elsif ($space eq 'course') {
9884: # FIXME - not supporting calls for a specific user
9885: return $env{join('.',('request.course',$qualifier))};
9886: # ------------------------------------------------------------------- user.role
9887: } elsif ($space eq 'role') {
9888: # FIXME - not supporting calls for a specific user
9889: my ($role,$where)=split(/\./,$env{'request.role'});
9890: if ($qualifier eq 'value') {
9891: return $role;
9892: } elsif ($qualifier eq 'extent') {
9893: return $where;
9894: }
9895: # ----------------------------------------------------------------- user.domain
9896: } elsif ($space eq 'domain') {
9897: return $udom;
9898: # ------------------------------------------------------------------- user.name
9899: } elsif ($space eq 'name') {
9900: return $uname;
9901: # ---------------------------------------------------- Any other user namespace
9902: } else {
9903: my %reply;
9904: if (!$publicuser) {
9905: %reply=&get($space,[$qualifierrest],$udom,$uname);
9906: }
9907: return $reply{$qualifierrest};
9908: }
9909: } elsif ($realm eq 'query') {
9910: # ---------------------------------------------- pull stuff out of query string
9911: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9912: [$spacequalifierrest]);
9913: return $env{'form.'.$spacequalifierrest};
9914: } elsif ($realm eq 'request') {
9915: # ------------------------------------------------------------- request.browser
9916: if ($space eq 'browser') {
9917: return $env{'browser.'.$qualifier};
9918: # ------------------------------------------------------------ request.filename
9919: } else {
9920: return $env{'request.'.$spacequalifierrest};
9921: }
9922: } elsif ($realm eq 'course') {
9923: # ---------------------------------------------------------- course.description
9924: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
9925: } elsif ($realm eq 'resource') {
9926:
9927: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
9928: if (!$symbparm) { $symbparm=&symbread(); }
9929: }
9930:
9931: if ($qualifier eq '') {
9932: if ($space eq 'title') {
9933: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9934: return &gettitle($symbparm);
9935: }
9936:
9937: if ($space eq 'map') {
9938: my ($map) = &decode_symb($symbparm);
9939: return &symbread($map);
9940: }
9941: if ($space eq 'maptitle') {
9942: my ($map) = &decode_symb($symbparm);
9943: return &gettitle($map);
9944: }
9945: if ($space eq 'filename') {
9946: if ($symbparm) {
9947: return &clutter((&decode_symb($symbparm))[2]);
9948: }
9949: return &hreflocation('',$env{'request.filename'});
9950: }
9951:
9952: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
9953: if ($space eq 'visibleparts') {
9954: my $navmap = Apache::lonnavmaps::navmap->new();
9955: my $item;
9956: if (ref($navmap)) {
9957: my $res = $navmap->getBySymb($symbparm);
9958: my $parts = $res->parts();
9959: if (ref($parts) eq 'ARRAY') {
9960: $item = join(',',@{$parts});
9961: }
9962: undef($navmap);
9963: }
9964: return $item;
9965: }
9966: }
9967: }
9968:
9969: my ($section, $group, @groups);
9970: my ($courselevelm,$courselevel);
9971: if (($courseid eq '') && ($cid)) {
9972: $courseid = $cid;
9973: }
9974: if (($symbparm && $courseid) &&
9975: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
9976:
9977: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
9978:
9979: # ----------------------------------------------------- Cascading lookup scheme
9980: my $symbp=$symbparm;
9981: my $mapp=&deversion((&decode_symb($symbp))[0]);
9982:
9983: my $symbparm=$symbp.'.'.$spacequalifierrest;
9984: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9985:
9986: if (($env{'user.name'} eq $uname) &&
9987: ($env{'user.domain'} eq $udom)) {
9988: $section=$env{'request.course.sec'};
9989: @groups = split(/:/,$env{'request.course.groups'});
9990: @groups=&sort_course_groups($courseid,@groups);
9991: } else {
9992: if (! defined($usection)) {
9993: $section=&getsection($udom,$uname,$courseid);
9994: } else {
9995: $section = $usection;
9996: }
9997: @groups = &get_users_groups($udom,$uname,$courseid);
9998: }
9999:
10000: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10001: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10002: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10003:
10004: $courselevel=$courseid.'.'.$spacequalifierrest;
10005: my $courselevelr=$courseid.'.'.$symbparm;
10006: $courselevelm=$courseid.'.'.$mapparm;
10007:
10008: # ----------------------------------------------------------- first, check user
10009:
10010: my $userreply=&resdata($uname,$udom,'user',
10011: ([$courselevelr,'resource'],
10012: [$courselevelm,'map' ],
10013: [$courselevel, 'course' ]));
10014: if (defined($userreply)) { return &get_reply($userreply); }
10015:
10016: # ------------------------------------------------ second, check some of course
10017: my $coursereply;
10018: if (@groups > 0) {
10019: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10020: $mapparm,$spacequalifierrest);
10021: if (defined($coursereply)) { return &get_reply($coursereply); }
10022: }
10023:
10024: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10025: $env{'course.'.$courseid.'.domain'},
10026: 'course',
10027: ([$seclevelr, 'resource'],
10028: [$seclevelm, 'map' ],
10029: [$seclevel, 'course' ],
10030: [$courselevelr,'resource']));
10031: if (defined($coursereply)) { return &get_reply($coursereply); }
10032:
10033: # ------------------------------------------------------ third, check map parms
10034: my %parmhash=();
10035: my $thisparm='';
10036: if (tie(%parmhash,'GDBM_File',
10037: $env{'request.course.fn'}.'_parms.db',
10038: &GDBM_READER(),0640)) {
10039: $thisparm=$parmhash{$symbparm};
10040: untie(%parmhash);
10041: }
10042: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10043: }
10044: # ------------------------------------------ fourth, look in resource metadata
10045:
10046: $spacequalifierrest=~s/\./\_/;
10047: my $filename;
10048: if (!$symbparm) { $symbparm=&symbread(); }
10049: if ($symbparm) {
10050: $filename=(&decode_symb($symbparm))[2];
10051: } else {
10052: $filename=$env{'request.filename'};
10053: }
10054: my $metadata=&metadata($filename,$spacequalifierrest);
10055: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10056: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
10057: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10058:
10059: # ---------------------------------------------- fourth, look in rest of course
10060: if ($symbparm && defined($courseid) &&
10061: $courseid eq $env{'request.course.id'}) {
10062: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10063: $env{'course.'.$courseid.'.domain'},
10064: 'course',
10065: ([$courselevelm,'map' ],
10066: [$courselevel, 'course']));
10067: if (defined($coursereply)) { return &get_reply($coursereply); }
10068: }
10069: # ------------------------------------------------------------------ Cascade up
10070: unless ($space eq '0') {
10071: my @parts=split(/_/,$space);
10072: my $id=pop(@parts);
10073: my $part=join('_',@parts);
10074: if ($part eq '') { $part='0'; }
10075: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10076: $symbparm,$udom,$uname,$section,1);
10077: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10078: }
10079: if ($recurse) { return undef; }
10080: my $pack_def=&packages_tab_default($filename,$varname);
10081: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10082: # ---------------------------------------------------- Any other user namespace
10083: } elsif ($realm eq 'environment') {
10084: # ----------------------------------------------------------------- environment
10085: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10086: return $env{'environment.'.$spacequalifierrest};
10087: } else {
10088: if ($uname eq 'anonymous' && $udom eq '') {
10089: return '';
10090: }
10091: my %returnhash=&userenvironment($udom,$uname,
10092: $spacequalifierrest);
10093: return $returnhash{$spacequalifierrest};
10094: }
10095: } elsif ($realm eq 'system') {
10096: # ----------------------------------------------------------------- system.time
10097: if ($space eq 'time') {
10098: return time;
10099: }
10100: } elsif ($realm eq 'server') {
10101: # ----------------------------------------------------------------- system.time
10102: if ($space eq 'name') {
10103: return $ENV{'SERVER_NAME'};
10104: }
10105: }
10106: return '';
10107: }
10108:
10109: sub get_reply {
10110: my ($reply_value) = @_;
10111: if (ref($reply_value) eq 'ARRAY') {
10112: if (wantarray) {
10113: return @$reply_value;
10114: }
10115: return $reply_value->[0];
10116: } else {
10117: return $reply_value;
10118: }
10119: }
10120:
10121: sub check_group_parms {
10122: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10123: my @groupitems = ();
10124: my $resultitem;
10125: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10126: foreach my $group (@{$groups}) {
10127: foreach my $level (@levels) {
10128: my $item = $courseid.'.['.$group.'].'.$level->[0];
10129: push(@groupitems,[$item,$level->[1]]);
10130: }
10131: }
10132: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10133: $env{'course.'.$courseid.'.domain'},
10134: 'course',@groupitems);
10135: return $coursereply;
10136: }
10137:
10138: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10139: my ($courseid,@groups) = @_;
10140: @groups = sort(@groups);
10141: return @groups;
10142: }
10143:
10144: sub packages_tab_default {
10145: my ($uri,$varname)=@_;
10146: my (undef,$part,$name)=split(/\./,$varname);
10147:
10148: my (@extension,@specifics,$do_default);
10149: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10150: my ($pack_type,$pack_part)=split(/_/,$package,2);
10151: if ($pack_type eq 'default') {
10152: $do_default=1;
10153: } elsif ($pack_type eq 'extension') {
10154: push(@extension,[$package,$pack_type,$pack_part]);
10155: } elsif ($pack_part eq $part || $pack_type eq 'part') {
10156: # only look at packages defaults for packages that this id is
10157: push(@specifics,[$package,$pack_type,$pack_part]);
10158: }
10159: }
10160: # first look for a package that matches the requested part id
10161: foreach my $package (@specifics) {
10162: my (undef,$pack_type,$pack_part)=@{$package};
10163: next if ($pack_part ne $part);
10164: if (defined($packagetab{"$pack_type&$name&default"})) {
10165: return $packagetab{"$pack_type&$name&default"};
10166: }
10167: }
10168: # look for any possible matching non extension_ package
10169: foreach my $package (@specifics) {
10170: my (undef,$pack_type,$pack_part)=@{$package};
10171: if (defined($packagetab{"$pack_type&$name&default"})) {
10172: return $packagetab{"$pack_type&$name&default"};
10173: }
10174: if ($pack_type eq 'part') { $pack_part='0'; }
10175: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10176: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10177: }
10178: }
10179: # look for any posible extension_ match
10180: foreach my $package (@extension) {
10181: my ($package,$pack_type)=@{$package};
10182: if (defined($packagetab{"$pack_type&$name&default"})) {
10183: return $packagetab{"$pack_type&$name&default"};
10184: }
10185: if (defined($packagetab{$package."&$name&default"})) {
10186: return $packagetab{$package."&$name&default"};
10187: }
10188: }
10189: # look for a global default setting
10190: if ($do_default && defined($packagetab{"default&$name&default"})) {
10191: return $packagetab{"default&$name&default"};
10192: }
10193: return undef;
10194: }
10195:
10196: sub add_prefix_and_part {
10197: my ($prefix,$part)=@_;
10198: my $keyroot;
10199: if (defined($prefix) && $prefix !~ /^__/) {
10200: # prefix that has a part already
10201: $keyroot=$prefix;
10202: } elsif (defined($prefix)) {
10203: # prefix that is missing a part
10204: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10205: } else {
10206: # no prefix at all
10207: if (defined($part)) { $keyroot='_'.$part; }
10208: }
10209: return $keyroot;
10210: }
10211:
10212: # ---------------------------------------------------------------- Get metadata
10213:
10214: my %metaentry;
10215: my %importedpartids;
10216: sub metadata {
10217: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10218: $uri=&declutter($uri);
10219: # if it is a non metadata possible uri return quickly
10220: if (($uri eq '') ||
10221: (($uri =~ m|^/*adm/|) &&
10222: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10223: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10224: return undef;
10225: }
10226: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
10227: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10228: return undef;
10229: }
10230: my $filename=$uri;
10231: $uri=~s/\.meta$//;
10232: #
10233: # Is the metadata already cached?
10234: # Look at timestamp of caching
10235: # Everything is cached by the main uri, libraries are never directly cached
10236: #
10237: if (!defined($liburi)) {
10238: my ($result,$cached)=&is_cached_new('meta',$uri);
10239: if (defined($cached)) { return $result->{':'.$what}; }
10240: }
10241: {
10242: # Imported parts would go here
10243: my %importedids=();
10244: my @origfileimportpartids=();
10245: my $importedparts=0;
10246: #
10247: # Is this a recursive call for a library?
10248: #
10249: # if (! exists($metacache{$uri})) {
10250: # $metacache{$uri}={};
10251: # }
10252: my $cachetime = 60*60;
10253: if ($liburi) {
10254: $liburi=&declutter($liburi);
10255: $filename=$liburi;
10256: } else {
10257: &devalidate_cache_new('meta',$uri);
10258: undef(%metaentry);
10259: }
10260: my %metathesekeys=();
10261: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10262: my $metastring;
10263: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10264: my $which = &hreflocation('','/'.($liburi || $uri));
10265: $metastring =
10266: &Apache::lonnet::ssi_body($which,
10267: ('grade_target' => 'meta'));
10268: $cachetime = 1; # only want this cached in the child not long term
10269: } elsif (($uri !~ m -^(editupload)/-) &&
10270: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10271: my $file=&filelocation('',&clutter($filename));
10272: #push(@{$metaentry{$uri.'.file'}},$file);
10273: $metastring=&getfile($file);
10274: }
10275: my $parser=HTML::LCParser->new(\$metastring);
10276: my $token;
10277: undef %metathesekeys;
10278: while ($token=$parser->get_token) {
10279: if ($token->[0] eq 'S') {
10280: if (defined($token->[2]->{'package'})) {
10281: #
10282: # This is a package - get package info
10283: #
10284: my $package=$token->[2]->{'package'};
10285: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10286: if (defined($token->[2]->{'id'})) {
10287: $keyroot.='_'.$token->[2]->{'id'};
10288: }
10289: if ($metaentry{':packages'}) {
10290: $metaentry{':packages'}.=','.$package.$keyroot;
10291: } else {
10292: $metaentry{':packages'}=$package.$keyroot;
10293: }
10294: foreach my $pack_entry (keys(%packagetab)) {
10295: my $part=$keyroot;
10296: $part=~s/^\_//;
10297: if ($pack_entry=~/^\Q$package\E\&/ ||
10298: $pack_entry=~/^\Q$package\E_0\&/) {
10299: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10300: # ignore package.tab specified default values
10301: # here &package_tab_default() will fetch those
10302: if ($subp eq 'default') { next; }
10303: my $value=$packagetab{$pack_entry};
10304: my $unikey;
10305: if ($pack =~ /_0$/) {
10306: $unikey='parameter_0_'.$name;
10307: $part=0;
10308: } else {
10309: $unikey='parameter'.$keyroot.'_'.$name;
10310: }
10311: if ($subp eq 'display') {
10312: $value.=' [Part: '.$part.']';
10313: }
10314: $metaentry{':'.$unikey.'.part'}=$part;
10315: $metathesekeys{$unikey}=1;
10316: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10317: $metaentry{':'.$unikey.'.'.$subp}=$value;
10318: }
10319: if (defined($metaentry{':'.$unikey.'.default'})) {
10320: $metaentry{':'.$unikey}=
10321: $metaentry{':'.$unikey.'.default'};
10322: }
10323: }
10324: }
10325: } else {
10326: #
10327: # This is not a package - some other kind of start tag
10328: #
10329: my $entry=$token->[1];
10330: my $unikey='';
10331:
10332: if ($entry eq 'import') {
10333: #
10334: # Importing a library here
10335: #
10336: my $location=$parser->get_text('/import');
10337: my $dir=$filename;
10338: $dir=~s|[^/]*$||;
10339: $location=&filelocation($dir,$location);
10340:
10341: my $importmode=$token->[2]->{'importmode'};
10342: if ($importmode eq 'problem') {
10343: # Import as problem/response
10344: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10345: } elsif ($importmode eq 'part') {
10346: # Import as part(s)
10347: $importedparts=1;
10348: # We need to get the original file and the imported file to get the part order correct
10349: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10350: # Load and inspect original file
10351: if ($#origfileimportpartids<0) {
10352: undef(%importedpartids);
10353: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10354: my $origfile=&getfile($origfilelocation);
10355: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10356: }
10357:
10358: # Load and inspect imported file
10359: my $impfile=&getfile($location);
10360: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10361: if ($#impfilepartids>=0) {
10362: # This problem had parts
10363: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10364: } else {
10365: # Importing by turning a single problem into a problem part
10366: # It gets the import-tags ID as part-ID
10367: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10368: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10369: }
10370: } else {
10371: # Normal import
10372: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10373: if (defined($token->[2]->{'id'})) {
10374: $unikey.='_'.$token->[2]->{'id'};
10375: }
10376: }
10377:
10378: if ($depthcount<20) {
10379: my $metadata =
10380: &metadata($uri,'keys', $location,$unikey,
10381: $depthcount+1);
10382: foreach my $meta (split(',',$metadata)) {
10383: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10384: $metathesekeys{$meta}=1;
10385: }
10386:
10387: }
10388: } else {
10389: #
10390: # Not importing, some other kind of non-package, non-library start tag
10391: #
10392: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10393: if (defined($token->[2]->{'id'})) {
10394: $unikey.='_'.$token->[2]->{'id'};
10395: }
10396: if (defined($token->[2]->{'name'})) {
10397: $unikey.='_'.$token->[2]->{'name'};
10398: }
10399: $metathesekeys{$unikey}=1;
10400: foreach my $param (@{$token->[3]}) {
10401: $metaentry{':'.$unikey.'.'.$param} =
10402: $token->[2]->{$param};
10403: }
10404: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10405: my $default=$metaentry{':'.$unikey.'.default'};
10406: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10407: # only ws inside the tag, and not in default, so use default
10408: # as value
10409: $metaentry{':'.$unikey}=$default;
10410: } elsif ( $internaltext =~ /\S/ ) {
10411: # something interesting inside the tag
10412: $metaentry{':'.$unikey}=$internaltext;
10413: } else {
10414: # no interesting values, don't set a default
10415: }
10416: # end of not-a-package not-a-library import
10417: }
10418: # end of not-a-package start tag
10419: }
10420: # the next is the end of "start tag"
10421: }
10422: }
10423: my ($extension) = ($uri =~ /\.(\w+)$/);
10424: $extension = lc($extension);
10425: if ($extension eq 'htm') { $extension='html'; }
10426:
10427: foreach my $key (keys(%packagetab)) {
10428: #no specific packages #how's our extension
10429: if ($key!~/^extension_\Q$extension\E&/) { next; }
10430: &metadata_create_package_def($uri,$key,'extension_'.$extension,
10431: \%metathesekeys);
10432: }
10433:
10434: if (!exists($metaentry{':packages'})
10435: || $packagetab{"import_defaults&extension_$extension"}) {
10436: foreach my $key (keys(%packagetab)) {
10437: #no specific packages well let's get default then
10438: if ($key!~/^default&/) { next; }
10439: &metadata_create_package_def($uri,$key,'default',
10440: \%metathesekeys);
10441: }
10442: }
10443: # are there custom rights to evaluate
10444: if ($metaentry{':copyright'} eq 'custom') {
10445:
10446: #
10447: # Importing a rights file here
10448: #
10449: unless ($depthcount) {
10450: my $location=$metaentry{':customdistributionfile'};
10451: my $dir=$filename;
10452: $dir=~s|[^/]*$||;
10453: $location=&filelocation($dir,$location);
10454: my $rights_metadata =
10455: &metadata($uri,'keys',$location,'_rights',
10456: $depthcount+1);
10457: foreach my $rights (split(',',$rights_metadata)) {
10458: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10459: $metathesekeys{$rights}=1;
10460: }
10461: }
10462: }
10463: # uniqifiy package listing
10464: my %seen;
10465: my @uniq_packages =
10466: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10467: $metaentry{':packages'} = join(',',@uniq_packages);
10468:
10469: if ($importedparts) {
10470: # We had imported parts and need to rebuild partorder
10471: $metaentry{':partorder'}='';
10472: $metathesekeys{'partorder'}=1;
10473: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10474: if ($origfileimportpartids[$index] eq 'part') {
10475: # original part, part of the problem
10476: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10477: } else {
10478: # we have imported parts at this position
10479: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10480: }
10481: }
10482: $metaentry{':partorder'}=~s/^\,//;
10483: }
10484:
10485: $metaentry{':keys'} = join(',',keys(%metathesekeys));
10486: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10487: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10488: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
10489: # this is the end of "was not already recently cached
10490: }
10491: return $metaentry{':'.$what};
10492: }
10493:
10494: sub metadata_create_package_def {
10495: my ($uri,$key,$package,$metathesekeys)=@_;
10496: my ($pack,$name,$subp)=split(/\&/,$key);
10497: if ($subp eq 'default') { next; }
10498:
10499: if (defined($metaentry{':packages'})) {
10500: $metaentry{':packages'}.=','.$package;
10501: } else {
10502: $metaentry{':packages'}=$package;
10503: }
10504: my $value=$packagetab{$key};
10505: my $unikey;
10506: $unikey='parameter_0_'.$name;
10507: $metaentry{':'.$unikey.'.part'}=0;
10508: $$metathesekeys{$unikey}=1;
10509: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10510: $metaentry{':'.$unikey.'.'.$subp}=$value;
10511: }
10512: if (defined($metaentry{':'.$unikey.'.default'})) {
10513: $metaentry{':'.$unikey}=
10514: $metaentry{':'.$unikey.'.default'};
10515: }
10516: }
10517:
10518: sub metadata_generate_part0 {
10519: my ($metadata,$metacache,$uri) = @_;
10520: my %allnames;
10521: foreach my $metakey (keys(%$metadata)) {
10522: if ($metakey=~/^parameter\_(.*)/) {
10523: my $part=$$metacache{':'.$metakey.'.part'};
10524: my $name=$$metacache{':'.$metakey.'.name'};
10525: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10526: $allnames{$name}=$part;
10527: }
10528: }
10529: }
10530: foreach my $name (keys(%allnames)) {
10531: $$metadata{"parameter_0_$name"}=1;
10532: my $key=":parameter_0_$name";
10533: $$metacache{"$key.part"}='0';
10534: $$metacache{"$key.name"}=$name;
10535: $$metacache{"$key.type"}=$$metacache{':parameter_'.
10536: $allnames{$name}.'_'.$name.
10537: '.type'};
10538: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10539: '.display'};
10540: my $expr='[Part: '.$allnames{$name}.']';
10541: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10542: $$metacache{"$key.display"}=$olddis;
10543: }
10544: }
10545:
10546: # ------------------------------------------------------ Devalidate title cache
10547:
10548: sub devalidate_title_cache {
10549: my ($url)=@_;
10550: if (!$env{'request.course.id'}) { return; }
10551: my $symb=&symbread($url);
10552: if (!$symb) { return; }
10553: my $key=$env{'request.course.id'}."\0".$symb;
10554: &devalidate_cache_new('title',$key);
10555: }
10556:
10557: # ------------------------------------------------- Get the title of a course
10558:
10559: sub current_course_title {
10560: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10561: }
10562: # ------------------------------------------------- Get the title of a resource
10563:
10564: sub gettitle {
10565: my $urlsymb=shift;
10566: my $symb=&symbread($urlsymb);
10567: if ($symb) {
10568: my $key=$env{'request.course.id'}."\0".$symb;
10569: my ($result,$cached)=&is_cached_new('title',$key);
10570: if (defined($cached)) {
10571: return $result;
10572: }
10573: my ($map,$resid,$url)=&decode_symb($symb);
10574: my $title='';
10575: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10576: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10577: } else {
10578: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10579: &GDBM_READER(),0640)) {
10580: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10581: $title=$bighash{'title_'.$mapid.'.'.$resid};
10582: untie(%bighash);
10583: }
10584: }
10585: $title=~s/\&colon\;/\:/gs;
10586: if ($title) {
10587: # Remember both $symb and $title for dynamic metadata
10588: $accesshash{$symb.'___crstitle'}=$title;
10589: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10590: # Cache this title and then return it
10591: return &do_cache_new('title',$key,$title,600);
10592: }
10593: $urlsymb=$url;
10594: }
10595: my $title=&metadata($urlsymb,'title');
10596: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10597: return $title;
10598: }
10599:
10600: sub get_slot {
10601: my ($which,$cnum,$cdom)=@_;
10602: if (!$cnum || !$cdom) {
10603: (undef,my $courseid)=&whichuser();
10604: $cdom=$env{'course.'.$courseid.'.domain'};
10605: $cnum=$env{'course.'.$courseid.'.num'};
10606: }
10607: my $key=join("\0",'slots',$cdom,$cnum,$which);
10608: my %slotinfo;
10609: if (exists($remembered{$key})) {
10610: $slotinfo{$which} = $remembered{$key};
10611: } else {
10612: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10613: &Apache::lonhomework::showhash(%slotinfo);
10614: my ($tmp)=keys(%slotinfo);
10615: if ($tmp=~/^error:/) { return (); }
10616: $remembered{$key} = $slotinfo{$which};
10617: }
10618: if (ref($slotinfo{$which}) eq 'HASH') {
10619: return %{$slotinfo{$which}};
10620: }
10621: return $slotinfo{$which};
10622: }
10623:
10624: sub get_reservable_slots {
10625: my ($cnum,$cdom,$uname,$udom) = @_;
10626: my $now = time;
10627: my $reservable_info;
10628: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10629: if (exists($remembered{$key})) {
10630: $reservable_info = $remembered{$key};
10631: } else {
10632: my %resv;
10633: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10634: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10635: $reservable_info = \%resv;
10636: $remembered{$key} = $reservable_info;
10637: }
10638: return $reservable_info;
10639: }
10640:
10641: sub get_course_slots {
10642: my ($cnum,$cdom) = @_;
10643: my $hashid=$cnum.':'.$cdom;
10644: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10645: if (defined($cached)) {
10646: if (ref($result) eq 'HASH') {
10647: return %{$result};
10648: }
10649: } else {
10650: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10651: my ($tmp) = keys(%slots);
10652: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10653: &do_cache_new('allslots',$hashid,\%slots,600);
10654: return %slots;
10655: }
10656: }
10657: return;
10658: }
10659:
10660: sub devalidate_slots_cache {
10661: my ($cnum,$cdom)=@_;
10662: my $hashid=$cnum.':'.$cdom;
10663: &devalidate_cache_new('allslots',$hashid);
10664: }
10665:
10666: sub get_coursechange {
10667: my ($cdom,$cnum) = @_;
10668: if ($cdom eq '' || $cnum eq '') {
10669: return unless ($env{'request.course.id'});
10670: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10671: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10672: }
10673: my $hashid=$cdom.'_'.$cnum;
10674: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10675: if ((defined($cached)) && ($change ne '')) {
10676: return $change;
10677: } else {
10678: my %crshash;
10679: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10680: if ($crshash{'internal.contentchange'} eq '') {
10681: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10682: if ($change eq '') {
10683: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10684: $change = $crshash{'internal.created'};
10685: }
10686: } else {
10687: $change = $crshash{'internal.contentchange'};
10688: }
10689: my $cachetime = 600;
10690: &do_cache_new('crschange',$hashid,$change,$cachetime);
10691: }
10692: return $change;
10693: }
10694:
10695: sub devalidate_coursechange_cache {
10696: my ($cnum,$cdom)=@_;
10697: my $hashid=$cnum.':'.$cdom;
10698: &devalidate_cache_new('crschange',$hashid);
10699: }
10700:
10701: # ------------------------------------------------- Update symbolic store links
10702:
10703: sub symblist {
10704: my ($mapname,%newhash)=@_;
10705: $mapname=&deversion(&declutter($mapname));
10706: my %hash;
10707: if (($env{'request.course.fn'}) && (%newhash)) {
10708: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10709: &GDBM_WRCREAT(),0640)) {
10710: foreach my $url (keys(%newhash)) {
10711: next if ($url eq 'last_known'
10712: && $env{'form.no_update_last_known'});
10713: $hash{declutter($url)}=&encode_symb($mapname,
10714: $newhash{$url}->[1],
10715: $newhash{$url}->[0]);
10716: }
10717: if (untie(%hash)) {
10718: return 'ok';
10719: }
10720: }
10721: }
10722: return 'error';
10723: }
10724:
10725: # --------------------------------------------------------------- Verify a symb
10726:
10727: sub symbverify {
10728: my ($symb,$thisurl,$encstate)=@_;
10729: my $thisfn=$thisurl;
10730: $thisfn=&declutter($thisfn);
10731: # direct jump to resource in page or to a sequence - will construct own symbs
10732: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10733: # check URL part
10734: my ($map,$resid,$url)=&decode_symb($symb);
10735:
10736: unless ($url eq $thisfn) { return 0; }
10737:
10738: $symb=&symbclean($symb);
10739: $thisurl=&deversion($thisurl);
10740: $thisfn=&deversion($thisfn);
10741:
10742: my %bighash;
10743: my $okay=0;
10744:
10745: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10746: &GDBM_READER(),0640)) {
10747: my $noclutter;
10748: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10749: $thisurl =~ s/\?.+$//;
10750: if ($map =~ m{^uploaded/.+\.page$}) {
10751: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10752: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10753: $noclutter = 1;
10754: }
10755: }
10756: my $ids;
10757: if ($noclutter) {
10758: $ids=$bighash{'ids_'.$thisurl};
10759: } else {
10760: $ids=$bighash{'ids_'.&clutter($thisurl)};
10761: }
10762: unless ($ids) {
10763: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10764: $ids=$bighash{$idkey};
10765: }
10766: if ($ids) {
10767: # ------------------------------------------------------------------- Has ID(s)
10768: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10769: $symb =~ s/\?.+$//;
10770: }
10771: foreach my $id (split(/\,/,$ids)) {
10772: my ($mapid,$resid)=split(/\./,$id);
10773: if (
10774: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10775: eq $symb) {
10776: if (ref($encstate)) {
10777: $$encstate = $bighash{'encrypted_'.$id};
10778: }
10779: if (($env{'request.role.adv'}) ||
10780: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10781: ($thisurl eq '/adm/navmaps')) {
10782: $okay=1;
10783: last;
10784: }
10785: }
10786: }
10787: }
10788: untie(%bighash);
10789: }
10790: return $okay;
10791: }
10792:
10793: # --------------------------------------------------------------- Clean-up symb
10794:
10795: sub symbclean {
10796: my $symb=shift;
10797: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10798: # remove version from map
10799: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10800:
10801: # remove version from URL
10802: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10803:
10804: # remove wrapper
10805:
10806: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10807: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10808: return $symb;
10809: }
10810:
10811: # ---------------------------------------------- Split symb to find map and url
10812:
10813: sub encode_symb {
10814: my ($map,$resid,$url)=@_;
10815: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10816: }
10817:
10818: sub decode_symb {
10819: my $symb=shift;
10820: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10821: my ($map,$resid,$url)=split(/___/,$symb);
10822: return (&fixversion($map),$resid,&fixversion($url));
10823: }
10824:
10825: sub fixversion {
10826: my $fn=shift;
10827: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10828: my %bighash;
10829: my $uri=&clutter($fn);
10830: my $key=$env{'request.course.id'}.'_'.$uri;
10831: # is this cached?
10832: my ($result,$cached)=&is_cached_new('courseresversion',$key);
10833: if (defined($cached)) { return $result; }
10834: # unfortunately not cached, or expired
10835: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10836: &GDBM_READER(),0640)) {
10837: if ($bighash{'version_'.$uri}) {
10838: my $version=$bighash{'version_'.$uri};
10839: unless (($version eq 'mostrecent') ||
10840: ($version==&getversion($uri))) {
10841: $uri=~s/\.(\w+)$/\.$version\.$1/;
10842: }
10843: }
10844: untie %bighash;
10845: }
10846: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10847: }
10848:
10849: sub deversion {
10850: my $url=shift;
10851: $url=~s/\.\d+\.(\w+)$/\.$1/;
10852: return $url;
10853: }
10854:
10855: # ------------------------------------------------------ Return symb list entry
10856:
10857: sub symbread {
10858: my ($thisfn,$donotrecurse)=@_;
10859: my $cache_str;
10860: if ($thisfn ne '') {
10861: $cache_str='request.symbread.cached.'.$thisfn;
10862: if ($env{$cache_str} ne '') {
10863: return $env{$cache_str};
10864: }
10865: } else {
10866: # no filename provided? try from environment
10867: if ($env{'request.symb'}) {
10868: return $env{$cache_str}=&symbclean($env{'request.symb'});
10869: }
10870: $thisfn=$env{'request.filename'};
10871: }
10872: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10873: # is that filename actually a symb? Verify, clean, and return
10874: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10875: if (&symbverify($thisfn,$1)) {
10876: return $env{$cache_str}=&symbclean($thisfn);
10877: }
10878: }
10879: $thisfn=declutter($thisfn);
10880: my %hash;
10881: my %bighash;
10882: my $syval='';
10883: if (($env{'request.course.fn'}) && ($thisfn)) {
10884: my $targetfn = $thisfn;
10885: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10886: $targetfn = 'adm/wrapper/'.$thisfn;
10887: }
10888: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10889: $targetfn=$1;
10890: }
10891: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10892: &GDBM_READER(),0640)) {
10893: $syval=$hash{$targetfn};
10894: untie(%hash);
10895: }
10896: # ---------------------------------------------------------- There was an entry
10897: if ($syval) {
10898: #unless ($syval=~/\_\d+$/) {
10899: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10900: #&appenv({'request.ambiguous' => $thisfn});
10901: #return $env{$cache_str}='';
10902: #}
10903: #$syval.=$1;
10904: #}
10905: } else {
10906: # ------------------------------------------------------- Was not in symb table
10907: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10908: &GDBM_READER(),0640)) {
10909: # ---------------------------------------------- Get ID(s) for current resource
10910: my $ids=$bighash{'ids_'.&clutter($thisfn)};
10911: unless ($ids) {
10912: $ids=$bighash{'ids_/'.$thisfn};
10913: }
10914: unless ($ids) {
10915: # alias?
10916: $ids=$bighash{'mapalias_'.$thisfn};
10917: }
10918: if ($ids) {
10919: # ------------------------------------------------------------------- Has ID(s)
10920: my @possibilities=split(/\,/,$ids);
10921: if ($#possibilities==0) {
10922: # ----------------------------------------------- There is only one possibility
10923: my ($mapid,$resid)=split(/\./,$ids);
10924: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10925: $resid,$thisfn);
10926: } elsif (!$donotrecurse) {
10927: # ------------------------------------------ There is more than one possibility
10928: my $realpossible=0;
10929: foreach my $id (@possibilities) {
10930: my $file=$bighash{'src_'.$id};
10931: if (&allowed('bre',$file)) {
10932: my ($mapid,$resid)=split(/\./,$id);
10933: if ($bighash{'map_type_'.$mapid} ne 'page') {
10934: $realpossible++;
10935: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10936: $resid,$thisfn);
10937: }
10938: }
10939: }
10940: if ($realpossible!=1) { $syval=''; }
10941: } else {
10942: $syval='';
10943: }
10944: }
10945: untie(%bighash)
10946: }
10947: }
10948: if ($syval) {
10949: return $env{$cache_str}=$syval;
10950: }
10951: }
10952: &appenv({'request.ambiguous' => $thisfn});
10953: return $env{$cache_str}='';
10954: }
10955:
10956: # ---------------------------------------------------------- Return random seed
10957:
10958: sub numval {
10959: my $txt=shift;
10960: $txt=~tr/A-J/0-9/;
10961: $txt=~tr/a-j/0-9/;
10962: $txt=~tr/K-T/0-9/;
10963: $txt=~tr/k-t/0-9/;
10964: $txt=~tr/U-Z/0-5/;
10965: $txt=~tr/u-z/0-5/;
10966: $txt=~s/\D//g;
10967: if ($_64bit) { if ($txt > 2**32) { return -1; } }
10968: return int($txt);
10969: }
10970:
10971: sub numval2 {
10972: my $txt=shift;
10973: $txt=~tr/A-J/0-9/;
10974: $txt=~tr/a-j/0-9/;
10975: $txt=~tr/K-T/0-9/;
10976: $txt=~tr/k-t/0-9/;
10977: $txt=~tr/U-Z/0-5/;
10978: $txt=~tr/u-z/0-5/;
10979: $txt=~s/\D//g;
10980: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10981: my $total;
10982: foreach my $val (@txts) { $total+=$val; }
10983: if ($_64bit) { if ($total > 2**32) { return -1; } }
10984: return int($total);
10985: }
10986:
10987: sub numval3 {
10988: use integer;
10989: my $txt=shift;
10990: $txt=~tr/A-J/0-9/;
10991: $txt=~tr/a-j/0-9/;
10992: $txt=~tr/K-T/0-9/;
10993: $txt=~tr/k-t/0-9/;
10994: $txt=~tr/U-Z/0-5/;
10995: $txt=~tr/u-z/0-5/;
10996: $txt=~s/\D//g;
10997: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10998: my $total;
10999: foreach my $val (@txts) { $total+=$val; }
11000: if ($_64bit) { $total=(($total<<32)>>32); }
11001: return $total;
11002: }
11003:
11004: sub digest {
11005: my ($data)=@_;
11006: my $digest=&Digest::MD5::md5($data);
11007: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11008: my ($e,$f);
11009: {
11010: use integer;
11011: $e=($a+$b);
11012: $f=($c+$d);
11013: if ($_64bit) {
11014: $e=(($e<<32)>>32);
11015: $f=(($f<<32)>>32);
11016: }
11017: }
11018: if (wantarray) {
11019: return ($e,$f);
11020: } else {
11021: my $g;
11022: {
11023: use integer;
11024: $g=($e+$f);
11025: if ($_64bit) {
11026: $g=(($g<<32)>>32);
11027: }
11028: }
11029: return $g;
11030: }
11031: }
11032:
11033: sub latest_rnd_algorithm_id {
11034: return '64bit5';
11035: }
11036:
11037: sub get_rand_alg {
11038: my ($courseid)=@_;
11039: if (!$courseid) { $courseid=(&whichuser())[1]; }
11040: if ($courseid) {
11041: return $env{"course.$courseid.rndseed"};
11042: }
11043: return &latest_rnd_algorithm_id();
11044: }
11045:
11046: sub validCODE {
11047: my ($CODE)=@_;
11048: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11049: return 0;
11050: }
11051:
11052: sub getCODE {
11053: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11054: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11055: defined($Apache::lonhomework::parsing_a_task) ) &&
11056: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11057: return $Apache::lonhomework::history{'resource.CODE'};
11058: }
11059: return undef;
11060: }
11061: #
11062: # Determines the random seed for a specific context:
11063: #
11064: # parameters:
11065: # symb - in course context the symb for the seed.
11066: # course_id - The course id of the form domain_coursenum.
11067: # domain - Domain for the user.
11068: # course - Course for the user.
11069: # cenv - environment of the course.
11070: #
11071: # NOTE:
11072: # All parameters are picked out of the environment if missing
11073: # or not defined.
11074: # If a symb cannot be determined the current time is used instead.
11075: #
11076: # For a given well defined symb, courside, domain, username,
11077: # and course environment, the seed is reproducible.
11078: #
11079: sub rndseed {
11080: my ($symb,$courseid,$domain,$username, $cenv)=@_;
11081: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11082: if (!defined($symb)) {
11083: unless ($symb=$wsymb) { return time; }
11084: }
11085: if (!defined $courseid) {
11086: $courseid=$wcourseid;
11087: }
11088: if (!defined $domain) { $domain=$wdomain; }
11089: if (!defined $username) { $username=$wusername }
11090:
11091: my $which;
11092: if (defined($cenv->{'rndseed'})) {
11093: $which = $cenv->{'rndseed'};
11094: } else {
11095: $which =&get_rand_alg($courseid);
11096: }
11097: if (defined(&getCODE())) {
11098:
11099: if ($which eq '64bit5') {
11100: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11101: } elsif ($which eq '64bit4') {
11102: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11103: } else {
11104: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11105: }
11106: } elsif ($which eq '64bit5') {
11107: return &rndseed_64bit5($symb,$courseid,$domain,$username);
11108: } elsif ($which eq '64bit4') {
11109: return &rndseed_64bit4($symb,$courseid,$domain,$username);
11110: } elsif ($which eq '64bit3') {
11111: return &rndseed_64bit3($symb,$courseid,$domain,$username);
11112: } elsif ($which eq '64bit2') {
11113: return &rndseed_64bit2($symb,$courseid,$domain,$username);
11114: } elsif ($which eq '64bit') {
11115: return &rndseed_64bit($symb,$courseid,$domain,$username);
11116: }
11117: return &rndseed_32bit($symb,$courseid,$domain,$username);
11118: }
11119:
11120: sub rndseed_32bit {
11121: my ($symb,$courseid,$domain,$username)=@_;
11122: {
11123: use integer;
11124: my $symbchck=unpack("%32C*",$symb) << 27;
11125: my $symbseed=numval($symb) << 22;
11126: my $namechck=unpack("%32C*",$username) << 17;
11127: my $nameseed=numval($username) << 12;
11128: my $domainseed=unpack("%32C*",$domain) << 7;
11129: my $courseseed=unpack("%32C*",$courseid);
11130: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11131: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11132: #&logthis("rndseed :$num:$symb");
11133: if ($_64bit) { $num=(($num<<32)>>32); }
11134: return $num;
11135: }
11136: }
11137:
11138: sub rndseed_64bit {
11139: my ($symb,$courseid,$domain,$username)=@_;
11140: {
11141: use integer;
11142: my $symbchck=unpack("%32S*",$symb) << 21;
11143: my $symbseed=numval($symb) << 10;
11144: my $namechck=unpack("%32S*",$username);
11145:
11146: my $nameseed=numval($username) << 21;
11147: my $domainseed=unpack("%32S*",$domain) << 10;
11148: my $courseseed=unpack("%32S*",$courseid);
11149:
11150: my $num1=$symbchck+$symbseed+$namechck;
11151: my $num2=$nameseed+$domainseed+$courseseed;
11152: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11153: #&logthis("rndseed :$num:$symb");
11154: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11155: return "$num1,$num2";
11156: }
11157: }
11158:
11159: sub rndseed_64bit2 {
11160: my ($symb,$courseid,$domain,$username)=@_;
11161: {
11162: use integer;
11163: # strings need to be an even # of cahracters long, it it is odd the
11164: # last characters gets thrown away
11165: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11166: my $symbseed=numval($symb) << 10;
11167: my $namechck=unpack("%32S*",$username.' ');
11168:
11169: my $nameseed=numval($username) << 21;
11170: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11171: my $courseseed=unpack("%32S*",$courseid.' ');
11172:
11173: my $num1=$symbchck+$symbseed+$namechck;
11174: my $num2=$nameseed+$domainseed+$courseseed;
11175: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11176: #&logthis("rndseed :$num:$symb");
11177: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11178: return "$num1,$num2";
11179: }
11180: }
11181:
11182: sub rndseed_64bit3 {
11183: my ($symb,$courseid,$domain,$username)=@_;
11184: {
11185: use integer;
11186: # strings need to be an even # of cahracters long, it it is odd the
11187: # last characters gets thrown away
11188: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11189: my $symbseed=numval2($symb) << 10;
11190: my $namechck=unpack("%32S*",$username.' ');
11191:
11192: my $nameseed=numval2($username) << 21;
11193: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11194: my $courseseed=unpack("%32S*",$courseid.' ');
11195:
11196: my $num1=$symbchck+$symbseed+$namechck;
11197: my $num2=$nameseed+$domainseed+$courseseed;
11198: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11199: #&logthis("rndseed :$num1:$num2:$_64bit");
11200: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11201:
11202: return "$num1:$num2";
11203: }
11204: }
11205:
11206: sub rndseed_64bit4 {
11207: my ($symb,$courseid,$domain,$username)=@_;
11208: {
11209: use integer;
11210: # strings need to be an even # of cahracters long, it it is odd the
11211: # last characters gets thrown away
11212: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11213: my $symbseed=numval3($symb) << 10;
11214: my $namechck=unpack("%32S*",$username.' ');
11215:
11216: my $nameseed=numval3($username) << 21;
11217: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11218: my $courseseed=unpack("%32S*",$courseid.' ');
11219:
11220: my $num1=$symbchck+$symbseed+$namechck;
11221: my $num2=$nameseed+$domainseed+$courseseed;
11222: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11223: #&logthis("rndseed :$num1:$num2:$_64bit");
11224: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11225:
11226: return "$num1:$num2";
11227: }
11228: }
11229:
11230: sub rndseed_64bit5 {
11231: my ($symb,$courseid,$domain,$username)=@_;
11232: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11233: return "$num1:$num2";
11234: }
11235:
11236: sub rndseed_CODE_64bit {
11237: my ($symb,$courseid,$domain,$username)=@_;
11238: {
11239: use integer;
11240: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11241: my $symbseed=numval2($symb);
11242: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11243: my $CODEseed=numval(&getCODE());
11244: my $courseseed=unpack("%32S*",$courseid.' ');
11245: my $num1=$symbseed+$CODEchck;
11246: my $num2=$CODEseed+$courseseed+$symbchck;
11247: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11248: #&logthis("rndseed :$num1:$num2:$symb");
11249: if ($_64bit) { $num1=(($num1<<32)>>32); }
11250: if ($_64bit) { $num2=(($num2<<32)>>32); }
11251: return "$num1:$num2";
11252: }
11253: }
11254:
11255: sub rndseed_CODE_64bit4 {
11256: my ($symb,$courseid,$domain,$username)=@_;
11257: {
11258: use integer;
11259: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11260: my $symbseed=numval3($symb);
11261: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11262: my $CODEseed=numval3(&getCODE());
11263: my $courseseed=unpack("%32S*",$courseid.' ');
11264: my $num1=$symbseed+$CODEchck;
11265: my $num2=$CODEseed+$courseseed+$symbchck;
11266: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11267: #&logthis("rndseed :$num1:$num2:$symb");
11268: if ($_64bit) { $num1=(($num1<<32)>>32); }
11269: if ($_64bit) { $num2=(($num2<<32)>>32); }
11270: return "$num1:$num2";
11271: }
11272: }
11273:
11274: sub rndseed_CODE_64bit5 {
11275: my ($symb,$courseid,$domain,$username)=@_;
11276: my $code = &getCODE();
11277: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11278: return "$num1:$num2";
11279: }
11280:
11281: sub setup_random_from_rndseed {
11282: my ($rndseed)=@_;
11283: if ($rndseed =~/([,:])/) {
11284: my ($num1,$num2)=split(/[,:]/,$rndseed);
11285: &Math::Random::random_set_seed(abs($num1),abs($num2));
11286: } else {
11287: &Math::Random::random_set_seed_from_phrase($rndseed);
11288: }
11289: }
11290:
11291: sub latest_receipt_algorithm_id {
11292: return 'receipt3';
11293: }
11294:
11295: sub recunique {
11296: my $fucourseid=shift;
11297: my $unique;
11298: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11299: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11300: $unique=$env{"course.$fucourseid.internal.encseed"};
11301: } else {
11302: $unique=$perlvar{'lonReceipt'};
11303: }
11304: return unpack("%32C*",$unique);
11305: }
11306:
11307: sub recprefix {
11308: my $fucourseid=shift;
11309: my $prefix;
11310: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11311: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11312: $prefix=$env{"course.$fucourseid.internal.encpref"};
11313: } else {
11314: $prefix=$perlvar{'lonHostID'};
11315: }
11316: return unpack("%32C*",$prefix);
11317: }
11318:
11319: sub ireceipt {
11320: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11321:
11322: my $return =&recprefix($fucourseid).'-';
11323:
11324: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11325: $env{'request.state'} eq 'construct') {
11326: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11327: return $return;
11328: }
11329:
11330: my $cuname=unpack("%32C*",$funame);
11331: my $cudom=unpack("%32C*",$fudom);
11332: my $cucourseid=unpack("%32C*",$fucourseid);
11333: my $cusymb=unpack("%32C*",$fusymb);
11334: my $cunique=&recunique($fucourseid);
11335: my $cpart=unpack("%32S*",$part);
11336: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11337:
11338: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
11339:
11340: $return.= ($cunique%$cuname+
11341: $cunique%$cudom+
11342: $cusymb%$cuname+
11343: $cusymb%$cudom+
11344: $cucourseid%$cuname+
11345: $cucourseid%$cudom+
11346: $cpart%$cuname+
11347: $cpart%$cudom);
11348: } else {
11349: $return.= ($cunique%$cuname+
11350: $cunique%$cudom+
11351: $cusymb%$cuname+
11352: $cusymb%$cudom+
11353: $cucourseid%$cuname+
11354: $cucourseid%$cudom);
11355: }
11356: return $return;
11357: }
11358:
11359: sub receipt {
11360: my ($part)=@_;
11361: my ($symb,$courseid,$domain,$name) = &whichuser();
11362: return &ireceipt($name,$domain,$courseid,$symb,$part);
11363: }
11364:
11365: sub whichuser {
11366: my ($passedsymb)=@_;
11367: my ($symb,$courseid,$domain,$name,$publicuser);
11368: if (defined($env{'form.grade_symb'})) {
11369: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11370: my $allowed=&allowed('vgr',$tmp_courseid);
11371: if (!$allowed &&
11372: exists($env{'request.course.sec'}) &&
11373: $env{'request.course.sec'} !~ /^\s*$/) {
11374: $allowed=&allowed('vgr',$tmp_courseid.
11375: '/'.$env{'request.course.sec'});
11376: }
11377: if ($allowed) {
11378: ($symb)=&get_env_multiple('form.grade_symb');
11379: $courseid=$tmp_courseid;
11380: ($domain)=&get_env_multiple('form.grade_domain');
11381: ($name)=&get_env_multiple('form.grade_username');
11382: return ($symb,$courseid,$domain,$name,$publicuser);
11383: }
11384: }
11385: if (!$passedsymb) {
11386: $symb=&symbread();
11387: } else {
11388: $symb=$passedsymb;
11389: }
11390: $courseid=$env{'request.course.id'};
11391: $domain=$env{'user.domain'};
11392: $name=$env{'user.name'};
11393: if ($name eq 'public' && $domain eq 'public') {
11394: if (!defined($env{'form.username'})) {
11395: $env{'form.username'}.=time.rand(10000000);
11396: }
11397: $name.=$env{'form.username'};
11398: }
11399: return ($symb,$courseid,$domain,$name,$publicuser);
11400:
11401: }
11402:
11403: # ------------------------------------------------------------ Serves up a file
11404: # returns either the contents of the file or
11405: # -1 if the file doesn't exist
11406: #
11407: # if the target is a file that was uploaded via DOCS,
11408: # a check will be made to see if a current copy exists on the local server,
11409: # if it does this will be served, otherwise a copy will be retrieved from
11410: # the home server for the course and stored in /home/httpd/html/userfiles on
11411: # the local server.
11412:
11413: sub getfile {
11414: my ($file) = @_;
11415: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11416: &repcopy($file);
11417: return &readfile($file);
11418: }
11419:
11420: sub repcopy_userfile {
11421: my ($file)=@_;
11422: my $londocroot = $perlvar{'lonDocRoot'};
11423: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11424: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11425: my ($cdom,$cnum,$filename) =
11426: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11427: my $uri="/uploaded/$cdom/$cnum/$filename";
11428: if (-e "$file") {
11429: # we already have a local copy, check it out
11430: my @fileinfo = stat($file);
11431: my $rtncode;
11432: my $info;
11433: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11434: if ($lwpresp ne 'ok') {
11435: # there is no such file anymore, even though we had a local copy
11436: if ($rtncode eq '404') {
11437: unlink($file);
11438: }
11439: return -1;
11440: }
11441: if ($info < $fileinfo[9]) {
11442: # nice, the file we have is up-to-date, just say okay
11443: return 'ok';
11444: } else {
11445: # the file is outdated, get rid of it
11446: unlink($file);
11447: }
11448: }
11449: # one way or the other, at this point, we don't have the file
11450: # construct the correct path for the file
11451: my @parts = ($cdom,$cnum);
11452: if ($filename =~ m|^(.+)/[^/]+$|) {
11453: push @parts, split(/\//,$1);
11454: }
11455: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11456: foreach my $part (@parts) {
11457: $path .= '/'.$part;
11458: if (!-e $path) {
11459: mkdir($path,0770);
11460: }
11461: }
11462: # now the path exists for sure
11463: # get a user agent
11464: my $ua=new LWP::UserAgent;
11465: my $transferfile=$file.'.in.transfer';
11466: # FIXME: this should flock
11467: if (-e $transferfile) { return 'ok'; }
11468: my $request;
11469: $uri=~s/^\///;
11470: my $homeserver = &homeserver($cnum,$cdom);
11471: my $protocol = $protocol{$homeserver};
11472: $protocol = 'http' if ($protocol ne 'https');
11473: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11474: my $response=$ua->request($request,$transferfile);
11475: # did it work?
11476: if ($response->is_error()) {
11477: unlink($transferfile);
11478: &logthis("Userfile repcopy failed for $uri");
11479: return -1;
11480: }
11481: # worked, rename the transfer file
11482: rename($transferfile,$file);
11483: return 'ok';
11484: }
11485:
11486: sub tokenwrapper {
11487: my $uri=shift;
11488: $uri=~s|^https?\://([^/]+)||;
11489: $uri=~s|^/||;
11490: $env{'user.environment'}=~/\/([^\/]+)\.id/;
11491: my $token=$1;
11492: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11493: if ($udom && $uname && $file) {
11494: $file=~s|(\?\.*)*$||;
11495: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11496: my $homeserver = &homeserver($uname,$udom);
11497: my $protocol = $protocol{$homeserver};
11498: $protocol = 'http' if ($protocol ne 'https');
11499: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11500: (($uri=~/\?/)?'&':'?').'token='.$token.
11501: '&tokenissued='.$perlvar{'lonHostID'};
11502: } else {
11503: return '/adm/notfound.html';
11504: }
11505: }
11506:
11507: # call with reqtype HEAD: get last modification time
11508: # call with reqtype GET: get the file contents
11509: # Do not call this with reqtype GET for large files! It loads everything into memory
11510: #
11511: sub getuploaded {
11512: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11513: $uri=~s/^\///;
11514: my $homeserver = &homeserver($cnum,$cdom);
11515: my $protocol = $protocol{$homeserver};
11516: $protocol = 'http' if ($protocol ne 'https');
11517: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11518: my $ua=new LWP::UserAgent;
11519: my $request=new HTTP::Request($reqtype,$uri);
11520: my $response=$ua->request($request);
11521: $$rtncode = $response->code;
11522: if (! $response->is_success()) {
11523: return 'failed';
11524: }
11525: if ($reqtype eq 'HEAD') {
11526: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11527: } elsif ($reqtype eq 'GET') {
11528: $$info = $response->content;
11529: }
11530: return 'ok';
11531: }
11532:
11533: sub readfile {
11534: my $file = shift;
11535: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11536: my $fh;
11537: open($fh,"<$file");
11538: my $a='';
11539: while (my $line = <$fh>) { $a .= $line; }
11540: return $a;
11541: }
11542:
11543: sub filelocation {
11544: my ($dir,$file) = @_;
11545: my $location;
11546: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11547:
11548: if ($file =~ m-^/adm/-) {
11549: $file=~s-^/adm/wrapper/-/-;
11550: $file=~s-^/adm/coursedocs/showdoc/-/-;
11551: }
11552:
11553: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11554: $location = $file;
11555: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11556: my ($udom,$uname,$filename)=
11557: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11558: my $home=&homeserver($uname,$udom);
11559: my $is_me=0;
11560: my @ids=¤t_machine_ids();
11561: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11562: if ($is_me) {
11563: $location=propath($udom,$uname).'/userfiles/'.$filename;
11564: } else {
11565: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11566: $udom.'/'.$uname.'/'.$filename;
11567: }
11568: } elsif ($file =~ m-^/adm/-) {
11569: $location = $perlvar{'lonDocRoot'}.'/'.$file;
11570: } else {
11571: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11572: $file=~s:^/(res|priv)/:/:;
11573: my $space=$1;
11574: if ( !( $file =~ m:^/:) ) {
11575: $location = $dir. '/'.$file;
11576: } else {
11577: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11578: }
11579: }
11580: $location=~s://+:/:g; # remove duplicate /
11581: while ($location=~m{/\.\./}) {
11582: if ($location =~ m{/[^/]+/\.\./}) {
11583: $location=~ s{/[^/]+/\.\./}{/}g;
11584: } else {
11585: $location=~ s{/\.\./}{/}g;
11586: }
11587: } #remove dir/..
11588: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11589: return $location;
11590: }
11591:
11592: sub hreflocation {
11593: my ($dir,$file)=@_;
11594: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11595: $file=filelocation($dir,$file);
11596: } elsif ($file=~m-^/adm/-) {
11597: $file=~s-^/adm/wrapper/-/-;
11598: $file=~s-^/adm/coursedocs/showdoc/-/-;
11599: }
11600: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11601: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11602: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11603: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11604: {/uploaded/$1/$2/}x;
11605: }
11606: if ($file=~ m{^/userfiles/}) {
11607: $file =~ s{^/userfiles/}{/uploaded/};
11608: }
11609: return $file;
11610: }
11611:
11612:
11613:
11614:
11615:
11616: sub current_machine_domains {
11617: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11618: }
11619:
11620: sub machine_domains {
11621: my ($hostname) = @_;
11622: my @domains;
11623: my %hostname = &all_hostnames();
11624: while( my($id, $name) = each(%hostname)) {
11625: # &logthis("-$id-$name-$hostname-");
11626: if ($hostname eq $name) {
11627: push(@domains,&host_domain($id));
11628: }
11629: }
11630: return @domains;
11631: }
11632:
11633: sub current_machine_ids {
11634: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11635: }
11636:
11637: sub machine_ids {
11638: my ($hostname) = @_;
11639: $hostname ||= &hostname($perlvar{'lonHostID'});
11640: my @ids;
11641: my %name_to_host = &all_names();
11642: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11643: return @{ $name_to_host{$hostname} };
11644: }
11645: return;
11646: }
11647:
11648: sub additional_machine_domains {
11649: my @domains;
11650: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11651: while( my $line = <$fh>) {
11652: $line =~ s/\s//g;
11653: push(@domains,$line);
11654: }
11655: return @domains;
11656: }
11657:
11658: sub default_login_domain {
11659: my $domain = $perlvar{'lonDefDomain'};
11660: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11661: foreach my $posdom (¤t_machine_domains(),
11662: &additional_machine_domains()) {
11663: if (lc($posdom) eq lc($testdomain)) {
11664: $domain=$posdom;
11665: last;
11666: }
11667: }
11668: return $domain;
11669: }
11670:
11671: # ------------------------------------------------------------- Declutters URLs
11672:
11673: sub declutter {
11674: my $thisfn=shift;
11675: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11676: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
11677: $thisfn=~s{^/home/httpd/html}{};
11678: }
11679: $thisfn=~s/^\///;
11680: $thisfn=~s|^adm/wrapper/||;
11681: $thisfn=~s|^adm/coursedocs/showdoc/||;
11682: $thisfn=~s/^res\///;
11683: $thisfn=~s/^priv\///;
11684: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11685: $thisfn=~s/\?.+$//;
11686: }
11687: return $thisfn;
11688: }
11689:
11690: # ------------------------------------------------------------- Clutter up URLs
11691:
11692: sub clutter {
11693: my $thisfn='/'.&declutter(shift);
11694: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11695: || $thisfn =~ m{^/adm/(includes|pages)} ) {
11696: $thisfn='/res'.$thisfn;
11697: }
11698: if ($thisfn !~m|^/adm|) {
11699: if ($thisfn =~ m|^/ext/|) {
11700: $thisfn='/adm/wrapper'.$thisfn;
11701: } else {
11702: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11703: my $embstyle=&Apache::loncommon::fileembstyle($ext);
11704: if ($embstyle eq 'ssi'
11705: || ($embstyle eq 'hdn')
11706: || ($embstyle eq 'rat')
11707: || ($embstyle eq 'prv')
11708: || ($embstyle eq 'ign')) {
11709: #do nothing with these
11710: } elsif (($embstyle eq 'img')
11711: || ($embstyle eq 'emb')
11712: || ($embstyle eq 'wrp')) {
11713: $thisfn='/adm/wrapper'.$thisfn;
11714: } elsif ($embstyle eq 'unk'
11715: && $thisfn!~/\.(sequence|page)$/) {
11716: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
11717: } else {
11718: # &logthis("Got a blank emb style");
11719: }
11720: }
11721: }
11722: return $thisfn;
11723: }
11724:
11725: sub clutter_with_no_wrapper {
11726: my $uri = &clutter(shift);
11727: if ($uri =~ m-^/adm/-) {
11728: $uri =~ s-^/adm/wrapper/-/-;
11729: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11730: }
11731: return $uri;
11732: }
11733:
11734: sub freeze_escape {
11735: my ($value)=@_;
11736: if (ref($value)) {
11737: $value=&nfreeze($value);
11738: return '__FROZEN__'.&escape($value);
11739: }
11740: return &escape($value);
11741: }
11742:
11743:
11744: sub thaw_unescape {
11745: my ($value)=@_;
11746: if ($value =~ /^__FROZEN__/) {
11747: substr($value,0,10,undef);
11748: $value=&unescape($value);
11749: return &thaw($value);
11750: }
11751: return &unescape($value);
11752: }
11753:
11754: sub correct_line_ends {
11755: my ($result)=@_;
11756: $$result =~s/\r\n/\n/mg;
11757: $$result =~s/\r/\n/mg;
11758: }
11759: # ================================================================ Main Program
11760:
11761: sub goodbye {
11762: &logthis("Starting Shut down");
11763: #not converted to using infrastruture and probably shouldn't be
11764: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11765: #converted
11766: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11767: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11768: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11769: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11770: #1.1 only
11771: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11772: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11773: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11774: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11775: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11776: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11777: &logthis(sprintf("%-20s is %s",'hits',$hits));
11778: &flushcourselogs();
11779: &logthis("Shutting down");
11780: }
11781:
11782: sub get_dns {
11783: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11784: if (!$ignore_cache) {
11785: my ($content,$cached)=
11786: &Apache::lonnet::is_cached_new('dns',$url);
11787: if ($cached) {
11788: &$func($content,$hashref);
11789: return;
11790: }
11791: }
11792:
11793: my %alldns;
11794: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11795: foreach my $dns (<$config>) {
11796: next if ($dns !~ /^\^(\S*)/x);
11797: my $line = $1;
11798: my ($host,$protocol) = split(/:/,$line);
11799: if ($protocol ne 'https') {
11800: $protocol = 'http';
11801: }
11802: $alldns{$host} = $protocol;
11803: }
11804: while (%alldns) {
11805: my ($dns) = keys(%alldns);
11806: my $ua=new LWP::UserAgent;
11807: $ua->timeout(30);
11808: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11809: my $response=$ua->request($request);
11810: delete($alldns{$dns});
11811: next if ($response->is_error());
11812: my @content = split("\n",$response->content);
11813: unless ($nocache) {
11814: &do_cache_new('dns',$url,\@content,30*24*60*60);
11815: }
11816: &$func(\@content,$hashref);
11817: return;
11818: }
11819: close($config);
11820: my $which = (split('/',$url))[3];
11821: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11822: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11823: my @content = <$config>;
11824: &$func(\@content,$hashref);
11825: return;
11826: }
11827:
11828: # ------------------------------------------------------Get DNS checksums file
11829: sub parse_dns_checksums_tab {
11830: my ($lines,$hashref) = @_;
11831: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11832: my $loncaparev = &get_server_loncaparev($machine_dom);
11833: my ($release,$timestamp) = split(/\-/,$loncaparev);
11834: my (%chksum,%revnum);
11835: if (ref($lines) eq 'ARRAY') {
11836: chomp(@{$lines});
11837: my $version = shift(@{$lines});
11838: if ($version eq $release) {
11839: foreach my $line (@{$lines}) {
11840: my ($file,$version,$shasum) = split(/,/,$line);
11841: $chksum{$file} = $shasum;
11842: $revnum{$file} = $version;
11843: }
11844: if (ref($hashref) eq 'HASH') {
11845: %{$hashref} = (
11846: sums => \%chksum,
11847: versions => \%revnum,
11848: );
11849: }
11850: }
11851: }
11852: return;
11853: }
11854:
11855: sub fetch_dns_checksums {
11856: my %checksums;
11857: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11858: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
11859: my ($release,$timestamp) = split(/\-/,$loncaparev);
11860: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
11861: \%checksums);
11862: return \%checksums;
11863: }
11864:
11865: # ------------------------------------------------------------ Read domain file
11866: {
11867: my $loaded;
11868: my %domain;
11869:
11870: sub parse_domain_tab {
11871: my ($lines) = @_;
11872: foreach my $line (@$lines) {
11873: next if ($line =~ /^(\#|\s*$ )/x);
11874:
11875: chomp($line);
11876: my ($name,@elements) = split(/:/,$line,9);
11877: my %this_domain;
11878: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11879: 'lang_def', 'city', 'longi', 'lati',
11880: 'primary') {
11881: $this_domain{$field} = shift(@elements);
11882: }
11883: $domain{$name} = \%this_domain;
11884: }
11885: }
11886:
11887: sub reset_domain_info {
11888: undef($loaded);
11889: undef(%domain);
11890: }
11891:
11892: sub load_domain_tab {
11893: my ($ignore_cache) = @_;
11894: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11895: my $fh;
11896: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11897: my @lines = <$fh>;
11898: &parse_domain_tab(\@lines);
11899: }
11900: close($fh);
11901: $loaded = 1;
11902: }
11903:
11904: sub domain {
11905: &load_domain_tab() if (!$loaded);
11906:
11907: my ($name,$what) = @_;
11908: return if ( !exists($domain{$name}) );
11909:
11910: if (!$what) {
11911: return $domain{$name}{'description'};
11912: }
11913: return $domain{$name}{$what};
11914: }
11915:
11916: sub domain_info {
11917: &load_domain_tab() if (!$loaded);
11918: return %domain;
11919: }
11920:
11921: }
11922:
11923:
11924: # ------------------------------------------------------------- Read hosts file
11925: {
11926: my %hostname;
11927: my %hostdom;
11928: my %libserv;
11929: my $loaded;
11930: my %name_to_host;
11931: my %internetdom;
11932: my %LC_dns_serv;
11933:
11934: sub parse_hosts_tab {
11935: my ($file) = @_;
11936: foreach my $configline (@$file) {
11937: next if ($configline =~ /^(\#|\s*$ )/x);
11938: chomp($configline);
11939: if ($configline =~ /^\^/) {
11940: if ($configline =~ /^\^([\w.\-]+)/) {
11941: $LC_dns_serv{$1} = 1;
11942: }
11943: next;
11944: }
11945: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11946: $name=~s/\s//g;
11947: if ($id && $domain && $role && $name) {
11948: $hostname{$id}=$name;
11949: push(@{$name_to_host{$name}}, $id);
11950: $hostdom{$id}=$domain;
11951: if ($role eq 'library') { $libserv{$id}=$name; }
11952: if (defined($protocol)) {
11953: if ($protocol eq 'https') {
11954: $protocol{$id} = $protocol;
11955: } else {
11956: $protocol{$id} = 'http';
11957: }
11958: } else {
11959: $protocol{$id} = 'http';
11960: }
11961: if (defined($intdom)) {
11962: $internetdom{$id} = $intdom;
11963: }
11964: }
11965: }
11966: }
11967:
11968: sub reset_hosts_info {
11969: &purge_remembered();
11970: &reset_domain_info();
11971: &reset_hosts_ip_info();
11972: undef(%name_to_host);
11973: undef(%hostname);
11974: undef(%hostdom);
11975: undef(%libserv);
11976: undef($loaded);
11977: }
11978:
11979: sub load_hosts_tab {
11980: my ($ignore_cache) = @_;
11981: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11982: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11983: my @config = <$config>;
11984: &parse_hosts_tab(\@config);
11985: close($config);
11986: $loaded=1;
11987: }
11988:
11989: sub hostname {
11990: &load_hosts_tab() if (!$loaded);
11991:
11992: my ($lonid) = @_;
11993: return $hostname{$lonid};
11994: }
11995:
11996: sub all_hostnames {
11997: &load_hosts_tab() if (!$loaded);
11998:
11999: return %hostname;
12000: }
12001:
12002: sub all_names {
12003: &load_hosts_tab() if (!$loaded);
12004:
12005: return %name_to_host;
12006: }
12007:
12008: sub all_host_domain {
12009: &load_hosts_tab() if (!$loaded);
12010: return %hostdom;
12011: }
12012:
12013: sub is_library {
12014: &load_hosts_tab() if (!$loaded);
12015:
12016: return exists($libserv{$_[0]});
12017: }
12018:
12019: sub all_library {
12020: &load_hosts_tab() if (!$loaded);
12021:
12022: return %libserv;
12023: }
12024:
12025: sub unique_library {
12026: #2x reverse removes all hostnames that appear more than once
12027: my %unique = reverse &all_library();
12028: return reverse %unique;
12029: }
12030:
12031: sub get_servers {
12032: &load_hosts_tab() if (!$loaded);
12033:
12034: my ($domain,$type) = @_;
12035: my %possible_hosts = ($type eq 'library') ? %libserv
12036: : %hostname;
12037: my %result;
12038: if (ref($domain) eq 'ARRAY') {
12039: while ( my ($host,$hostname) = each(%possible_hosts)) {
12040: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
12041: $result{$host} = $hostname;
12042: }
12043: }
12044: } else {
12045: while ( my ($host,$hostname) = each(%possible_hosts)) {
12046: if ($hostdom{$host} eq $domain) {
12047: $result{$host} = $hostname;
12048: }
12049: }
12050: }
12051: return %result;
12052: }
12053:
12054: sub get_unique_servers {
12055: my %unique = reverse &get_servers(@_);
12056: return reverse %unique;
12057: }
12058:
12059: sub host_domain {
12060: &load_hosts_tab() if (!$loaded);
12061:
12062: my ($lonid) = @_;
12063: return $hostdom{$lonid};
12064: }
12065:
12066: sub all_domains {
12067: &load_hosts_tab() if (!$loaded);
12068:
12069: my %seen;
12070: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12071: return @uniq;
12072: }
12073:
12074: sub internet_dom {
12075: &load_hosts_tab() if (!$loaded);
12076:
12077: my ($lonid) = @_;
12078: return $internetdom{$lonid};
12079: }
12080:
12081: sub is_LC_dns {
12082: &load_hosts_tab() if (!$loaded);
12083:
12084: my ($hostname) = @_;
12085: return exists($LC_dns_serv{$hostname});
12086: }
12087:
12088: }
12089:
12090: {
12091: my %iphost;
12092: my %name_to_ip;
12093: my %lonid_to_ip;
12094:
12095: sub get_hosts_from_ip {
12096: my ($ip) = @_;
12097: my %iphosts = &get_iphost();
12098: if (ref($iphosts{$ip})) {
12099: return @{$iphosts{$ip}};
12100: }
12101: return;
12102: }
12103:
12104: sub reset_hosts_ip_info {
12105: undef(%iphost);
12106: undef(%name_to_ip);
12107: undef(%lonid_to_ip);
12108: }
12109:
12110: sub get_host_ip {
12111: my ($lonid) = @_;
12112: if (exists($lonid_to_ip{$lonid})) {
12113: return $lonid_to_ip{$lonid};
12114: }
12115: my $name=&hostname($lonid);
12116: my $ip = gethostbyname($name);
12117: return if (!$ip || length($ip) ne 4);
12118: $ip=inet_ntoa($ip);
12119: $name_to_ip{$name} = $ip;
12120: $lonid_to_ip{$lonid} = $ip;
12121: return $ip;
12122: }
12123:
12124: sub get_iphost {
12125: my ($ignore_cache) = @_;
12126:
12127: if (!$ignore_cache) {
12128: if (%iphost) {
12129: return %iphost;
12130: }
12131: my ($ip_info,$cached)=
12132: &Apache::lonnet::is_cached_new('iphost','iphost');
12133: if ($cached) {
12134: %iphost = %{$ip_info->[0]};
12135: %name_to_ip = %{$ip_info->[1]};
12136: %lonid_to_ip = %{$ip_info->[2]};
12137: return %iphost;
12138: }
12139: }
12140:
12141: # get yesterday's info for fallback
12142: my %old_name_to_ip;
12143: my ($ip_info,$cached)=
12144: &Apache::lonnet::is_cached_new('iphost','iphost');
12145: if ($cached) {
12146: %old_name_to_ip = %{$ip_info->[1]};
12147: }
12148:
12149: my %name_to_host = &all_names();
12150: foreach my $name (keys(%name_to_host)) {
12151: my $ip;
12152: if (!exists($name_to_ip{$name})) {
12153: $ip = gethostbyname($name);
12154: if (!$ip || length($ip) ne 4) {
12155: if (defined($old_name_to_ip{$name})) {
12156: $ip = $old_name_to_ip{$name};
12157: &logthis("Can't find $name defaulting to old $ip");
12158: } else {
12159: &logthis("Name $name no IP found");
12160: next;
12161: }
12162: } else {
12163: $ip=inet_ntoa($ip);
12164: }
12165: $name_to_ip{$name} = $ip;
12166: } else {
12167: $ip = $name_to_ip{$name};
12168: }
12169: foreach my $id (@{ $name_to_host{$name} }) {
12170: $lonid_to_ip{$id} = $ip;
12171: }
12172: push(@{$iphost{$ip}},@{$name_to_host{$name}});
12173: }
12174: &do_cache_new('iphost','iphost',
12175: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12176: 48*60*60);
12177:
12178: return %iphost;
12179: }
12180:
12181: #
12182: # Given a DNS returns the loncapa host name for that DNS
12183: #
12184: sub host_from_dns {
12185: my ($dns) = @_;
12186: my @hosts;
12187: my $ip;
12188:
12189: if (exists($name_to_ip{$dns})) {
12190: $ip = $name_to_ip{$dns};
12191: }
12192: if (!$ip) {
12193: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12194: if (length($ip) == 4) {
12195: $ip = &IO::Socket::inet_ntoa($ip);
12196: }
12197: }
12198: if ($ip) {
12199: @hosts = get_hosts_from_ip($ip);
12200: return $hosts[0];
12201: }
12202: return undef;
12203: }
12204:
12205: sub get_internet_names {
12206: my ($lonid) = @_;
12207: return if ($lonid eq '');
12208: my ($idnref,$cached)=
12209: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12210: if ($cached) {
12211: return $idnref;
12212: }
12213: my $ip = &get_host_ip($lonid);
12214: my @hosts = &get_hosts_from_ip($ip);
12215: my %iphost = &get_iphost();
12216: my (@idns,%seen);
12217: foreach my $id (@hosts) {
12218: my $dom = &host_domain($id);
12219: my $prim_id = &domain($dom,'primary');
12220: my $prim_ip = &get_host_ip($prim_id);
12221: next if ($seen{$prim_ip});
12222: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12223: foreach my $id (@{$iphost{$prim_ip}}) {
12224: my $intdom = &internet_dom($id);
12225: unless (grep(/^\Q$intdom\E$/,@idns)) {
12226: push(@idns,$intdom);
12227: }
12228: }
12229: }
12230: $seen{$prim_ip} = 1;
12231: }
12232: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12233: }
12234:
12235: }
12236:
12237: sub all_loncaparevs {
12238: return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11);
12239: }
12240:
12241: # ---------------------------------------------------------- Read loncaparev table
12242: {
12243: sub load_loncaparevs {
12244: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12245: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12246: while (my $configline=<$config>) {
12247: chomp($configline);
12248: my ($hostid,$loncaparev)=split(/:/,$configline);
12249: $loncaparevs{$hostid}=$loncaparev;
12250: }
12251: close($config);
12252: }
12253: }
12254: }
12255: }
12256:
12257: # ---------------------------------------------------------- Read serverhostID table
12258: {
12259: sub load_serverhomeIDs {
12260: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12261: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12262: while (my $configline=<$config>) {
12263: chomp($configline);
12264: my ($name,$id)=split(/:/,$configline);
12265: $serverhomeIDs{$name}=$id;
12266: }
12267: close($config);
12268: }
12269: }
12270: }
12271: }
12272:
12273:
12274: BEGIN {
12275:
12276: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12277: unless ($readit) {
12278: {
12279: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12280: %perlvar = (%perlvar,%{$configvars});
12281: }
12282:
12283:
12284: # ------------------------------------------------------ Read spare server file
12285: {
12286: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12287:
12288: while (my $configline=<$config>) {
12289: chomp($configline);
12290: if ($configline) {
12291: my ($host,$type) = split(':',$configline,2);
12292: if (!defined($type) || $type eq '') { $type = 'default' };
12293: push(@{ $spareid{$type} }, $host);
12294: }
12295: }
12296: close($config);
12297: }
12298: # ------------------------------------------------------------ Read permissions
12299: {
12300: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12301:
12302: while (my $configline=<$config>) {
12303: chomp($configline);
12304: if ($configline) {
12305: my ($role,$perm)=split(/ /,$configline);
12306: if ($perm ne '') { $pr{$role}=$perm; }
12307: }
12308: }
12309: close($config);
12310: }
12311:
12312: # -------------------------------------------- Read plain texts for permissions
12313: {
12314: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12315:
12316: while (my $configline=<$config>) {
12317: chomp($configline);
12318: if ($configline) {
12319: my ($short,@plain)=split(/:/,$configline);
12320: %{$prp{$short}} = ();
12321: if (@plain > 0) {
12322: $prp{$short}{'std'} = $plain[0];
12323: for (my $i=1; $i<@plain; $i++) {
12324: $prp{$short}{'alt'.$i} = $plain[$i];
12325: }
12326: }
12327: }
12328: }
12329: close($config);
12330: }
12331:
12332: # ---------------------------------------------------------- Read package table
12333: {
12334: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12335:
12336: while (my $configline=<$config>) {
12337: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12338: chomp($configline);
12339: my ($short,$plain)=split(/:/,$configline);
12340: my ($pack,$name)=split(/\&/,$short);
12341: if ($plain ne '') {
12342: $packagetab{$pack.'&'.$name.'&name'}=$name;
12343: $packagetab{$short}=$plain;
12344: }
12345: }
12346: close($config);
12347: }
12348:
12349: # ---------------------------------------------------------- Read loncaparev table
12350:
12351: &load_loncaparevs();
12352:
12353: # ---------------------------------------------------------- Read serverhostID table
12354:
12355: &load_serverhomeIDs();
12356:
12357: # ---------------------------------------------------------- Read releaseslist XML
12358: {
12359: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12360: if (-e $file) {
12361: my $parser = HTML::LCParser->new($file);
12362: while (my $token = $parser->get_token()) {
12363: if ($token->[0] eq 'S') {
12364: my $item = $token->[1];
12365: my $name = $token->[2]{'name'};
12366: my $value = $token->[2]{'value'};
12367: if ($item ne '' && $name ne '' && $value ne '') {
12368: my $release = $parser->get_text();
12369: $release =~ s/(^\s*|\s*$ )//gx;
12370: $needsrelease{$item.':'.$name.':'.$value} = $release;
12371: }
12372: }
12373: }
12374: }
12375: }
12376:
12377: # ---------------------------------------------------------- Read managers table
12378: {
12379: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12380: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12381: while (my $configline=<$config>) {
12382: chomp($configline);
12383: next if ($configline =~ /^\#/);
12384: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12385: $managerstab{$configline} = 1;
12386: }
12387: }
12388: close($config);
12389: }
12390: }
12391: }
12392:
12393: # ------------- set up temporary directory
12394: {
12395: $tmpdir = LONCAPA::tempdir();
12396:
12397: }
12398:
12399: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12400: 'compress_threshold'=> 20_000,
12401: });
12402:
12403: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12404: $dumpcount=0;
12405: $locknum=0;
12406:
12407: &logtouch();
12408: &logthis('<font color="yellow">INFO: Read configuration</font>');
12409: $readit=1;
12410: {
12411: use integer;
12412: my $test=(2**32)+1;
12413: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12414: &logthis(" Detected 64bit platform ($_64bit)");
12415: }
12416: }
12417: }
12418:
12419: 1;
12420: __END__
12421:
12422: =pod
12423:
12424: =head1 NAME
12425:
12426: Apache::lonnet - Subroutines to ask questions about things in the network.
12427:
12428: =head1 SYNOPSIS
12429:
12430: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12431:
12432: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12433:
12434: Common parameters:
12435:
12436: =over 4
12437:
12438: =item *
12439:
12440: $uname : an internal username (if $cname expecting a course Id specifically)
12441:
12442: =item *
12443:
12444: $udom : a domain (if $cdom expecting a course's domain specifically)
12445:
12446: =item *
12447:
12448: $symb : a resource instance identifier
12449:
12450: =item *
12451:
12452: $namespace : the name of a .db file that contains the data needed or
12453: being set.
12454:
12455: =back
12456:
12457: =head1 OVERVIEW
12458:
12459: lonnet provides subroutines which interact with the
12460: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12461: about classes, users, and resources.
12462:
12463: For many of these objects you can also use this to store data about
12464: them or modify them in various ways.
12465:
12466: =head2 Symbs
12467:
12468: To identify a specific instance of a resource, LON-CAPA uses symbols
12469: or "symbs"X<symb>. These identifiers are built from the URL of the
12470: map, the resource number of the resource in the map, and the URL of
12471: the resource itself. The latter is somewhat redundant, but might help
12472: if maps change.
12473:
12474: An example is
12475:
12476: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12477:
12478: The respective map entry is
12479:
12480: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12481: title="Problem 2">
12482: </resource>
12483:
12484: Symbs are used by the random number generator, as well as to store and
12485: restore data specific to a certain instance of for example a problem.
12486:
12487: =head2 Storing And Retrieving Data
12488:
12489: X<store()>X<cstore()>X<restore()>Three of the most important functions
12490: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12491: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12492: is is the non-critical message twin of cstore. These functions are for
12493: handlers to store a perl hash to a user's permanent data space in an
12494: easy manner, and to retrieve it again on another call. It is expected
12495: that a handler would use this once at the beginning to retrieve data,
12496: and then again once at the end to send only the new data back.
12497:
12498: The data is stored in the user's data directory on the user's
12499: homeserver under the ID of the course.
12500:
12501: The hash that is returned by restore will have all of the previous
12502: value for all of the elements of the hash.
12503:
12504: Example:
12505:
12506: #creating a hash
12507: my %hash;
12508: $hash{'foo'}='bar';
12509:
12510: #storing it
12511: &Apache::lonnet::cstore(\%hash);
12512:
12513: #changing a value
12514: $hash{'foo'}='notbar';
12515:
12516: #adding a new value
12517: $hash{'bar'}='foo';
12518: &Apache::lonnet::cstore(\%hash);
12519:
12520: #retrieving the hash
12521: my %history=&Apache::lonnet::restore();
12522:
12523: #print the hash
12524: foreach my $key (sort(keys(%history))) {
12525: print("\%history{$key} = $history{$key}");
12526: }
12527:
12528: Will print out:
12529:
12530: %history{1:foo} = bar
12531: %history{1:keys} = foo:timestamp
12532: %history{1:timestamp} = 990455579
12533: %history{2:bar} = foo
12534: %history{2:foo} = notbar
12535: %history{2:keys} = foo:bar:timestamp
12536: %history{2:timestamp} = 990455580
12537: %history{bar} = foo
12538: %history{foo} = notbar
12539: %history{timestamp} = 990455580
12540: %history{version} = 2
12541:
12542: Note that the special hash entries C<keys>, C<version> and
12543: C<timestamp> were added to the hash. C<version> will be equal to the
12544: total number of versions of the data that have been stored. The
12545: C<timestamp> attribute will be the UNIX time the hash was
12546: stored. C<keys> is available in every historical section to list which
12547: keys were added or changed at a specific historical revision of a
12548: hash.
12549:
12550: B<Warning>: do not store the hash that restore returns directly. This
12551: will cause a mess since it will restore the historical keys as if the
12552: were new keys. I.E. 1:foo will become 1:1:foo etc.
12553:
12554: Calling convention:
12555:
12556: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12557: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12558:
12559: For more detailed information, see lonnet specific documentation.
12560:
12561: =head1 RETURN MESSAGES
12562:
12563: =over 4
12564:
12565: =item * B<con_lost>: unable to contact remote host
12566:
12567: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12568: when the connection is brought back up
12569:
12570: =item * B<con_failed>: unable to contact remote host and unable to save message
12571: for later delivery
12572:
12573: =item * B<error:>: an error a occurred, a description of the error follows the :
12574:
12575: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12576: that was requested
12577:
12578: =back
12579:
12580: =head1 PUBLIC SUBROUTINES
12581:
12582: =head2 Session Environment Functions
12583:
12584: =over 4
12585:
12586: =item *
12587: X<appenv()>
12588: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12589: the user envirnoment file, and will be restored for each access this
12590: user makes during this session, also modifies the %env for the current
12591: process. Optional rolesarrayref - if defined contains a reference to an array
12592: of roles which are exempt from the restriction on modifying user.role entries
12593: in the user's environment.db and in %env.
12594:
12595: =item *
12596: X<delenv()>
12597: B<delenv($delthis,$regexp)>: removes all items from the session
12598: environment file that begin with $delthis. If the
12599: optional second arg - $regexp - is true, $delthis is treated as a
12600: regular expression, otherwise \Q$delthis\E is used.
12601: The values are also deleted from the current processes %env.
12602:
12603: =item * get_env_multiple($name)
12604:
12605: gets $name from the %env hash, it seemlessly handles the cases where multiple
12606: values may be defined and end up as an array ref.
12607:
12608: returns an array of values
12609:
12610: =back
12611:
12612: =head2 User Information
12613:
12614: =over 4
12615:
12616: =item *
12617: X<queryauthenticate()>
12618: B<queryauthenticate($uname,$udom)>: try to determine user's current
12619: authentication scheme
12620:
12621: =item *
12622: X<authenticate()>
12623: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12624: authenticate user from domain's lib servers (first use the current
12625: one). C<$upass> should be the users password.
12626: $checkdefauth is optional (value is 1 if a check should be made to
12627: authenticate user using default authentication method, and allow
12628: account creation if username does not have account in the domain).
12629: $clientcancheckhost is optional (value is 1 if checking whether the
12630: server can host will occur on the client side in lonauth.pm).
12631:
12632: =item *
12633: X<homeserver()>
12634: B<homeserver($uname,$udom)>: find the server which has
12635: the user's directory and files (there must be only one), this caches
12636: the answer, and also caches if there is a borken connection.
12637:
12638: =item *
12639: X<idget()>
12640: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12641: (IDs are a unique resource in a domain, there must be only 1 ID per
12642: username, and only 1 username per ID in a specific domain) (returns
12643: hash: id=>name,id=>name)
12644:
12645: =item *
12646: X<idrget()>
12647: B<idrget($udom,@unames)>: find the IDs behind a list of
12648: usernames (returns hash: name=>id,name=>id)
12649:
12650: =item *
12651: X<idput()>
12652: B<idput($udom,%ids)>: store away a list of names and associated IDs
12653:
12654: =item *
12655: X<rolesinit()>
12656: B<rolesinit($udom,$username)>: get user privileges.
12657: returns user role, first access and timer interval hashes
12658:
12659: =item *
12660: X<privileged()>
12661: B<privileged($username,$domain)>: returns a true if user has a
12662: privileged and active role (i.e. su or dc), false otherwise.
12663:
12664: =item *
12665: X<getsection()>
12666: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12667: course $cname, return section name/number or '' for "not in course"
12668: and '-1' for "no section"
12669:
12670: =item *
12671: X<userenvironment()>
12672: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12673: passed in @what from the requested user's environment, returns a hash
12674:
12675: =item *
12676: X<userlog_query()>
12677: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12678: activity.log file. %filters defines filters applied when parsing the
12679: log file. These can be start or end timestamps, or the type of action
12680: - log to look for Login or Logout events, check for Checkin or
12681: Checkout, role for role selection. The response is in the form
12682: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12683: escaped strings of the action recorded in the activity.log file.
12684:
12685: =back
12686:
12687: =head2 User Roles
12688:
12689: =over 4
12690:
12691: =item *
12692:
12693: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12694: F: full access
12695: U,I,K: authentication modes (cxx only)
12696: '': forbidden
12697: 1: user needs to choose course
12698: 2: browse allowed
12699: A: passphrase authentication needed
12700:
12701: =item *
12702:
12703: constructaccess($url,$setpriv) : check for access to construction space URL
12704:
12705: See if the owner domain and name in the URL match those in the
12706: expected environment. If so, return three element list
12707: ($ownername,$ownerdomain,$ownerhome).
12708:
12709: Otherwise return the null string.
12710:
12711: If second argument 'setpriv' is true, it assigns the privileges,
12712: and returns the same three element list, unless the owner has
12713: blocked "ad hoc" Domain Coordinator access to the Author Space,
12714: in which case the null string is returned.
12715:
12716: =item *
12717:
12718: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12719: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12720: and course level
12721:
12722: =item *
12723:
12724: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12725: (rolesplain.tab); plain text explanation of a user role term.
12726: $type is Course (default) or Community.
12727: If $forcedefault evaluates to true, text returned will be default
12728: text for $type. Otherwise, if this is a course, the text returned
12729: will be a custom name for the role (if defined in the course's
12730: environment). If no custom name is defined the default is returned.
12731:
12732: =item *
12733:
12734: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12735: All arguments are optional. Returns a hash of a roles, either for
12736: co-author/assistant author roles for a user's Construction Space
12737: (default), or if $context is 'userroles', roles for the user himself,
12738: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12739: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12740: For each key, value is set to colon-separated start and end times for
12741: the role. If no username and domain are specified, will default to
12742: current user/domain. Types, roles, and roledoms are references to arrays
12743: of role statuses (active, future or previous), roles
12744: (e.g., cc,in, st etc.) and domains of the roles which can be used
12745: to restrict the list of roles reported. If no array ref is
12746: provided for types, will default to return only active roles.
12747:
12748: =item *
12749:
12750: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12751: user: $uname:$udom has a role in the course: $cdom_$cnum.
12752:
12753: Additional optional arguments are: $type (if role checking is to be restricted
12754: to certain user status types -- previous (expired roles), active (currently
12755: available roles) or future (roles available in the future), and
12756: $hideprivileged -- if true will not report course roles for users who
12757: have active Domain Coordinator role in course's domain or in additional
12758: domains (specified in 'Domains to check for privileged users' in course
12759: environment -- set via: Course Settings -> Classlists and staff listing).
12760:
12761: =item *
12762:
12763: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12764: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12765: $possdomains and $possroles are optional array refs -- to domains to check and
12766: roles to check. If $possdomains is not specified, a dump will be done of the
12767: users' roles.db to check for a dc or su role in any domain. This can be
12768: time consuming if &privileged is called repeatedly (e.g., when displaying a
12769: classlist), so in such cases, supplying a $possdomains array is preferred, as
12770: this then allows &privileged_by_domain() to be used, which caches the identity
12771: of privileged users, eliminating the need for repeated calls to &dump().
12772:
12773: =item *
12774:
12775: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12776: where the outer hash keys are domains specified in the $possdomains array ref,
12777: next inner hash keys are privileged roles specified in the $roles array ref,
12778: and the innermost hash contains key = value pairs for username:domain = end:start
12779: for active or future "privileged" users with that role in that domain. To avoid
12780: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12781: innerhash are cached using priv_$role and $dom as the identifiers.
12782:
12783: =back
12784:
12785: =head2 User Modification
12786:
12787: =over 4
12788:
12789: =item *
12790:
12791: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12792: user for the level given by URL. Optional start and end dates (leave empty
12793: string or zero for "no date")
12794:
12795: =item *
12796:
12797: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12798: change a users, password, possible return values are: ok,
12799: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12800: refused
12801:
12802: =item *
12803:
12804: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12805:
12806: =item *
12807:
12808: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12809: $forceid,$desiredhome,$email,$inststatus,$candelete) :
12810:
12811: will update user information (firstname,middlename,lastname,generation,
12812: permanentemail), and if forceid is true, student/employee ID also.
12813: A user's institutional affiliation(s) can also be updated.
12814: User information fields will not be overwritten with empty entries
12815: unless the field is included in the $candelete array reference.
12816: This array is included when a single user is modified via "Manage Users",
12817: or when Autoupdate.pl is run by cron in a domain.
12818:
12819: =item *
12820:
12821: modifystudent
12822:
12823: modify a student's enrollment and identification information.
12824: The course id is resolved based on the current user's environment.
12825: This means the invoking user must be a course coordinator or otherwise
12826: associated with a course.
12827:
12828: This call is essentially a wrapper for lonnet::modifyuser and
12829: lonnet::modify_student_enrollment
12830:
12831: Inputs:
12832:
12833: =over 4
12834:
12835: =item B<$udom> Student's loncapa domain
12836:
12837: =item B<$uname> Student's loncapa login name
12838:
12839: =item B<$uid> Student/Employee ID
12840:
12841: =item B<$umode> Student's authentication mode
12842:
12843: =item B<$upass> Student's password
12844:
12845: =item B<$first> Student's first name
12846:
12847: =item B<$middle> Student's middle name
12848:
12849: =item B<$last> Student's last name
12850:
12851: =item B<$gene> Student's generation
12852:
12853: =item B<$usec> Student's section in course
12854:
12855: =item B<$end> Unix time of the roles expiration
12856:
12857: =item B<$start> Unix time of the roles start date
12858:
12859: =item B<$forceid> If defined, allow $uid to be changed
12860:
12861: =item B<$desiredhome> server to use as home server for student
12862:
12863: =item B<$email> Student's permanent e-mail address
12864:
12865: =item B<$type> Type of enrollment (auto or manual)
12866:
12867: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
12868:
12869: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12870:
12871: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12872:
12873: =item B<$context> role change context (shown in User Management Logs display in a course)
12874:
12875: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12876:
12877: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
12878:
12879: =back
12880:
12881: =item *
12882:
12883: modify_student_enrollment
12884:
12885: Change a student's enrollment status in a class. The environment variable
12886: 'role.request.course' must be defined for this function to proceed.
12887:
12888: Inputs:
12889:
12890: =over 4
12891:
12892: =item $udom, student's domain
12893:
12894: =item $uname, student's name
12895:
12896: =item $uid, student's user id
12897:
12898: =item $first, student's first name
12899:
12900: =item $middle
12901:
12902: =item $last
12903:
12904: =item $gene
12905:
12906: =item $usec
12907:
12908: =item $end
12909:
12910: =item $start
12911:
12912: =item $type
12913:
12914: =item $locktype
12915:
12916: =item $cid
12917:
12918: =item $selfenroll
12919:
12920: =item $context
12921:
12922: =item $credits, number of credits student will earn from this class
12923:
12924: =back
12925:
12926:
12927: =item *
12928:
12929: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12930: custom role; give a custom role to a user for the level given by URL. Specify
12931: name and domain of role author, and role name
12932:
12933: =item *
12934:
12935: revokerole($udom,$uname,$url,$role) : revoke a role for url
12936:
12937: =item *
12938:
12939: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12940:
12941: =back
12942:
12943: =head2 Course Infomation
12944:
12945: =over 4
12946:
12947: =item *
12948:
12949: coursedescription($courseid,$options) : returns a hash of information about the
12950: specified course id, including all environment settings for the
12951: course, the description of the course will be in the hash under the
12952: key 'description'
12953:
12954: $options is an optional parameter that if supplied is a hash reference that controls
12955: what how this function works. It has the following key/values:
12956:
12957: =over 4
12958:
12959: =item freshen_cache
12960:
12961: If defined, and the environment cache for the course is valid, it is
12962: returned in the returned hash.
12963:
12964: =item one_time
12965:
12966: If defined, the last cache time is set to _now_
12967:
12968: =item user
12969:
12970: If defined, the supplied username is used instead of the current user.
12971:
12972:
12973: =back
12974:
12975: =item *
12976:
12977: resdata($name,$domain,$type,@which) : request for current parameter
12978: setting for a specific $type, where $type is either 'course' or 'user',
12979: @what should be a list of parameters to ask about. This routine caches
12980: answers for 10 minutes.
12981:
12982: =item *
12983:
12984: get_courseresdata($courseid, $domain) : dump the entire course resource
12985: data base, returning a hash that is keyed by the resource name and has
12986: values that are the resource value. I believe that the timestamps and
12987: versions are also returned.
12988:
12989: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12990: supplemental content area. This routine caches the number of files for
12991: 10 minutes.
12992:
12993: =back
12994:
12995: =head2 Course Modification
12996:
12997: =over 4
12998:
12999: =item *
13000:
13001: writecoursepref($courseid,%prefs) : write preferences (environment
13002: database) for a course
13003:
13004: =item *
13005:
13006: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13007:
13008: =item *
13009:
13010: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
13011:
13012: =item *
13013:
13014: is_course($courseid), is_course($cdom, $cnum)
13015:
13016: Accepts either a combined $courseid (in the form of domain_courseid) or the
13017: two component version $cdom, $cnum. It checks if the specified course exists.
13018:
13019: Returns:
13020: undef if the course doesn't exist, otherwise
13021: in scalar context the combined courseid.
13022: in list context the two components of the course identifier, domain and
13023: courseid.
13024:
13025: =back
13026:
13027: =head2 Resource Subroutines
13028:
13029: =over 4
13030:
13031: =item *
13032:
13033: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
13034:
13035: =item *
13036:
13037: repcopy($filename) : subscribes to the requested file, and attempts to
13038: replicate from the owning library server, Might return
13039: 'unavailable', 'not_found', 'forbidden', 'ok', or
13040: 'bad_request', also attempts to grab the metadata for the
13041: resource. Expects the local filesystem pathname
13042: (/home/httpd/html/res/....)
13043:
13044: =back
13045:
13046: =head2 Resource Information
13047:
13048: =over 4
13049:
13050: =item *
13051:
13052: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13053: and returns the value of a variety of different possible values,
13054: $varname should be a request string, and the other parameters can be
13055: used to specify who and what one is asking about. Ordinarily, $cid
13056: does not need to be specified, as it is retrived from
13057: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13058: within lonuserstate::loadmap() when initializing a course, before
13059: $env{'request.course.id'} has been set, so it needs to be provided
13060: in that one case.
13061:
13062: Possible values for $varname are environment.lastname (or other item
13063: from the envirnment hash), user.name (or someother aspect about the
13064: user), resource.0.maxtries (or some other part and parameter of a
13065: resource)
13066:
13067: =item *
13068:
13069: directcondval($number) : get current value of a condition; reads from a state
13070: string
13071:
13072: =item *
13073:
13074: condval($condidx) : value of condition index based on state
13075:
13076: =item *
13077:
13078: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13079: resource's metadata, $what should be either a specific key, or either
13080: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13081: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13082:
13083: this function automatically caches all requests
13084:
13085: =item *
13086:
13087: metadata_query($query,$custom,$customshow) : make a metadata query against the
13088: network of library servers; returns file handle of where SQL and regex results
13089: will be stored for query
13090:
13091: =item *
13092:
13093: symbread($filename) : return symbolic list entry (filename argument optional);
13094: returns the data handle
13095:
13096: =item *
13097:
13098: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13099: and is a possible symb for the URL in $thisfn, and if is an encrypted
13100: resource that the user accessed using /enc/ returns a 1 on success, 0
13101: on failure, user must be in a course, as it assumes the existence of
13102: the course initial hash, and uses $env('request.course.id'}. The third
13103: arg is an optional reference to a scalar. If this arg is passed in the
13104: call to symbverify, it will be set to 1 if the symb has been set to be
13105: encrypted; otherwise it will be null.
13106:
13107: =item *
13108:
13109: symbclean($symb) : removes versions numbers from a symb, returns the
13110: cleaned symb
13111:
13112: =item *
13113:
13114: is_on_map($uri) : checks if the $uri is somewhere on the current
13115: course map, user must be in a course for it to work.
13116:
13117: =item *
13118:
13119: numval($salt) : return random seed value (addend for rndseed)
13120:
13121: =item *
13122:
13123: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13124: a random seed, all arguments are optional, if they aren't sent it uses the
13125: environment to derive them. Note: if symb isn't sent and it can't get one
13126: from &symbread it will use the current time as its return value
13127:
13128: =item *
13129:
13130: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13131: unfakeable, receipt
13132:
13133: =item *
13134:
13135: receipt() : API to ireceipt working off of env values; given out to users
13136:
13137: =item *
13138:
13139: countacc($url) : count the number of accesses to a given URL
13140:
13141: =item *
13142:
13143: checkout($symb,$tuname,$tudom,$tcrsid) : creates a record of a user having looked at an item, most likely printed out or otherwise using a resource
13144:
13145: =item *
13146:
13147: checkin($token) : updates that a resource has beeen returned (a hard copy version for instance) and returns the data that $token was Checkout with ($symb, $tuname, $tudom, and $tcrsid)
13148:
13149: =item *
13150:
13151: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13152:
13153: =item *
13154:
13155: devalidate($symb) : devalidate temporary spreadsheet calculations,
13156: forcing spreadsheet to reevaluate the resource scores next time.
13157:
13158: =item *
13159:
13160: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13161: when viewing in course context.
13162:
13163: input: six args -- filename (decluttered), course number, course domain,
13164: url, symb (if registered) and group (if this is a
13165: group item -- e.g., bulletin board, group page etc.).
13166:
13167: output: array of five scalars --
13168: $cfile -- url for file editing if editable on current server
13169: $home -- homeserver of resource (i.e., for author if published,
13170: or course if uploaded.).
13171: $switchserver -- 1 if server switch will be needed.
13172: $forceedit -- 1 if icon/link should be to go to edit mode
13173: $forceview -- 1 if icon/link should be to go to view mode
13174:
13175: =item *
13176:
13177: is_course_upload($file,$cnum,$cdom)
13178:
13179: Used in course context to determine if current file was uploaded to
13180: the course (i.e., would be found in /userfiles/docs on the course's
13181: homeserver.
13182:
13183: input: 3 args -- filename (decluttered), course number and course domain.
13184: output: boolean -- 1 if file was uploaded.
13185:
13186: =back
13187:
13188: =head2 Storing/Retreiving Data
13189:
13190: =over 4
13191:
13192: =item *
13193:
13194: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13195: for this url; hashref needs to be given and should be a \%hashname; the
13196: remaining args aren't required and if they aren't passed or are '' they will
13197: be derived from the env
13198:
13199: =item *
13200:
13201: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13202: uses critical subroutine
13203:
13204: =item *
13205:
13206: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13207: all args are optional
13208:
13209: =item *
13210:
13211: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13212: dumps the complete (or key matching regexp) namespace into a hash
13213: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13214: normally &store()ed into
13215:
13216: $range should be either an integer '100' (give me the first 100
13217: matching records)
13218: or be two integers sperated by a - with no spaces
13219: '30-50' (give me the 30th through the 50th matching
13220: records)
13221:
13222:
13223: =item *
13224:
13225: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13226: replaces a &store() version of data with a replacement set of data
13227: for a particular resource in a namespace passed in the $storehash hash
13228: reference
13229:
13230: =item *
13231:
13232: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13233: works very similar to store/cstore, but all data is stored in a
13234: temporary location and can be reset using tmpreset, $storehash should
13235: be a hash reference, returns nothing on success
13236:
13237: =item *
13238:
13239: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13240: similar to restore, but all data is stored in a temporary location and
13241: can be reset using tmpreset. Returns a hash of values on success,
13242: error string otherwise.
13243:
13244: =item *
13245:
13246: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13247: deltes all keys for $symb form the temporary storage hash.
13248:
13249: =item *
13250:
13251: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13252: reference filled in from namesp ($udom and $uname are optional)
13253:
13254: =item *
13255:
13256: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13257: namesp ($udom and $uname are optional)
13258:
13259: =item *
13260:
13261: dump($namespace,$udom,$uname,$regexp,$range) :
13262: dumps the complete (or key matching regexp) namespace into a hash
13263: ($udom, $uname, $regexp, $range are optional)
13264:
13265: $range should be either an integer '100' (give me the first 100
13266: matching records)
13267: or be two integers sperated by a - with no spaces
13268: '30-50' (give me the 30th through the 50th matching
13269: records)
13270: =item *
13271:
13272: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13273: $store can be a scalar, an array reference, or if the amount to be
13274: incremented is > 1, a hash reference.
13275:
13276: ($udom and $uname are optional)
13277:
13278: =item *
13279:
13280: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13281: ($udom and $uname are optional)
13282:
13283: =item *
13284:
13285: cput($namespace,$storehash,$udom,$uname) : critical put
13286: ($udom and $uname are optional)
13287:
13288: =item *
13289:
13290: newput($namespace,$storehash,$udom,$uname) :
13291:
13292: Attempts to store the items in the $storehash, but only if they don't
13293: currently exist, if this succeeds you can be certain that you have
13294: successfully created a new key value pair in the $namespace db.
13295:
13296:
13297: Args:
13298: $namespace: name of database to store values to
13299: $storehash: hashref to store to the db
13300: $udom: (optional) domain of user containing the db
13301: $uname: (optional) name of user caontaining the db
13302:
13303: Returns:
13304: 'ok' -> succeeded in storing all keys of $storehash
13305: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13306: least <key> already existed in the db (other
13307: requested keys may also already exist)
13308: 'error: <msg>' -> unable to tie the DB or other error occurred
13309: 'con_lost' -> unable to contact request server
13310: 'refused' -> action was not allowed by remote machine
13311:
13312:
13313: =item *
13314:
13315: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13316: reference filled in from namesp (encrypts the return communication)
13317: ($udom and $uname are optional)
13318:
13319: =item *
13320:
13321: log($udom,$name,$home,$message) : write to permanent log for user; use
13322: critical subroutine
13323:
13324: =item *
13325:
13326: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13327: array reference filled in from namespace found in domain level on either
13328: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13329:
13330: =item *
13331:
13332: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13333: domain level either on specified domain server ($uhome) or primary domain
13334: server ($udom and $uhome are optional)
13335:
13336: =item *
13337:
13338: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13339: for: authentication, language, quotas, timezone, date locale, and portal URL in
13340: the target domain.
13341:
13342: May also include additional key => value pairs for the following groups:
13343:
13344: =over
13345:
13346: =item
13347: disk quotas (MB allocated by default to portfolios and authoring spaces).
13348:
13349: =over
13350:
13351: =item defaultquota, authorquota
13352:
13353: =back
13354:
13355: =item
13356: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13357: portfolio for users).
13358:
13359: =over
13360:
13361: =item
13362: aboutme, blog, webdav, portfolio
13363:
13364: =back
13365:
13366: =item
13367: requestcourses: ability to request courses, and how requests are processed.
13368:
13369: =over
13370:
13371: =item
13372: official, unofficial, community, textbook
13373:
13374: =back
13375:
13376: =item
13377: inststatus: types of institutional affiliation, and order in which they are displayed.
13378:
13379: =over
13380:
13381: =item
13382: inststatustypes, inststatusorder, inststatusguest
13383:
13384: =back
13385:
13386: =item
13387: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13388: for course's uploaded content.
13389:
13390: =over
13391:
13392: =item
13393: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13394: communityquota, textbookquota
13395:
13396: =back
13397:
13398: =item
13399: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13400: on your servers.
13401:
13402: =over
13403:
13404: =item
13405: remotesessions, hostedsessions
13406:
13407: =back
13408:
13409: =back
13410:
13411: In cases where a domain coordinator has never used the "Set Domain Configuration"
13412: utility to create a configuration.db file on a domain's primary library server
13413: only the following domain defaults: auth_def, auth_arg_def, lang_def
13414: -- corresponding values are authentication type (internal, krb4, krb5,
13415: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13416: will be available. Values are retrieved from cache (if current), unless the
13417: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13418: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13419:
13420: Typical usage:
13421:
13422: %domdefaults = &get_domain_defaults($target_domain);
13423:
13424: =back
13425:
13426: =head2 Network Status Functions
13427:
13428: =over 4
13429:
13430: =item *
13431:
13432: dirlist() : return directory list based on URI (first arg).
13433:
13434: Inputs: 1 required, 5 optional.
13435:
13436: =over
13437:
13438: =item
13439: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13440:
13441: =item
13442: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13443:
13444: =item
13445: $username - username of user/course to be listed. Extracted from $uri if absent.
13446:
13447: =item
13448: $getpropath - boolean: 1 if prepend path using &propath().
13449:
13450: =item
13451: $getuserdir - boolean: 1 if prepend path for "userfiles".
13452:
13453: =item
13454: $alternateRoot - path to prepend in place of path from $uri.
13455:
13456: =back
13457:
13458: Returns: Array of up to two items.
13459:
13460: =over
13461:
13462: a reference to an array of files/subdirectories
13463:
13464: =over
13465:
13466: Each element in the array of files/subdirectories is a & separated list of
13467: item name and the result of running stat on the item. If dirlist was requested
13468: for a file instead of a directory, the item name will be ''. For a directory
13469: listing, if the item is a metadata file, the element will end &N&M
13470: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13471: default copyright set (1).
13472:
13473: =back
13474:
13475: a scalar containing error condition (if encountered).
13476:
13477: =over
13478:
13479: =item
13480: no_host (no homeserver identified for $username:$domain).
13481:
13482: =item
13483: no_such_host (server contacted for listing not identified as valid host).
13484:
13485: =item
13486: con_lost (connection to remote server failed).
13487:
13488: =item
13489: refused (invalid $username:$domain received on lond side).
13490:
13491: =item
13492: no_such_dir (directory at specified path on lond side does not exist).
13493:
13494: =item
13495: empty (directory at specified path on lond side is empty).
13496:
13497: =over
13498:
13499: This is currently not encountered because the &ls3, &ls2,
13500: &ls (_handler) routines on the lond side do not filter out
13501: . and .. from a directory listing.
13502:
13503: =back
13504:
13505: =back
13506:
13507: =back
13508:
13509: =item *
13510:
13511: spareserver() : find server with least workload from spare.tab
13512:
13513:
13514: =item *
13515:
13516: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13517: if there is no corresponding loncapa host.
13518:
13519: =back
13520:
13521:
13522: =head2 Apache Request
13523:
13524: =over 4
13525:
13526: =item *
13527:
13528: ssi($url,%hash) : server side include, does a complete request cycle on url to
13529: localhost, posts hash
13530:
13531: =back
13532:
13533: =head2 Data to String to Data
13534:
13535: =over 4
13536:
13537: =item *
13538:
13539: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13540: and '&' separators, supports elements that are arrayrefs and hashrefs
13541:
13542: =item *
13543:
13544: hashref2str($hashref) : convert a hashref into a string complete with
13545: escaping and '=' and '&' separators, supports elements that are
13546: arrayrefs and hashrefs
13547:
13548: =item *
13549:
13550: arrayref2str($arrayref) : convert an arrayref into a string complete
13551: with escaping and '&' separators, supports elements that are arrayrefs
13552: and hashrefs
13553:
13554: =item *
13555:
13556: str2hash($string) : convert string to hash using unescaping and
13557: splitting on '=' and '&', supports elements that are arrayrefs and
13558: hashrefs
13559:
13560: =item *
13561:
13562: str2array($string) : convert string to hash using unescaping and
13563: splitting on '&', supports elements that are arrayrefs and hashrefs
13564:
13565: =back
13566:
13567: =head2 Logging Routines
13568:
13569:
13570: These routines allow one to make log messages in the lonnet.log and
13571: lonnet.perm logfiles.
13572:
13573: =over 4
13574:
13575: =item *
13576:
13577: logtouch() : make sure the logfile, lonnet.log, exists
13578:
13579: =item *
13580:
13581: logthis() : append message to the normal lonnet.log file, it gets
13582: preiodically rolled over and deleted.
13583:
13584: =item *
13585:
13586: logperm() : append a permanent message to lonnet.perm.log, this log
13587: file never gets deleted by any automated portion of the system, only
13588: messages of critical importance should go in here.
13589:
13590:
13591: =back
13592:
13593: =head2 General File Helper Routines
13594:
13595: =over 4
13596:
13597: =item *
13598:
13599: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13600: (a) files in /uploaded
13601: (i) If a local copy of the file exists -
13602: compares modification date of local copy with last-modified date for
13603: definitive version stored on home server for course. If local copy is
13604: stale, requests a new version from the home server and stores it.
13605: If the original has been removed from the home server, then local copy
13606: is unlinked.
13607: (ii) If local copy does not exist -
13608: requests the file from the home server and stores it.
13609:
13610: If $caller is 'uploadrep':
13611: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13612: for request for files originally uploaded via DOCS.
13613: - returns 'ok' if fresh local copy now available, -1 otherwise.
13614:
13615: Otherwise:
13616: This indicates a call from the content generation phase of the request.
13617: - returns the entire contents of the file or -1.
13618:
13619: (b) files in /res
13620: - returns the entire contents of a file or -1;
13621: it properly subscribes to and replicates the file if neccessary.
13622:
13623:
13624: =item *
13625:
13626: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13627: reference
13628:
13629: returns either a stat() list of data about the file or an empty list
13630: if the file doesn't exist or couldn't find out about it (connection
13631: problems or user unknown)
13632:
13633: =item *
13634:
13635: filelocation($dir,$file) : returns file system location of a file
13636: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13637: directory that relative $file lookups are to looked in ($dir of /a/dir
13638: and a file of ../bob will become /a/bob)
13639:
13640: =item *
13641:
13642: hreflocation($dir,$file) : returns file system location or a URL; same as
13643: filelocation except for hrefs
13644:
13645: =item *
13646:
13647: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
13648: also removes beginning /home/httpd/html unless /priv/ follows it.
13649:
13650: =back
13651:
13652: =head2 Usererfile file routines (/uploaded*)
13653:
13654: =over 4
13655:
13656: =item *
13657:
13658: userfileupload(): main rotine for putting a file in a user or course's
13659: filespace, arguments are,
13660:
13661: formname - required - this is the name of the element in $env where the
13662: filename, and the contents of the file to create/modifed exist
13663: the filename is in $env{'form.'.$formname.'.filename'} and the
13664: contents of the file is located in $env{'form.'.$formname}
13665: context - if coursedoc, store the file in the course of the active role
13666: of the current user;
13667: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13668: if 'canceloverwrite': delete file in tmp/overwrites directory
13669: subdir - required - subdirectory to put the file in under ../userfiles/
13670: if undefined, it will be placed in "unknown"
13671:
13672: (This routine calls clean_filename() to remove any dangerous
13673: characters from the filename, and then calls finuserfileupload() to
13674: complete the transaction)
13675:
13676: returns either the url of the uploaded file (/uploaded/....) if successful
13677: and /adm/notfound.html if unsuccessful
13678:
13679: =item *
13680:
13681: clean_filename(): routine for cleaing a filename up for storage in
13682: userfile space, argument is:
13683:
13684: filename - proposed filename
13685:
13686: returns: the new clean filename
13687:
13688: =item *
13689:
13690: finishuserfileupload(): routine that creates and sends the file to
13691: userspace, probably shouldn't be called directly
13692:
13693: docuname: username or courseid of destination for the file
13694: docudom: domain of user/course of destination for the file
13695: formname: same as for userfileupload()
13696: fname: filename (including subdirectories) for the file
13697: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13698: allfiles: reference to hash used to store objects found by parser
13699: codebase: reference to hash used for codebases of java objects found by parser
13700: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13701: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13702: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13703: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13704: context: if 'overwrite', will move the uploaded file from its temporary location to
13705: userfiles to facilitate overwriting a previously uploaded file with same name.
13706: mimetype: reference to scalar to accommodate mime type determined
13707: from File::MMagic if $parser = parse.
13708:
13709: returns either the url of the uploaded file (/uploaded/....) if successful
13710: and /adm/notfound.html if unsuccessful (or an error message if context
13711: was 'overwrite').
13712:
13713:
13714: =item *
13715:
13716: renameuserfile(): renames an existing userfile to a new name
13717:
13718: Args:
13719: docuname: username or courseid of destination for the file
13720: docudom: domain of user/course of destination for the file
13721: old: current file name (including any subdirs under userfiles)
13722: new: desired file name (including any subdirs under userfiles)
13723:
13724: =item *
13725:
13726: mkdiruserfile(): creates a directory is a userfiles dir
13727:
13728: Args:
13729: docuname: username or courseid of destination for the file
13730: docudom: domain of user/course of destination for the file
13731: dir: dir to create (including any subdirs under userfiles)
13732:
13733: =item *
13734:
13735: removeuserfile(): removes a file that exists in userfiles
13736:
13737: Args:
13738: docuname: username or courseid of destination for the file
13739: docudom: domain of user/course of destination for the file
13740: fname: filname to delete (including any subdirs under userfiles)
13741:
13742: =item *
13743:
13744: removeuploadedurl(): convience function for removeuserfile()
13745:
13746: Args:
13747: url: a full /uploaded/... url to delete
13748:
13749: =item *
13750:
13751: get_portfile_permissions():
13752: Args:
13753: domain: domain of user or course contain the portfolio files
13754: user: name of user or num of course contain the portfolio files
13755: Returns:
13756: hashref of a dump of the proper file_permissions.db
13757:
13758:
13759: =item *
13760:
13761: get_access_controls():
13762:
13763: Args:
13764: current_permissions: the hash ref returned from get_portfile_permissions()
13765: group: (optional) the group you want the files associated with
13766: file: (optional) the file you want access info on
13767:
13768: Returns:
13769: a hash (keys are file names) of hashes containing
13770: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13771: values are XML containing access control settings (see below)
13772:
13773: Internal notes:
13774:
13775: access controls are stored in file_permissions.db as key=value pairs.
13776: key -> path to file/file_name\0uniqueID:scope_end_start
13777: where scope -> public,guest,course,group,domains or users.
13778: end -> UNIX time for end of access (0 -> no end date)
13779: start -> UNIX time for start of access
13780:
13781: value -> XML description of access control
13782: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13783: <start></start>
13784: <end></end>
13785:
13786: <password></password> for scope type = guest
13787:
13788: <domain></domain> for scope type = course or group
13789: <number></number>
13790: <roles id="">
13791: <role></role>
13792: <access></access>
13793: <section></section>
13794: <group></group>
13795: </roles>
13796:
13797: <dom></dom> for scope type = domains
13798:
13799: <users> for scope type = users
13800: <user>
13801: <uname></uname>
13802: <udom></udom>
13803: </user>
13804: </users>
13805: </scope>
13806:
13807: Access data is also aggregated for each file in an additional key=value pair:
13808: key -> path to file/file_name\0accesscontrol
13809: value -> reference to hash
13810: hash contains key = value pairs
13811: where key = uniqueID:scope_end_start
13812: value = UNIX time record was last updated
13813:
13814: Used to improve speed of look-ups of access controls for each file.
13815:
13816: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13817:
13818: =item *
13819:
13820: modify_access_controls():
13821:
13822: Modifies access controls for a portfolio file
13823: Args
13824: 1. file name
13825: 2. reference to hash of required changes,
13826: 3. domain
13827: 4. username
13828: where domain,username are the domain of the portfolio owner
13829: (either a user or a course)
13830:
13831: Returns:
13832: 1. result of additions or updates ('ok' or 'error', with error message).
13833: 2. result of deletions ('ok' or 'error', with error message).
13834: 3. reference to hash of any new or updated access controls.
13835: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13836: key = integer (inbound ID)
13837: value = uniqueID
13838:
13839: =item *
13840:
13841: get_timebased_id():
13842:
13843: Attempts to get a unique timestamp-based suffix for use with items added to a
13844: course via the Course Editor (e.g., folders, composite pages,
13845: group bulletin boards).
13846:
13847: Args: (first three required; six others optional)
13848:
13849: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13850: docssequence, or name of group
13851:
13852: 2. keyid (alphanumeric): name of temporary locking key in hash,
13853: e.g., num, boardids
13854:
13855: 3. namespace: name of gdbm file used to store suffixes already assigned;
13856: file will be named nohist_namespace.db
13857:
13858: 4. cdom: domain of course; default is current course domain from %env
13859:
13860: 5. cnum: course number; default is current course number from %env
13861:
13862: 6. idtype: set to concat if an additional digit is to be appended to the
13863: unix timestamp to form the suffix, if the plain timestamp is already
13864: in use. Default is to not do this, but simply increment the unix
13865: timestamp by 1 until a unique key is obtained.
13866:
13867: 7. who: holder of locking key; defaults to user:domain for user.
13868:
13869: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13870: retrying); default is 3.
13871:
13872: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13873:
13874: Returns:
13875:
13876: 1. suffix obtained (numeric)
13877:
13878: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13879:
13880: 3. error: contains (localized) error message if an error occurred.
13881:
13882:
13883: =back
13884:
13885: =head2 HTTP Helper Routines
13886:
13887: =over 4
13888:
13889: =item *
13890:
13891: escape() : unpack non-word characters into CGI-compatible hex codes
13892:
13893: =item *
13894:
13895: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13896:
13897: =back
13898:
13899: =head1 PRIVATE SUBROUTINES
13900:
13901: =head2 Underlying communication routines (Shouldn't call)
13902:
13903: =over 4
13904:
13905: =item *
13906:
13907: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13908:
13909: =item *
13910:
13911: reply() : uses subreply to send a message to remote machine, logs all failures
13912:
13913: =item *
13914:
13915: critical() : passes a critical message to another server; if cannot
13916: get through then place message in connection buffer directory and
13917: returns con_delayed, if incapable of saving message, returns
13918: con_failed
13919:
13920: =item *
13921:
13922: reconlonc() : tries to reconnect lonc client processes.
13923:
13924: =back
13925:
13926: =head2 Resource Access Logging
13927:
13928: =over 4
13929:
13930: =item *
13931:
13932: flushcourselogs() : flush (save) buffer logs and access logs
13933:
13934: =item *
13935:
13936: courselog($what) : save message for course in hash
13937:
13938: =item *
13939:
13940: courseacclog($what) : save message for course using &courselog(). Perform
13941: special processing for specific resource types (problems, exams, quizzes, etc).
13942:
13943: =item *
13944:
13945: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13946: as a PerlChildExitHandler
13947:
13948: =back
13949:
13950: =head2 Other
13951:
13952: =over 4
13953:
13954: =item *
13955:
13956: symblist($mapname,%newhash) : update symbolic storage links
13957:
13958: =back
13959:
13960: =cut
13961:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>