Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1082
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1082 ! raeburn 4: # $Id: lonnet.pm,v 1.1081 2010/08/17 22:22:05 raeburn Exp $
1.178 www 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: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 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:
1.971 jms 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:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1079 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.1024 raeburn 95: use File::MMagic;
1.807 albertel 96: use LONCAPA qw(:DEFAULT :match);
1.740 www 97: use LONCAPA::Configuration;
1.676 albertel 98:
1.195 www 99: my $readit;
1.550 foxr 100: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 101:
1.619 albertel 102: require Exporter;
103:
104: our @ISA = qw (Exporter);
105: our @EXPORT = qw(%env);
106:
1.449 matthew 107:
1.1 albertel 108: # --------------------------------------------------------------------- Logging
1.729 www 109: {
110: my $logid;
111: sub instructor_log {
1.957 raeburn 112: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
113: if (($cnum eq '') || ($cdom eq '')) {
114: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
115: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
116: }
1.729 www 117: $logid++;
1.957 raeburn 118: my $now = time();
119: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 120: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 121: { $id => {
122: 'exe_uname' => $env{'user.name'},
123: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 124: 'exe_time' => $now,
1.730 www 125: 'exe_ip' => $ENV{'REMOTE_ADDR'},
126: 'delflag' => $delflag,
127: 'logentry' => $storehash,
128: 'uname' => $uname,
129: 'udom' => $udom,
130: }
1.957 raeburn 131: },$cdom,$cnum);
1.729 www 132: }
133: }
1.1 albertel 134:
1.163 harris41 135: sub logtouch {
136: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 137: unless (-e "$execdir/logs/lonnet.log") {
138: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 139: close $fh;
140: }
141: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
142: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
143: }
144:
1.1 albertel 145: sub logthis {
146: my $message=shift;
147: my $execdir=$perlvar{'lonDaemons'};
148: my $now=time;
149: my $local=localtime($now);
1.448 albertel 150: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 151: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
152: print $fh $logstring;
1.448 albertel 153: close($fh);
154: }
1.1 albertel 155: return 1;
156: }
157:
158: sub logperm {
159: my $message=shift;
160: my $execdir=$perlvar{'lonDaemons'};
161: my $now=time;
162: my $local=localtime($now);
1.448 albertel 163: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
164: print $fh "$now:$message:$local\n";
165: close($fh);
166: }
1.1 albertel 167: return 1;
168: }
169:
1.850 albertel 170: sub create_connection {
1.853 albertel 171: my ($hostname,$lonid) = @_;
1.851 albertel 172: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 173: Type => SOCK_STREAM,
174: Timeout => 10);
175: return 0 if (!$client);
1.890 albertel 176: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 177: my $result = <$client>;
178: chomp($result);
179: return 1 if ($result eq 'done');
180: return 0;
181: }
182:
1.983 raeburn 183: sub get_server_timezone {
184: my ($cnum,$cdom) = @_;
185: my $home=&homeserver($cnum,$cdom);
186: if ($home ne 'no_host') {
187: my $cachetime = 24*3600;
188: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
189: if (defined($cached)) {
190: return $timezone;
191: } else {
192: my $timezone = &reply('servertimezone',$home);
193: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
194: }
195: }
196: }
1.850 albertel 197:
1.993 raeburn 198: sub get_server_loncaparev {
1.1073 raeburn 199: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 200: if (defined($lonhost)) {
201: if (!defined(&hostname($lonhost))) {
202: undef($lonhost);
203: }
204: }
205: if (!defined($lonhost)) {
206: if (defined(&domain($dom,'primary'))) {
207: $lonhost=&domain($dom,'primary');
208: if ($lonhost eq 'no_host') {
209: undef($lonhost);
210: }
211: }
212: }
213: if (defined($lonhost)) {
1.1073 raeburn 214: my $cachetime = 12*3600;
215: if (!$ignore_cache) {
216: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
217: if (defined($cached)) {
218: return $loncaparev;
219: }
220: }
221: my ($answer,$loncaparev);
222: my @ids=¤t_machine_ids();
223: if (grep(/^\Q$lonhost\E$/,@ids)) {
224: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 225: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 226: $loncaparev = $1;
227: }
228: } else {
229: $answer = &reply('serverloncaparev',$lonhost);
230: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
231: if ($caller eq 'loncron') {
232: my $ua=new LWP::UserAgent;
1.1082 ! raeburn 233: $ua->timeout(4);
1.1073 raeburn 234: my $protocol = $protocol{$lonhost};
235: $protocol = 'http' if ($protocol ne 'https');
236: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
237: my $request=new HTTP::Request('GET',$url);
238: my $response=$ua->request($request);
239: unless ($response->is_error()) {
240: my $content = $response->content;
1.1081 raeburn 241: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 242: $loncaparev = $1;
243: }
244: }
245: } else {
246: $loncaparev = $loncaparevs{$lonhost};
247: }
1.1081 raeburn 248: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 249: $loncaparev = $1;
250: }
1.993 raeburn 251: }
1.1073 raeburn 252: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 253: }
254: }
255:
1.1074 raeburn 256: sub get_server_homeID {
257: my ($hostname,$ignore_cache,$caller) = @_;
258: unless ($ignore_cache) {
259: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
260: if (defined($cached)) {
261: return $serverhomeID;
262: }
263: }
264: my $cachetime = 12*3600;
265: my $serverhomeID;
266: if ($caller eq 'loncron') {
267: my @machine_ids = &machine_ids($hostname);
268: foreach my $id (@machine_ids) {
269: my $response = &reply('serverhomeID',$id);
270: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
271: $serverhomeID = $response;
272: last;
273: }
274: }
275: if ($serverhomeID eq '') {
276: $serverhomeID = $machine_ids[-1];
277: }
278: } else {
279: $serverhomeID = $serverhomeIDs{$hostname};
280: }
281: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
282: }
283:
1.1 albertel 284: # -------------------------------------------------- Non-critical communication
285: sub subreply {
286: my ($cmd,$server)=@_;
1.838 albertel 287: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 288: #
289: # With loncnew process trimming, there's a timing hole between lonc server
290: # process exit and the master server picking up the listen on the AF_UNIX
291: # socket. In that time interval, a lock file will exist:
292:
293: my $lockfile=$peerfile.".lock";
294: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
295: sleep(1);
296: }
297: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 298: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 299: #
1.550 foxr 300: # We'll give the connection a few tries before abandoning it. If
301: # connection is not possible, we'll con_lost back to the client.
302: #
303: my $client;
304: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
305: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
306: Type => SOCK_STREAM,
307: Timeout => 10);
1.869 albertel 308: if ($client) {
1.550 foxr 309: last; # Connected!
1.850 albertel 310: } else {
1.853 albertel 311: &create_connection(&hostname($server),$server);
1.550 foxr 312: }
1.850 albertel 313: sleep(1); # Try again later if failed connection.
1.550 foxr 314: }
315: my $answer;
316: if ($client) {
1.704 albertel 317: print $client "sethost:$server:$cmd\n";
1.550 foxr 318: $answer=<$client>;
319: if (!$answer) { $answer="con_lost"; }
320: chomp($answer);
321: } else {
322: $answer = 'con_lost'; # Failed connection.
323: }
1.1 albertel 324: return $answer;
325: }
326:
327: sub reply {
328: my ($cmd,$server)=@_;
1.838 albertel 329: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 330: my $answer=subreply($cmd,$server);
1.65 www 331: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 332: &logthis("<font color=\"blue\">WARNING:".
1.12 www 333: " $cmd to $server returned $answer</font>");
334: }
1.1 albertel 335: return $answer;
336: }
337:
338: # ----------------------------------------------------------- Send USR1 to lonc
339:
340: sub reconlonc {
1.891 albertel 341: my ($lonid) = @_;
342: my $hostname = &hostname($lonid);
343: if ($lonid) {
344: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
345: if ($hostname && -e $peerfile) {
346: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
347: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
348: Type => SOCK_STREAM,
349: Timeout => 10);
350: if ($client) {
351: print $client ("reset_retries\n");
352: my $answer=<$client>;
353: #reset just this one.
354: }
355: }
356: return;
357: }
358:
1.836 www 359: &logthis("Trying to reconnect lonc");
1.1 albertel 360: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 361: if (open(my $fh,"<$loncfile")) {
1.1 albertel 362: my $loncpid=<$fh>;
363: chomp($loncpid);
364: if (kill 0 => $loncpid) {
365: &logthis("lonc at pid $loncpid responding, sending USR1");
366: kill USR1 => $loncpid;
367: sleep 1;
1.836 www 368: } else {
1.12 www 369: &logthis(
1.672 albertel 370: "<font color=\"blue\">WARNING:".
1.12 www 371: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 372: }
373: } else {
1.836 www 374: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 375: }
376: }
377:
378: # ------------------------------------------------------ Critical communication
1.12 www 379:
1.1 albertel 380: sub critical {
381: my ($cmd,$server)=@_;
1.838 albertel 382: unless (&hostname($server)) {
1.672 albertel 383: &logthis("<font color=\"blue\">WARNING:".
1.89 www 384: " Critical message to unknown server ($server)</font>");
385: return 'no_such_host';
386: }
1.1 albertel 387: my $answer=reply($cmd,$server);
388: if ($answer eq 'con_lost') {
389: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 390: my $answer=reply($cmd,$server);
1.1 albertel 391: if ($answer eq 'con_lost') {
392: my $now=time;
393: my $middlename=$cmd;
1.5 www 394: $middlename=substr($middlename,0,16);
1.1 albertel 395: $middlename=~s/\W//g;
396: my $dfilename=
1.305 www 397: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
398: $dumpcount++;
1.1 albertel 399: {
1.448 albertel 400: my $dfh;
401: if (open($dfh,">$dfilename")) {
402: print $dfh "$cmd\n";
403: close($dfh);
404: }
1.1 albertel 405: }
406: sleep 2;
407: my $wcmd='';
408: {
1.448 albertel 409: my $dfh;
410: if (open($dfh,"<$dfilename")) {
411: $wcmd=<$dfh>;
412: close($dfh);
413: }
1.1 albertel 414: }
415: chomp($wcmd);
1.7 www 416: if ($wcmd eq $cmd) {
1.672 albertel 417: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 418: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 419: &logperm("D:$server:$cmd");
420: return 'con_delayed';
421: } else {
1.672 albertel 422: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 423: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 424: &logperm("F:$server:$cmd");
425: return 'con_failed';
426: }
427: }
428: }
429: return $answer;
1.405 albertel 430: }
431:
1.755 albertel 432: # ------------------------------------------- check if return value is an error
433:
434: sub error {
435: my ($result) = @_;
1.756 albertel 436: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 437: if ($2 == 2) { return undef; }
438: return $1;
439: }
440: return undef;
441: }
442:
1.783 albertel 443: sub convert_and_load_session_env {
444: my ($lonidsdir,$handle)=@_;
445: my @profile;
446: {
1.917 albertel 447: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
448: if (!$opened) {
1.915 albertel 449: return 0;
450: }
1.783 albertel 451: flock($idf,LOCK_SH);
452: @profile=<$idf>;
453: close($idf);
454: }
455: my %temp_env;
456: foreach my $line (@profile) {
1.786 albertel 457: if ($line !~ m/=/) {
458: return 0;
459: }
1.783 albertel 460: chomp($line);
461: my ($envname,$envvalue)=split(/=/,$line,2);
462: $temp_env{&unescape($envname)} = &unescape($envvalue);
463: }
464: unlink("$lonidsdir/$handle.id");
465: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
466: 0640)) {
467: %disk_env = %temp_env;
468: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
469: untie(%disk_env);
470: }
1.786 albertel 471: return 1;
1.783 albertel 472: }
473:
1.374 www 474: # ------------------------------------------- Transfer profile into environment
1.780 albertel 475: my $env_loaded;
476: sub transfer_profile_to_env {
1.788 albertel 477: my ($lonidsdir,$handle,$force_transfer) = @_;
478: if (!$force_transfer && $env_loaded) { return; }
1.374 www 479:
1.720 albertel 480: if (!defined($lonidsdir)) {
481: $lonidsdir = $perlvar{'lonIDsDir'};
482: }
483: if (!defined($handle)) {
484: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
485: }
486:
1.786 albertel 487: my $convert;
488: {
1.917 albertel 489: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
490: if (!$opened) {
1.915 albertel 491: return;
492: }
1.786 albertel 493: flock($idf,LOCK_SH);
494: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
495: &GDBM_READER(),0640)) {
496: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
497: untie(%disk_env);
498: } else {
499: $convert = 1;
500: }
501: }
502: if ($convert) {
503: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
504: &logthis("Failed to load session, or convert session.");
505: }
1.374 www 506: }
1.783 albertel 507:
1.786 albertel 508: my %remove;
1.783 albertel 509: while ( my $envname = each(%env) ) {
1.433 matthew 510: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
511: if ($time < time-300) {
1.783 albertel 512: $remove{$key}++;
1.433 matthew 513: }
514: }
515: }
1.783 albertel 516:
1.619 albertel 517: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 518: $env_loaded=1;
1.783 albertel 519: foreach my $expired_key (keys(%remove)) {
1.433 matthew 520: &delenv($expired_key);
1.374 www 521: }
1.1 albertel 522: }
523:
1.916 albertel 524: # ---------------------------------------------------- Check for valid session
525: sub check_for_valid_session {
526: my ($r) = @_;
527: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
528: my $lonid=$cookies{'lonID'};
529: return undef if (!$lonid);
530:
531: my $handle=&LONCAPA::clean_handle($lonid->value);
532: my $lonidsdir=$r->dir_config('lonIDsDir');
533: return undef if (!-e "$lonidsdir/$handle.id");
534:
1.917 albertel 535: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
536: return undef if (!$opened);
1.916 albertel 537:
538: flock($idf,LOCK_SH);
539: my %disk_env;
540: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
541: &GDBM_READER(),0640)) {
542: return undef;
543: }
544:
545: if (!defined($disk_env{'user.name'})
546: || !defined($disk_env{'user.domain'})) {
547: return undef;
548: }
549: return $handle;
550: }
551:
1.830 albertel 552: sub timed_flock {
553: my ($file,$lock_type) = @_;
554: my $failed=0;
555: eval {
556: local $SIG{__DIE__}='DEFAULT';
557: local $SIG{ALRM}=sub {
558: $failed=1;
559: die("failed lock");
560: };
561: alarm(13);
562: flock($file,$lock_type);
563: alarm(0);
564: };
565: if ($failed) {
566: return undef;
567: } else {
568: return 1;
569: }
570: }
571:
1.5 www 572: # ---------------------------------------------------------- Append Environment
573:
574: sub appenv {
1.949 raeburn 575: my ($newenv,$roles) = @_;
576: if (ref($newenv) eq 'HASH') {
577: foreach my $key (keys(%{$newenv})) {
578: my $refused = 0;
579: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
580: $refused = 1;
581: if (ref($roles) eq 'ARRAY') {
582: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
583: if (grep(/^\Q$role\E$/,@{$roles})) {
584: $refused = 0;
585: }
586: }
587: }
588: if ($refused) {
589: &logthis("<font color=\"blue\">WARNING: ".
590: "Attempt to modify environment ".$key." to ".$newenv->{$key}
591: .'</font>');
592: delete($newenv->{$key});
593: } else {
594: $env{$key}=$newenv->{$key};
595: }
596: }
597: my $opened = open(my $env_file,'+<',$env{'user.environment'});
598: if ($opened
599: && &timed_flock($env_file,LOCK_EX)
600: &&
601: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
602: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
603: while (my ($key,$value) = each(%{$newenv})) {
604: $disk_env{$key} = $value;
605: }
606: untie(%disk_env);
1.35 www 607: }
1.191 harris41 608: }
1.56 www 609: return 'ok';
610: }
611: # ----------------------------------------------------- Delete from Environment
612:
613: sub delenv {
1.987 raeburn 614: my ($delthis,$regexp) = @_;
1.56 www 615: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 616: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 617: "Attempt to delete from environment ".$delthis);
618: return 'error';
619: }
1.917 albertel 620: my $opened = open(my $env_file,'+<',$env{'user.environment'});
621: if ($opened
1.915 albertel 622: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 623: &&
624: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
625: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 626: foreach my $key (keys(%disk_env)) {
1.987 raeburn 627: if ($regexp) {
628: if ($key=~/^$delthis/) {
629: delete($env{$key});
630: delete($disk_env{$key});
631: }
632: } else {
633: if ($key=~/^\Q$delthis\E/) {
634: delete($env{$key});
635: delete($disk_env{$key});
636: }
637: }
1.448 albertel 638: }
1.783 albertel 639: untie(%disk_env);
1.5 www 640: }
641: return 'ok';
1.369 albertel 642: }
643:
1.790 albertel 644: sub get_env_multiple {
645: my ($name) = @_;
646: my @values;
647: if (defined($env{$name})) {
648: # exists is it an array
649: if (ref($env{$name})) {
650: @values=@{ $env{$name} };
651: } else {
652: $values[0]=$env{$name};
653: }
654: }
655: return(@values);
656: }
657:
1.958 www 658: # ------------------------------------------------------------------- Locking
659:
660: sub set_lock {
661: my ($text)=@_;
662: $locknum++;
663: my $id=$$.'-'.$locknum;
664: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
665: 'session.lock.'.$id => $text});
666: return $id;
667: }
668:
669: sub get_locks {
670: my $num=0;
671: my %texts=();
672: foreach my $lock (split(/\,/,$env{'session.locks'})) {
673: if ($lock=~/\w/) {
674: $num++;
675: $texts{$lock}=$env{'session.lock.'.$lock};
676: }
677: }
678: return ($num,%texts);
679: }
680:
681: sub remove_lock {
682: my ($id)=@_;
683: my $newlocks='';
684: foreach my $lock (split(/\,/,$env{'session.locks'})) {
685: if (($lock=~/\w/) && ($lock ne $id)) {
686: $newlocks.=','.$lock;
687: }
688: }
689: &appenv({'session.locks' => $newlocks});
690: &delenv('session.lock.'.$id);
691: }
692:
693: sub remove_all_locks {
694: my $activelocks=$env{'session.locks'};
695: foreach my $lock (split(/\,/,$env{'session.locks'})) {
696: if ($lock=~/\w/) {
697: &remove_lock($lock);
698: }
699: }
700: }
701:
702:
1.369 albertel 703: # ------------------------------------------ Find out current server userload
704: sub userload {
705: my $numusers=0;
706: {
707: opendir(LONIDS,$perlvar{'lonIDsDir'});
708: my $filename;
709: my $curtime=time;
710: while ($filename=readdir(LONIDS)) {
1.925 albertel 711: next if ($filename eq '.' || $filename eq '..');
712: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 713: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 714: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 715: }
716: closedir(LONIDS);
717: }
718: my $userloadpercent=0;
719: my $maxuserload=$perlvar{'lonUserLoadLim'};
720: if ($maxuserload) {
1.371 albertel 721: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 722: }
1.372 albertel 723: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 724: return $userloadpercent;
1.283 www 725: }
726:
1.1 albertel 727: # ------------------------------ Find server with least workload from spare.tab
1.11 www 728:
1.1 albertel 729: sub spareserver {
1.670 albertel 730: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 731: my $spare_server;
1.370 albertel 732: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 733: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
734: : $userloadpercent;
735:
736: foreach my $try_server (@{ $spareid{'primary'} }) {
737: ($spare_server, $lowest_load) =
738: &compare_server_load($try_server, $spare_server, $lowest_load);
739: }
740:
741: my $found_server = ($spare_server ne '' && $lowest_load < 100);
742:
743: if (!$found_server) {
744: foreach my $try_server (@{ $spareid{'default'} }) {
745: ($spare_server, $lowest_load) =
746: &compare_server_load($try_server, $spare_server, $lowest_load);
747: }
748: }
749:
750: if (!$want_server_name) {
1.968 raeburn 751: my $protocol = 'http';
752: if ($protocol{$spare_server} eq 'https') {
753: $protocol = $protocol{$spare_server};
754: }
1.1001 raeburn 755: if (defined($spare_server)) {
756: my $hostname = &hostname($spare_server);
757: if (defined($hostname)) {
758: $spare_server = $protocol.'://'.$hostname;
759: }
760: }
1.784 albertel 761: }
762: return $spare_server;
763: }
764:
765: sub compare_server_load {
766: my ($try_server, $spare_server, $lowest_load) = @_;
767:
768: my $loadans = &reply('load', $try_server);
769: my $userloadans = &reply('userload',$try_server);
770:
771: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1072 www 772: return; #didn't get a number from the server
1.784 albertel 773: }
774:
775: my $load;
776: if ($loadans =~ /\d/) {
777: if ($userloadans =~ /\d/) {
778: #both are numbers, pick the bigger one
779: $load = ($loadans > $userloadans) ? $loadans
780: : $userloadans;
1.411 albertel 781: } else {
1.784 albertel 782: $load = $loadans;
1.411 albertel 783: }
1.784 albertel 784: } else {
785: $load = $userloadans;
786: }
787:
788: if (($load =~ /\d/) && ($load < $lowest_load)) {
789: $spare_server = $try_server;
790: $lowest_load = $load;
1.370 albertel 791: }
1.784 albertel 792: return ($spare_server,$lowest_load);
1.202 matthew 793: }
1.914 albertel 794:
795: # --------------------------- ask offload servers if user already has a session
796: sub find_existing_session {
797: my ($udom,$uname) = @_;
798: foreach my $try_server (@{ $spareid{'primary'} },
799: @{ $spareid{'default'} }) {
800: return $try_server if (&has_user_session($try_server, $udom, $uname));
801: }
802: return;
803: }
804:
805: # -------------------------------- ask if server already has a session for user
806: sub has_user_session {
807: my ($lonid,$udom,$uname) = @_;
808: my $result = &reply(join(':','userhassession',
809: map {&escape($_)} ($udom,$uname)),$lonid);
810: return 1 if ($result eq 'ok');
811:
812: return 0;
813: }
814:
1.1076 raeburn 815: # --------- determine least loaded server in a user's domain which allows login
816:
817: sub choose_server {
818: my ($udom) = @_;
819: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 820: my %servers = &get_servers($udom);
1.1076 raeburn 821: my $lowest_load = 30000;
822: my ($login_host,$hostname);
823: foreach my $lonhost (keys(%servers)) {
824: my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
825: if ($loginvia eq '') {
826: ($login_host, $lowest_load) =
827: &compare_server_load($lonhost, $login_host, $lowest_load);
828: }
829: }
830: if ($login_host ne '') {
831: $hostname = $servers{$login_host};
832: }
833: return ($login_host,$hostname);
834: }
835:
1.202 matthew 836: # --------------------------------------------- Try to change a user's password
837:
838: sub changepass {
1.799 raeburn 839: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 840: $currentpass = &escape($currentpass);
841: $newpass = &escape($newpass);
1.1030 raeburn 842: my $lonhost = $perlvar{'lonHostID'};
843: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 844: $server);
845: if (! $answer) {
846: &logthis("No reply on password change request to $server ".
847: "by $uname in domain $udom.");
848: } elsif ($answer =~ "^ok") {
849: &logthis("$uname in $udom successfully changed their password ".
850: "on $server.");
851: } elsif ($answer =~ "^pwchange_failure") {
852: &logthis("$uname in $udom was unable to change their password ".
853: "on $server. The action was blocked by either lcpasswd ".
854: "or pwchange");
855: } elsif ($answer =~ "^non_authorized") {
856: &logthis("$uname in $udom did not get their password correct when ".
857: "attempting to change it on $server.");
858: } elsif ($answer =~ "^auth_mode_error") {
859: &logthis("$uname in $udom attempted to change their password despite ".
860: "not being locally or internally authenticated on $server.");
861: } elsif ($answer =~ "^unknown_user") {
862: &logthis("$uname in $udom attempted to change their password ".
863: "on $server but were unable to because $server is not ".
864: "their home server.");
865: } elsif ($answer =~ "^refused") {
866: &logthis("$server refused to change $uname in $udom password because ".
867: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 868: } elsif ($answer =~ "invalid_client") {
869: &logthis("$server refused to change $uname in $udom password because ".
870: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 871: }
872: return $answer;
1.1 albertel 873: }
874:
1.169 harris41 875: # ----------------------- Try to determine user's current authentication scheme
876:
877: sub queryauthenticate {
878: my ($uname,$udom)=@_;
1.456 albertel 879: my $uhome=&homeserver($uname,$udom);
880: if (!$uhome) {
881: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
882: return 'no_host';
883: }
884: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
885: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
886: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 887: }
1.456 albertel 888: return $answer;
1.169 harris41 889: }
890:
1.1 albertel 891: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 892:
1.1 albertel 893: sub authenticate {
1.1073 raeburn 894: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 895: $upass=&escape($upass);
896: $uname= &LONCAPA::clean_username($uname);
1.836 www 897: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 898: my $newhome;
1.836 www 899: if ((!$uhome) || ($uhome eq 'no_host')) {
900: # Maybe the machine was offline and only re-appeared again recently?
901: &reconlonc();
902: # One more
1.952 raeburn 903: $uhome=&homeserver($uname,$udom,1);
904: if (($uhome eq 'no_host') && $checkdefauth) {
905: if (defined(&domain($udom,'primary'))) {
906: $newhome=&domain($udom,'primary');
907: }
908: if ($newhome ne '') {
909: $uhome = $newhome;
910: }
911: }
1.836 www 912: if ((!$uhome) || ($uhome eq 'no_host')) {
913: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 914: return 'no_host';
915: }
1.1 albertel 916: }
1.1073 raeburn 917: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 918: if ($answer eq 'authorized') {
1.952 raeburn 919: if ($newhome) {
920: &logthis("User $uname at $udom authorized by $uhome, but needs account");
921: return 'no_account_on_host';
922: } else {
923: &logthis("User $uname at $udom authorized by $uhome");
924: return $uhome;
925: }
1.471 albertel 926: }
927: if ($answer eq 'non_authorized') {
928: &logthis("User $uname at $udom rejected by $uhome");
929: return 'no_host';
1.9 www 930: }
1.471 albertel 931: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 932: return 'no_host';
933: }
934:
1.1073 raeburn 935: sub can_host_session {
1.1074 raeburn 936: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 937: my $canhost = 1;
1.1074 raeburn 938: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 939: if (ref($remotesessions) eq 'HASH') {
940: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 941: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 942: $canhost = 0;
943: } else {
944: $canhost = 1;
945: }
946: }
947: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 948: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 949: $canhost = 1;
950: } else {
951: $canhost = 0;
952: }
953: }
954: if ($canhost) {
955: if ($remotesessions->{'version'} ne '') {
956: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
957: if ($reqmajor ne '' && $reqminor ne '') {
958: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
959: my $major = $1;
960: my $minor = $2;
961: if (($major < $reqmajor ) ||
962: (($major == $reqmajor) && ($minor < $reqminor))) {
963: $canhost = 0;
964: }
965: } else {
966: $canhost = 0;
967: }
968: }
969: }
970: }
971: }
972: if ($canhost) {
973: if (ref($hostedsessions) eq 'HASH') {
974: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
975: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
976: $canhost = 0;
977: } else {
978: $canhost = 1;
979: }
980: }
981: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
982: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
983: $canhost = 1;
984: } else {
985: $canhost = 0;
986: }
987: }
988: }
989: }
990: return $canhost;
991: }
992:
1.1 albertel 993: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 994:
1.599 albertel 995: my %homecache;
1.1 albertel 996: sub homeserver {
1.230 stredwic 997: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 998: my $index="$uname:$udom";
1.426 albertel 999:
1.599 albertel 1000: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1001:
1002: my %servers = &get_servers($udom,'library');
1003: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1004: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1005: exists($badServerCache{$tryserver}));
1.841 albertel 1006:
1007: my $answer=reply("home:$udom:$uname",$tryserver);
1008: if ($answer eq 'found') {
1009: delete($badServerCache{$tryserver});
1010: return $homecache{$index}=$tryserver;
1011: } elsif ($answer eq 'no_host') {
1012: $badServerCache{$tryserver}=1;
1013: }
1.1 albertel 1014: }
1015: return 'no_host';
1.70 www 1016: }
1017:
1018: # ------------------------------------- Find the usernames behind a list of IDs
1019:
1020: sub idget {
1021: my ($udom,@ids)=@_;
1022: my %returnhash=();
1023:
1.841 albertel 1024: my %servers = &get_servers($udom,'library');
1025: foreach my $tryserver (keys(%servers)) {
1026: my $idlist=join('&',@ids);
1027: $idlist=~tr/A-Z/a-z/;
1028: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1029: my @answer=();
1030: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1031: @answer=split(/\&/,$reply);
1032: } ;
1033: my $i;
1034: for ($i=0;$i<=$#ids;$i++) {
1035: if ($answer[$i]) {
1036: $returnhash{$ids[$i]}=$answer[$i];
1037: }
1038: }
1039: }
1.70 www 1040: return %returnhash;
1041: }
1042:
1043: # ------------------------------------- Find the IDs behind a list of usernames
1044:
1045: sub idrget {
1046: my ($udom,@unames)=@_;
1047: my %returnhash=();
1.800 albertel 1048: foreach my $uname (@unames) {
1049: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1050: }
1.70 www 1051: return %returnhash;
1052: }
1053:
1054: # ------------------------------- Store away a list of names and associated IDs
1055:
1056: sub idput {
1057: my ($udom,%ids)=@_;
1058: my %servers=();
1.800 albertel 1059: foreach my $uname (keys(%ids)) {
1060: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1061: my $uhom=&homeserver($uname,$udom);
1.70 www 1062: if ($uhom ne 'no_host') {
1.800 albertel 1063: my $id=&escape($ids{$uname});
1.70 www 1064: $id=~tr/A-Z/a-z/;
1.800 albertel 1065: my $esc_unam=&escape($uname);
1.70 www 1066: if ($servers{$uhom}) {
1.800 albertel 1067: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1068: } else {
1.800 albertel 1069: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1070: }
1071: }
1.191 harris41 1072: }
1.800 albertel 1073: foreach my $server (keys(%servers)) {
1074: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1075: }
1.344 www 1076: }
1077:
1.1023 raeburn 1078: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1079: sub dump_dom {
1.1023 raeburn 1080: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1081: if (!$udom) {
1082: $udom=$env{'user.domain'};
1083: }
1084: my %returnhash;
1.1023 raeburn 1085: if ($udom) {
1086: my $uname = &get_domainconfiguser($udom);
1087: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1088: }
1089: return %returnhash;
1090: }
1091:
1.1023 raeburn 1092: # ------------------------------------------ get items from domain db files
1.806 raeburn 1093:
1094: sub get_dom {
1.860 raeburn 1095: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1096: my $items='';
1097: foreach my $item (@$storearr) {
1098: $items.=&escape($item).'&';
1099: }
1100: $items=~s/\&$//;
1.860 raeburn 1101: if (!$udom) {
1102: $udom=$env{'user.domain'};
1103: if (defined(&domain($udom,'primary'))) {
1104: $uhome=&domain($udom,'primary');
1105: } else {
1.874 albertel 1106: undef($uhome);
1.860 raeburn 1107: }
1108: } else {
1109: if (!$uhome) {
1110: if (defined(&domain($udom,'primary'))) {
1111: $uhome=&domain($udom,'primary');
1112: }
1113: }
1114: }
1115: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1116: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1117: my %returnhash;
1.875 albertel 1118: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1119: return %returnhash;
1120: }
1.806 raeburn 1121: my @pairs=split(/\&/,$rep);
1122: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1123: return @pairs;
1124: }
1125: my $i=0;
1126: foreach my $item (@$storearr) {
1127: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1128: $i++;
1129: }
1130: return %returnhash;
1131: } else {
1.880 banghart 1132: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1133: }
1134: }
1135:
1136: # -------------------------------------------- put items in domain db files
1137:
1138: sub put_dom {
1.860 raeburn 1139: my ($namespace,$storehash,$udom,$uhome)=@_;
1140: if (!$udom) {
1141: $udom=$env{'user.domain'};
1142: if (defined(&domain($udom,'primary'))) {
1143: $uhome=&domain($udom,'primary');
1144: } else {
1.874 albertel 1145: undef($uhome);
1.860 raeburn 1146: }
1147: } else {
1148: if (!$uhome) {
1149: if (defined(&domain($udom,'primary'))) {
1150: $uhome=&domain($udom,'primary');
1151: }
1152: }
1153: }
1154: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1155: my $items='';
1156: foreach my $item (keys(%$storehash)) {
1157: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1158: }
1159: $items=~s/\&$//;
1160: return &reply("putdom:$udom:$namespace:$items",$uhome);
1161: } else {
1.860 raeburn 1162: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1163: }
1164: }
1165:
1.1023 raeburn 1166: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1167: sub newput_dom {
1.1023 raeburn 1168: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1169: my $result;
1170: if (!$udom) {
1171: $udom=$env{'user.domain'};
1172: }
1.1023 raeburn 1173: if ($udom) {
1174: my $uname = &get_domainconfiguser($udom);
1175: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1176: }
1177: return $result;
1178: }
1179:
1.1023 raeburn 1180: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1181: sub del_dom {
1.1023 raeburn 1182: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1183: if (ref($storearr) eq 'ARRAY') {
1184: if (!$udom) {
1185: $udom=$env{'user.domain'};
1186: }
1.1023 raeburn 1187: if ($udom) {
1188: my $uname = &get_domainconfiguser($udom);
1189: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1190: }
1191: }
1192: }
1193:
1.1023 raeburn 1194: # ----------------------------------construct domainconfig user for a domain
1195: sub get_domainconfiguser {
1196: my ($udom) = @_;
1197: return $udom.'-domainconfig';
1198: }
1199:
1.837 raeburn 1200: sub retrieve_inst_usertypes {
1201: my ($udom) = @_;
1202: my (%returnhash,@order);
1.989 raeburn 1203: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1204: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1205: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1206: %returnhash = %{$domdefs{'inststatustypes'}};
1207: @order = @{$domdefs{'inststatusorder'}};
1208: } else {
1209: if (defined(&domain($udom,'primary'))) {
1210: my $uhome=&domain($udom,'primary');
1211: my $rep=&reply("inst_usertypes:$udom",$uhome);
1212: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1213: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1214: return (\%returnhash,\@order);
1215: }
1216: my ($hashitems,$orderitems) = split(/:/,$rep);
1217: my @pairs=split(/\&/,$hashitems);
1218: foreach my $item (@pairs) {
1219: my ($key,$value)=split(/=/,$item,2);
1220: $key = &unescape($key);
1221: next if ($key =~ /^error: 2 /);
1222: $returnhash{$key}=&thaw_unescape($value);
1223: }
1224: my @esc_order = split(/\&/,$orderitems);
1225: foreach my $item (@esc_order) {
1226: push(@order,&unescape($item));
1227: }
1228: } else {
1229: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1230: }
1231: }
1232: return (\%returnhash,\@order);
1233: }
1234:
1.868 raeburn 1235: sub is_domainimage {
1236: my ($url) = @_;
1237: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1238: if (&domain($1) ne '') {
1239: return '1';
1240: }
1241: }
1242: return;
1243: }
1244:
1.899 raeburn 1245: sub inst_directory_query {
1246: my ($srch) = @_;
1247: my $udom = $srch->{'srchdomain'};
1248: my %results;
1249: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1250: my $outcome;
1.899 raeburn 1251: if ($homeserver ne '') {
1.904 albertel 1252: my $queryid=&reply("querysend:instdirsearch:".
1253: &escape($srch->{'srchby'}).':'.
1254: &escape($srch->{'srchterm'}).':'.
1255: &escape($srch->{'srchtype'}),$homeserver);
1256: my $host=&hostname($homeserver);
1257: if ($queryid !~/^\Q$host\E\_/) {
1258: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1259: return;
1260: }
1261: my $response = &get_query_reply($queryid);
1262: my $maxtries = 5;
1263: my $tries = 1;
1264: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1265: $response = &get_query_reply($queryid);
1266: $tries ++;
1267: }
1268:
1269: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1270: if ($response eq 'unavailable') {
1271: $outcome = $response;
1272: } else {
1273: $outcome = 'ok';
1274: my @matches = split(/\n/,$response);
1275: foreach my $match (@matches) {
1276: my ($key,$value) = split(/=/,$match);
1277: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1278: }
1.899 raeburn 1279: }
1280: }
1281: }
1.909 raeburn 1282: return ($outcome,%results);
1.899 raeburn 1283: }
1284:
1285: sub usersearch {
1286: my ($srch) = @_;
1287: my $dom = $srch->{'srchdomain'};
1288: my %results;
1289: my %libserv = &all_library();
1290: my $query = 'usersearch';
1291: foreach my $tryserver (keys(%libserv)) {
1292: if (&host_domain($tryserver) eq $dom) {
1293: my $host=&hostname($tryserver);
1294: my $queryid=
1.911 raeburn 1295: &reply("querysend:".&escape($query).':'.
1296: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1297: &escape($srch->{'srchtype'}).':'.
1298: &escape($srch->{'srchterm'}),$tryserver);
1299: if ($queryid !~/^\Q$host\E\_/) {
1300: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1301: next;
1.899 raeburn 1302: }
1303: my $reply = &get_query_reply($queryid);
1304: my $maxtries = 1;
1305: my $tries = 1;
1306: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1307: $reply = &get_query_reply($queryid);
1308: $tries ++;
1309: }
1310: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1311: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1312: } else {
1.911 raeburn 1313: my @matches;
1314: if ($reply =~ /\n/) {
1315: @matches = split(/\n/,$reply);
1316: } else {
1317: @matches = split(/\&/,$reply);
1318: }
1.899 raeburn 1319: foreach my $match (@matches) {
1320: my ($uname,$udom,%userhash);
1.911 raeburn 1321: foreach my $entry (split(/:/,$match)) {
1322: my ($key,$value) =
1323: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1324: $userhash{$key} = $value;
1325: if ($key eq 'username') {
1326: $uname = $value;
1327: } elsif ($key eq 'domain') {
1328: $udom = $value;
1.911 raeburn 1329: }
1.899 raeburn 1330: }
1331: $results{$uname.':'.$udom} = \%userhash;
1332: }
1333: }
1334: }
1335: }
1336: return %results;
1337: }
1338:
1.912 raeburn 1339: sub get_instuser {
1340: my ($udom,$uname,$id) = @_;
1341: my $homeserver = &domain($udom,'primary');
1342: my ($outcome,%results);
1343: if ($homeserver ne '') {
1344: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1345: &escape($id).':'.&escape($udom),$homeserver);
1346: my $host=&hostname($homeserver);
1347: if ($queryid !~/^\Q$host\E\_/) {
1348: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1349: return;
1350: }
1351: my $response = &get_query_reply($queryid);
1352: my $maxtries = 5;
1353: my $tries = 1;
1354: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1355: $response = &get_query_reply($queryid);
1356: $tries ++;
1357: }
1358: if (!&error($response) && $response ne 'refused') {
1359: if ($response eq 'unavailable') {
1360: $outcome = $response;
1361: } else {
1362: $outcome = 'ok';
1363: my @matches = split(/\n/,$response);
1364: foreach my $match (@matches) {
1365: my ($key,$value) = split(/=/,$match);
1366: $results{&unescape($key)} = &thaw_unescape($value);
1367: }
1368: }
1369: }
1370: }
1371: my %userinfo;
1372: if (ref($results{$uname}) eq 'HASH') {
1373: %userinfo = %{$results{$uname}};
1374: }
1375: return ($outcome,%userinfo);
1376: }
1377:
1378: sub inst_rulecheck {
1.923 raeburn 1379: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1380: my %returnhash;
1381: if ($udom ne '') {
1382: if (ref($rules) eq 'ARRAY') {
1383: @{$rules} = map {&escape($_);} (@{$rules});
1384: my $rulestr = join(':',@{$rules});
1385: my $homeserver=&domain($udom,'primary');
1386: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1387: my $response;
1388: if ($item eq 'username') {
1389: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1390: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1391: $homeserver));
1.923 raeburn 1392: } elsif ($item eq 'id') {
1393: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1394: ':'.&escape($id).':'.$rulestr,
1395: $homeserver));
1.945 raeburn 1396: } elsif ($item eq 'selfcreate') {
1397: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1398: &escape($udom).':'.&escape($uname).
1399: ':'.$rulestr,$homeserver));
1.923 raeburn 1400: }
1.912 raeburn 1401: if ($response ne 'refused') {
1402: my @pairs=split(/\&/,$response);
1403: foreach my $item (@pairs) {
1404: my ($key,$value)=split(/=/,$item,2);
1405: $key = &unescape($key);
1406: next if ($key =~ /^error: 2 /);
1407: $returnhash{$key}=&thaw_unescape($value);
1408: }
1409: }
1410: }
1411: }
1412: }
1413: return %returnhash;
1414: }
1415:
1416: sub inst_userrules {
1.923 raeburn 1417: my ($udom,$check) = @_;
1.912 raeburn 1418: my (%ruleshash,@ruleorder);
1419: if ($udom ne '') {
1420: my $homeserver=&domain($udom,'primary');
1421: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1422: my $response;
1423: if ($check eq 'id') {
1424: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1425: $homeserver);
1.943 raeburn 1426: } elsif ($check eq 'email') {
1427: $response=&reply('instemailrules:'.&escape($udom),
1428: $homeserver);
1.923 raeburn 1429: } else {
1430: $response=&reply('instuserrules:'.&escape($udom),
1431: $homeserver);
1432: }
1.912 raeburn 1433: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1434: ($response ne 'unknown_cmd') &&
1.912 raeburn 1435: ($response ne 'no_such_host')) {
1436: my ($hashitems,$orderitems) = split(/:/,$response);
1437: my @pairs=split(/\&/,$hashitems);
1438: foreach my $item (@pairs) {
1439: my ($key,$value)=split(/=/,$item,2);
1440: $key = &unescape($key);
1441: next if ($key =~ /^error: 2 /);
1442: $ruleshash{$key}=&thaw_unescape($value);
1443: }
1444: my @esc_order = split(/\&/,$orderitems);
1445: foreach my $item (@esc_order) {
1446: push(@ruleorder,&unescape($item));
1447: }
1448: }
1449: }
1450: }
1451: return (\%ruleshash,\@ruleorder);
1452: }
1453:
1.976 raeburn 1454: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1455:
1456: sub get_domain_defaults {
1457: my ($domain) = @_;
1458: my $cachetime = 60*60*24;
1459: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1460: if (defined($cached)) {
1461: if (ref($result) eq 'HASH') {
1462: return %{$result};
1463: }
1464: }
1465: my %domdefaults;
1466: my %domconfig =
1.989 raeburn 1467: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1468: 'requestcourses','inststatus',
1.1073 raeburn 1469: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1470: if (ref($domconfig{'defaults'}) eq 'HASH') {
1471: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1472: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1473: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1474: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1475: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1476: } else {
1477: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1478: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1479: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1480: }
1.976 raeburn 1481: if (ref($domconfig{'quotas'}) eq 'HASH') {
1482: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1483: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1484: } else {
1485: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1486: }
1487: my @usertools = ('aboutme','blog','portfolio');
1488: foreach my $item (@usertools) {
1489: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1490: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1491: }
1492: }
1493: }
1.985 raeburn 1494: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1495: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1496: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1497: }
1498: }
1.989 raeburn 1499: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1500: foreach my $item ('inststatustypes','inststatusorder') {
1501: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1502: }
1503: }
1.1047 raeburn 1504: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1505: foreach my $item ('canuse_pdfforms') {
1506: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1507: }
1508: }
1.1073 raeburn 1509: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1510: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1511: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1512: }
1513: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1514: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1515: }
1516: }
1.943 raeburn 1517: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1518: $cachetime);
1519: return %domdefaults;
1520: }
1521:
1.344 www 1522: # --------------------------------------------------- Assign a key to a student
1523:
1524: sub assign_access_key {
1.364 www 1525: #
1526: # a valid key looks like uname:udom#comments
1527: # comments are being appended
1528: #
1.498 www 1529: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1530: $kdom=
1.620 albertel 1531: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1532: $knum=
1.620 albertel 1533: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1534: $cdom=
1.620 albertel 1535: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1536: $cnum=
1.620 albertel 1537: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1538: $udom=$env{'user.name'} unless (defined($udom));
1539: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1540: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1541: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1542: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1543: # assigned to this person
1544: # - this should not happen,
1.345 www 1545: # unless something went wrong
1546: # the first time around
1547: # ready to assign
1.364 www 1548: $logentry=$1.'; '.$logentry;
1.496 www 1549: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1550: $kdom,$knum) eq 'ok') {
1.345 www 1551: # key now belongs to user
1.346 www 1552: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1553: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1554: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1555: return 'ok';
1556: } else {
1557: return
1558: 'error: Count not permanently assign key, will need to be re-entered later.';
1559: }
1560: } else {
1561: return 'error: Could not assign key, try again later.';
1562: }
1.364 www 1563: } elsif (!$existing{$ckey}) {
1.345 www 1564: # the key does not exist
1565: return 'error: The key does not exist';
1566: } else {
1567: # the key is somebody else's
1568: return 'error: The key is already in use';
1569: }
1.344 www 1570: }
1571:
1.364 www 1572: # ------------------------------------------ put an additional comment on a key
1573:
1574: sub comment_access_key {
1575: #
1576: # a valid key looks like uname:udom#comments
1577: # comments are being appended
1578: #
1579: my ($ckey,$cdom,$cnum,$logentry)=@_;
1580: $cdom=
1.620 albertel 1581: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1582: $cnum=
1.620 albertel 1583: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1584: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1585: if ($existing{$ckey}) {
1586: $existing{$ckey}.='; '.$logentry;
1587: # ready to assign
1.367 www 1588: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1589: $cdom,$cnum) eq 'ok') {
1590: return 'ok';
1591: } else {
1592: return 'error: Count not store comment.';
1593: }
1594: } else {
1595: # the key does not exist
1596: return 'error: The key does not exist';
1597: }
1598: }
1599:
1.344 www 1600: # ------------------------------------------------------ Generate a set of keys
1601:
1602: sub generate_access_keys {
1.364 www 1603: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1604: $cdom=
1.620 albertel 1605: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1606: $cnum=
1.620 albertel 1607: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1608: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1609: unless (($cdom) && ($cnum)) { return 0; }
1610: if ($number>10000) { return 0; }
1611: sleep(2); # make sure don't get same seed twice
1612: srand(time()^($$+($$<<15))); # from "Programming Perl"
1613: my $total=0;
1614: for (my $i=1;$i<=$number;$i++) {
1615: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1616: sprintf("%lx",int(100000*rand)).'-'.
1617: sprintf("%lx",int(100000*rand));
1618: $newkey=~s/1/g/g; # folks mix up 1 and l
1619: $newkey=~s/0/h/g; # and also 0 and O
1620: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1621: if ($existing{$newkey}) {
1622: $i--;
1623: } else {
1.364 www 1624: if (&put('accesskeys',
1625: { $newkey => '# generated '.localtime().
1.620 albertel 1626: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1627: '; '.$logentry },
1628: $cdom,$cnum) eq 'ok') {
1.344 www 1629: $total++;
1630: }
1631: }
1632: }
1.620 albertel 1633: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1634: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1635: return $total;
1636: }
1637:
1638: # ------------------------------------------------------- Validate an accesskey
1639:
1640: sub validate_access_key {
1641: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1642: $cdom=
1.620 albertel 1643: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1644: $cnum=
1.620 albertel 1645: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1646: $udom=$env{'user.domain'} unless (defined($udom));
1647: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1648: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1649: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1650: }
1651:
1652: # ------------------------------------- Find the section of student in a course
1.652 albertel 1653: sub devalidate_getsection_cache {
1654: my ($udom,$unam,$courseid)=@_;
1655: my $hashid="$udom:$unam:$courseid";
1656: &devalidate_cache_new('getsection',$hashid);
1657: }
1.298 matthew 1658:
1.815 albertel 1659: sub courseid_to_courseurl {
1660: my ($courseid) = @_;
1661: #already url style courseid
1662: return $courseid if ($courseid =~ m{^/});
1663:
1664: if (exists($env{'course.'.$courseid.'.num'})) {
1665: my $cnum = $env{'course.'.$courseid.'.num'};
1666: my $cdom = $env{'course.'.$courseid.'.domain'};
1667: return "/$cdom/$cnum";
1668: }
1669:
1670: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1671: if (exists($courseinfo{'num'})) {
1672: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1673: }
1674:
1675: return undef;
1676: }
1677:
1.298 matthew 1678: sub getsection {
1679: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1680: my $cachetime=1800;
1.551 albertel 1681:
1682: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1683: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1684: if (defined($cached)) { return $result; }
1685:
1.298 matthew 1686: my %Pending;
1687: my %Expired;
1688: #
1689: # Each role can either have not started yet (pending), be active,
1690: # or have expired.
1691: #
1692: # If there is an active role, we are done.
1693: #
1694: # If there is more than one role which has not started yet,
1695: # choose the one which will start sooner
1696: # If there is one role which has not started yet, return it.
1697: #
1698: # If there is more than one expired role, choose the one which ended last.
1699: # If there is a role which has expired, return it.
1700: #
1.815 albertel 1701: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1702: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1703: foreach my $key (keys(%roleshash)) {
1.479 albertel 1704: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1705: my $section=$1;
1706: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1707: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1708: my $now=time;
1.548 albertel 1709: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1710: $Expired{$end}=$section;
1711: next;
1712: }
1.548 albertel 1713: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1714: $Pending{$start}=$section;
1715: next;
1716: }
1.599 albertel 1717: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1718: }
1719: #
1720: # Presumedly there will be few matching roles from the above
1721: # loop and the sorting time will be negligible.
1722: if (scalar(keys(%Pending))) {
1723: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1724: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1725: }
1726: if (scalar(keys(%Expired))) {
1727: my @sorted = sort {$a <=> $b} keys(%Expired);
1728: my $time = pop(@sorted);
1.599 albertel 1729: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1730: }
1.599 albertel 1731: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1732: }
1.70 www 1733:
1.599 albertel 1734: sub save_cache {
1735: &purge_remembered();
1.722 albertel 1736: #&Apache::loncommon::validate_page();
1.620 albertel 1737: undef(%env);
1.780 albertel 1738: undef($env_loaded);
1.599 albertel 1739: }
1.452 albertel 1740:
1.599 albertel 1741: my $to_remember=-1;
1742: my %remembered;
1743: my %accessed;
1744: my $kicks=0;
1745: my $hits=0;
1.849 albertel 1746: sub make_key {
1747: my ($name,$id) = @_;
1.872 albertel 1748: if (length($id) > 65
1749: && length(&escape($id)) > 200) {
1750: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1751: }
1.849 albertel 1752: return &escape($name.':'.$id);
1753: }
1754:
1.599 albertel 1755: sub devalidate_cache_new {
1756: my ($name,$id,$debug) = @_;
1757: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1758: $id=&make_key($name,$id);
1.599 albertel 1759: $memcache->delete($id);
1760: delete($remembered{$id});
1761: delete($accessed{$id});
1762: }
1763:
1764: sub is_cached_new {
1765: my ($name,$id,$debug) = @_;
1.849 albertel 1766: $id=&make_key($name,$id);
1.599 albertel 1767: if (exists($remembered{$id})) {
1768: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1769: $accessed{$id}=[&gettimeofday()];
1770: $hits++;
1771: return ($remembered{$id},1);
1772: }
1773: my $value = $memcache->get($id);
1774: if (!(defined($value))) {
1775: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1776: return (undef,undef);
1.416 albertel 1777: }
1.599 albertel 1778: if ($value eq '__undef__') {
1779: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1780: $value=undef;
1781: }
1782: &make_room($id,$value,$debug);
1783: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1784: return ($value,1);
1785: }
1786:
1787: sub do_cache_new {
1788: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1789: $id=&make_key($name,$id);
1.599 albertel 1790: my $setvalue=$value;
1791: if (!defined($setvalue)) {
1792: $setvalue='__undef__';
1793: }
1.623 albertel 1794: if (!defined($time) ) {
1795: $time=600;
1796: }
1.599 albertel 1797: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1798: my $result = $memcache->set($id,$setvalue,$time);
1799: if (! $result) {
1.872 albertel 1800: &logthis("caching of id -> $id failed");
1.910 albertel 1801: $memcache->disconnect_all();
1.872 albertel 1802: }
1.600 albertel 1803: # need to make a copy of $value
1.919 albertel 1804: &make_room($id,$value,$debug);
1.599 albertel 1805: return $value;
1806: }
1807:
1808: sub make_room {
1809: my ($id,$value,$debug)=@_;
1.919 albertel 1810:
1811: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1812: : $value;
1.599 albertel 1813: if ($to_remember<0) { return; }
1814: $accessed{$id}=[&gettimeofday()];
1815: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1816: my $to_kick;
1817: my $max_time=0;
1818: foreach my $other (keys(%accessed)) {
1819: if (&tv_interval($accessed{$other}) > $max_time) {
1820: $to_kick=$other;
1821: $max_time=&tv_interval($accessed{$other});
1822: }
1823: }
1824: delete($remembered{$to_kick});
1825: delete($accessed{$to_kick});
1826: $kicks++;
1827: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1828: return;
1829: }
1830:
1.599 albertel 1831: sub purge_remembered {
1.604 albertel 1832: #&logthis("Tossing ".scalar(keys(%remembered)));
1833: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1834: undef(%remembered);
1835: undef(%accessed);
1.428 albertel 1836: }
1.70 www 1837: # ------------------------------------- Read an entry from a user's environment
1838:
1839: sub userenvironment {
1840: my ($udom,$unam,@what)=@_;
1.976 raeburn 1841: my $items;
1842: foreach my $item (@what) {
1843: $items.=&escape($item).'&';
1844: }
1845: $items=~s/\&$//;
1.70 www 1846: my %returnhash=();
1.1009 raeburn 1847: my $uhome = &homeserver($unam,$udom);
1848: unless ($uhome eq 'no_host') {
1849: my @answer=split(/\&/,
1850: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1851: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1852: return %returnhash;
1853: }
1.1009 raeburn 1854: my $i;
1855: for ($i=0;$i<=$#what;$i++) {
1856: $returnhash{$what[$i]}=&unescape($answer[$i]);
1857: }
1.70 www 1858: }
1859: return %returnhash;
1.1 albertel 1860: }
1861:
1.617 albertel 1862: # ---------------------------------------------------------- Get a studentphoto
1863: sub studentphoto {
1864: my ($udom,$unam,$ext) = @_;
1865: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1866: if (defined($env{'request.course.id'})) {
1.708 raeburn 1867: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1868: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1869: return(&retrievestudentphoto($udom,$unam,$ext));
1870: } else {
1871: my ($result,$perm_reqd)=
1.707 albertel 1872: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1873: if ($result eq 'ok') {
1874: if (!($perm_reqd eq 'yes')) {
1875: return(&retrievestudentphoto($udom,$unam,$ext));
1876: }
1877: }
1878: }
1879: }
1880: } else {
1881: my ($result,$perm_reqd) =
1.707 albertel 1882: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1883: if ($result eq 'ok') {
1884: if (!($perm_reqd eq 'yes')) {
1885: return(&retrievestudentphoto($udom,$unam,$ext));
1886: }
1887: }
1888: }
1889: return '/adm/lonKaputt/lonlogo_broken.gif';
1890: }
1891:
1892: sub retrievestudentphoto {
1893: my ($udom,$unam,$ext,$type) = @_;
1894: my $home=&Apache::lonnet::homeserver($unam,$udom);
1895: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1896: if ($ret eq 'ok') {
1897: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1898: if ($type eq 'thumbnail') {
1899: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1900: }
1901: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1902: return $tokenurl;
1903: } else {
1904: if ($type eq 'thumbnail') {
1905: return '/adm/lonKaputt/genericstudent_tn.gif';
1906: } else {
1907: return '/adm/lonKaputt/lonlogo_broken.gif';
1908: }
1.617 albertel 1909: }
1910: }
1911:
1.263 www 1912: # -------------------------------------------------------------------- New chat
1913:
1914: sub chatsend {
1.724 raeburn 1915: my ($newentry,$anon,$group)=@_;
1.620 albertel 1916: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1917: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1918: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1919: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1920: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1921: &escape($newentry)).':'.$group,$chome);
1.292 www 1922: }
1923:
1924: # ------------------------------------------ Find current version of a resource
1925:
1926: sub getversion {
1927: my $fname=&clutter(shift);
1928: unless ($fname=~/^\/res\//) { return -1; }
1929: return ¤tversion(&filelocation('',$fname));
1930: }
1931:
1932: sub currentversion {
1933: my $fname=shift;
1.599 albertel 1934: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1935: if (defined($cached)) { return $result; }
1.292 www 1936: my $author=$fname;
1937: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1938: my ($udom,$uname)=split(/\//,$author);
1939: my $home=homeserver($uname,$udom);
1940: if ($home eq 'no_host') {
1941: return -1;
1942: }
1943: my $answer=reply("currentversion:$fname",$home);
1944: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1945: return -1;
1946: }
1.599 albertel 1947: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1948: }
1949:
1.1 albertel 1950: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1951:
1.1 albertel 1952: sub subscribe {
1953: my $fname=shift;
1.761 raeburn 1954: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1955: $fname=~s/[\n\r]//g;
1.1 albertel 1956: my $author=$fname;
1957: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1958: my ($udom,$uname)=split(/\//,$author);
1959: my $home=homeserver($uname,$udom);
1.335 albertel 1960: if ($home eq 'no_host') {
1961: return 'not_found';
1.1 albertel 1962: }
1963: my $answer=reply("sub:$fname",$home);
1.64 www 1964: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1965: $answer.=' by '.$home;
1966: }
1.1 albertel 1967: return $answer;
1968: }
1969:
1.8 www 1970: # -------------------------------------------------------------- Replicate file
1971:
1972: sub repcopy {
1973: my $filename=shift;
1.23 www 1974: $filename=~s/\/+/\//g;
1.607 raeburn 1975: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1976: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1977: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1978: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1979: return &repcopy_userfile($filename);
1980: }
1.532 albertel 1981: $filename=~s/[\n\r]//g;
1.8 www 1982: my $transname="$filename.in.transfer";
1.828 www 1983: # FIXME: this should flock
1.607 raeburn 1984: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1985: my $remoteurl=subscribe($filename);
1.64 www 1986: if ($remoteurl =~ /^con_lost by/) {
1987: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1988: return 'unavailable';
1.8 www 1989: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1990: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1991: return 'not_found';
1.64 www 1992: } elsif ($remoteurl =~ /^rejected by/) {
1993: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1994: return 'forbidden';
1.20 www 1995: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1996: return 'ok';
1.8 www 1997: } else {
1.290 www 1998: my $author=$filename;
1999: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2000: my ($udom,$uname)=split(/\//,$author);
2001: my $home=homeserver($uname,$udom);
2002: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2003: my @parts=split(/\//,$filename);
2004: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2005: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2006: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2007: return 'bad_request';
1.8 www 2008: }
2009: my $count;
2010: for ($count=5;$count<$#parts;$count++) {
2011: $path.="/$parts[$count]";
2012: if ((-e $path)!=1) {
2013: mkdir($path,0777);
2014: }
2015: }
2016: my $ua=new LWP::UserAgent;
2017: my $request=new HTTP::Request('GET',"$remoteurl");
2018: my $response=$ua->request($request,$transname);
2019: if ($response->is_error()) {
2020: unlink($transname);
2021: my $message=$response->status_line;
1.672 albertel 2022: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2023: ." LWP get: $message: $filename</font>");
1.607 raeburn 2024: return 'unavailable';
1.8 www 2025: } else {
1.16 www 2026: if ($remoteurl!~/\.meta$/) {
2027: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2028: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2029: if ($mresponse->is_error()) {
2030: unlink($filename.'.meta');
2031: &logthis(
1.672 albertel 2032: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2033: }
2034: }
1.8 www 2035: rename($transname,$filename);
1.607 raeburn 2036: return 'ok';
1.8 www 2037: }
1.290 www 2038: }
1.8 www 2039: }
1.330 www 2040: }
2041:
2042: # ------------------------------------------------ Get server side include body
2043: sub ssi_body {
1.381 albertel 2044: my ($filelink,%form)=@_;
1.606 matthew 2045: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2046: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2047: }
1.953 www 2048: my $output='';
2049: my $response;
1.980 raeburn 2050: if ($filelink=~/^https?\:/) {
1.954 raeburn 2051: ($output,$response)=&externalssi($filelink);
1.953 www 2052: } else {
1.1004 droeschl 2053: $filelink .= $filelink=~/\?/ ? '&' : '?';
2054: $filelink .= 'inhibitmenu=yes';
1.953 www 2055: ($output,$response)=&ssi($filelink,%form);
2056: }
1.778 albertel 2057: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2058: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2059: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2060: if (wantarray) {
2061: return ($output, $response);
2062: } else {
2063: return $output;
2064: }
1.8 www 2065: }
2066:
1.15 www 2067: # --------------------------------------------------------- Server Side Include
2068:
1.782 albertel 2069: sub absolute_url {
2070: my ($host_name) = @_;
2071: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2072: if ($host_name eq '') {
2073: $host_name = $ENV{'SERVER_NAME'};
2074: }
2075: return $protocol.$host_name;
2076: }
2077:
1.942 foxr 2078: #
2079: # Server side include.
2080: # Parameters:
2081: # fn Possibly encrypted resource name/id.
2082: # form Hash that describes how the rendering should be done
2083: # and other things.
1.944 foxr 2084: # Returns:
1.950 raeburn 2085: # Scalar context: The content of the response.
2086: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2087: #
1.15 www 2088: sub ssi {
2089:
1.944 foxr 2090: my ($fn,%form)=@_;
1.15 www 2091: my $ua=new LWP::UserAgent;
1.23 www 2092: my $request;
1.711 albertel 2093:
2094: $form{'no_update_last_known'}=1;
1.895 albertel 2095: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2096: if (%form) {
1.782 albertel 2097: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2098: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2099: } else {
1.782 albertel 2100: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2101: }
2102:
1.15 www 2103: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2104: my $response=$ua->request($request);
2105:
1.944 foxr 2106: if (wantarray) {
2107: return ($response->content, $response);
2108: } else {
2109: return $response->content;
1.942 foxr 2110: }
1.324 www 2111: }
2112:
2113: sub externalssi {
2114: my ($url)=@_;
2115: my $ua=new LWP::UserAgent;
2116: my $request=new HTTP::Request('GET',$url);
2117: my $response=$ua->request($request);
1.954 raeburn 2118: if (wantarray) {
2119: return ($response->content, $response);
2120: } else {
2121: return $response->content;
2122: }
1.15 www 2123: }
1.254 www 2124:
1.492 albertel 2125: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2126:
2127: sub allowuploaded {
2128: my ($srcurl,$url)=@_;
2129: $url=&clutter(&declutter($url));
2130: my $dir=$url;
2131: $dir=~s/\/[^\/]+$//;
2132: my %httpref=();
2133: my $httpurl=&hreflocation('',$url);
2134: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2135: &Apache::lonnet::appenv(\%httpref);
1.254 www 2136: }
1.477 raeburn 2137:
1.478 albertel 2138: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2139: # input: action, courseID, current domain, intended
1.637 raeburn 2140: # path to file, source of file, instruction to parse file for objects,
2141: # ref to hash for embedded objects,
2142: # ref to hash for codebase of java objects.
2143: #
1.485 raeburn 2144: # output: url to file (if action was uploaddoc),
2145: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2146: #
1.478 albertel 2147: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2148: # course.
1.477 raeburn 2149: #
1.478 albertel 2150: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2151: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2152: # course's home server.
1.477 raeburn 2153: #
1.478 albertel 2154: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2155: # be copied from $source (current location) to
2156: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2157: # and will then be copied to
2158: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2159: # course's home server.
1.485 raeburn 2160: #
1.481 raeburn 2161: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2162: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2163: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2164: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2165: # in course's home server.
1.637 raeburn 2166: #
1.477 raeburn 2167:
2168: sub process_coursefile {
1.638 albertel 2169: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2170: my $fetchresult;
1.638 albertel 2171: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2172: if ($action eq 'propagate') {
1.638 albertel 2173: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2174: $home);
1.481 raeburn 2175: } else {
1.477 raeburn 2176: my $fpath = '';
2177: my $fname = $file;
1.478 albertel 2178: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2179: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2180: my $filepath = &build_filepath($fpath);
1.481 raeburn 2181: if ($action eq 'copy') {
2182: if ($source eq '') {
2183: $fetchresult = 'no source file';
2184: return $fetchresult;
2185: } else {
2186: my $destination = $filepath.'/'.$fname;
2187: rename($source,$destination);
2188: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2189: $home);
1.481 raeburn 2190: }
2191: } elsif ($action eq 'uploaddoc') {
2192: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2193: print $fh $env{'form.'.$source};
1.481 raeburn 2194: close($fh);
1.637 raeburn 2195: if ($parser eq 'parse') {
1.1024 raeburn 2196: my $mm = new File::MMagic;
2197: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2198: if ($mime_type eq 'text/html') {
2199: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2200: unless ($parse_result eq 'ok') {
2201: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2202: }
1.637 raeburn 2203: }
2204: }
1.477 raeburn 2205: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2206: $home);
1.481 raeburn 2207: if ($fetchresult eq 'ok') {
2208: return '/uploaded/'.$fpath.'/'.$fname;
2209: } else {
2210: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2211: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2212: return '/adm/notfound.html';
2213: }
1.477 raeburn 2214: }
2215: }
1.485 raeburn 2216: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2217: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2218: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2219: }
2220: return $fetchresult;
2221: }
2222:
1.637 raeburn 2223: sub build_filepath {
2224: my ($fpath) = @_;
2225: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2226: unless ($fpath eq '') {
2227: my @parts=split('/',$fpath);
2228: foreach my $part (@parts) {
2229: $filepath.= '/'.$part;
2230: if ((-e $filepath)!=1) {
2231: mkdir($filepath,0777);
2232: }
2233: }
2234: }
2235: return $filepath;
2236: }
2237:
2238: sub store_edited_file {
1.638 albertel 2239: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2240: my $file = $primary_url;
2241: $file =~ s#^/uploaded/$docudom/$docuname/##;
2242: my $fpath = '';
2243: my $fname = $file;
2244: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2245: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2246: my $filepath = &build_filepath($fpath);
2247: open(my $fh,'>'.$filepath.'/'.$fname);
2248: print $fh $content;
2249: close($fh);
1.638 albertel 2250: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2251: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2252: $home);
1.637 raeburn 2253: if ($$fetchresult eq 'ok') {
2254: return '/uploaded/'.$fpath.'/'.$fname;
2255: } else {
1.638 albertel 2256: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2257: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2258: return '/adm/notfound.html';
2259: }
2260: }
2261:
1.531 albertel 2262: sub clean_filename {
1.831 albertel 2263: my ($fname,$args)=@_;
1.315 www 2264: # Replace Windows backslashes by forward slashes
1.257 www 2265: $fname=~s/\\/\//g;
1.831 albertel 2266: if (!$args->{'keep_path'}) {
2267: # Get rid of everything but the actual filename
2268: $fname=~s/^.*\/([^\/]+)$/$1/;
2269: }
1.315 www 2270: # Replace spaces by underscores
2271: $fname=~s/\s+/\_/g;
2272: # Replace all other weird characters by nothing
1.831 albertel 2273: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2274: # Replace all .\d. sequences with _\d. so they no longer look like version
2275: # numbers
2276: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2277: return $fname;
2278: }
1.1051 raeburn 2279: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2280: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2281: # image with the same aspect ratio as the original, but with dimensions which do
2282: # not exceed $resizewidth and $resizeheight.
2283:
1.984 neumanie 2284: sub resizeImage {
1.1051 raeburn 2285: my ($img_path,$resizewidth,$resizeheight) = @_;
2286: my $ima = Image::Magick->new;
2287: my $resized;
2288: if (-e $img_path) {
2289: $ima->Read($img_path);
2290: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2291: my $width = $ima->Get('width');
2292: my $height = $ima->Get('height');
2293: if ($width > $resizewidth) {
2294: my $factor = $width/$resizewidth;
2295: my $newheight = $height/$factor;
2296: $ima->Scale(width=>$resizewidth,height=>$newheight);
2297: $resized = 1;
2298: }
2299: }
2300: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2301: my $width = $ima->Get('width');
2302: my $height = $ima->Get('height');
2303: if ($height > $resizeheight) {
2304: my $factor = $height/$resizeheight;
2305: my $newwidth = $width/$factor;
2306: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2307: $resized = 1;
2308: }
2309: }
2310: if ($resized) {
2311: $ima->Write($img_path);
2312: }
2313: }
2314: return;
1.977 amueller 2315: }
2316:
1.608 albertel 2317: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2318: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2319: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2320: # $coursedoc - if true up to the current course
2321: # if false
2322: # $subdir - directory in userfile to store the file into
1.858 raeburn 2323: # $parser - instruction to parse file for objects ($parser = parse)
2324: # $allfiles - reference to hash for embedded objects
2325: # $codebase - reference to hash for codebase of java objects
2326: # $desuname - username for permanent storage of uploaded file
2327: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2328: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2329: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2330: # $resizewidth - width (pixels) to which to resize uploaded image
2331: # $resizeheight - height (pixels) to which to resize uploaded image
1.858 raeburn 2332: #
1.686 albertel 2333: # output: url of file in userspace, or error: <message>
2334: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2335:
1.531 albertel 2336: sub userfileupload {
1.860 raeburn 2337: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051 raeburn 2338: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531 albertel 2339: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2340: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2341: $fname=&clean_filename($fname);
1.315 www 2342: # See if there is anything left
1.257 www 2343: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2344: chop($env{'form.'.$formname});
1.523 raeburn 2345: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2346: my $now = time;
2347: my $filepath = 'tmp/helprequests/'.$now;
2348: my @parts=split(/\//,$filepath);
2349: my $fullpath = $perlvar{'lonDaemons'};
2350: for (my $i=0;$i<@parts;$i++) {
2351: $fullpath .= '/'.$parts[$i];
2352: if ((-e $fullpath)!=1) {
2353: mkdir($fullpath,0777);
2354: }
2355: }
2356: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2357: print $fh $env{'form.'.$formname};
1.523 raeburn 2358: close($fh);
1.741 raeburn 2359: return $fullpath.'/'.$fname;
2360: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2361: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2362: '_'.$env{'user.domain'}.'/pending';
2363: my @parts=split(/\//,$filepath);
2364: my $fullpath = $perlvar{'lonDaemons'};
2365: for (my $i=0;$i<@parts;$i++) {
2366: $fullpath .= '/'.$parts[$i];
2367: if ((-e $fullpath)!=1) {
2368: mkdir($fullpath,0777);
2369: }
2370: }
2371: open(my $fh,'>'.$fullpath.'/'.$fname);
2372: print $fh $env{'form.'.$formname};
2373: close($fh);
2374: return $fullpath.'/'.$fname;
1.523 raeburn 2375: }
1.995 raeburn 2376: if ($subdir eq 'scantron') {
2377: $fname = 'scantron_orig_'.$fname;
2378: } else {
1.258 www 2379: # Create the directory if not present
1.995 raeburn 2380: $fname="$subdir/$fname";
2381: }
1.259 www 2382: if ($coursedoc) {
1.638 albertel 2383: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2384: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2385: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2386: return &finishuserfileupload($docuname,$docudom,
2387: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2388: $codebase,$thumbwidth,$thumbheight,
2389: $resizewidth,$resizeheight);
1.481 raeburn 2390: } else {
1.620 albertel 2391: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2392: return &process_coursefile('uploaddoc',$docuname,$docudom,
2393: $fname,$formname,$parser,
2394: $allfiles,$codebase);
1.481 raeburn 2395: }
1.719 banghart 2396: } elsif (defined($destuname)) {
2397: my $docuname=$destuname;
2398: my $docudom=$destudom;
1.860 raeburn 2399: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2400: $parser,$allfiles,$codebase,
1.1051 raeburn 2401: $thumbwidth,$thumbheight,
2402: $resizewidth,$resizeheight);
1.719 banghart 2403:
1.259 www 2404: } else {
1.638 albertel 2405: my $docuname=$env{'user.name'};
2406: my $docudom=$env{'user.domain'};
1.714 raeburn 2407: if (exists($env{'form.group'})) {
2408: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2409: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2410: }
1.860 raeburn 2411: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2412: $parser,$allfiles,$codebase,
1.1051 raeburn 2413: $thumbwidth,$thumbheight,
2414: $resizewidth,$resizeheight);
1.259 www 2415: }
1.271 www 2416: }
2417:
2418: sub finishuserfileupload {
1.860 raeburn 2419: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051 raeburn 2420: $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477 raeburn 2421: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2422: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2423:
1.860 raeburn 2424: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2425: $file=$fname;
2426: if ($fname=~m|/|) {
2427: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2428: $path.=$fnamepath.'/';
2429: }
1.259 www 2430: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2431: my $count;
2432: for ($count=4;$count<=$#parts;$count++) {
2433: $filepath.="/$parts[$count]";
2434: if ((-e $filepath)!=1) {
2435: mkdir($filepath,0777);
2436: }
2437: }
1.984 neumanie 2438:
1.258 www 2439: # Save the file
2440: {
1.701 albertel 2441: if (!open(FH,'>'.$filepath.'/'.$file)) {
2442: &logthis('Failed to create '.$filepath.'/'.$file);
2443: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2444: return '/adm/notfound.html';
2445: }
2446: if (!print FH ($env{'form.'.$formname})) {
2447: &logthis('Failed to write to '.$filepath.'/'.$file);
2448: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2449: return '/adm/notfound.html';
2450: }
1.570 albertel 2451: close(FH);
1.1051 raeburn 2452: if ($resizewidth && $resizeheight) {
2453: my $mm = new File::MMagic;
2454: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2455: if ($mime_type =~ m{^image/}) {
2456: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2457: }
1.977 amueller 2458: }
1.258 www 2459: }
1.637 raeburn 2460: if ($parser eq 'parse') {
1.1024 raeburn 2461: my $mm = new File::MMagic;
2462: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2463: if ($mime_type eq 'text/html') {
2464: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2465: $allfiles,$codebase);
2466: unless ($parse_result eq 'ok') {
2467: &logthis('Failed to parse '.$filepath.$file.
2468: ' for embedded media: '.$parse_result);
2469: }
1.637 raeburn 2470: }
2471: }
1.860 raeburn 2472: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2473: my $input = $filepath.'/'.$file;
2474: my $output = $filepath.'/'.'tn-'.$file;
2475: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2476: system("convert -sample $thumbsize $input $output");
2477: if (-e $filepath.'/'.'tn-'.$file) {
2478: $fetchthumb = 1;
2479: }
2480: }
1.858 raeburn 2481:
1.259 www 2482: # Notify homeserver to grep it
2483: #
1.984 neumanie 2484: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2485: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2486: if ($fetchresult eq 'ok') {
1.860 raeburn 2487: if ($fetchthumb) {
2488: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2489: if ($thumbresult ne 'ok') {
2490: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2491: $docuhome.': '.$thumbresult);
2492: }
2493: }
1.259 www 2494: #
1.258 www 2495: # Return the URL to it
1.494 albertel 2496: return '/uploaded/'.$path.$file;
1.263 www 2497: } else {
1.494 albertel 2498: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2499: ': '.$fetchresult);
1.263 www 2500: return '/adm/notfound.html';
1.858 raeburn 2501: }
1.493 albertel 2502: }
2503:
1.637 raeburn 2504: sub extract_embedded_items {
1.961 raeburn 2505: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2506: my @state = ();
2507: my %javafiles = (
2508: codebase => '',
2509: code => '',
2510: archive => ''
2511: );
2512: my %mediafiles = (
2513: src => '',
2514: movie => '',
2515: );
1.648 raeburn 2516: my $p;
2517: if ($content) {
2518: $p = HTML::LCParser->new($content);
2519: } else {
1.961 raeburn 2520: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2521: }
1.641 albertel 2522: while (my $t=$p->get_token()) {
1.640 albertel 2523: if ($t->[0] eq 'S') {
2524: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2525: push(@state, $tagname);
1.648 raeburn 2526: if (lc($tagname) eq 'allow') {
2527: &add_filetype($allfiles,$attr->{'src'},'src');
2528: }
1.640 albertel 2529: if (lc($tagname) eq 'img') {
2530: &add_filetype($allfiles,$attr->{'src'},'src');
2531: }
1.886 albertel 2532: if (lc($tagname) eq 'a') {
2533: &add_filetype($allfiles,$attr->{'href'},'href');
2534: }
1.645 raeburn 2535: if (lc($tagname) eq 'script') {
2536: if ($attr->{'archive'} =~ /\.jar$/i) {
2537: &add_filetype($allfiles,$attr->{'archive'},'archive');
2538: } else {
2539: &add_filetype($allfiles,$attr->{'src'},'src');
2540: }
2541: }
2542: if (lc($tagname) eq 'link') {
2543: if (lc($attr->{'rel'}) eq 'stylesheet') {
2544: &add_filetype($allfiles,$attr->{'href'},'href');
2545: }
2546: }
1.640 albertel 2547: if (lc($tagname) eq 'object' ||
2548: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2549: foreach my $item (keys(%javafiles)) {
2550: $javafiles{$item} = '';
2551: }
2552: }
2553: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2554: my $name = lc($attr->{'name'});
2555: foreach my $item (keys(%javafiles)) {
2556: if ($name eq $item) {
2557: $javafiles{$item} = $attr->{'value'};
2558: last;
2559: }
2560: }
2561: foreach my $item (keys(%mediafiles)) {
2562: if ($name eq $item) {
2563: &add_filetype($allfiles, $attr->{'value'}, 'value');
2564: last;
2565: }
2566: }
2567: }
2568: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2569: foreach my $item (keys(%javafiles)) {
2570: if ($attr->{$item}) {
2571: $javafiles{$item} = $attr->{$item};
2572: last;
2573: }
2574: }
2575: foreach my $item (keys(%mediafiles)) {
2576: if ($attr->{$item}) {
2577: &add_filetype($allfiles,$attr->{$item},$item);
2578: last;
2579: }
2580: }
2581: }
2582: } elsif ($t->[0] eq 'E') {
2583: my ($tagname) = ($t->[1]);
2584: if ($javafiles{'codebase'} ne '') {
2585: $javafiles{'codebase'} .= '/';
2586: }
2587: if (lc($tagname) eq 'applet' ||
2588: lc($tagname) eq 'object' ||
2589: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2590: ) {
2591: foreach my $item (keys(%javafiles)) {
2592: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2593: my $file=$javafiles{'codebase'}.$javafiles{$item};
2594: &add_filetype($allfiles,$file,$item);
2595: }
2596: }
2597: }
2598: pop @state;
2599: }
2600: }
1.637 raeburn 2601: return 'ok';
2602: }
2603:
1.639 albertel 2604: sub add_filetype {
2605: my ($allfiles,$file,$type)=@_;
2606: if (exists($allfiles->{$file})) {
2607: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2608: push(@{$allfiles->{$file}}, &escape($type));
2609: }
2610: } else {
2611: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2612: }
2613: }
2614:
1.493 albertel 2615: sub removeuploadedurl {
1.984 neumanie 2616: my ($url)=@_;
2617: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2618: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2619: }
2620:
2621: sub removeuserfile {
2622: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2623: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2624: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2625: if ($result eq 'ok') {
1.798 raeburn 2626: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2627: my $metafile = $fname.'.meta';
2628: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2629: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2630: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2631: my $sqlresult =
1.823 albertel 2632: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2633: 'portfolio_metadata',$group,
2634: 'delete');
1.798 raeburn 2635: }
2636: }
2637: return $result;
1.257 www 2638: }
1.15 www 2639:
1.530 albertel 2640: sub mkdiruserfile {
2641: my ($docuname,$docudom,$dir)=@_;
2642: my $home=&homeserver($docuname,$docudom);
2643: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2644: }
2645:
1.531 albertel 2646: sub renameuserfile {
2647: my ($docuname,$docudom,$old,$new)=@_;
2648: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2649: my $result = &reply("renameuserfile:$docudom:$docuname:".
2650: &escape("$old").':'.&escape("$new"),$home);
2651: if ($result eq 'ok') {
2652: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2653: my $oldmeta = $old.'.meta';
2654: my $newmeta = $new.'.meta';
2655: my $metaresult =
2656: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2657: my $url = "/uploaded/$docudom/$docuname/$old";
2658: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2659: my $sqlresult =
1.823 albertel 2660: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2661: 'portfolio_metadata',$group,
2662: 'delete');
1.798 raeburn 2663: }
2664: }
2665: return $result;
1.531 albertel 2666: }
2667:
1.14 www 2668: # ------------------------------------------------------------------------- Log
2669:
2670: sub log {
2671: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2672: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2673: }
2674:
2675: # ------------------------------------------------------------------ Course Log
1.352 www 2676: #
2677: # This routine flushes several buffers of non-mission-critical nature
2678: #
1.157 www 2679:
2680: sub flushcourselogs {
1.352 www 2681: &logthis('Flushing log buffers');
2682: #
2683: # course logs
2684: # This is a log of all transactions in a course, which can be used
2685: # for data mining purposes
2686: #
2687: # It also collects the courseid database, which lists last transaction
2688: # times and course titles for all courseids
2689: #
2690: my %courseidbuffer=();
1.921 raeburn 2691: foreach my $crsid (keys(%courselogs)) {
1.352 www 2692: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2693: &escape($courselogs{$crsid}),
2694: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2695: delete $courselogs{$crsid};
2696: } else {
2697: &logthis('Failed to flush log buffer for '.$crsid);
2698: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2699: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2700: " exceeded maximum size, deleting.</font>");
2701: delete $courselogs{$crsid};
2702: }
1.352 www 2703: }
1.920 raeburn 2704: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2705: 'description' => $coursedescrbuf{$crsid},
2706: 'inst_code' => $courseinstcodebuf{$crsid},
2707: 'type' => $coursetypebuf{$crsid},
2708: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2709: };
1.191 harris41 2710: }
1.352 www 2711: #
2712: # Write course id database (reverse lookup) to homeserver of courses
2713: # Is used in pickcourse
2714: #
1.840 albertel 2715: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2716: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2717: $courseidbuffer{$crs_home},
2718: $crs_home,'timeonly');
1.352 www 2719: }
2720: #
2721: # File accesses
2722: # Writes to the dynamic metadata of resources to get hit counts, etc.
2723: #
1.449 matthew 2724: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2725: if ($entry =~ /___count$/) {
2726: my ($dom,$name);
1.807 albertel 2727: ($dom,$name,undef)=
1.811 albertel 2728: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2729: if (! defined($dom) || $dom eq '' ||
2730: ! defined($name) || $name eq '') {
1.620 albertel 2731: my $cid = $env{'request.course.id'};
2732: $dom = $env{'request.'.$cid.'.domain'};
2733: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2734: }
1.450 matthew 2735: my $value = $accesshash{$entry};
2736: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2737: my %temphash=($url => $value);
1.449 matthew 2738: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2739: if ($result eq 'ok') {
2740: delete $accesshash{$entry};
2741: } elsif ($result eq 'unknown_cmd') {
2742: # Target server has old code running on it.
1.450 matthew 2743: my %temphash=($entry => $value);
1.449 matthew 2744: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2745: delete $accesshash{$entry};
2746: }
2747: }
2748: } else {
1.811 albertel 2749: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2750: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2751: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2752: delete $accesshash{$entry};
2753: }
1.185 www 2754: }
1.191 harris41 2755: }
1.352 www 2756: #
2757: # Roles
2758: # Reverse lookup of user roles for course faculty/staff and co-authorship
2759: #
1.800 albertel 2760: foreach my $entry (keys(%userrolehash)) {
1.351 www 2761: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2762: split(/\:/,$entry);
2763: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2764: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2765: $rudom,$runame) eq 'ok') {
2766: delete $userrolehash{$entry};
2767: }
2768: }
1.662 raeburn 2769: #
2770: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2771: #
2772: my %domrolebuffer = ();
1.1000 raeburn 2773: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2774: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2775: if ($domrolebuffer{$rudom}) {
2776: $domrolebuffer{$rudom}.='&'.&escape($entry).
2777: '='.&escape($domainrolehash{$entry});
2778: } else {
2779: $domrolebuffer{$rudom}.=&escape($entry).
2780: '='.&escape($domainrolehash{$entry});
2781: }
2782: delete $domainrolehash{$entry};
2783: }
2784: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2785: my %servers = &get_servers($dom,'library');
2786: foreach my $tryserver (keys(%servers)) {
2787: unless (&reply('domroleput:'.$dom.':'.
2788: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2789: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2790: }
1.662 raeburn 2791: }
2792: }
1.186 www 2793: $dumpcount++;
1.157 www 2794: }
2795:
2796: sub courselog {
2797: my $what=shift;
1.158 www 2798: $what=time.':'.$what;
1.620 albertel 2799: unless ($env{'request.course.id'}) { return ''; }
2800: $coursedombuf{$env{'request.course.id'}}=
2801: $env{'course.'.$env{'request.course.id'}.'.domain'};
2802: $coursenumbuf{$env{'request.course.id'}}=
2803: $env{'course.'.$env{'request.course.id'}.'.num'};
2804: $coursehombuf{$env{'request.course.id'}}=
2805: $env{'course.'.$env{'request.course.id'}.'.home'};
2806: $coursedescrbuf{$env{'request.course.id'}}=
2807: $env{'course.'.$env{'request.course.id'}.'.description'};
2808: $courseinstcodebuf{$env{'request.course.id'}}=
2809: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2810: $courseownerbuf{$env{'request.course.id'}}=
2811: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2812: $coursetypebuf{$env{'request.course.id'}}=
2813: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2814: if (defined $courselogs{$env{'request.course.id'}}) {
2815: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2816: } else {
1.620 albertel 2817: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2818: }
1.620 albertel 2819: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2820: &flushcourselogs();
2821: }
1.158 www 2822: }
2823:
2824: sub courseacclog {
2825: my $fnsymb=shift;
1.620 albertel 2826: unless ($env{'request.course.id'}) { return ''; }
2827: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2828: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2829: $what.=':POST';
1.583 matthew 2830: # FIXME: Probably ought to escape things....
1.800 albertel 2831: foreach my $key (keys(%env)) {
2832: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2833: my $formitem = $1;
2834: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2835: $what.=':'.$formitem.'='.$env{$key};
2836: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2837: $what.=':'.$formitem.'='.$env{$key};
2838: }
1.158 www 2839: }
1.191 harris41 2840: }
1.583 matthew 2841: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2842: # FIXME: We should not be depending on a form parameter that someone
2843: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2844: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2845: $what.= ':POST';
2846: # FIXME: Probably ought to escape things....
2847: foreach my $element ('courseexp','crsfulltext','crsrelated',
2848: 'crsdiscuss') {
1.620 albertel 2849: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2850: }
2851: }
1.158 www 2852: }
2853: &courselog($what);
1.149 www 2854: }
2855:
1.185 www 2856: sub countacc {
2857: my $url=&declutter(shift);
1.458 matthew 2858: return if (! defined($url) || $url eq '');
1.620 albertel 2859: unless ($env{'request.course.id'}) { return ''; }
2860: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2861: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2862: $accesshash{$key}++;
1.185 www 2863: }
1.349 www 2864:
1.361 www 2865: sub linklog {
2866: my ($from,$to)=@_;
2867: $from=&declutter($from);
2868: $to=&declutter($to);
2869: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2870: $accesshash{$to.'___'.$from.'___goto'}=1;
2871: }
2872:
1.349 www 2873: sub userrolelog {
2874: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2875: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2876: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2877: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2878: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2879: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2880: $userrolehash
2881: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2882: =$tend.':'.$tstart;
1.662 raeburn 2883: }
1.898 albertel 2884: if (($env{'request.role'} =~ /dc\./) &&
2885: (($trole=~/^au/) || ($trole=~/^in/) ||
2886: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2887: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2888: ($trole=~/^co/))) {
1.898 albertel 2889: $userrolehash
2890: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2891: =$tend.':'.$tstart;
2892: }
1.662 raeburn 2893: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2894: ($trole=~/^li/) || ($trole=~/^li/) ||
2895: ($trole=~/^au/) || ($trole=~/^dg/) ||
2896: ($trole=~/^sc/)) {
2897: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2898: $domainrolehash
2899: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2900: = $tend.':'.$tstart;
2901: }
1.351 www 2902: }
2903:
1.957 raeburn 2904: sub courserolelog {
2905: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2906: if (($trole eq 'cc') || ($trole eq 'in') ||
2907: ($trole eq 'ep') || ($trole eq 'ad') ||
2908: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 2909: ($trole=~/^cr/) || ($trole eq 'gr') ||
2910: ($trole eq 'co')) {
1.957 raeburn 2911: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2912: my $cdom = $1;
2913: my $cnum = $2;
2914: my $sec = $3;
2915: my $namespace = 'rolelog';
2916: my %storehash = (
2917: role => $trole,
2918: start => $tstart,
2919: end => $tend,
2920: selfenroll => $selfenroll,
2921: context => $context,
2922: );
2923: if ($trole eq 'gr') {
2924: $namespace = 'groupslog';
2925: $storehash{'group'} = $sec;
2926: } else {
2927: $storehash{'section'} = $sec;
2928: }
2929: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2930: if (($trole ne 'st') || ($sec ne '')) {
2931: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2932: }
1.957 raeburn 2933: }
2934: }
2935: return;
2936: }
2937:
1.351 www 2938: sub get_course_adv_roles {
1.948 raeburn 2939: my ($cid,$codes) = @_;
1.620 albertel 2940: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2941: my %coursehash=&coursedescription($cid);
1.988 raeburn 2942: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 2943: my %nothide=();
1.800 albertel 2944: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 2945: if ($user !~ /:/) {
2946: $nothide{join(':',split(/[\@]/,$user))}=1;
2947: } else {
2948: $nothide{$user}=1;
2949: }
1.470 www 2950: }
1.351 www 2951: my %returnhash=();
2952: my %dumphash=
2953: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2954: my $now=time;
1.997 raeburn 2955: my %privileged;
1.1000 raeburn 2956: foreach my $entry (keys(%dumphash)) {
1.800 albertel 2957: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2958: if (($tstart) && ($tstart<0)) { next; }
2959: if (($tend) && ($tend<$now)) { next; }
2960: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2961: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2962: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 2963: unless (ref($privileged{$domain}) eq 'HASH') {
2964: my %dompersonnel =
1.998 raeburn 2965: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 2966: $privileged{$domain} = {};
2967: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 2968: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 2969: foreach my $user (keys(%{$dompersonnel{$server}})) {
2970: my ($trole,$uname,$udom) = split(/:/,$user);
2971: $privileged{$udom}{$uname} = 1;
2972: }
2973: }
2974: }
2975: }
2976: if ((exists($privileged{$domain}{$username})) &&
2977: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2978: if ($role eq 'cr') { next; }
1.948 raeburn 2979: if ($codes) {
2980: if ($section) { $role .= ':'.$section; }
2981: if ($returnhash{$role}) {
2982: $returnhash{$role}.=','.$username.':'.$domain;
2983: } else {
2984: $returnhash{$role}=$username.':'.$domain;
2985: }
1.351 www 2986: } else {
1.988 raeburn 2987: my $key=&plaintext($role,$crstype);
1.973 bisitz 2988: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 2989: if ($returnhash{$key}) {
2990: $returnhash{$key}.=','.$username.':'.$domain;
2991: } else {
2992: $returnhash{$key}=$username.':'.$domain;
2993: }
1.351 www 2994: }
1.948 raeburn 2995: }
1.400 www 2996: return %returnhash;
2997: }
2998:
2999: sub get_my_roles {
1.937 raeburn 3000: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3001: unless (defined($uname)) { $uname=$env{'user.name'}; }
3002: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3003: my (%dumphash,%nothide);
1.858 raeburn 3004: if ($context eq 'userroles') {
3005: %dumphash = &dump('roles',$udom,$uname);
3006: } else {
3007: %dumphash=
1.400 www 3008: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3009: if ($hidepriv) {
3010: my %coursehash=&coursedescription($udom.'_'.$uname);
3011: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3012: if ($user !~ /:/) {
3013: $nothide{join(':',split(/[\@]/,$user))} = 1;
3014: } else {
3015: $nothide{$user} = 1;
3016: }
3017: }
3018: }
1.858 raeburn 3019: }
1.400 www 3020: my %returnhash=();
3021: my $now=time;
1.999 raeburn 3022: my %privileged;
1.800 albertel 3023: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3024: my ($role,$tend,$tstart);
3025: if ($context eq 'userroles') {
3026: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3027: } else {
3028: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3029: }
1.400 www 3030: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3031: my $status = 'active';
1.939 raeburn 3032: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3033: $status = 'previous';
3034: }
3035: if (($tstart) && ($now<$tstart)) {
3036: $status = 'future';
3037: }
3038: if (ref($types) eq 'ARRAY') {
3039: if (!grep(/^\Q$status\E$/,@{$types})) {
3040: next;
3041: }
3042: } else {
3043: if ($status ne 'active') {
3044: next;
3045: }
3046: }
1.867 raeburn 3047: my ($rolecode,$username,$domain,$section,$area);
3048: if ($context eq 'userroles') {
3049: ($area,$rolecode) = split(/_/,$entry);
3050: (undef,$domain,$username,$section) = split(/\//,$area);
3051: } else {
3052: ($role,$username,$domain,$section) = split(/\:/,$entry);
3053: }
1.832 raeburn 3054: if (ref($roledoms) eq 'ARRAY') {
3055: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3056: next;
3057: }
3058: }
3059: if (ref($roles) eq 'ARRAY') {
3060: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3061: if ($role =~ /^cr\//) {
3062: if (!grep(/^cr$/,@{$roles})) {
3063: next;
3064: }
3065: } else {
3066: next;
3067: }
1.832 raeburn 3068: }
1.867 raeburn 3069: }
1.937 raeburn 3070: if ($hidepriv) {
1.999 raeburn 3071: if ($context eq 'userroles') {
3072: if ((&privileged($username,$domain)) &&
3073: (!$nothide{$username.':'.$domain})) {
3074: next;
3075: }
3076: } else {
3077: unless (ref($privileged{$domain}) eq 'HASH') {
3078: my %dompersonnel =
3079: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3080: $privileged{$domain} = {};
3081: if (keys(%dompersonnel)) {
3082: foreach my $server (keys(%dompersonnel)) {
3083: if (ref($dompersonnel{$server}) eq 'HASH') {
3084: foreach my $user (keys(%{$dompersonnel{$server}})) {
3085: my ($trole,$uname,$udom) = split(/:/,$user);
3086: $privileged{$udom}{$uname} = $trole;
3087: }
3088: }
3089: }
3090: }
3091: }
3092: if (exists($privileged{$domain}{$username})) {
3093: if (!$nothide{$username.':'.$domain}) {
3094: next;
3095: }
3096: }
1.937 raeburn 3097: }
3098: }
1.933 raeburn 3099: if ($withsec) {
3100: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3101: $tstart.':'.$tend;
3102: } else {
3103: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3104: }
1.832 raeburn 3105: }
1.373 www 3106: return %returnhash;
1.399 www 3107: }
3108:
3109: # ----------------------------------------------------- Frontpage Announcements
3110: #
3111: #
3112:
3113: sub postannounce {
3114: my ($server,$text)=@_;
1.844 albertel 3115: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3116: unless ($text=~/\w/) { $text=''; }
3117: return &reply('setannounce:'.&escape($text),$server);
3118: }
3119:
3120: sub getannounce {
1.448 albertel 3121:
3122: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3123: my $announcement='';
1.800 albertel 3124: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3125: close($fh);
1.399 www 3126: if ($announcement=~/\w/) {
3127: return
3128: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3129: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3130: } else {
3131: return '';
3132: }
3133: } else {
3134: return '';
3135: }
1.351 www 3136: }
1.353 www 3137:
3138: # ---------------------------------------------------------- Course ID routines
3139: # Deal with domain's nohist_courseid.db files
3140: #
3141:
3142: sub courseidput {
1.921 raeburn 3143: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3144: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3145: my $outcome;
3146: if ($caller eq 'timeonly') {
3147: my $cids = '';
3148: foreach my $item (keys(%$storehash)) {
3149: $cids.=&escape($item).'&';
3150: }
3151: $cids=~s/\&$//;
3152: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3153: $coursehome);
3154: } else {
3155: my $items = '';
3156: foreach my $item (keys(%$storehash)) {
3157: $items.= &escape($item).'='.
3158: &freeze_escape($$storehash{$item}).'&';
3159: }
3160: $items=~s/\&$//;
3161: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3162: $coursehome);
1.918 raeburn 3163: }
3164: if ($outcome eq 'unknown_cmd') {
3165: my $what;
3166: foreach my $cid (keys(%$storehash)) {
3167: $what .= &escape($cid).'=';
1.921 raeburn 3168: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3169: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3170: }
3171: $what =~ s/\:$/&/;
3172: }
3173: $what =~ s/\&$//;
3174: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3175: } else {
3176: return $outcome;
3177: }
1.353 www 3178: }
3179:
3180: sub courseiddump {
1.921 raeburn 3181: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3182: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3183: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3184: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3185: my $as_hash = 1;
3186: my %returnhash;
3187: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3188: my %libserv = &all_library();
3189: foreach my $tryserver (keys(%libserv)) {
3190: if ( ( $hostidflag == 1
3191: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3192: || (!defined($hostidflag)) ) {
3193:
1.918 raeburn 3194: if (($domfilter eq '') ||
3195: (&host_domain($tryserver) eq $domfilter)) {
3196: my $rep =
3197: &reply('courseiddump:'.&host_domain($tryserver).':'.
3198: $sincefilter.':'.&escape($descfilter).':'.
3199: &escape($instcodefilter).':'.&escape($ownerfilter).
3200: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3201: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3202: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3203: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3204: &escape($cc_clone).':'.$cloneonly.':'.
3205: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3206: &escape($creationcontext).':'.$domcloner,
3207: $tryserver);
1.918 raeburn 3208: my @pairs=split(/\&/,$rep);
3209: foreach my $item (@pairs) {
3210: my ($key,$value)=split(/\=/,$item,2);
3211: $key = &unescape($key);
3212: next if ($key =~ /^error: 2 /);
3213: my $result = &thaw_unescape($value);
3214: if (ref($result) eq 'HASH') {
3215: $returnhash{$key}=$result;
3216: } else {
1.921 raeburn 3217: my @responses = split(/:/,$value);
3218: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3219: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3220: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3221: }
1.1008 raeburn 3222: }
1.353 www 3223: }
3224: }
3225: }
3226: }
3227: return %returnhash;
3228: }
3229:
1.1055 raeburn 3230: sub courselastaccess {
3231: my ($cdom,$cnum,$hostidref) = @_;
3232: my %returnhash;
3233: if ($cdom && $cnum) {
3234: my $chome = &homeserver($cnum,$cdom);
3235: if ($chome ne 'no_host') {
3236: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3237: &extract_lastaccess(\%returnhash,$rep);
3238: }
3239: } else {
3240: if (!$cdom) { $cdom=''; }
3241: my %libserv = &all_library();
3242: foreach my $tryserver (keys(%libserv)) {
3243: if (ref($hostidref) eq 'ARRAY') {
3244: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3245: }
3246: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3247: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3248: &extract_lastaccess(\%returnhash,$rep);
3249: }
3250: }
3251: }
3252: return %returnhash;
3253: }
3254:
3255: sub extract_lastaccess {
3256: my ($returnhash,$rep) = @_;
3257: if (ref($returnhash) eq 'HASH') {
3258: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3259: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3260: $rep eq '') {
3261: my @pairs=split(/\&/,$rep);
3262: foreach my $item (@pairs) {
3263: my ($key,$value)=split(/\=/,$item,2);
3264: $key = &unescape($key);
3265: next if ($key =~ /^error: 2 /);
3266: $returnhash->{$key} = &thaw_unescape($value);
3267: }
3268: }
3269: }
3270: return;
3271: }
3272:
1.658 raeburn 3273: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3274:
3275: sub dcmailput {
1.685 raeburn 3276: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3277: my $status = &Apache::lonnet::critical(
1.740 www 3278: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3279: &escape($message),$server);
1.662 raeburn 3280: return $status;
3281: }
3282:
1.658 raeburn 3283: sub dcmaildump {
3284: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3285: my %returnhash=();
1.846 albertel 3286:
3287: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3288: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3289: &escape($enddate).':';
3290: my @esc_senders=map { &escape($_)} @$senders;
3291: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3292: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3293: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3294: if (($key) && ($value)) {
3295: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3296: }
3297: }
3298: }
3299: return %returnhash;
3300: }
1.662 raeburn 3301: # ---------------------------------------------------------- Domain roles
3302:
3303: sub get_domain_roles {
3304: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3305: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3306: $startdate = '.';
3307: }
1.1018 raeburn 3308: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3309: $enddate = '.';
3310: }
1.922 raeburn 3311: my $rolelist;
3312: if (ref($roles) eq 'ARRAY') {
3313: $rolelist = join(':',@{$roles});
3314: }
1.662 raeburn 3315: my %personnel = ();
1.841 albertel 3316:
3317: my %servers = &get_servers($dom,'library');
3318: foreach my $tryserver (keys(%servers)) {
3319: %{$personnel{$tryserver}}=();
3320: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3321: &escape($startdate).':'.
3322: &escape($enddate).':'.
3323: &escape($rolelist), $tryserver))) {
3324: my ($key,$value) = split(/\=/,$line,2);
3325: if (($key) && ($value)) {
3326: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3327: }
3328: }
1.662 raeburn 3329: }
3330: return %personnel;
3331: }
1.658 raeburn 3332:
1.1057 www 3333: # ----------------------------------------------------------- Interval timing
1.149 www 3334:
1.504 albertel 3335: sub get_first_access {
3336: my ($type,$argsymb)=@_;
1.790 albertel 3337: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3338: if ($argsymb) { $symb=$argsymb; }
3339: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3340: if ($type eq 'course') {
3341: $res='course';
3342: } elsif ($type eq 'map') {
1.588 albertel 3343: $res=&symbread($map);
3344: } else {
3345: $res=$symb;
3346: }
3347: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3348: return $times{"$courseid\0$res"};
1.504 albertel 3349: }
3350:
3351: sub set_first_access {
3352: my ($type)=@_;
1.790 albertel 3353: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3354: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3355: if ($type eq 'course') {
3356: $res='course';
3357: } elsif ($type eq 'map') {
1.588 albertel 3358: $res=&symbread($map);
3359: } else {
3360: $res=$symb;
3361: }
3362: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3363: if (!$firstaccess) {
1.588 albertel 3364: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3365: }
3366: return 'already_set';
1.504 albertel 3367: }
3368:
1.110 www 3369: # --------------------------------------------- Set Expire Date for Spreadsheet
3370:
3371: sub expirespread {
3372: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3373: my $cid=$env{'request.course.id'};
1.110 www 3374: if ($cid) {
3375: my $now=time;
3376: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3377: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3378: $env{'course.'.$cid.'.num'}.
1.110 www 3379: ':nohist_expirationdates:'.
3380: &escape($key).'='.$now,
1.620 albertel 3381: $env{'course.'.$cid.'.home'})
1.110 www 3382: }
3383: return 'ok';
1.14 www 3384: }
3385:
1.109 www 3386: # ----------------------------------------------------- Devalidate Spreadsheets
3387:
3388: sub devalidate {
1.325 www 3389: my ($symb,$uname,$udom)=@_;
1.620 albertel 3390: my $cid=$env{'request.course.id'};
1.109 www 3391: if ($cid) {
1.391 matthew 3392: # delete the stored spreadsheets for
3393: # - the student level sheet of this user in course's homespace
3394: # - the assessment level sheet for this resource
3395: # for this user in user's homespace
1.553 albertel 3396: # - current conditional state info
1.325 www 3397: my $key=$uname.':'.$udom.':';
1.109 www 3398: my $status=
1.299 matthew 3399: &del('nohist_calculatedsheets',
1.391 matthew 3400: [$key.'studentcalc:'],
1.620 albertel 3401: $env{'course.'.$cid.'.domain'},
3402: $env{'course.'.$cid.'.num'})
1.133 albertel 3403: .' '.
3404: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3405: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3406: unless ($status eq 'ok ok') {
3407: &logthis('Could not devalidate spreadsheet '.
1.325 www 3408: $uname.' at '.$udom.' for '.
1.109 www 3409: $symb.': '.$status);
1.133 albertel 3410: }
1.553 albertel 3411: &delenv('user.state.'.$cid);
1.109 www 3412: }
3413: }
3414:
1.265 albertel 3415: sub get_scalar {
3416: my ($string,$end) = @_;
3417: my $value;
3418: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3419: $value = $1;
3420: } elsif ($$string =~ s/^([^&]*?)&//) {
3421: $value = $1;
3422: }
3423: return &unescape($value);
3424: }
3425:
3426: sub array2str {
3427: my (@array) = @_;
3428: my $result=&arrayref2str(\@array);
3429: $result=~s/^__ARRAY_REF__//;
3430: $result=~s/__END_ARRAY_REF__$//;
3431: return $result;
3432: }
3433:
1.204 albertel 3434: sub arrayref2str {
3435: my ($arrayref) = @_;
1.265 albertel 3436: my $result='__ARRAY_REF__';
1.204 albertel 3437: foreach my $elem (@$arrayref) {
1.265 albertel 3438: if(ref($elem) eq 'ARRAY') {
3439: $result.=&arrayref2str($elem).'&';
3440: } elsif(ref($elem) eq 'HASH') {
3441: $result.=&hashref2str($elem).'&';
3442: } elsif(ref($elem)) {
3443: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3444: } else {
3445: $result.=&escape($elem).'&';
3446: }
3447: }
3448: $result=~s/\&$//;
1.265 albertel 3449: $result .= '__END_ARRAY_REF__';
1.204 albertel 3450: return $result;
3451: }
3452:
1.168 albertel 3453: sub hash2str {
1.204 albertel 3454: my (%hash) = @_;
3455: my $result=&hashref2str(\%hash);
1.265 albertel 3456: $result=~s/^__HASH_REF__//;
3457: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3458: return $result;
3459: }
3460:
3461: sub hashref2str {
3462: my ($hashref)=@_;
1.265 albertel 3463: my $result='__HASH_REF__';
1.800 albertel 3464: foreach my $key (sort(keys(%$hashref))) {
3465: if (ref($key) eq 'ARRAY') {
3466: $result.=&arrayref2str($key).'=';
3467: } elsif (ref($key) eq 'HASH') {
3468: $result.=&hashref2str($key).'=';
3469: } elsif (ref($key)) {
1.265 albertel 3470: $result.='=';
1.800 albertel 3471: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3472: } else {
1.800 albertel 3473: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3474: }
3475:
1.800 albertel 3476: if(ref($hashref->{$key}) eq 'ARRAY') {
3477: $result.=&arrayref2str($hashref->{$key}).'&';
3478: } elsif(ref($hashref->{$key}) eq 'HASH') {
3479: $result.=&hashref2str($hashref->{$key}).'&';
3480: } elsif(ref($hashref->{$key})) {
1.265 albertel 3481: $result.='&';
1.800 albertel 3482: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3483: } else {
1.800 albertel 3484: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3485: }
3486: }
1.168 albertel 3487: $result=~s/\&$//;
1.265 albertel 3488: $result .= '__END_HASH_REF__';
1.168 albertel 3489: return $result;
3490: }
3491:
3492: sub str2hash {
1.265 albertel 3493: my ($string)=@_;
3494: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3495: return %$hash;
3496: }
3497:
3498: sub str2hashref {
1.168 albertel 3499: my ($string) = @_;
1.265 albertel 3500:
3501: my %hash;
3502:
3503: if($string !~ /^__HASH_REF__/) {
3504: if (! ($string eq '' || !defined($string))) {
3505: $hash{'error'}='Not hash reference';
3506: }
3507: return (\%hash, $string);
3508: }
3509:
3510: $string =~ s/^__HASH_REF__//;
3511:
3512: while($string !~ /^__END_HASH_REF__/) {
3513: #key
3514: my $key='';
3515: if($string =~ /^__HASH_REF__/) {
3516: ($key, $string)=&str2hashref($string);
3517: if(defined($key->{'error'})) {
3518: $hash{'error'}='Bad data';
3519: return (\%hash, $string);
3520: }
3521: } elsif($string =~ /^__ARRAY_REF__/) {
3522: ($key, $string)=&str2arrayref($string);
3523: if($key->[0] eq 'Array reference error') {
3524: $hash{'error'}='Bad data';
3525: return (\%hash, $string);
3526: }
3527: } else {
3528: $string =~ s/^(.*?)=//;
1.267 albertel 3529: $key=&unescape($1);
1.265 albertel 3530: }
3531: $string =~ s/^=//;
3532:
3533: #value
3534: my $value='';
3535: if($string =~ /^__HASH_REF__/) {
3536: ($value, $string)=&str2hashref($string);
3537: if(defined($value->{'error'})) {
3538: $hash{'error'}='Bad data';
3539: return (\%hash, $string);
3540: }
3541: } elsif($string =~ /^__ARRAY_REF__/) {
3542: ($value, $string)=&str2arrayref($string);
3543: if($value->[0] eq 'Array reference error') {
3544: $hash{'error'}='Bad data';
3545: return (\%hash, $string);
3546: }
3547: } else {
3548: $value=&get_scalar(\$string,'__END_HASH_REF__');
3549: }
3550: $string =~ s/^&//;
3551:
3552: $hash{$key}=$value;
1.204 albertel 3553: }
1.265 albertel 3554:
3555: $string =~ s/^__END_HASH_REF__//;
3556:
3557: return (\%hash, $string);
1.204 albertel 3558: }
3559:
3560: sub str2array {
1.265 albertel 3561: my ($string)=@_;
3562: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3563: return @$array;
3564: }
3565:
3566: sub str2arrayref {
1.204 albertel 3567: my ($string) = @_;
1.265 albertel 3568: my @array;
3569:
3570: if($string !~ /^__ARRAY_REF__/) {
3571: if (! ($string eq '' || !defined($string))) {
3572: $array[0]='Array reference error';
3573: }
3574: return (\@array, $string);
3575: }
3576:
3577: $string =~ s/^__ARRAY_REF__//;
3578:
3579: while($string !~ /^__END_ARRAY_REF__/) {
3580: my $value='';
3581: if($string =~ /^__HASH_REF__/) {
3582: ($value, $string)=&str2hashref($string);
3583: if(defined($value->{'error'})) {
3584: $array[0] ='Array reference error';
3585: return (\@array, $string);
3586: }
3587: } elsif($string =~ /^__ARRAY_REF__/) {
3588: ($value, $string)=&str2arrayref($string);
3589: if($value->[0] eq 'Array reference error') {
3590: $array[0] ='Array reference error';
3591: return (\@array, $string);
3592: }
3593: } else {
3594: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3595: }
3596: $string =~ s/^&//;
3597:
3598: push(@array, $value);
1.191 harris41 3599: }
1.265 albertel 3600:
3601: $string =~ s/^__END_ARRAY_REF__//;
3602:
3603: return (\@array, $string);
1.168 albertel 3604: }
3605:
1.167 albertel 3606: # -------------------------------------------------------------------Temp Store
3607:
1.168 albertel 3608: sub tmpreset {
3609: my ($symb,$namespace,$domain,$stuname) = @_;
3610: if (!$symb) {
3611: $symb=&symbread();
1.620 albertel 3612: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3613: }
3614: $symb=escape($symb);
3615:
1.620 albertel 3616: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3617: $namespace=~s/\//\_/g;
3618: $namespace=~s/\W//g;
3619:
1.620 albertel 3620: if (!$domain) { $domain=$env{'user.domain'}; }
3621: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3622: if ($domain eq 'public' && $stuname eq 'public') {
3623: $stuname=$ENV{'REMOTE_ADDR'};
3624: }
1.168 albertel 3625: my $path=$perlvar{'lonDaemons'}.'/tmp';
3626: my %hash;
3627: if (tie(%hash,'GDBM_File',
3628: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3629: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3630: foreach my $key (keys(%hash)) {
1.180 albertel 3631: if ($key=~ /:$symb/) {
1.168 albertel 3632: delete($hash{$key});
3633: }
3634: }
3635: }
3636: }
3637:
1.167 albertel 3638: sub tmpstore {
1.168 albertel 3639: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3640:
3641: if (!$symb) {
3642: $symb=&symbread();
1.620 albertel 3643: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3644: }
3645: $symb=escape($symb);
3646:
3647: if (!$namespace) {
3648: # I don't think we would ever want to store this for a course.
3649: # it seems this will only be used if we don't have a course.
1.620 albertel 3650: #$namespace=$env{'request.course.id'};
1.168 albertel 3651: #if (!$namespace) {
1.620 albertel 3652: $namespace=$env{'request.state'};
1.168 albertel 3653: #}
3654: }
3655: $namespace=~s/\//\_/g;
3656: $namespace=~s/\W//g;
1.620 albertel 3657: if (!$domain) { $domain=$env{'user.domain'}; }
3658: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3659: if ($domain eq 'public' && $stuname eq 'public') {
3660: $stuname=$ENV{'REMOTE_ADDR'};
3661: }
1.168 albertel 3662: my $now=time;
3663: my %hash;
3664: my $path=$perlvar{'lonDaemons'}.'/tmp';
3665: if (tie(%hash,'GDBM_File',
3666: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3667: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3668: $hash{"version:$symb"}++;
3669: my $version=$hash{"version:$symb"};
3670: my $allkeys='';
3671: foreach my $key (keys(%$storehash)) {
3672: $allkeys.=$key.':';
1.591 albertel 3673: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3674: }
3675: $hash{"$version:$symb:timestamp"}=$now;
3676: $allkeys.='timestamp';
3677: $hash{"$version:keys:$symb"}=$allkeys;
3678: if (untie(%hash)) {
3679: return 'ok';
3680: } else {
3681: return "error:$!";
3682: }
3683: } else {
3684: return "error:$!";
3685: }
3686: }
1.167 albertel 3687:
1.168 albertel 3688: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3689:
1.168 albertel 3690: sub tmprestore {
3691: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3692:
1.168 albertel 3693: if (!$symb) {
3694: $symb=&symbread();
1.620 albertel 3695: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3696: }
3697: $symb=escape($symb);
3698:
1.620 albertel 3699: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3700:
1.620 albertel 3701: if (!$domain) { $domain=$env{'user.domain'}; }
3702: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3703: if ($domain eq 'public' && $stuname eq 'public') {
3704: $stuname=$ENV{'REMOTE_ADDR'};
3705: }
1.168 albertel 3706: my %returnhash;
3707: $namespace=~s/\//\_/g;
3708: $namespace=~s/\W//g;
3709: my %hash;
3710: my $path=$perlvar{'lonDaemons'}.'/tmp';
3711: if (tie(%hash,'GDBM_File',
3712: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3713: &GDBM_READER(),0640)) {
1.168 albertel 3714: my $version=$hash{"version:$symb"};
3715: $returnhash{'version'}=$version;
3716: my $scope;
3717: for ($scope=1;$scope<=$version;$scope++) {
3718: my $vkeys=$hash{"$scope:keys:$symb"};
3719: my @keys=split(/:/,$vkeys);
3720: my $key;
3721: $returnhash{"$scope:keys"}=$vkeys;
3722: foreach $key (@keys) {
1.591 albertel 3723: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3724: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3725: }
3726: }
1.168 albertel 3727: if (!(untie(%hash))) {
3728: return "error:$!";
3729: }
3730: } else {
3731: return "error:$!";
3732: }
3733: return %returnhash;
1.167 albertel 3734: }
3735:
1.9 www 3736: # ----------------------------------------------------------------------- Store
3737:
3738: sub store {
1.124 www 3739: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3740: my $home='';
3741:
1.168 albertel 3742: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3743:
1.213 www 3744: $symb=&symbclean($symb);
1.122 albertel 3745: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3746:
1.620 albertel 3747: if (!$domain) { $domain=$env{'user.domain'}; }
3748: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3749:
3750: &devalidate($symb,$stuname,$domain);
1.109 www 3751:
3752: $symb=escape($symb);
1.187 www 3753: if (!$namespace) {
1.620 albertel 3754: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3755: return '';
3756: }
3757: }
1.620 albertel 3758: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3759:
3760: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3761: $$storehash{'host'}=$perlvar{'lonHostID'};
3762:
1.12 www 3763: my $namevalue='';
1.800 albertel 3764: foreach my $key (keys(%$storehash)) {
3765: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3766: }
1.12 www 3767: $namevalue=~s/\&$//;
1.187 www 3768: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3769: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3770: }
3771:
1.47 www 3772: # -------------------------------------------------------------- Critical Store
3773:
3774: sub cstore {
1.124 www 3775: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3776: my $home='';
3777:
1.168 albertel 3778: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3779:
1.213 www 3780: $symb=&symbclean($symb);
1.122 albertel 3781: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3782:
1.620 albertel 3783: if (!$domain) { $domain=$env{'user.domain'}; }
3784: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3785:
3786: &devalidate($symb,$stuname,$domain);
1.109 www 3787:
3788: $symb=escape($symb);
1.187 www 3789: if (!$namespace) {
1.620 albertel 3790: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3791: return '';
3792: }
3793: }
1.620 albertel 3794: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3795:
3796: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3797: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3798:
1.47 www 3799: my $namevalue='';
1.800 albertel 3800: foreach my $key (keys(%$storehash)) {
3801: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3802: }
1.47 www 3803: $namevalue=~s/\&$//;
1.187 www 3804: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3805: return critical
3806: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3807: }
3808:
1.9 www 3809: # --------------------------------------------------------------------- Restore
3810:
3811: sub restore {
1.124 www 3812: my ($symb,$namespace,$domain,$stuname) = @_;
3813: my $home='';
3814:
1.168 albertel 3815: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3816:
1.122 albertel 3817: if (!$symb) {
3818: unless ($symb=escape(&symbread())) { return ''; }
3819: } else {
1.213 www 3820: $symb=&escape(&symbclean($symb));
1.122 albertel 3821: }
1.188 www 3822: if (!$namespace) {
1.620 albertel 3823: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3824: return '';
3825: }
3826: }
1.620 albertel 3827: if (!$domain) { $domain=$env{'user.domain'}; }
3828: if (!$stuname) { $stuname=$env{'user.name'}; }
3829: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3830: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3831:
1.12 www 3832: my %returnhash=();
1.800 albertel 3833: foreach my $line (split(/\&/,$answer)) {
3834: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3835: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3836: }
1.75 www 3837: my $version;
3838: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3839: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3840: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3841: }
1.75 www 3842: }
1.13 www 3843: return %returnhash;
1.34 www 3844: }
3845:
3846: # ---------------------------------------------------------- Course Description
3847:
3848: sub coursedescription {
1.731 albertel 3849: my ($courseid,$args)=@_;
1.34 www 3850: $courseid=~s/^\///;
1.49 www 3851: $courseid=~s/\_/\//g;
1.34 www 3852: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3853: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3854: my $normalid=$cdomain.'_'.$cnum;
3855: # need to always cache even if we get errors otherwise we keep
3856: # trying and trying and trying to get the course description.
3857: my %envhash=();
3858: my %returnhash=();
1.731 albertel 3859:
3860: my $expiretime=600;
3861: if ($env{'request.course.id'} eq $normalid) {
3862: $expiretime=120;
3863: }
3864:
3865: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3866: if (!$args->{'freshen_cache'}
3867: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3868: foreach my $key (keys(%env)) {
3869: next if ($key !~ /^\Q$prefix\E(.*)/);
3870: my ($setting) = $1;
3871: $returnhash{$setting} = $env{$key};
3872: }
3873: return %returnhash;
3874: }
3875:
3876: # get the data agin
3877: if (!$args->{'one_time'}) {
3878: $envhash{'course.'.$normalid.'.last_cache'}=time;
3879: }
1.811 albertel 3880:
1.34 www 3881: if ($chome ne 'no_host') {
1.302 albertel 3882: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3883: if (!exists($returnhash{'con_lost'})) {
3884: $returnhash{'home'}= $chome;
3885: $returnhash{'domain'} = $cdomain;
3886: $returnhash{'num'} = $cnum;
1.741 raeburn 3887: if (!defined($returnhash{'type'})) {
3888: $returnhash{'type'} = 'Course';
3889: }
1.130 albertel 3890: while (my ($name,$value) = each %returnhash) {
1.53 www 3891: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3892: }
1.270 www 3893: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3894: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3895: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3896: $envhash{'course.'.$normalid.'.home'}=$chome;
3897: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3898: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3899: }
3900: }
1.731 albertel 3901: if (!$args->{'one_time'}) {
1.949 raeburn 3902: &appenv(\%envhash);
1.731 albertel 3903: }
1.302 albertel 3904: return %returnhash;
1.461 www 3905: }
3906:
1.1080 raeburn 3907: sub update_released_required {
3908: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
3909: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
3910: $cid = $env{'request.course.id'};
3911: $cdom = $env{'course.'.$cid.'.domain'};
3912: $cnum = $env{'course.'.$cid.'.num'};
3913: $chome = $env{'course.'.$cid.'.home'};
3914: }
3915: if ($needsrelease) {
3916: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
3917: my $needsupdate;
3918: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
3919: $needsupdate = 1;
3920: } else {
3921: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
3922: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
3923: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
3924: $needsupdate = 1;
3925: }
3926: }
3927: if ($needsupdate) {
3928: my %needshash = (
3929: 'internal.releaserequired' => $needsrelease,
3930: );
3931: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
3932: if ($putresult eq 'ok') {
3933: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
3934: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
3935: if (ref($crsinfo{$cid}) eq 'HASH') {
3936: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
3937: &courseidput($cdom,\%crsinfo,$chome,'notime');
3938: }
3939: }
3940: }
3941: }
3942: return;
3943: }
3944:
1.461 www 3945: # -------------------------------------------------See if a user is privileged
3946:
3947: sub privileged {
3948: my ($username,$domain)=@_;
3949: my $rolesdump=&reply("dump:$domain:$username:roles",
3950: &homeserver($username,$domain));
1.1033 raeburn 3951: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3952: ($rolesdump =~ /^error:/)) {
3953: return 0;
3954: }
1.461 www 3955: my $now=time;
3956: if ($rolesdump ne '') {
1.800 albertel 3957: foreach my $entry (split(/&/,$rolesdump)) {
3958: if ($entry!~/^rolesdef_/) {
3959: my ($area,$role)=split(/=/,$entry);
1.461 www 3960: $area=~s/\_\w\w$//;
3961: my ($trole,$tend,$tstart)=split(/_/,$role);
3962: if (($trole eq 'dc') || ($trole eq 'su')) {
3963: my $active=1;
3964: if ($tend) {
3965: if ($tend<$now) { $active=0; }
3966: }
3967: if ($tstart) {
3968: if ($tstart>$now) { $active=0; }
3969: }
3970: if ($active) { return 1; }
3971: }
3972: }
3973: }
3974: }
3975: return 0;
1.9 www 3976: }
1.1 albertel 3977:
1.103 harris41 3978: # -------------------------------------------------------- Get user privileges
1.11 www 3979:
3980: sub rolesinit {
3981: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 3982: my $now=time;
3983: my %userroles = ('user.login.time' => $now);
1.1078 raeburn 3984: my $extra = &freeze_escape({'clientcheckrole' => 1});
3985: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 3986: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1078 raeburn 3987: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 3988: return \%userroles;
3989: }
1.11 www 3990: my %allroles=();
1.678 raeburn 3991: my %allgroups=();
3992: my $group_privs;
1.11 www 3993:
3994: if ($rolesdump ne '') {
1.800 albertel 3995: foreach my $entry (split(/&/,$rolesdump)) {
3996: if ($entry!~/^rolesdef_/) {
3997: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3998: $area=~s/\_\w\w$//;
1.678 raeburn 3999: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4000: if ($role=~/^cr/) {
1.807 albertel 4001: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4002: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4003: ($tend,$tstart)=split('_',$trest);
4004: } else {
4005: $trole=$role;
4006: }
1.678 raeburn 4007: } elsif ($role =~ m|^gr/|) {
4008: ($trole,$tend,$tstart) = split(/_/,$role);
4009: ($trole,$group_privs) = split(/\//,$trole);
4010: $group_privs = &unescape($group_privs);
1.587 albertel 4011: } else {
4012: ($trole,$tend,$tstart)=split(/_/,$role);
4013: }
1.743 albertel 4014: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4015: $username);
4016: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4017: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4018: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4019: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4020: my $spec=$trole.'.'.$area;
4021: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4022: if ($trole =~ /^cr\//) {
1.567 raeburn 4023: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4024: } elsif ($trole eq 'gr') {
4025: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4026: } else {
1.567 raeburn 4027: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4028: }
1.12 www 4029: }
1.662 raeburn 4030: }
1.191 harris41 4031: }
1.743 albertel 4032: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4033: $userroles{'user.adv'} = $adv;
4034: $userroles{'user.author'} = $author;
1.620 albertel 4035: $env{'user.adv'}=$adv;
1.11 www 4036: }
1.743 albertel 4037: return \%userroles;
1.11 www 4038: }
4039:
1.567 raeburn 4040: sub set_arearole {
4041: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4042: # log the associated role with the area
4043: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4044: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4045: }
4046:
4047: sub custom_roleprivs {
4048: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4049: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4050: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4051: if (&hostname($homsvr) ne '') {
1.567 raeburn 4052: my ($rdummy,$roledef)=
4053: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4054: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4055: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4056: if (defined($syspriv)) {
1.1043 raeburn 4057: if ($trest =~ /^$match_community$/) {
4058: $syspriv =~ s/bre\&S//;
4059: }
1.567 raeburn 4060: $$allroles{'cm./'}.=':'.$syspriv;
4061: $$allroles{$spec.'./'}.=':'.$syspriv;
4062: }
4063: if ($tdomain ne '') {
4064: if (defined($dompriv)) {
4065: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4066: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4067: }
4068: if (($trest ne '') && (defined($coursepriv))) {
4069: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4070: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4071: }
4072: }
4073: }
4074: }
4075: }
4076:
1.678 raeburn 4077: sub group_roleprivs {
4078: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4079: my $access = 1;
4080: my $now = time;
4081: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4082: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4083: if ($access) {
1.811 albertel 4084: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4085: $$allgroups{$course}{$group} .=':'.$group_privs;
4086: }
4087: }
1.567 raeburn 4088:
4089: sub standard_roleprivs {
4090: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4091: if (defined($pr{$trole.':s'})) {
4092: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4093: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4094: }
4095: if ($tdomain ne '') {
4096: if (defined($pr{$trole.':d'})) {
4097: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4098: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4099: }
4100: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4101: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4102: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4103: }
4104: }
4105: }
4106:
4107: sub set_userprivs {
1.1064 raeburn 4108: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4109: my $author=0;
4110: my $adv=0;
1.678 raeburn 4111: my %grouproles = ();
4112: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4113: my @groupkeys;
1.1000 raeburn 4114: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4115: push(@groupkeys,$role);
4116: }
4117: if (ref($groups_roles) eq 'HASH') {
4118: foreach my $key (keys(%{$groups_roles})) {
4119: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4120: push(@groupkeys,$key);
4121: }
4122: }
4123: }
4124: if (@groupkeys > 0) {
4125: foreach my $role (@groupkeys) {
4126: my ($trole,$area,$sec,$extendedarea);
4127: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4128: $trole = $1;
4129: $area = $2;
4130: $sec = $3;
4131: $extendedarea = $area.$sec;
4132: if (exists($$allgroups{$area})) {
4133: foreach my $group (keys(%{$$allgroups{$area}})) {
4134: my $spec = $trole.'.'.$extendedarea;
4135: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4136: $$allgroups{$area}{$group};
1.1064 raeburn 4137: }
1.678 raeburn 4138: }
4139: }
4140: }
4141: }
4142: }
1.800 albertel 4143: foreach my $group (keys(%grouproles)) {
4144: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4145: }
1.800 albertel 4146: foreach my $role (keys(%{$allroles})) {
4147: my %thesepriv;
1.941 raeburn 4148: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4149: foreach my $item (split(/:/,$$allroles{$role})) {
4150: if ($item ne '') {
4151: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4152: if ($restrictions eq '') {
4153: $thesepriv{$privilege}='F';
4154: } elsif ($thesepriv{$privilege} ne 'F') {
4155: $thesepriv{$privilege}.=$restrictions;
4156: }
4157: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4158: }
4159: }
4160: my $thesestr='';
1.800 albertel 4161: foreach my $priv (keys(%thesepriv)) {
4162: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4163: }
4164: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4165: }
4166: return ($author,$adv);
4167: }
4168:
1.994 raeburn 4169: sub role_status {
1.1002 raeburn 4170: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4171: my @pwhere = ();
4172: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4173: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4174: unless (!defined($$role) || $$role eq '') {
4175: $$where=join('.',@pwhere);
4176: $$trolecode=$$role.'.'.$$where;
4177: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4178: $$tstatus='is';
4179: if ($$tstart && $$tstart>$then) {
4180: $$tstatus='future';
1.1034 raeburn 4181: if ($$tstart<$now) {
4182: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4183: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4184: my (%allroles,%allgroups,$group_privs,
4185: %groups_roles,@rolecodes);
1.1002 raeburn 4186: my %userroles = (
4187: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4188: );
1.1064 raeburn 4189: @rolecodes = ('cm');
1.1002 raeburn 4190: my $spec=$$role.'.'.$$where;
4191: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4192: if ($$role =~ /^cr\//) {
4193: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4194: push(@rolecodes,'cr');
1.1002 raeburn 4195: } elsif ($$role eq 'gr') {
1.1064 raeburn 4196: push(@rolecodes,$$role);
1.1002 raeburn 4197: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4198: $env{'user.name'});
1.1064 raeburn 4199: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4200: (undef,my $group_privs) = split(/\//,$trole);
4201: $group_privs = &unescape($group_privs);
4202: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4203: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4204: if (keys(%course_roles) > 0) {
4205: my ($tnum) = ($trest =~ /^($match_courseid)/);
4206: if ($tdomain ne '' && $tnum ne '') {
4207: foreach my $key (keys(%course_roles)) {
4208: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4209: my $crsrole = $1;
4210: my $crssec = $2;
4211: if ($crsrole =~ /^cr/) {
4212: unless (grep(/^cr$/,@rolecodes)) {
4213: push(@rolecodes,'cr');
4214: }
4215: } else {
4216: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4217: push(@rolecodes,$crsrole);
4218: }
4219: }
4220: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4221: if ($crssec ne '') {
4222: $rolekey .= '/'.$crssec;
4223: }
4224: $rolekey .= './';
4225: $groups_roles{$rolekey} = \@rolecodes;
4226: }
4227: }
4228: }
4229: }
1.1002 raeburn 4230: } else {
1.1064 raeburn 4231: push(@rolecodes,$$role);
1.1002 raeburn 4232: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4233: }
1.1064 raeburn 4234: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4235: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4236: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4237: }
4238: }
1.1034 raeburn 4239: $$tstatus = 'is';
1.1002 raeburn 4240: }
1.994 raeburn 4241: }
4242: if ($$tend) {
4243: if ($$tend<$then) {
4244: $$tstatus='expired';
4245: } elsif ($$tend<$now) {
4246: $$tstatus='will_not';
4247: }
4248: }
4249: }
4250: }
4251: }
4252:
4253: sub check_adhoc_privs {
1.1002 raeburn 4254: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994 raeburn 4255: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4256: if ($env{$cckey}) {
4257: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4258: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4259: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4260: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4261: }
4262: } else {
4263: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4264: }
4265: }
4266:
4267: sub set_adhoc_privileges {
4268: # role can be cc or ca
4269: my ($dcdom,$pickedcourse,$role) = @_;
4270: my $area = '/'.$dcdom.'/'.$pickedcourse;
4271: my $spec = $role.'.'.$area;
4272: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4273: $env{'user.name'});
4274: my %ccrole = ();
4275: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4276: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4277: &appenv(\%userroles,[$role,'cm']);
4278: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4279: &appenv( {'request.role' => $spec,
4280: 'request.role.domain' => $dcdom,
4281: 'request.course.sec' => ''
4282: }
4283: );
4284: my $tadv=0;
4285: if (&allowed('adv') eq 'F') { $tadv=1; }
4286: &appenv({'request.role.adv' => $tadv});
4287: }
4288:
1.12 www 4289: # --------------------------------------------------------------- get interface
4290:
4291: sub get {
1.131 albertel 4292: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4293: my $items='';
1.800 albertel 4294: foreach my $item (@$storearr) {
4295: $items.=&escape($item).'&';
1.191 harris41 4296: }
1.12 www 4297: $items=~s/\&$//;
1.620 albertel 4298: if (!$udomain) { $udomain=$env{'user.domain'}; }
4299: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4300: my $uhome=&homeserver($uname,$udomain);
4301:
1.133 albertel 4302: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4303: my @pairs=split(/\&/,$rep);
1.273 albertel 4304: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4305: return @pairs;
4306: }
1.15 www 4307: my %returnhash=();
1.42 www 4308: my $i=0;
1.800 albertel 4309: foreach my $item (@$storearr) {
4310: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4311: $i++;
1.191 harris41 4312: }
1.15 www 4313: return %returnhash;
1.27 www 4314: }
4315:
4316: # --------------------------------------------------------------- del interface
4317:
4318: sub del {
1.133 albertel 4319: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4320: my $items='';
1.800 albertel 4321: foreach my $item (@$storearr) {
4322: $items.=&escape($item).'&';
1.191 harris41 4323: }
1.984 neumanie 4324:
1.27 www 4325: $items=~s/\&$//;
1.620 albertel 4326: if (!$udomain) { $udomain=$env{'user.domain'}; }
4327: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4328: my $uhome=&homeserver($uname,$udomain);
4329: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4330: }
4331:
4332: # -------------------------------------------------------------- dump interface
4333:
4334: sub dump {
1.755 albertel 4335: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4336: if (!$udomain) { $udomain=$env{'user.domain'}; }
4337: if (!$uname) { $uname=$env{'user.name'}; }
4338: my $uhome=&homeserver($uname,$udomain);
4339: if ($regexp) {
4340: $regexp=&escape($regexp);
4341: } else {
4342: $regexp='.';
4343: }
4344: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4345: my @pairs=split(/\&/,$rep);
4346: my %returnhash=();
4347: foreach my $item (@pairs) {
4348: my ($key,$value)=split(/=/,$item,2);
4349: $key = &unescape($key);
4350: next if ($key =~ /^error: 2 /);
4351: $returnhash{$key}=&thaw_unescape($value);
4352: }
4353: return %returnhash;
1.407 www 4354: }
4355:
1.717 albertel 4356: # --------------------------------------------------------- dumpstore interface
4357:
4358: sub dumpstore {
4359: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4360: if (!$udomain) { $udomain=$env{'user.domain'}; }
4361: if (!$uname) { $uname=$env{'user.name'}; }
4362: my $uhome=&homeserver($uname,$udomain);
4363: if ($regexp) {
4364: $regexp=&escape($regexp);
4365: } else {
4366: $regexp='.';
4367: }
4368: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4369: my @pairs=split(/\&/,$rep);
4370: my %returnhash=();
4371: foreach my $item (@pairs) {
4372: my ($key,$value)=split(/=/,$item,2);
4373: next if ($key =~ /^error: 2 /);
4374: $returnhash{$key}=&thaw_unescape($value);
4375: }
4376: return %returnhash;
1.717 albertel 4377: }
4378:
1.407 www 4379: # -------------------------------------------------------------- keys interface
4380:
4381: sub getkeys {
4382: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4383: if (!$udomain) { $udomain=$env{'user.domain'}; }
4384: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4385: my $uhome=&homeserver($uname,$udomain);
4386: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4387: my @keyarray=();
1.800 albertel 4388: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4389: next if ($key =~ /^error: 2 /);
1.800 albertel 4390: push(@keyarray,&unescape($key));
1.407 www 4391: }
4392: return @keyarray;
1.318 matthew 4393: }
4394:
1.319 matthew 4395: # --------------------------------------------------------------- currentdump
4396: sub currentdump {
1.328 matthew 4397: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4398: $courseid = $env{'request.course.id'} if (! defined($courseid));
4399: $sdom = $env{'user.domain'} if (! defined($sdom));
4400: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4401: my $uhome = &homeserver($sname,$sdom);
4402: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4403: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4404: #
1.318 matthew 4405: my %returnhash=();
1.319 matthew 4406: #
4407: if ($rep eq "unknown_cmd") {
4408: # an old lond will not know currentdump
4409: # Do a dump and make it look like a currentdump
1.822 albertel 4410: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4411: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4412: my %hash = @tmp;
4413: @tmp=();
1.424 matthew 4414: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4415: } else {
4416: my @pairs=split(/\&/,$rep);
1.800 albertel 4417: foreach my $pair (@pairs) {
4418: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4419: my ($symb,$param) = split(/:/,$key);
4420: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4421: &thaw_unescape($value);
1.319 matthew 4422: }
1.191 harris41 4423: }
1.12 www 4424: return %returnhash;
1.424 matthew 4425: }
4426:
4427: sub convert_dump_to_currentdump{
4428: my %hash = %{shift()};
4429: my %returnhash;
4430: # Code ripped from lond, essentially. The only difference
4431: # here is the unescaping done by lonnet::dump(). Conceivably
4432: # we might run in to problems with parameter names =~ /^v\./
4433: while (my ($key,$value) = each(%hash)) {
4434: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4435: $symb = &unescape($symb);
4436: $param = &unescape($param);
1.424 matthew 4437: next if ($v eq 'version' || $symb eq 'keys');
4438: next if (exists($returnhash{$symb}) &&
4439: exists($returnhash{$symb}->{$param}) &&
4440: $returnhash{$symb}->{'v.'.$param} > $v);
4441: $returnhash{$symb}->{$param}=$value;
4442: $returnhash{$symb}->{'v.'.$param}=$v;
4443: }
4444: #
4445: # Remove all of the keys in the hashes which keep track of
4446: # the version of the parameter.
4447: while (my ($symb,$param_hash) = each(%returnhash)) {
4448: # use a foreach because we are going to delete from the hash.
4449: foreach my $key (keys(%$param_hash)) {
4450: delete($param_hash->{$key}) if ($key =~ /^v\./);
4451: }
4452: }
4453: return \%returnhash;
1.12 www 4454: }
4455:
1.627 albertel 4456: # ------------------------------------------------------ critical inc interface
4457:
4458: sub cinc {
4459: return &inc(@_,'critical');
4460: }
4461:
1.449 matthew 4462: # --------------------------------------------------------------- inc interface
4463:
4464: sub inc {
1.627 albertel 4465: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4466: if (!$udomain) { $udomain=$env{'user.domain'}; }
4467: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4468: my $uhome=&homeserver($uname,$udomain);
4469: my $items='';
4470: if (! ref($store)) {
4471: # got a single value, so use that instead
4472: $items = &escape($store).'=&';
4473: } elsif (ref($store) eq 'SCALAR') {
4474: $items = &escape($$store).'=&';
4475: } elsif (ref($store) eq 'ARRAY') {
4476: $items = join('=&',map {&escape($_);} @{$store});
4477: } elsif (ref($store) eq 'HASH') {
4478: while (my($key,$value) = each(%{$store})) {
4479: $items.= &escape($key).'='.&escape($value).'&';
4480: }
4481: }
4482: $items=~s/\&$//;
1.627 albertel 4483: if ($critical) {
4484: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4485: } else {
4486: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4487: }
1.449 matthew 4488: }
4489:
1.12 www 4490: # --------------------------------------------------------------- put interface
4491:
4492: sub put {
1.134 albertel 4493: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4494: if (!$udomain) { $udomain=$env{'user.domain'}; }
4495: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4496: my $uhome=&homeserver($uname,$udomain);
1.12 www 4497: my $items='';
1.800 albertel 4498: foreach my $item (keys(%$storehash)) {
4499: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4500: }
1.12 www 4501: $items=~s/\&$//;
1.134 albertel 4502: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4503: }
4504:
1.631 albertel 4505: # ------------------------------------------------------------ newput interface
4506:
4507: sub newput {
4508: my ($namespace,$storehash,$udomain,$uname)=@_;
4509: if (!$udomain) { $udomain=$env{'user.domain'}; }
4510: if (!$uname) { $uname=$env{'user.name'}; }
4511: my $uhome=&homeserver($uname,$udomain);
4512: my $items='';
4513: foreach my $key (keys(%$storehash)) {
4514: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4515: }
4516: $items=~s/\&$//;
4517: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4518: }
4519:
4520: # --------------------------------------------------------- putstore interface
4521:
1.524 raeburn 4522: sub putstore {
1.715 albertel 4523: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4524: if (!$udomain) { $udomain=$env{'user.domain'}; }
4525: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4526: my $uhome=&homeserver($uname,$udomain);
4527: my $items='';
1.715 albertel 4528: foreach my $key (keys(%$storehash)) {
4529: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4530: }
1.715 albertel 4531: $items=~s/\&$//;
1.716 albertel 4532: my $esc_symb=&escape($symb);
4533: my $esc_v=&escape($version);
1.715 albertel 4534: my $reply =
1.716 albertel 4535: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4536: $uhome);
4537: if ($reply eq 'unknown_cmd') {
1.716 albertel 4538: # gfall back to way things use to be done
1.715 albertel 4539: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4540: $uname);
1.524 raeburn 4541: }
1.715 albertel 4542: return $reply;
4543: }
4544:
4545: sub old_putstore {
1.716 albertel 4546: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4547: if (!$udomain) { $udomain=$env{'user.domain'}; }
4548: if (!$uname) { $uname=$env{'user.name'}; }
4549: my $uhome=&homeserver($uname,$udomain);
4550: my %newstorehash;
1.800 albertel 4551: foreach my $item (keys(%$storehash)) {
4552: my $key = $version.':'.&escape($symb).':'.$item;
4553: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4554: }
4555: my $items='';
4556: my %allitems = ();
1.800 albertel 4557: foreach my $item (keys(%newstorehash)) {
4558: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4559: my $key = $1.':keys:'.$2;
4560: $allitems{$key} .= $3.':';
4561: }
1.800 albertel 4562: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4563: }
1.800 albertel 4564: foreach my $item (keys(%allitems)) {
4565: $allitems{$item} =~ s/\:$//;
4566: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4567: }
4568: $items=~s/\&$//;
4569: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4570: }
4571:
1.47 www 4572: # ------------------------------------------------------ critical put interface
4573:
4574: sub cput {
1.134 albertel 4575: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4576: if (!$udomain) { $udomain=$env{'user.domain'}; }
4577: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4578: my $uhome=&homeserver($uname,$udomain);
1.47 www 4579: my $items='';
1.800 albertel 4580: foreach my $item (keys(%$storehash)) {
4581: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4582: }
1.47 www 4583: $items=~s/\&$//;
1.134 albertel 4584: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4585: }
4586:
4587: # -------------------------------------------------------------- eget interface
4588:
4589: sub eget {
1.133 albertel 4590: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4591: my $items='';
1.800 albertel 4592: foreach my $item (@$storearr) {
4593: $items.=&escape($item).'&';
1.191 harris41 4594: }
1.12 www 4595: $items=~s/\&$//;
1.620 albertel 4596: if (!$udomain) { $udomain=$env{'user.domain'}; }
4597: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4598: my $uhome=&homeserver($uname,$udomain);
4599: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4600: my @pairs=split(/\&/,$rep);
4601: my %returnhash=();
1.42 www 4602: my $i=0;
1.800 albertel 4603: foreach my $item (@$storearr) {
4604: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4605: $i++;
1.191 harris41 4606: }
1.12 www 4607: return %returnhash;
4608: }
4609:
1.667 albertel 4610: # ------------------------------------------------------------ tmpput interface
4611: sub tmpput {
1.802 raeburn 4612: my ($storehash,$server,$context)=@_;
1.667 albertel 4613: my $items='';
1.800 albertel 4614: foreach my $item (keys(%$storehash)) {
4615: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4616: }
4617: $items=~s/\&$//;
1.802 raeburn 4618: if (defined($context)) {
4619: $items .= ':'.&escape($context);
4620: }
1.667 albertel 4621: return &reply("tmpput:$items",$server);
4622: }
4623:
4624: # ------------------------------------------------------------ tmpget interface
4625: sub tmpget {
1.688 albertel 4626: my ($token,$server)=@_;
4627: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4628: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4629: my %returnhash;
4630: foreach my $item (split(/\&/,$rep)) {
4631: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4632: next if ($key =~ /^error: 2 /);
1.667 albertel 4633: $returnhash{&unescape($key)}=&thaw_unescape($value);
4634: }
4635: return %returnhash;
4636: }
4637:
1.688 albertel 4638: # ------------------------------------------------------------ tmpget interface
4639: sub tmpdel {
4640: my ($token,$server)=@_;
4641: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4642: return &reply("tmpdel:$token",$server);
4643: }
4644:
1.765 albertel 4645: # -------------------------------------------------- portfolio access checking
4646:
4647: sub portfolio_access {
1.766 albertel 4648: my ($requrl) = @_;
1.765 albertel 4649: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4650: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4651: if ($result) {
4652: my %setters;
4653: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4654: my ($startblock,$endblock) =
4655: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4656: if ($startblock && $endblock) {
4657: return 'B';
4658: }
4659: } else {
4660: my ($startblock,$endblock) =
4661: &Apache::loncommon::blockcheck(\%setters,'port');
4662: if ($startblock && $endblock) {
4663: return 'B';
4664: }
4665: }
4666: }
1.765 albertel 4667: if ($result eq 'ok') {
1.766 albertel 4668: return 'F';
1.765 albertel 4669: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4670: return 'A';
1.765 albertel 4671: }
1.766 albertel 4672: return '';
1.765 albertel 4673: }
4674:
4675: sub get_portfolio_access {
1.767 albertel 4676: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4677:
4678: if (!ref($access_hash)) {
4679: my $current_perms = &get_portfile_permissions($udom,$unum);
4680: my %access_controls = &get_access_controls($current_perms,$group,
4681: $file_name);
4682: $access_hash = $access_controls{$file_name};
4683: }
4684:
1.765 albertel 4685: my ($public,$guest,@domains,@users,@courses,@groups);
4686: my $now = time;
4687: if (ref($access_hash) eq 'HASH') {
4688: foreach my $key (keys(%{$access_hash})) {
4689: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4690: if ($start > $now) {
4691: next;
4692: }
4693: if ($end && $end<$now) {
4694: next;
4695: }
4696: if ($scope eq 'public') {
4697: $public = $key;
4698: last;
4699: } elsif ($scope eq 'guest') {
4700: $guest = $key;
4701: } elsif ($scope eq 'domains') {
4702: push(@domains,$key);
4703: } elsif ($scope eq 'users') {
4704: push(@users,$key);
4705: } elsif ($scope eq 'course') {
4706: push(@courses,$key);
4707: } elsif ($scope eq 'group') {
4708: push(@groups,$key);
4709: }
4710: }
4711: if ($public) {
4712: return 'ok';
4713: }
4714: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4715: if ($guest) {
4716: return $guest;
4717: }
4718: } else {
4719: if (@domains > 0) {
4720: foreach my $domkey (@domains) {
4721: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4722: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4723: return 'ok';
4724: }
4725: }
4726: }
4727: }
4728: if (@users > 0) {
4729: foreach my $userkey (@users) {
1.865 raeburn 4730: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4731: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4732: if (ref($item) eq 'HASH') {
4733: if (($item->{'uname'} eq $env{'user.name'}) &&
4734: ($item->{'udom'} eq $env{'user.domain'})) {
4735: return 'ok';
4736: }
4737: }
4738: }
4739: }
1.765 albertel 4740: }
4741: }
4742: my %roleshash;
4743: my @courses_and_groups = @courses;
4744: push(@courses_and_groups,@groups);
4745: if (@courses_and_groups > 0) {
4746: my (%allgroups,%allroles);
4747: my ($start,$end,$role,$sec,$group);
4748: foreach my $envkey (%env) {
1.1060 raeburn 4749: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4750: my $cid = $2.'_'.$3;
4751: if ($1 eq 'gr') {
4752: $group = $4;
4753: $allgroups{$cid}{$group} = $env{$envkey};
4754: } else {
4755: if ($4 eq '') {
4756: $sec = 'none';
4757: } else {
4758: $sec = $4;
4759: }
4760: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4761: }
1.811 albertel 4762: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4763: my $cid = $2.'_'.$3;
4764: if ($4 eq '') {
4765: $sec = 'none';
4766: } else {
4767: $sec = $4;
4768: }
4769: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4770: }
4771: }
4772: if (keys(%allroles) == 0) {
4773: return;
4774: }
4775: foreach my $key (@courses_and_groups) {
4776: my %content = %{$$access_hash{$key}};
4777: my $cnum = $content{'number'};
4778: my $cdom = $content{'domain'};
4779: my $cid = $cdom.'_'.$cnum;
4780: if (!exists($allroles{$cid})) {
4781: next;
4782: }
4783: foreach my $role_id (keys(%{$content{'roles'}})) {
4784: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4785: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4786: my @status = @{$content{'roles'}{$role_id}{'access'}};
4787: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4788: foreach my $role (keys(%{$allroles{$cid}})) {
4789: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4790: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4791: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4792: if (grep/^all$/,@sections) {
4793: return 'ok';
4794: } else {
4795: if (grep/^$sec$/,@sections) {
4796: return 'ok';
4797: }
4798: }
4799: }
4800: }
4801: if (keys(%{$allgroups{$cid}}) == 0) {
4802: if (grep/^none$/,@groups) {
4803: return 'ok';
4804: }
4805: } else {
4806: if (grep/^all$/,@groups) {
4807: return 'ok';
4808: }
4809: foreach my $group (keys(%{$allgroups{$cid}})) {
4810: if (grep/^$group$/,@groups) {
4811: return 'ok';
4812: }
4813: }
4814: }
4815: }
4816: }
4817: }
4818: }
4819: }
4820: if ($guest) {
4821: return $guest;
4822: }
4823: }
4824: }
4825: return;
4826: }
4827:
4828: sub course_group_datechecker {
4829: my ($dates,$now,$status) = @_;
4830: my ($start,$end) = split(/\./,$dates);
4831: if (!$start && !$end) {
4832: return 'ok';
4833: }
4834: if (grep/^active$/,@{$status}) {
4835: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4836: return 'ok';
4837: }
4838: }
4839: if (grep/^previous$/,@{$status}) {
4840: if ($end > $now ) {
4841: return 'ok';
4842: }
4843: }
4844: if (grep/^future$/,@{$status}) {
4845: if ($start > $now) {
4846: return 'ok';
4847: }
4848: }
4849: return;
4850: }
4851:
4852: sub parse_portfolio_url {
4853: my ($url) = @_;
4854:
4855: my ($type,$udom,$unum,$group,$file_name);
4856:
1.823 albertel 4857: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4858: $type = 1;
4859: $udom = $1;
4860: $unum = $2;
4861: $file_name = $3;
1.823 albertel 4862: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4863: $type = 2;
4864: $udom = $1;
4865: $unum = $2;
4866: $group = $3;
4867: $file_name = $3.'/'.$4;
4868: }
4869: if (wantarray) {
4870: return ($type,$udom,$unum,$file_name,$group);
4871: }
4872: return $type;
4873: }
4874:
4875: sub is_portfolio_url {
4876: my ($url) = @_;
4877: return scalar(&parse_portfolio_url($url));
4878: }
4879:
1.798 raeburn 4880: sub is_portfolio_file {
4881: my ($file) = @_;
1.820 raeburn 4882: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4883: return 1;
4884: }
4885: return;
4886: }
4887:
1.976 raeburn 4888: sub usertools_access {
1.985 raeburn 4889: my ($uname,$udom,$tool,$action,$context) = @_;
4890: my ($access,%tools);
4891: if ($context eq '') {
4892: $context = 'tools';
4893: }
4894: if ($context eq 'requestcourses') {
4895: %tools = (
4896: official => 1,
4897: unofficial => 1,
1.1006 raeburn 4898: community => 1,
1.985 raeburn 4899: );
4900: } else {
4901: %tools = (
4902: aboutme => 1,
4903: blog => 1,
4904: portfolio => 1,
4905: );
4906: }
1.976 raeburn 4907: return if (!defined($tools{$tool}));
4908:
4909: if ((!defined($udom)) || (!defined($uname))) {
4910: $udom = $env{'user.domain'};
4911: $uname = $env{'user.name'};
4912: }
4913:
1.978 raeburn 4914: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4915: if ($action ne 'reload') {
1.985 raeburn 4916: if ($context eq 'requestcourses') {
4917: return $env{'environment.canrequest.'.$tool};
4918: } else {
4919: return $env{'environment.availabletools.'.$tool};
4920: }
4921: }
1.976 raeburn 4922: }
4923:
4924: my ($toolstatus,$inststatus);
4925:
1.985 raeburn 4926: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4927: ($action ne 'reload')) {
4928: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 4929: $inststatus = $env{'environment.inststatus'};
4930: } else {
1.1025 raeburn 4931: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985 raeburn 4932: $toolstatus = $userenv{$context.'.'.$tool};
1.976 raeburn 4933: $inststatus = $userenv{'inststatus'};
4934: }
4935:
4936: if ($toolstatus ne '') {
4937: if ($toolstatus) {
4938: $access = 1;
4939: } else {
4940: $access = 0;
4941: }
4942: return $access;
4943: }
4944:
4945: my $is_adv = &is_advanced_user($udom,$uname);
4946: my %domdef = &get_domain_defaults($udom);
4947: if (ref($domdef{$tool}) eq 'HASH') {
4948: if ($is_adv) {
4949: if ($domdef{$tool}{'_LC_adv'} ne '') {
4950: if ($domdef{$tool}{'_LC_adv'}) {
4951: $access = 1;
4952: } else {
4953: $access = 0;
4954: }
4955: return $access;
4956: }
4957: }
4958: if ($inststatus ne '') {
4959: my ($hasaccess,$hasnoaccess);
4960: foreach my $affiliation (split(/:/,$inststatus)) {
4961: if ($domdef{$tool}{$affiliation} ne '') {
4962: if ($domdef{$tool}{$affiliation}) {
4963: $hasaccess = 1;
4964: } else {
4965: $hasnoaccess = 1;
4966: }
4967: }
4968: }
4969: if ($hasaccess || $hasnoaccess) {
4970: if ($hasaccess) {
4971: $access = 1;
4972: } elsif ($hasnoaccess) {
4973: $access = 0;
4974: }
4975: return $access;
4976: }
4977: } else {
4978: if ($domdef{$tool}{'default'} ne '') {
4979: if ($domdef{$tool}{'default'}) {
4980: $access = 1;
4981: } elsif ($domdef{$tool}{'default'} == 0) {
4982: $access = 0;
4983: }
4984: return $access;
4985: }
4986: }
4987: } else {
1.985 raeburn 4988: if ($context eq 'tools') {
4989: $access = 1;
4990: } else {
4991: $access = 0;
4992: }
1.976 raeburn 4993: return $access;
4994: }
4995: }
4996:
1.1050 raeburn 4997: sub is_course_owner {
4998: my ($cdom,$cnum,$udom,$uname) = @_;
4999: if (($udom eq '') || ($uname eq '')) {
5000: $udom = $env{'user.domain'};
5001: $uname = $env{'user.name'};
5002: }
5003: unless (($udom eq '') || ($uname eq '')) {
5004: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5005: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5006: return 1;
5007: } else {
5008: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5009: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5010: return 1;
5011: }
5012: }
5013: }
5014: }
5015: return;
5016: }
5017:
1.976 raeburn 5018: sub is_advanced_user {
5019: my ($udom,$uname) = @_;
5020: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5021: my %allroles;
5022: my $is_adv;
5023: foreach my $role (keys(%roleshash)) {
5024: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5025: my $area = '/'.$tdomain.'/'.$trest;
5026: if ($sec ne '') {
5027: $area .= '/'.$sec;
5028: }
5029: if (($area ne '') && ($trole ne '')) {
5030: my $spec=$trole.'.'.$area;
5031: if ($trole =~ /^cr\//) {
5032: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5033: } elsif ($trole ne 'gr') {
5034: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5035: }
5036: }
5037: }
5038: foreach my $role (keys(%allroles)) {
5039: last if ($is_adv);
5040: foreach my $item (split(/:/,$allroles{$role})) {
5041: if ($item ne '') {
5042: my ($privilege,$restrictions)=split(/&/,$item);
5043: if ($privilege eq 'adv') {
5044: $is_adv = 1;
5045: last;
5046: }
5047: }
5048: }
5049: }
5050: return $is_adv;
5051: }
1.798 raeburn 5052:
1.1035 raeburn 5053: sub check_can_request {
1.1036 raeburn 5054: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5055: my $canreq = 0;
5056: my ($types,$typename) = &Apache::loncommon::course_types();
5057: my @options = ('approval','validate','autolimit');
5058: my $optregex = join('|',@options);
5059: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5060: foreach my $type (@{$types}) {
5061: if (&usertools_access($env{'user.name'},
5062: $env{'user.domain'},
5063: $type,undef,'requestcourses')) {
5064: $canreq ++;
1.1036 raeburn 5065: if (ref($request_domains) eq 'HASH') {
5066: push(@{$request_domains->{$type}},$env{'user.domain'});
5067: }
1.1035 raeburn 5068: if ($dom eq $env{'user.domain'}) {
5069: $can_request->{$type} = 1;
5070: }
5071: }
5072: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5073: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5074: if (@curr > 0) {
1.1036 raeburn 5075: foreach my $item (@curr) {
5076: if (ref($request_domains) eq 'HASH') {
5077: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5078: if ($otherdom ne '') {
5079: if (ref($request_domains->{$type}) eq 'ARRAY') {
5080: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5081: push(@{$request_domains->{$type}},$otherdom);
5082: }
5083: } else {
5084: push(@{$request_domains->{$type}},$otherdom);
5085: }
5086: }
5087: }
5088: }
5089: unless($dom eq $env{'user.domain'}) {
5090: $canreq ++;
1.1035 raeburn 5091: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5092: $can_request->{$type} = 1;
5093: }
5094: }
5095: }
5096: }
5097: }
5098: }
5099: return $canreq;
5100: }
5101:
1.341 www 5102: # ---------------------------------------------- Custom access rule evaluation
5103:
5104: sub customaccess {
5105: my ($priv,$uri)=@_;
1.807 albertel 5106: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5107: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5108: $udom = &LONCAPA::clean_domain($udom);
5109: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5110: my $access=0;
1.800 albertel 5111: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5112: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5113: if ($type eq 'user') {
5114: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5115: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5116: if ($tdom) {
5117: if ($tdom ne $env{'user.domain'}) { next; }
5118: }
1.896 albertel 5119: if ($tuname) {
5120: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5121: }
5122: $access=($effect eq 'allow');
5123: last;
5124: }
5125: } else {
5126: if ($role) {
5127: if ($role ne $urole) { next; }
5128: }
5129: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5130: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5131: if ($tdom) {
5132: if ($tdom ne $udom) { next; }
5133: }
5134: if ($tcrs) {
5135: if ($tcrs ne $ucrs) { next; }
5136: }
5137: if ($tsec) {
5138: if ($tsec ne $usec) { next; }
5139: }
5140: $access=($effect eq 'allow');
5141: last;
5142: }
5143: if ($realm eq '' && $role eq '') {
5144: $access=($effect eq 'allow');
5145: }
1.402 bowersj2 5146: }
1.341 www 5147: }
5148: return $access;
5149: }
5150:
1.103 harris41 5151: # ------------------------------------------------- Check for a user privilege
1.12 www 5152:
5153: sub allowed {
1.810 raeburn 5154: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5155: my $ver_orguri=$uri;
1.439 www 5156: $uri=&deversion($uri);
1.152 www 5157: my $orguri=$uri;
1.52 www 5158: $uri=&declutter($uri);
1.809 raeburn 5159:
1.810 raeburn 5160: if ($priv eq 'evb') {
5161: # Evade communication block restrictions for specified role in a course
5162: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5163: return $1;
5164: } else {
5165: return;
5166: }
5167: }
5168:
1.620 albertel 5169: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5170: # Free bre access to adm and meta resources
1.775 albertel 5171: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5172: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5173: && ($priv eq 'bre')) {
1.14 www 5174: return 'F';
1.159 www 5175: }
5176:
1.545 banghart 5177: # Free bre access to user's own portfolio contents
1.714 raeburn 5178: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5179: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5180: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5181: my %setters;
5182: my ($startblock,$endblock) =
5183: &Apache::loncommon::blockcheck(\%setters,'port');
5184: if ($startblock && $endblock) {
5185: return 'B';
5186: } else {
5187: return 'F';
5188: }
1.545 banghart 5189: }
5190:
1.762 raeburn 5191: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5192: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5193: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5194: if (exists($env{'request.course.id'})) {
5195: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5196: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5197: if (($domain eq $cdom) && ($name eq $cnum)) {
5198: my $courseprivid=$env{'request.course.id'};
5199: $courseprivid=~s/\_/\//;
5200: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5201: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5202: return $1;
1.762 raeburn 5203: } else {
5204: if ($env{'request.course.sec'}) {
5205: $courseprivid.='/'.$env{'request.course.sec'};
5206: }
5207: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5208: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5209: return $2;
5210: }
1.714 raeburn 5211: }
5212: }
5213: }
5214: }
5215:
1.159 www 5216: # Free bre to public access
5217:
5218: if ($priv eq 'bre') {
1.238 www 5219: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5220: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5221: return 'F';
5222: }
1.238 www 5223: if ($copyright eq 'priv') {
5224: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5225: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5226: return '';
5227: }
5228: }
5229: if ($copyright eq 'domain') {
5230: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5231: unless (($env{'user.domain'} eq $1) ||
5232: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5233: return '';
5234: }
1.262 matthew 5235: }
1.620 albertel 5236: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5237: # Library role, so allow browsing of resources in this domain.
5238: return 'F';
1.238 www 5239: }
1.341 www 5240: if ($copyright eq 'custom') {
5241: unless (&customaccess($priv,$uri)) { return ''; }
5242: }
1.14 www 5243: }
1.264 matthew 5244: # Domain coordinator is trying to create a course
1.620 albertel 5245: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5246: # uri is the requested domain in this case.
5247: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5248: # a role of dc for the domain in question.
1.620 albertel 5249: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5250: }
1.29 www 5251:
1.52 www 5252: my $thisallowed='';
5253: my $statecond=0;
5254: my $courseprivid='';
5255:
1.1039 raeburn 5256: my $ownaccess;
1.1043 raeburn 5257: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5258: if (($priv eq 'bro') && ($env{'user.author'})) {
5259: if ($uri eq '') {
5260: $ownaccess = 1;
5261: } else {
5262: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5263: my $udom = $env{'user.domain'};
5264: my $uname = $env{'user.name'};
5265: if ($uri =~ m{^\Q$udom\E/?$}) {
5266: $ownaccess = 1;
1.1040 raeburn 5267: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5268: unless ($uri =~ m{\.\./}) {
5269: $ownaccess = 1;
5270: }
5271: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5272: my $now = time;
5273: if ($uri =~ m{^([^/]+)/?$}) {
5274: my $adom = $1;
5275: foreach my $key (keys(%env)) {
1.1042 raeburn 5276: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5277: my ($start,$end) = split('.',$env{$key});
5278: if (($now >= $start) && (!$end || $end < $now)) {
5279: $ownaccess = 1;
5280: last;
5281: }
5282: }
5283: }
5284: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5285: my $adom = $1;
5286: my $aname = $2;
1.1042 raeburn 5287: foreach my $role ('ca','aa') {
5288: if ($env{"user.role.$role./$adom/$aname"}) {
5289: my ($start,$end) =
5290: split('.',$env{"user.role.$role./$adom/$aname"});
5291: if (($now >= $start) && (!$end || $end < $now)) {
5292: $ownaccess = 1;
5293: last;
5294: }
1.1039 raeburn 5295: }
5296: }
5297: }
5298: }
5299: }
5300: }
5301: }
5302:
1.52 www 5303: # Course
5304:
1.620 albertel 5305: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5306: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5307: $thisallowed.=$1;
5308: }
1.52 www 5309: }
1.29 www 5310:
1.52 www 5311: # Domain
5312:
1.620 albertel 5313: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5314: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5315: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5316: $thisallowed.=$1;
5317: }
1.12 www 5318: }
1.52 www 5319:
5320: # Course: uri itself is a course
1.66 www 5321: my $courseuri=$uri;
5322: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5323: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5324:
1.620 albertel 5325: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5326: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5327: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5328: $thisallowed.=$1;
5329: }
1.12 www 5330: }
1.29 www 5331:
1.665 albertel 5332: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5333: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5334: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5335: $thisallowed='';
1.671 raeburn 5336: my ($match)=&is_on_map($uri);
5337: if ($match) {
5338: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5339: =~/\Q$priv\E\&([^\:]*)/) {
5340: $thisallowed.=$1;
5341: }
5342: } else {
1.705 albertel 5343: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5344: if ($refuri) {
5345: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5346: $thisallowed='F';
1.671 raeburn 5347: } else {
5348: $refuri=&declutter($refuri);
5349: my ($match) = &is_on_map($refuri);
5350: if ($match) {
5351: $thisallowed='F';
5352: }
1.669 raeburn 5353: }
1.671 raeburn 5354: }
5355: }
1.314 www 5356: }
1.492 albertel 5357:
1.766 albertel 5358: if ($priv eq 'bre'
5359: && $thisallowed ne 'F'
5360: && $thisallowed ne '2'
5361: && &is_portfolio_url($uri)) {
5362: $thisallowed = &portfolio_access($uri);
5363: }
5364:
1.52 www 5365: # Full access at system, domain or course-wide level? Exit.
1.29 www 5366: if ($thisallowed=~/F/) {
5367: return 'F';
5368: }
5369:
1.52 www 5370: # If this is generating or modifying users, exit with special codes
1.29 www 5371:
1.643 www 5372: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5373: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5374: my ($audom,$auname)=split('/',$uri);
1.643 www 5375: # no author name given, so this just checks on the general right to make a co-author in this domain
5376: unless ($auname) { return $thisallowed; }
5377: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5378: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5379: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5380: ($audom ne $env{'request.role.domain'}))) { return ''; }
5381: }
1.52 www 5382: return $thisallowed;
5383: }
5384: #
1.103 harris41 5385: # Gathered so far: system, domain and course wide privileges
1.52 www 5386: #
5387: # Course: See if uri or referer is an individual resource that is part of
5388: # the course
5389:
1.620 albertel 5390: if ($env{'request.course.id'}) {
1.232 www 5391:
1.620 albertel 5392: $courseprivid=$env{'request.course.id'};
5393: if ($env{'request.course.sec'}) {
5394: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5395: }
5396: $courseprivid=~s/\_/\//;
5397: my $checkreferer=1;
1.232 www 5398: my ($match,$cond)=&is_on_map($uri);
5399: if ($match) {
5400: $statecond=$cond;
1.620 albertel 5401: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5402: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5403: $thisallowed.=$1;
5404: $checkreferer=0;
5405: }
1.29 www 5406: }
1.83 www 5407:
1.148 www 5408: if ($checkreferer) {
1.620 albertel 5409: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5410: unless ($refuri) {
1.800 albertel 5411: foreach my $key (keys(%env)) {
5412: if ($key=~/^httpref\..*\*/) {
5413: my $pattern=$key;
1.156 www 5414: $pattern=~s/^httpref\.\/res\///;
1.148 www 5415: $pattern=~s/\*/\[\^\/\]\+/g;
5416: $pattern=~s/\//\\\//g;
1.152 www 5417: if ($orguri=~/$pattern/) {
1.800 albertel 5418: $refuri=$env{$key};
1.148 www 5419: }
5420: }
1.191 harris41 5421: }
1.148 www 5422: }
1.232 www 5423:
1.148 www 5424: if ($refuri) {
1.152 www 5425: $refuri=&declutter($refuri);
1.232 www 5426: my ($match,$cond)=&is_on_map($refuri);
5427: if ($match) {
5428: my $refstatecond=$cond;
1.620 albertel 5429: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5430: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5431: $thisallowed.=$1;
1.53 www 5432: $uri=$refuri;
5433: $statecond=$refstatecond;
1.52 www 5434: }
5435: }
1.148 www 5436: }
1.29 www 5437: }
1.52 www 5438: }
1.29 www 5439:
1.52 www 5440: #
1.103 harris41 5441: # Gathered now: all privileges that could apply, and condition number
1.52 www 5442: #
5443: #
5444: # Full or no access?
5445: #
1.29 www 5446:
1.52 www 5447: if ($thisallowed=~/F/) {
5448: return 'F';
5449: }
1.29 www 5450:
1.52 www 5451: unless ($thisallowed) {
5452: return '';
5453: }
1.29 www 5454:
1.52 www 5455: # Restrictions exist, deal with them
5456: #
5457: # C:according to course preferences
5458: # R:according to resource settings
5459: # L:unless locked
5460: # X:according to user session state
5461: #
5462:
5463: # Possibly locked functionality, check all courses
1.54 www 5464: # Locks might take effect only after 10 minutes cache expiration for other
5465: # courses, and 2 minutes for current course
1.52 www 5466:
5467: my $envkey;
5468: if ($thisallowed=~/L/) {
1.1000 raeburn 5469: foreach $envkey (keys(%env)) {
1.54 www 5470: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5471: my $courseid=$2;
5472: my $roleid=$1.'.'.$2;
1.92 www 5473: $courseid=~s/^\///;
1.54 www 5474: my $expiretime=600;
1.620 albertel 5475: if ($env{'request.role'} eq $roleid) {
1.54 www 5476: $expiretime=120;
5477: }
5478: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5479: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5480: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5481: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5482: }
1.620 albertel 5483: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5484: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5485: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5486: &log($env{'user.domain'},$env{'user.name'},
5487: $env{'user.home'},
1.57 www 5488: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5489: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5490: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5491: return '';
5492: }
5493: }
1.620 albertel 5494: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5495: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5496: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5497: &log($env{'user.domain'},$env{'user.name'},
5498: $env{'user.home'},
1.57 www 5499: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5500: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5501: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5502: return '';
5503: }
5504: }
5505: }
1.29 www 5506: }
1.52 www 5507: }
5508:
5509: #
5510: # Rest of the restrictions depend on selected course
5511: #
5512:
1.620 albertel 5513: unless ($env{'request.course.id'}) {
1.766 albertel 5514: if ($thisallowed eq 'A') {
5515: return 'A';
1.814 raeburn 5516: } elsif ($thisallowed eq 'B') {
5517: return 'B';
1.766 albertel 5518: } else {
5519: return '1';
5520: }
1.52 www 5521: }
1.29 www 5522:
1.52 www 5523: #
5524: # Now user is definitely in a course
5525: #
1.53 www 5526:
5527:
5528: # Course preferences
5529:
5530: if ($thisallowed=~/C/) {
1.620 albertel 5531: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5532: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5533: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5534: =~/\Q$rolecode\E/) {
1.689 albertel 5535: if ($priv ne 'pch') {
5536: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5537: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5538: $env{'request.course.id'});
5539: }
1.237 www 5540: return '';
5541: }
5542:
1.620 albertel 5543: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5544: =~/\Q$unamedom\E/) {
1.689 albertel 5545: if ($priv ne 'pch') {
5546: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5547: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5548: $env{'request.course.id'});
5549: }
1.54 www 5550: return '';
5551: }
1.53 www 5552: }
5553:
5554: # Resource preferences
5555:
5556: if ($thisallowed=~/R/) {
1.620 albertel 5557: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5558: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5559: if ($priv ne 'pch') {
5560: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5561: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5562: }
5563: return '';
1.54 www 5564: }
1.53 www 5565: }
1.30 www 5566:
1.246 www 5567: # Restricted by state or randomout?
1.30 www 5568:
1.52 www 5569: if ($thisallowed=~/X/) {
1.620 albertel 5570: if ($env{'acc.randomout'}) {
1.579 albertel 5571: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5572: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5573: return '';
5574: }
1.247 www 5575: }
5576: if (&condval($statecond)) {
1.52 www 5577: return '2';
5578: } else {
5579: return '';
5580: }
5581: }
1.30 www 5582:
1.766 albertel 5583: if ($thisallowed eq 'A') {
5584: return 'A';
1.814 raeburn 5585: } elsif ($thisallowed eq 'B') {
5586: return 'B';
1.766 albertel 5587: }
1.52 www 5588: return 'F';
1.232 www 5589: }
5590:
1.710 albertel 5591: sub split_uri_for_cond {
5592: my $uri=&deversion(&declutter(shift));
5593: my @uriparts=split(/\//,$uri);
5594: my $filename=pop(@uriparts);
5595: my $pathname=join('/',@uriparts);
5596: return ($pathname,$filename);
5597: }
1.232 www 5598: # --------------------------------------------------- Is a resource on the map?
5599:
5600: sub is_on_map {
1.710 albertel 5601: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5602: #Trying to find the conditional for the file
1.620 albertel 5603: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5604: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5605: if ($match) {
1.289 bowersj2 5606: return (1,$1);
5607: } else {
1.434 www 5608: return (0,0);
1.289 bowersj2 5609: }
1.12 www 5610: }
5611:
1.427 www 5612: # --------------------------------------------------------- Get symb from alias
5613:
5614: sub get_symb_from_alias {
5615: my $symb=shift;
5616: my ($map,$resid,$url)=&decode_symb($symb);
5617: # Already is a symb
5618: if ($url) { return $symb; }
5619: # Must be an alias
5620: my $aliassymb='';
5621: my %bighash;
1.620 albertel 5622: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5623: &GDBM_READER(),0640)) {
5624: my $rid=$bighash{'mapalias_'.$symb};
5625: if ($rid) {
5626: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5627: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5628: $resid,$bighash{'src_'.$rid});
1.427 www 5629: }
5630: untie %bighash;
5631: }
5632: return $aliassymb;
5633: }
5634:
1.12 www 5635: # ----------------------------------------------------------------- Define Role
5636:
5637: sub definerole {
5638: if (allowed('mcr','/')) {
5639: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5640: foreach my $role (split(':',$sysrole)) {
5641: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5642: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5643: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5644: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5645: return "refused:s:$crole&$cqual";
5646: }
5647: }
1.191 harris41 5648: }
1.800 albertel 5649: foreach my $role (split(':',$domrole)) {
5650: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5651: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5652: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5653: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5654: return "refused:d:$crole&$cqual";
5655: }
5656: }
1.191 harris41 5657: }
1.800 albertel 5658: foreach my $role (split(':',$courole)) {
5659: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5660: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5661: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5662: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5663: return "refused:c:$crole&$cqual";
5664: }
5665: }
1.191 harris41 5666: }
1.620 albertel 5667: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5668: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5669: "rolesdef_$rolename=".
5670: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5671: return reply($command,$env{'user.home'});
1.12 www 5672: } else {
5673: return 'refused';
5674: }
1.105 harris41 5675: }
5676:
5677: # ---------------- Make a metadata query against the network of library servers
5678:
5679: sub metadata_query {
1.244 matthew 5680: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5681: my %rhash;
1.845 albertel 5682: my %libserv = &all_library();
1.244 matthew 5683: my @server_list = (defined($server_array) ? @$server_array
5684: : keys(%libserv) );
5685: for my $server (@server_list) {
1.118 harris41 5686: unless ($custom or $customshow) {
5687: my $reply=&reply("querysend:".&escape($query),$server);
5688: $rhash{$server}=$reply;
5689: }
5690: else {
5691: my $reply=&reply("querysend:".&escape($query).':'.
5692: &escape($custom).':'.&escape($customshow),
5693: $server);
5694: $rhash{$server}=$reply;
5695: }
1.112 harris41 5696: }
1.118 harris41 5697: return \%rhash;
1.240 www 5698: }
5699:
5700: # ----------------------------------------- Send log queries and wait for reply
5701:
5702: sub log_query {
5703: my ($uname,$udom,$query,%filters)=@_;
5704: my $uhome=&homeserver($uname,$udom);
5705: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5706: my $uhost=&hostname($uhome);
1.800 albertel 5707: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5708: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5709: $uhome);
1.479 albertel 5710: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5711: return get_query_reply($queryid);
5712: }
5713:
1.818 raeburn 5714: # -------------------------- Update MySQL table for portfolio file
5715:
5716: sub update_portfolio_table {
1.821 raeburn 5717: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5718: if ($group ne '') {
5719: $file_name =~s /^\Q$group\E//;
5720: }
1.818 raeburn 5721: my $homeserver = &homeserver($uname,$udom);
5722: my $queryid=
1.821 raeburn 5723: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5724: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5725: my $reply = &get_query_reply($queryid);
5726: return $reply;
5727: }
5728:
1.899 raeburn 5729: # -------------------------- Update MySQL allusers table
5730:
5731: sub update_allusers_table {
5732: my ($uname,$udom,$names) = @_;
5733: my $homeserver = &homeserver($uname,$udom);
5734: my $queryid=
5735: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5736: 'lastname='.&escape($names->{'lastname'}).'%%'.
5737: 'firstname='.&escape($names->{'firstname'}).'%%'.
5738: 'middlename='.&escape($names->{'middlename'}).'%%'.
5739: 'generation='.&escape($names->{'generation'}).'%%'.
5740: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5741: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 5742: return;
1.899 raeburn 5743: }
5744:
1.508 raeburn 5745: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5746:
5747: sub fetch_enrollment_query {
1.511 raeburn 5748: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5749: my $homeserver;
1.547 raeburn 5750: my $maxtries = 1;
1.508 raeburn 5751: if ($context eq 'automated') {
5752: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5753: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5754: } else {
5755: $homeserver = &homeserver($cnum,$dom);
5756: }
1.838 albertel 5757: my $host=&hostname($homeserver);
1.506 raeburn 5758: my $cmd = '';
1.1000 raeburn 5759: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5760: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5761: }
5762: $cmd =~ s/%%$//;
5763: $cmd = &escape($cmd);
5764: my $query = 'fetchenrollment';
1.620 albertel 5765: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5766: unless ($queryid=~/^\Q$host\E\_/) {
5767: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5768: return 'error: '.$queryid;
5769: }
1.506 raeburn 5770: my $reply = &get_query_reply($queryid);
1.547 raeburn 5771: my $tries = 1;
5772: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5773: $reply = &get_query_reply($queryid);
5774: $tries ++;
5775: }
1.526 raeburn 5776: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5777: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5778: } else {
1.901 albertel 5779: my @responses = split(/:/,$reply);
1.515 raeburn 5780: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5781: foreach my $line (@responses) {
5782: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5783: $$replyref{$key} = $value;
5784: }
5785: } else {
1.506 raeburn 5786: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5787: foreach my $line (@responses) {
5788: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5789: $$replyref{$key} = $value;
5790: if ($value > 0) {
1.800 albertel 5791: foreach my $item (@{$$affiliatesref{$key}}) {
5792: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5793: my $destname = $pathname.'/'.$filename;
5794: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5795: if ($xml_classlist =~ /^error/) {
5796: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5797: } else {
1.506 raeburn 5798: if ( open(FILE,">$destname") ) {
5799: print FILE &unescape($xml_classlist);
5800: close(FILE);
1.526 raeburn 5801: } else {
5802: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5803: }
5804: }
5805: }
5806: }
5807: }
5808: }
5809: return 'ok';
5810: }
5811: return 'error';
5812: }
5813:
1.242 www 5814: sub get_query_reply {
5815: my $queryid=shift;
1.240 www 5816: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5817: my $reply='';
5818: for (1..100) {
5819: sleep 2;
5820: if (-e $replyfile.'.end') {
1.448 albertel 5821: if (open(my $fh,$replyfile)) {
1.904 albertel 5822: $reply = join('',<$fh>);
5823: close($fh);
1.240 www 5824: } else { return 'error: reply_file_error'; }
1.242 www 5825: return &unescape($reply);
5826: }
1.240 www 5827: }
1.242 www 5828: return 'timeout:'.$queryid;
1.240 www 5829: }
5830:
5831: sub courselog_query {
1.241 www 5832: #
5833: # possible filters:
5834: # url: url or symb
5835: # username
5836: # domain
5837: # action: view, submit, grade
5838: # start: timestamp
5839: # end: timestamp
5840: #
1.240 www 5841: my (%filters)=@_;
1.620 albertel 5842: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5843: if ($filters{'url'}) {
5844: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5845: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5846: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5847: }
1.620 albertel 5848: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5849: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5850: return &log_query($cname,$cdom,'courselog',%filters);
5851: }
5852:
5853: sub userlog_query {
1.858 raeburn 5854: #
5855: # possible filters:
5856: # action: log check role
5857: # start: timestamp
5858: # end: timestamp
5859: #
1.240 www 5860: my ($uname,$udom,%filters)=@_;
5861: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5862: }
5863:
1.506 raeburn 5864: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5865:
5866: sub auto_run {
1.508 raeburn 5867: my ($cnum,$cdom) = @_;
1.876 raeburn 5868: my $response = 0;
5869: my $settings;
5870: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5871: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5872: $settings = $domconfig{'autoenroll'};
5873: if ($settings->{'run'} eq '1') {
5874: $response = 1;
5875: }
5876: } else {
1.934 raeburn 5877: my $homeserver;
5878: if (&is_course($cdom,$cnum)) {
5879: $homeserver = &homeserver($cnum,$cdom);
5880: } else {
5881: $homeserver = &domain($cdom,'primary');
5882: }
5883: if ($homeserver ne 'no_host') {
5884: $response = &reply('autorun:'.$cdom,$homeserver);
5885: }
1.876 raeburn 5886: }
1.506 raeburn 5887: return $response;
5888: }
1.776 albertel 5889:
1.506 raeburn 5890: sub auto_get_sections {
1.508 raeburn 5891: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 5892: my $homeserver;
5893: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5894: $homeserver = &homeserver($cnum,$cdom);
5895: }
5896: if (!defined($homeserver)) {
5897: if ($cdom =~ /^$match_domain$/) {
5898: $homeserver = &domain($cdom,'primary');
5899: }
5900: }
5901: my @secs;
5902: if (defined($homeserver)) {
5903: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5904: unless ($response eq 'refused') {
5905: @secs = split(/:/,$response);
5906: }
1.506 raeburn 5907: }
5908: return @secs;
5909: }
1.776 albertel 5910:
1.506 raeburn 5911: sub auto_new_course {
1.508 raeburn 5912: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5913: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 5914: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 5915: return $response;
5916: }
1.776 albertel 5917:
1.506 raeburn 5918: sub auto_validate_courseID {
1.508 raeburn 5919: my ($cnum,$cdom,$inst_course_id) = @_;
5920: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 5921: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 5922: return $response;
5923: }
1.776 albertel 5924:
1.1007 raeburn 5925: sub auto_validate_instcode {
1.1020 raeburn 5926: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 5927: my ($homeserver,$response);
5928: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5929: $homeserver = &homeserver($cnum,$cdom);
5930: }
5931: if (!defined($homeserver)) {
5932: if ($cdom =~ /^$match_domain$/) {
5933: $homeserver = &domain($cdom,'primary');
5934: }
5935: }
1.1065 raeburn 5936: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
5937: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 5938: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
5939: return ($outcome,$description);
1.1007 raeburn 5940: }
5941:
1.506 raeburn 5942: sub auto_create_password {
1.873 raeburn 5943: my ($cnum,$cdom,$authparam,$udom) = @_;
5944: my ($homeserver,$response);
1.506 raeburn 5945: my $create_passwd = 0;
5946: my $authchk = '';
1.873 raeburn 5947: if ($udom =~ /^$match_domain$/) {
5948: $homeserver = &domain($udom,'primary');
5949: }
5950: if ($homeserver eq '') {
5951: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5952: $homeserver = &homeserver($cnum,$cdom);
5953: }
5954: }
5955: if ($homeserver eq '') {
5956: $authchk = 'nodomain';
1.506 raeburn 5957: } else {
1.873 raeburn 5958: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5959: if ($response eq 'refused') {
5960: $authchk = 'refused';
5961: } else {
1.901 albertel 5962: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 5963: }
1.506 raeburn 5964: }
5965: return ($authparam,$create_passwd,$authchk);
5966: }
5967:
1.706 raeburn 5968: sub auto_photo_permission {
5969: my ($cnum,$cdom,$students) = @_;
5970: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 5971: my ($outcome,$perm_reqd,$conditions) =
5972: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 5973: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5974: return (undef,undef);
5975: }
1.706 raeburn 5976: return ($outcome,$perm_reqd,$conditions);
5977: }
5978:
5979: sub auto_checkphotos {
5980: my ($uname,$udom,$pid) = @_;
5981: my $homeserver = &homeserver($uname,$udom);
5982: my ($result,$resulttype);
5983: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 5984: &escape($uname).':'.&escape($pid),
5985: $homeserver));
1.709 albertel 5986: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5987: return (undef,undef);
5988: }
1.706 raeburn 5989: if ($outcome) {
5990: ($result,$resulttype) = split(/:/,$outcome);
5991: }
5992: return ($result,$resulttype);
5993: }
5994:
5995: sub auto_photochoice {
5996: my ($cnum,$cdom) = @_;
5997: my $homeserver = &homeserver($cnum,$cdom);
5998: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 5999: &escape($cdom),
6000: $homeserver)));
1.709 albertel 6001: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6002: return (undef,undef);
6003: }
1.706 raeburn 6004: return ($update,$comment);
6005: }
6006:
6007: sub auto_photoupdate {
6008: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6009: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6010: my $host=&hostname($homeserver);
1.706 raeburn 6011: my $cmd = '';
6012: my $maxtries = 1;
1.800 albertel 6013: foreach my $affiliate (keys(%{$affiliatesref})) {
6014: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6015: }
6016: $cmd =~ s/%%$//;
6017: $cmd = &escape($cmd);
6018: my $query = 'institutionalphotos';
6019: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6020: unless ($queryid=~/^\Q$host\E\_/) {
6021: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6022: return 'error: '.$queryid;
6023: }
6024: my $reply = &get_query_reply($queryid);
6025: my $tries = 1;
6026: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6027: $reply = &get_query_reply($queryid);
6028: $tries ++;
6029: }
6030: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6031: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6032: } else {
6033: my @responses = split(/:/,$reply);
6034: my $outcome = shift(@responses);
6035: foreach my $item (@responses) {
6036: my ($key,$value) = split(/=/,$item);
6037: $$photo{$key} = $value;
6038: }
6039: return $outcome;
6040: }
6041: return 'error';
6042: }
6043:
1.521 raeburn 6044: sub auto_instcode_format {
1.793 albertel 6045: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6046: $cat_order) = @_;
1.521 raeburn 6047: my $courses = '';
1.772 raeburn 6048: my @homeservers;
1.521 raeburn 6049: if ($caller eq 'global') {
1.841 albertel 6050: my %servers = &get_servers($codedom,'library');
6051: foreach my $tryserver (keys(%servers)) {
6052: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6053: push(@homeservers,$tryserver);
6054: }
1.584 raeburn 6055: }
1.1022 raeburn 6056: } elsif ($caller eq 'requests') {
6057: if ($codedom =~ /^$match_domain$/) {
6058: my $chome = &domain($codedom,'primary');
6059: unless ($chome eq 'no_host') {
6060: push(@homeservers,$chome);
6061: }
6062: }
1.521 raeburn 6063: } else {
1.772 raeburn 6064: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6065: }
1.793 albertel 6066: foreach my $code (keys(%{$instcodes})) {
6067: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6068: }
6069: chop($courses);
1.772 raeburn 6070: my $ok_response = 0;
6071: my $response;
6072: while (@homeservers > 0 && $ok_response == 0) {
6073: my $server = shift(@homeservers);
6074: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6075: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6076: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6077: split(/:/,$response);
1.772 raeburn 6078: %{$codes} = (%{$codes},&str2hash($codes_str));
6079: push(@{$codetitles},&str2array($codetitles_str));
6080: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6081: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6082: $ok_response = 1;
6083: }
6084: }
6085: if ($ok_response) {
1.521 raeburn 6086: return 'ok';
1.772 raeburn 6087: } else {
6088: return $response;
1.521 raeburn 6089: }
6090: }
6091:
1.792 raeburn 6092: sub auto_instcode_defaults {
6093: my ($domain,$returnhash,$code_order) = @_;
6094: my @homeservers;
1.841 albertel 6095:
6096: my %servers = &get_servers($domain,'library');
6097: foreach my $tryserver (keys(%servers)) {
6098: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6099: push(@homeservers,$tryserver);
6100: }
1.792 raeburn 6101: }
1.841 albertel 6102:
1.792 raeburn 6103: my $response;
1.841 albertel 6104: foreach my $server (@homeservers) {
1.792 raeburn 6105: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6106: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6107:
6108: foreach my $pair (split(/\&/,$response)) {
6109: my ($name,$value)=split(/\=/,$pair);
6110: if ($name eq 'code_order') {
6111: @{$code_order} = split(/\&/,&unescape($value));
6112: } else {
6113: $returnhash->{&unescape($name)}=&unescape($value);
6114: }
6115: }
6116: return 'ok';
1.792 raeburn 6117: }
1.841 albertel 6118:
6119: return $response;
1.1003 raeburn 6120: }
6121:
6122: sub auto_possible_instcodes {
1.1007 raeburn 6123: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6124: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6125: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6126: return;
6127: }
1.1003 raeburn 6128: my (@homeservers,$uhome);
6129: if (defined(&domain($domain,'primary'))) {
6130: $uhome=&domain($domain,'primary');
6131: push(@homeservers,&domain($domain,'primary'));
6132: } else {
6133: my %servers = &get_servers($domain,'library');
6134: foreach my $tryserver (keys(%servers)) {
6135: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6136: push(@homeservers,$tryserver);
6137: }
6138: }
6139: }
6140: my $response;
6141: foreach my $server (@homeservers) {
6142: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6143: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6144: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6145: split(':',$response);
6146: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6147: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6148: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6149: my ($name,$value)=split('=',$item);
6150: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6151: }
6152: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6153: my ($name,$value)=split('=',$item);
6154: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6155: }
6156: return 'ok';
6157: }
6158: return $response;
6159: }
1.792 raeburn 6160:
1.1010 raeburn 6161: sub auto_courserequest_checks {
6162: my ($dom) = @_;
1.1020 raeburn 6163: my ($homeserver,%validations);
6164: if ($dom =~ /^$match_domain$/) {
6165: $homeserver = &domain($dom,'primary');
6166: }
6167: unless ($homeserver eq 'no_host') {
6168: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6169: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6170: my @items = split(/&/,$response);
6171: foreach my $item (@items) {
6172: my ($key,$value) = split('=',$item);
6173: $validations{&unescape($key)} = &thaw_unescape($value);
6174: }
6175: }
6176: }
1.1010 raeburn 6177: return %validations;
6178: }
6179:
1.1020 raeburn 6180: sub auto_courserequest_validation {
6181: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6182: my ($homeserver,$response);
6183: if ($dom =~ /^$match_domain$/) {
6184: $homeserver = &domain($dom,'primary');
6185: }
6186: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6187:
1.1020 raeburn 6188: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6189: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6190: ':'.&escape($instcode).':'.&escape($instseclist),
6191: $homeserver));
6192: }
6193: return $response;
6194: }
6195:
1.777 albertel 6196: sub auto_validate_class_sec {
1.918 raeburn 6197: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6198: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6199: my $ownerlist;
6200: if (ref($owners) eq 'ARRAY') {
6201: $ownerlist = join(',',@{$owners});
6202: } else {
6203: $ownerlist = $owners;
6204: }
1.773 raeburn 6205: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6206: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6207: return $response;
6208: }
6209:
1.679 raeburn 6210: # ------------------------------------------------------- Course Group routines
6211:
6212: sub get_coursegroups {
1.809 raeburn 6213: my ($cdom,$cnum,$group,$namespace) = @_;
6214: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6215: }
6216:
1.679 raeburn 6217: sub modify_coursegroup {
6218: my ($cdom,$cnum,$groupsettings) = @_;
6219: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6220: }
6221:
1.809 raeburn 6222: sub toggle_coursegroup_status {
6223: my ($cdom,$cnum,$group,$action) = @_;
6224: my ($from_namespace,$to_namespace);
6225: if ($action eq 'delete') {
6226: $from_namespace = 'coursegroups';
6227: $to_namespace = 'deleted_groups';
6228: } else {
6229: $from_namespace = 'deleted_groups';
6230: $to_namespace = 'coursegroups';
6231: }
6232: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6233: if (my $tmp = &error(%curr_group)) {
6234: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6235: return ('read error',$tmp);
6236: } else {
6237: my %savedsettings = %curr_group;
1.809 raeburn 6238: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6239: my $deloutcome;
6240: if ($result eq 'ok') {
1.809 raeburn 6241: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6242: } else {
6243: return ('write error',$result);
6244: }
6245: if ($deloutcome eq 'ok') {
6246: return 'ok';
6247: } else {
6248: return ('delete error',$deloutcome);
6249: }
6250: }
6251: }
6252:
1.679 raeburn 6253: sub modify_group_roles {
1.957 raeburn 6254: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6255: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6256: my $role = 'gr/'.&escape($userprivs);
6257: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6258: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6259: if ($result eq 'ok') {
6260: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6261: }
1.679 raeburn 6262: return $result;
6263: }
6264:
6265: sub modify_coursegroup_membership {
6266: my ($cdom,$cnum,$membership) = @_;
6267: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6268: return $result;
6269: }
6270:
1.682 raeburn 6271: sub get_active_groups {
6272: my ($udom,$uname,$cdom,$cnum) = @_;
6273: my $now = time;
6274: my %groups = ();
6275: foreach my $key (keys(%env)) {
1.811 albertel 6276: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6277: my ($start,$end) = split(/\./,$env{$key});
6278: if (($end!=0) && ($end<$now)) { next; }
6279: if (($start!=0) && ($start>$now)) { next; }
6280: if ($1 eq $cdom && $2 eq $cnum) {
6281: $groups{$3} = $env{$key} ;
6282: }
6283: }
6284: }
6285: return %groups;
6286: }
6287:
1.683 raeburn 6288: sub get_group_membership {
6289: my ($cdom,$cnum,$group) = @_;
6290: return(&dump('groupmembership',$cdom,$cnum,$group));
6291: }
6292:
6293: sub get_users_groups {
6294: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6295: my @usersgroups;
1.683 raeburn 6296: my $cachetime=1800;
6297:
6298: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6299: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6300: if (defined($cached)) {
1.734 albertel 6301: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6302: } else {
6303: $grouplist = '';
1.816 raeburn 6304: my $courseurl = &courseid_to_courseurl($courseid);
6305: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 6306: my $access_end = $env{'course.'.$courseid.
6307: '.default_enrollment_end_date'};
6308: my $now = time;
6309: foreach my $key (keys(%roleshash)) {
6310: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6311: my $group = $1;
6312: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6313: my $start = $2;
6314: my $end = $1;
6315: if ($start == -1) { next; } # deleted from group
6316: if (($start!=0) && ($start>$now)) { next; }
6317: if (($end!=0) && ($end<$now)) {
6318: if ($access_end && $access_end < $now) {
6319: if ($access_end - $end < 86400) {
6320: push(@usersgroups,$group);
1.733 raeburn 6321: }
6322: }
1.817 raeburn 6323: next;
1.733 raeburn 6324: }
1.817 raeburn 6325: push(@usersgroups,$group);
1.683 raeburn 6326: }
6327: }
6328: }
1.817 raeburn 6329: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6330: $grouplist = join(':',@usersgroups);
6331: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6332: }
1.733 raeburn 6333: return @usersgroups;
1.683 raeburn 6334: }
6335:
6336: sub devalidate_getgroups_cache {
6337: my ($udom,$uname,$cdom,$cnum)=@_;
6338: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6339:
1.683 raeburn 6340: my $hashid="$udom:$uname:$courseid";
6341: &devalidate_cache_new('getgroups',$hashid);
6342: }
6343:
1.12 www 6344: # ------------------------------------------------------------------ Plain Text
6345:
6346: sub plaintext {
1.988 raeburn 6347: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6348: if ($short =~ m{^cr/}) {
1.758 albertel 6349: return (split('/',$short))[-1];
6350: }
1.742 raeburn 6351: if (!defined($cid)) {
6352: $cid = $env{'request.course.id'};
6353: }
6354: my %rolenames = (
1.1008 raeburn 6355: Course => 'std',
6356: Community => 'alt1',
1.742 raeburn 6357: );
1.1037 raeburn 6358: if ($cid ne '') {
6359: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6360: unless ($forcedefault) {
6361: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6362: &Apache::lonlocal::mt_escape(\$roletext);
6363: return &Apache::lonlocal::mt($roletext);
6364: }
6365: }
6366: }
6367: if ((defined($type)) && (defined($rolenames{$type})) &&
6368: (defined($rolenames{$type})) &&
6369: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6370: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6371: } elsif ($cid ne '') {
6372: my $crstype = $env{'course.'.$cid.'.type'};
6373: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6374: (defined($prp{$short}{$rolenames{$crstype}}))) {
6375: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6376: }
1.742 raeburn 6377: }
1.1037 raeburn 6378: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6379: }
6380:
6381: # ----------------------------------------------------------------- Assign Role
6382:
6383: sub assignrole {
1.957 raeburn 6384: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6385: $context)=@_;
1.21 www 6386: my $mrole;
6387: if ($role =~ /^cr\//) {
1.393 www 6388: my $cwosec=$url;
1.811 albertel 6389: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6390: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6391: my $refused = 1;
6392: if ($context eq 'requestcourses') {
6393: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6394: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6395: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6396: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6397: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6398: if ($crsenv{'internal.courseowner'} eq
6399: $env{'user.name'}.':'.$env{'user.domain'}) {
6400: $refused = '';
6401: }
6402: }
6403: }
6404: }
6405: }
6406: if ($refused) {
6407: &logthis('Refused custom assignrole: '.
6408: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6409: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6410: return 'refused';
6411: }
1.104 www 6412: }
1.21 www 6413: $mrole='cr';
1.678 raeburn 6414: } elsif ($role =~ /^gr\//) {
6415: my $cwogrp=$url;
1.811 albertel 6416: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6417: unless (&allowed('mdg',$cwogrp)) {
6418: &logthis('Refused group assignrole: '.
6419: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6420: $env{'user.name'}.' at '.$env{'user.domain'});
6421: return 'refused';
6422: }
6423: $mrole='gr';
1.21 www 6424: } else {
1.82 www 6425: my $cwosec=$url;
1.811 albertel 6426: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6427: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6428: my $refused;
6429: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6430: if (!(&allowed('c'.$role,$url))) {
6431: $refused = 1;
6432: }
6433: } else {
6434: $refused = 1;
6435: }
1.947 raeburn 6436: if ($refused) {
1.1045 raeburn 6437: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6438: if (!$selfenroll && $context eq 'course') {
6439: my %crsenv;
6440: if ($role eq 'cc' || $role eq 'co') {
6441: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6442: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6443: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6444: if ($crsenv{'internal.courseowner'} eq
6445: $env{'user.name'}.':'.$env{'user.domain'}) {
6446: $refused = '';
6447: }
6448: }
6449: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6450: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6451: if ($crsenv{'internal.courseowner'} eq
6452: $env{'user.name'}.':'.$env{'user.domain'}) {
6453: $refused = '';
6454: }
6455: }
6456: }
6457: }
6458: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6459: $refused = '';
1.1017 raeburn 6460: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6461: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6462: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6463: my $wrongcc;
6464: if ($cnum =~ /^$match_community$/) {
6465: $wrongcc = 1 if ($role eq 'cc');
6466: } else {
6467: $wrongcc = 1 if ($role eq 'co');
6468: }
6469: unless ($wrongcc) {
6470: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6471: if ($crsenv{'internal.courseowner'} eq
6472: $env{'user.name'}.':'.$env{'user.domain'}) {
6473: $refused = '';
6474: }
1.1017 raeburn 6475: }
6476: }
6477: }
6478: if ($refused) {
1.947 raeburn 6479: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6480: ' '.$role.' '.$end.' '.$start.' by '.
6481: $env{'user.name'}.' at '.$env{'user.domain'});
6482: return 'refused';
6483: }
1.932 raeburn 6484: }
1.104 www 6485: }
1.21 www 6486: $mrole=$role;
6487: }
1.620 albertel 6488: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6489: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6490: if ($end) { $command.='_'.$end; }
1.21 www 6491: if ($start) {
6492: if ($end) {
1.81 www 6493: $command.='_'.$start;
1.21 www 6494: } else {
1.81 www 6495: $command.='_0_'.$start;
1.21 www 6496: }
6497: }
1.739 raeburn 6498: my $origstart = $start;
6499: my $origend = $end;
1.957 raeburn 6500: my $delflag;
1.357 www 6501: # actually delete
6502: if ($deleteflag) {
1.373 www 6503: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6504: # modify command to delete the role
1.620 albertel 6505: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6506: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6507: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6508: # set start and finish to negative values for userrolelog
6509: $start=-1;
6510: $end=-1;
1.957 raeburn 6511: $delflag = 1;
1.357 www 6512: }
6513: }
6514: # send command
1.349 www 6515: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6516: # log new user role if status is ok
1.349 www 6517: if ($answer eq 'ok') {
1.663 raeburn 6518: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6519: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6520: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6521: unless ($role =~ /^gr/) {
6522: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6523: $origstart,$selfenroll,$context);
1.739 raeburn 6524: }
1.1053 raeburn 6525: if ($role eq 'cc') {
6526: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6527: }
1.349 www 6528: }
6529: return $answer;
1.169 harris41 6530: }
6531:
1.1053 raeburn 6532: sub autoupdate_coowners {
6533: my ($url,$end,$start,$uname,$udom) = @_;
6534: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6535: if (($cdom ne '') && ($cnum ne '')) {
6536: my $now = time;
6537: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6538: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6539: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6540: my $instcode = $coursehash{'internal.coursecode'};
6541: if ($instcode ne '') {
1.1056 raeburn 6542: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6543: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6544: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6545: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6546: if ($result eq 'valid') {
6547: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6548: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6549: push(@newcoowners,$coowner);
6550: }
6551: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6552: push(@newcoowners,$uname.':'.$udom);
6553: }
6554: @newcoowners = sort(@newcoowners);
6555: } else {
6556: push(@newcoowners,$uname.':'.$udom);
6557: }
6558: } else {
6559: if ($coursehash{'internal.co-owners'}) {
6560: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6561: unless ($coowner eq $uname.':'.$udom) {
6562: push(@newcoowners,$coowner);
6563: }
6564: }
6565: unless (@newcoowners > 0) {
6566: $delcoowners = 1;
6567: $coowners = '';
6568: }
6569: }
6570: }
6571: if (@newcoowners || $delcoowners) {
6572: &store_coowners($cdom,$cnum,$coursehash{'home'},
6573: $delcoowners,@newcoowners);
6574: }
6575: }
6576: }
6577: }
6578: }
6579: }
6580: }
6581:
6582: sub store_coowners {
6583: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6584: my $cid = $cdom.'_'.$cnum;
6585: my ($coowners,$delresult,$putresult);
6586: if (@newcoowners) {
6587: $coowners = join(',',@newcoowners);
6588: my %coownershash = (
6589: 'internal.co-owners' => $coowners,
6590: );
6591: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6592: if ($putresult eq 'ok') {
6593: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6594: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6595: }
6596: }
6597: }
6598: if ($delcoowners) {
6599: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6600: if ($delresult eq 'ok') {
6601: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6602: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6603: }
6604: }
6605: }
6606: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6607: my %crsinfo =
6608: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6609: if (ref($crsinfo{$cid}) eq 'HASH') {
6610: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6611: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6612: }
6613: }
6614: }
6615:
1.169 harris41 6616: # -------------------------------------------------- Modify user authentication
1.197 www 6617: # Overrides without validation
6618:
1.169 harris41 6619: sub modifyuserauth {
6620: my ($udom,$uname,$umode,$upass)=@_;
6621: my $uhome=&homeserver($uname,$udom);
1.197 www 6622: unless (&allowed('mau',$udom)) { return 'refused'; }
6623: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6624: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6625: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6626: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6627: &escape($upass),$uhome);
1.620 albertel 6628: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6629: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6630: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6631: &log($udom,,$uname,$uhome,
1.620 albertel 6632: 'Authentication changed by '.$env{'user.domain'}.', '.
6633: $env{'user.name'}.', '.$umode.
1.197 www 6634: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6635: unless ($reply eq 'ok') {
1.197 www 6636: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6637: return 'error: '.$reply;
6638: }
1.170 harris41 6639: return 'ok';
1.80 www 6640: }
6641:
1.81 www 6642: # --------------------------------------------------------------- Modify a user
1.80 www 6643:
1.81 www 6644: sub modifyuser {
1.206 matthew 6645: my ($udom, $uname, $uid,
6646: $umode, $upass, $first,
6647: $middle, $last, $gene,
1.1058 raeburn 6648: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6649: $udom= &LONCAPA::clean_domain($udom);
6650: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 6651: my $showcandelete = 'none';
6652: if (ref($candelete) eq 'ARRAY') {
6653: if (@{$candelete} > 0) {
6654: $showcandelete = join(', ',@{$candelete});
6655: }
6656: }
1.81 www 6657: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6658: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 6659: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6660: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6661: ' desiredhome not specified').
1.620 albertel 6662: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6663: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6664: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 6665: my $newuser;
6666: if ($uhome eq 'no_host') {
6667: $newuser = 1;
6668: }
1.80 www 6669: # ----------------------------------------------------------------- Create User
1.406 albertel 6670: if (($uhome eq 'no_host') &&
6671: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6672: my $unhome='';
1.844 albertel 6673: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6674: $unhome = $desiredhome;
1.620 albertel 6675: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6676: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6677: } else { # load balancing routine for determining $unhome
1.81 www 6678: my $loadm=10000000;
1.841 albertel 6679: my %servers = &get_servers($udom,'library');
6680: foreach my $tryserver (keys(%servers)) {
6681: my $answer=reply('load',$tryserver);
6682: if (($answer=~/\d+/) && ($answer<$loadm)) {
6683: $loadm=$answer;
6684: $unhome=$tryserver;
6685: }
1.80 www 6686: }
6687: }
6688: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6689: return 'error: unable to find a home server for '.$uname.
6690: ' in domain '.$udom;
1.80 www 6691: }
6692: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6693: &escape($upass),$unhome);
6694: unless ($reply eq 'ok') {
6695: return 'error: '.$reply;
6696: }
1.230 stredwic 6697: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6698: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6699: return 'error: unable verify users home machine.';
1.80 www 6700: }
1.209 matthew 6701: } # End of creation of new user
1.80 www 6702: # ---------------------------------------------------------------------- Add ID
6703: if ($uid) {
6704: $uid=~tr/A-Z/a-z/;
6705: my %uidhash=&idrget($udom,$uname);
1.196 www 6706: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6707: && (!$forceid)) {
1.80 www 6708: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6709: return 'error: user id "'.$uid.'" does not match '.
6710: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6711: }
6712: } else {
6713: &idput($udom,($uname => $uid));
6714: }
6715: }
6716: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6717: my @tmp=&get('environment',
1.899 raeburn 6718: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6719: 'permanentemail','inststatus'],
1.134 albertel 6720: $udom,$uname);
1.1075 raeburn 6721: my (%names,%oldnames);
1.313 matthew 6722: if ($tmp[0] =~ m/^error:.*/) {
6723: %names=();
6724: } else {
6725: %names = @tmp;
1.1075 raeburn 6726: %oldnames = %names;
1.313 matthew 6727: }
1.388 www 6728: #
1.1058 raeburn 6729: # If name, email and/or uid are blank (e.g., because an uploaded file
6730: # of users did not contain them), do not overwrite existing values
6731: # unless field is in $candelete array ref.
6732: #
6733:
6734: my @fields = ('firstname','middlename','lastname','generation',
6735: 'permanentemail','id');
6736: my %newvalues;
6737: if (ref($candelete) eq 'ARRAY') {
6738: foreach my $field (@fields) {
6739: if (grep(/^\Q$field\E$/,@{$candelete})) {
6740: if ($field eq 'firstname') {
6741: $names{$field} = $first;
6742: } elsif ($field eq 'middlename') {
6743: $names{$field} = $middle;
6744: } elsif ($field eq 'lastname') {
6745: $names{$field} = $last;
6746: } elsif ($field eq 'generation') {
6747: $names{$field} = $gene;
6748: } elsif ($field eq 'permanentemail') {
6749: $names{$field} = $email;
6750: } elsif ($field eq 'id') {
6751: $names{$field} = $uid;
6752: }
6753: }
6754: }
6755: }
1.388 www 6756: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6757: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6758: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6759: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6760: if ($email) {
6761: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6762: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6763: }
1.899 raeburn 6764: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6765: if (defined($inststatus)) {
6766: $names{'inststatus'} = '';
6767: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6768: if (ref($usertypes) eq 'HASH') {
6769: my @okstatuses;
6770: foreach my $item (split(/:/,$inststatus)) {
6771: if (defined($usertypes->{$item})) {
6772: push(@okstatuses,$item);
6773: }
6774: }
6775: if (@okstatuses) {
6776: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6777: }
6778: }
6779: }
1.1075 raeburn 6780: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 6781: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 6782: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 6783: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6784: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6785: } else {
6786: $logmsg .= ' during self creation';
6787: }
1.1075 raeburn 6788: my $changed;
6789: if ($newuser) {
6790: $changed = 1;
6791: } else {
6792: foreach my $field (@fields) {
6793: if ($names{$field} ne $oldnames{$field}) {
6794: $changed = 1;
6795: last;
6796: }
6797: }
6798: }
6799: unless ($changed) {
6800: $logmsg = 'No changes in user information needed for: '.$logmsg;
6801: &logthis($logmsg);
6802: return 'ok';
6803: }
6804: my $reply = &put('environment', \%names, $udom,$uname);
6805: if ($reply ne 'ok') {
6806: return 'error: '.$reply;
6807: }
6808: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
6809: &devalidate_cache_new('namescache',$uname.':'.$udom);
6810: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 6811: &logthis($logmsg);
1.134 albertel 6812: return 'ok';
1.80 www 6813: }
6814:
1.81 www 6815: # -------------------------------------------------------------- Modify student
1.80 www 6816:
1.81 www 6817: sub modifystudent {
6818: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6819: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6820: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6821: if (!$cid) {
1.620 albertel 6822: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6823: return 'not_in_class';
6824: }
1.80 www 6825: }
6826: # --------------------------------------------------------------- Make the user
1.81 www 6827: my $reply=&modifyuser
1.209 matthew 6828: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6829: $desiredhome,$email,$inststatus);
1.80 www 6830: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6831: # This will cause &modify_student_enrollment to get the uid from the
6832: # students environment
6833: $uid = undef if (!$forceid);
1.455 albertel 6834: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6835: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6836: return $reply;
6837: }
6838:
6839: sub modify_student_enrollment {
1.957 raeburn 6840: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6841: my ($cdom,$cnum,$chome);
6842: if (!$cid) {
1.620 albertel 6843: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6844: return 'not_in_class';
6845: }
1.620 albertel 6846: $cdom=$env{'course.'.$cid.'.domain'};
6847: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6848: } else {
6849: ($cdom,$cnum)=split(/_/,$cid);
6850: }
1.620 albertel 6851: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6852: if (!$chome) {
1.457 raeburn 6853: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6854: }
1.455 albertel 6855: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6856: # Make sure the user exists
1.81 www 6857: my $uhome=&homeserver($uname,$udom);
6858: if (($uhome eq '') || ($uhome eq 'no_host')) {
6859: return 'error: no such user';
6860: }
1.297 matthew 6861: # Get student data if we were not given enough information
6862: if (!defined($first) || $first eq '' ||
6863: !defined($last) || $last eq '' ||
6864: !defined($uid) || $uid eq '' ||
6865: !defined($middle) || $middle eq '' ||
6866: !defined($gene) || $gene eq '') {
1.294 matthew 6867: # They did not supply us with enough data to enroll the student, so
6868: # we need to pick up more information.
1.297 matthew 6869: my %tmp = &get('environment',
1.294 matthew 6870: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6871: ,$udom,$uname);
6872:
1.800 albertel 6873: #foreach my $key (keys(%tmp)) {
6874: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6875: #}
1.294 matthew 6876: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6877: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6878: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6879: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6880: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6881: }
1.556 albertel 6882: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 6883: my $reply=cput('classlist',
6884: {"$uname:$udom" =>
1.515 raeburn 6885: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 6886: $cdom,$cnum);
1.81 www 6887: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6888: return 'error: '.$reply;
1.652 albertel 6889: } else {
6890: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 6891: }
1.297 matthew 6892: # Add student role to user
1.83 www 6893: my $uurl='/'.$cid;
1.81 www 6894: $uurl=~s/\_/\//g;
6895: if ($usec) {
6896: $uurl.='/'.$usec;
6897: }
1.957 raeburn 6898: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 6899: }
6900:
1.556 albertel 6901: sub format_name {
6902: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6903: my $name;
6904: if ($first ne 'lastname') {
6905: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6906: } else {
6907: if ($lastname=~/\S/) {
6908: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6909: $name=~s/\s+,/,/;
6910: } else {
6911: $name.= $firstname.' '.$middlename.' '.$generation;
6912: }
6913: }
6914: $name=~s/^\s+//;
6915: $name=~s/\s+$//;
6916: $name=~s/\s+/ /g;
6917: return $name;
6918: }
6919:
1.84 www 6920: # ------------------------------------------------- Write to course preferences
6921:
6922: sub writecoursepref {
6923: my ($courseid,%prefs)=@_;
6924: $courseid=~s/^\///;
6925: $courseid=~s/\_/\//g;
6926: my ($cdomain,$cnum)=split(/\//,$courseid);
6927: my $chome=homeserver($cnum,$cdomain);
6928: if (($chome eq '') || ($chome eq 'no_host')) {
6929: return 'error: no such course';
6930: }
6931: my $cstring='';
1.800 albertel 6932: foreach my $pref (keys(%prefs)) {
6933: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 6934: }
1.84 www 6935: $cstring=~s/\&$//;
6936: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6937: }
6938:
6939: # ---------------------------------------------------------- Make/modify course
6940:
6941: sub createcourse {
1.741 raeburn 6942: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 6943: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 6944: $url=&declutter($url);
6945: my $cid='';
1.1028 raeburn 6946: if ($context eq 'requestcourses') {
6947: my $can_create = 0;
6948: my ($ownername,$ownerdom) = split(':',$course_owner);
6949: if ($udom eq $ownerdom) {
6950: if (&usertools_access($ownername,$ownerdom,$category,undef,
6951: $context)) {
6952: $can_create = 1;
6953: }
6954: } else {
6955: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
6956: $category);
6957: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
6958: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
6959: if (@curr > 0) {
6960: my @options = qw(approval validate autolimit);
6961: my $optregex = join('|',@options);
6962: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
6963: $can_create = 1;
6964: }
6965: }
6966: }
6967: }
6968: if ($can_create) {
6969: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
6970: unless (&allowed('ccc',$udom)) {
6971: return 'refused';
6972: }
1.1017 raeburn 6973: }
6974: } else {
6975: return 'refused';
6976: }
1.1028 raeburn 6977: } elsif (!&allowed('ccc',$udom)) {
6978: return 'refused';
1.84 www 6979: }
1.1011 raeburn 6980: # --------------------------------------------------------------- Get Unique ID
6981: my $uname;
6982: if ($cnum =~ /^$match_courseid$/) {
6983: my $chome=&homeserver($cnum,$udom,'true');
6984: if (($chome eq '') || ($chome eq 'no_host')) {
6985: $uname = $cnum;
6986: } else {
1.1038 raeburn 6987: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6988: }
6989: } else {
1.1038 raeburn 6990: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 6991: }
6992: return $uname if ($uname =~ /^error/);
6993: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 6994: if (!defined($course_server)) {
6995: if (defined(&domain($udom,'primary'))) {
6996: $course_server = &domain($udom,'primary');
6997: } else {
6998: $course_server = $env{'user.home'};
6999: }
7000: }
7001: my %host_servers =
7002: &Apache::lonnet::get_servers($udom,'library');
7003: unless ($host_servers{$course_server}) {
7004: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7005: }
1.84 www 7006: # ------------------------------------------------------------- Make the course
7007: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7008: $course_server);
1.84 www 7009: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7010: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7011: if (($uhome eq '') || ($uhome eq 'no_host')) {
7012: return 'error: no such course';
7013: }
1.271 www 7014: # ----------------------------------------------------------------- Course made
1.516 raeburn 7015: # log existence
1.1029 raeburn 7016: my $now = time;
1.918 raeburn 7017: my $newcourse = {
7018: $udom.'_'.$uname => {
1.921 raeburn 7019: description => $description,
7020: inst_code => $inst_code,
7021: owner => $course_owner,
7022: type => $crstype,
1.1029 raeburn 7023: creator => $env{'user.name'}.':'.
7024: $env{'user.domain'},
7025: created => $now,
7026: context => $context,
1.918 raeburn 7027: },
7028: };
1.921 raeburn 7029: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7030: # set toplevel url
1.271 www 7031: my $topurl=$url;
7032: unless ($nonstandard) {
7033: # ------------------------------------------ For standard courses, make top url
7034: my $mapurl=&clutter($url);
1.278 www 7035: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7036: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7037: <map>
7038: <resource id="1" type="start"></resource>
7039: <resource id="2" src="$mapurl"></resource>
7040: <resource id="3" type="finish"></resource>
7041: <link index="1" from="1" to="2"></link>
7042: <link index="2" from="2" to="3"></link>
7043: </map>
7044: ENDINITMAP
7045: $topurl=&declutter(
1.638 albertel 7046: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7047: );
7048: }
7049: # ----------------------------------------------------------- Write preferences
1.84 www 7050: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7051: ('description' => $description,
7052: 'url' => $topurl,
7053: 'internal.creator' => $env{'user.name'}.':'.
7054: $env{'user.domain'},
7055: 'internal.created' => $now,
7056: 'internal.creationcontext' => $context)
7057: );
1.84 www 7058: return '/'.$udom.'/'.$uname;
7059: }
7060:
1.1011 raeburn 7061: # ------------------------------------------------------------------- Create ID
7062: sub generate_coursenum {
1.1038 raeburn 7063: my ($udom,$crstype) = @_;
1.1011 raeburn 7064: my $domdesc = &domain($udom);
7065: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7066: my $first;
7067: if ($crstype eq 'Community') {
7068: $first = '0';
7069: } else {
7070: $first = int(1+rand(9));
7071: }
7072: my $uname=$first.
1.1011 raeburn 7073: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7074: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7075: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7076: # ----------------------------------------------- Make sure that does not exist
7077: my $uhome=&homeserver($uname,$udom,'true');
7078: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7079: if ($crstype eq 'Community') {
7080: $first = '0';
7081: } else {
7082: $first = int(1+rand(9));
7083: }
7084: $uname=$first.
1.1011 raeburn 7085: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7086: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7087: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7088: $uhome=&homeserver($uname,$udom,'true');
7089: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7090: return 'error: unable to generate unique course-ID';
7091: }
7092: }
7093: return $uname;
7094: }
7095:
1.813 albertel 7096: sub is_course {
7097: my ($cdom,$cnum) = @_;
7098: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7099: undef,'.');
1.813 albertel 7100: if (exists($courses{$cdom.'_'.$cnum})) {
7101: return 1;
7102: }
7103: return 0;
7104: }
7105:
1.1015 raeburn 7106: sub store_userdata {
7107: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7108: my $result;
1.1016 raeburn 7109: if ($datakey ne '') {
1.1013 raeburn 7110: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7111: if ($udom eq '' || $uname eq '') {
7112: $udom = $env{'user.domain'};
7113: $uname = $env{'user.name'};
7114: }
7115: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7116: if (($uhome eq '') || ($uhome eq 'no_host')) {
7117: $result = 'error: no_host';
7118: } else {
7119: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7120: $storehash->{'host'} = $perlvar{'lonHostID'};
7121:
7122: my $namevalue='';
7123: foreach my $key (keys(%{$storehash})) {
7124: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7125: }
7126: $namevalue=~s/\&$//;
7127: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 7128: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 7129: }
7130: } else {
7131: $result = 'error: data to store was not a hash reference';
7132: }
7133: } else {
7134: $result= 'error: invalid requestkey';
7135: }
7136: return $result;
7137: }
7138:
1.21 www 7139: # ---------------------------------------------------------- Assign Custom Role
7140:
7141: sub assigncustomrole {
1.957 raeburn 7142: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7143: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7144: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7145: }
7146:
7147: # ----------------------------------------------------------------- Revoke Role
7148:
7149: sub revokerole {
1.957 raeburn 7150: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7151: my $now=time;
1.965 raeburn 7152: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7153: }
7154:
7155: # ---------------------------------------------------------- Revoke Custom Role
7156:
7157: sub revokecustomrole {
1.957 raeburn 7158: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7159: my $now=time;
1.357 www 7160: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7161: $deleteflag,$selfenroll,$context);
1.17 www 7162: }
7163:
1.533 banghart 7164: # ------------------------------------------------------------ Disk usage
1.535 albertel 7165: sub diskusage {
1.955 raeburn 7166: my ($udom,$uname,$directorypath,$getpropath)=@_;
7167: $directorypath =~ s/\/$//;
7168: my $listing=&reply('du2:'.&escape($directorypath).':'
7169: .&escape($getpropath).':'.&escape($uname).':'
7170: .&escape($udom),homeserver($uname,$udom));
7171: if ($listing eq 'unknown_cmd') {
7172: if ($getpropath) {
7173: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7174: }
7175: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7176: }
1.514 albertel 7177: return $listing;
1.512 banghart 7178: }
7179:
1.566 banghart 7180: sub is_locked {
7181: my ($file_name, $domain, $user) = @_;
7182: my @check;
7183: my $is_locked;
7184: push @check, $file_name;
1.613 albertel 7185: my %locked = &get('file_permissions',\@check,
1.620 albertel 7186: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7187: my ($tmp)=keys(%locked);
7188: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7189:
1.566 banghart 7190: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7191: $is_locked = 'false';
7192: foreach my $entry (@{$locked{$file_name}}) {
7193: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7194: $is_locked = 'true';
7195: last;
1.745 raeburn 7196: }
7197: }
1.566 banghart 7198: } else {
7199: $is_locked = 'false';
7200: }
7201: }
7202:
1.759 albertel 7203: sub declutter_portfile {
7204: my ($file) = @_;
1.833 albertel 7205: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7206: return $file;
7207: }
7208:
1.559 banghart 7209: # ------------------------------------------------------------- Mark as Read Only
7210:
7211: sub mark_as_readonly {
7212: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7213: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7214: my ($tmp)=keys(%current_permissions);
7215: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7216: foreach my $file (@{$files}) {
1.759 albertel 7217: $file = &declutter_portfile($file);
1.561 banghart 7218: push(@{$current_permissions{$file}},$what);
1.559 banghart 7219: }
1.613 albertel 7220: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7221: return;
7222: }
7223:
1.572 banghart 7224: # ------------------------------------------------------------Save Selected Files
7225:
7226: sub save_selected_files {
7227: my ($user, $path, @files) = @_;
7228: my $filename = $user."savedfiles";
1.573 banghart 7229: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7230: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7231: foreach my $file (@files) {
1.620 albertel 7232: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7233: }
7234: foreach my $file (@other_files) {
1.574 banghart 7235: print (OUT $file."\n");
1.572 banghart 7236: }
1.574 banghart 7237: close (OUT);
1.572 banghart 7238: return 'ok';
7239: }
7240:
1.574 banghart 7241: sub clear_selected_files {
7242: my ($user) = @_;
7243: my $filename = $user."savedfiles";
7244: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7245: print (OUT undef);
7246: close (OUT);
7247: return ("ok");
7248: }
7249:
1.572 banghart 7250: sub files_in_path {
7251: my ($user, $path) = @_;
7252: my $filename = $user."savedfiles";
7253: my %return_files;
1.574 banghart 7254: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7255: while (my $line_in = <IN>) {
1.574 banghart 7256: chomp ($line_in);
7257: my @paths_and_file = split (m!/!, $line_in);
7258: my $file_part = pop (@paths_and_file);
7259: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7260: $path_part.='/';
7261: my $path_and_file = $path_part.$file_part;
7262: if ($path_part eq $path) {
7263: $return_files{$file_part}= 'selected';
7264: }
7265: }
1.574 banghart 7266: close (IN);
7267: return (\%return_files);
1.572 banghart 7268: }
7269:
7270: # called in portfolio select mode, to show files selected NOT in current directory
7271: sub files_not_in_path {
7272: my ($user, $path) = @_;
7273: my $filename = $user."savedfiles";
7274: my @return_files;
7275: my $path_part;
1.800 albertel 7276: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7277: while (my $line = <IN>) {
1.572 banghart 7278: #ok, I know it's clunky, but I want it to work
1.800 albertel 7279: my @paths_and_file = split(m|/|, $line);
7280: my $file_part = pop(@paths_and_file);
7281: chomp($file_part);
7282: my $path_part = join('/', @paths_and_file);
1.572 banghart 7283: $path_part .= '/';
7284: my $path_and_file = $path_part.$file_part;
7285: if ($path_part ne $path) {
1.800 albertel 7286: push(@return_files, ($path_and_file));
1.572 banghart 7287: }
7288: }
1.800 albertel 7289: close(OUT);
1.574 banghart 7290: return (@return_files);
1.572 banghart 7291: }
7292:
1.745 raeburn 7293: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7294:
1.745 raeburn 7295: sub get_portfile_permissions {
7296: my ($domain,$user) = @_;
1.613 albertel 7297: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7298: my ($tmp)=keys(%current_permissions);
7299: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7300: return \%current_permissions;
7301: }
7302:
7303: #---------------------------------------------Get portfolio file access controls
7304:
1.749 raeburn 7305: sub get_access_controls {
1.745 raeburn 7306: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7307: my %access;
7308: my $real_file = $file;
7309: $file =~ s/\.meta$//;
1.745 raeburn 7310: if (defined($file)) {
1.749 raeburn 7311: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7312: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7313: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7314: }
7315: }
1.745 raeburn 7316: } else {
1.749 raeburn 7317: foreach my $key (keys(%{$current_permissions})) {
7318: if ($key =~ /\0accesscontrol$/) {
7319: if (defined($group)) {
7320: if ($key !~ m-^\Q$group\E/-) {
7321: next;
7322: }
7323: }
7324: my ($fullpath) = split(/\0/,$key);
7325: if (ref($$current_permissions{$key}) eq 'HASH') {
7326: foreach my $control (keys(%{$$current_permissions{$key}})) {
7327: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7328: }
7329: }
7330: }
7331: }
7332: }
7333: return %access;
7334: }
7335:
7336: sub modify_access_controls {
7337: my ($file_name,$changes,$domain,$user)=@_;
7338: my ($outcome,$deloutcome);
7339: my %store_permissions;
7340: my %new_values;
7341: my %new_control;
7342: my %translation;
7343: my @deletions = ();
7344: my $now = time;
7345: if (exists($$changes{'activate'})) {
7346: if (ref($$changes{'activate'}) eq 'HASH') {
7347: my @newitems = sort(keys(%{$$changes{'activate'}}));
7348: my $numnew = scalar(@newitems);
7349: for (my $i=0; $i<$numnew; $i++) {
7350: my $newkey = $newitems[$i];
7351: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7352: if ($newkey =~ /^\d+:/) {
7353: $newkey =~ s/^(\d+)/$newid/;
7354: $translation{$1} = $newid;
7355: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7356: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7357: $translation{$1} = $newid;
7358: }
1.749 raeburn 7359: $new_values{$file_name."\0".$newkey} =
7360: $$changes{'activate'}{$newitems[$i]};
7361: $new_control{$newkey} = $now;
7362: }
7363: }
7364: }
7365: my %todelete;
7366: my %changed_items;
7367: foreach my $action ('delete','update') {
7368: if (exists($$changes{$action})) {
7369: if (ref($$changes{$action}) eq 'HASH') {
7370: foreach my $key (keys(%{$$changes{$action}})) {
7371: my ($itemnum) = ($key =~ /^([^:]+):/);
7372: if ($action eq 'delete') {
7373: $todelete{$itemnum} = 1;
7374: } else {
7375: $changed_items{$itemnum} = $key;
7376: }
7377: }
1.745 raeburn 7378: }
7379: }
1.749 raeburn 7380: }
7381: # get lock on access controls for file.
7382: my $lockhash = {
7383: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7384: ':'.$env{'user.domain'},
7385: };
7386: my $tries = 0;
7387: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7388:
7389: while (($gotlock ne 'ok') && $tries <3) {
7390: $tries ++;
7391: sleep 1;
7392: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7393: }
7394: if ($gotlock eq 'ok') {
7395: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7396: my ($tmp)=keys(%curr_permissions);
7397: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7398: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7399: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7400: if (ref($curr_controls) eq 'HASH') {
7401: foreach my $control_item (keys(%{$curr_controls})) {
7402: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7403: if (defined($todelete{$itemnum})) {
7404: push(@deletions,$file_name."\0".$control_item);
7405: } else {
7406: if (defined($changed_items{$itemnum})) {
7407: $new_control{$changed_items{$itemnum}} = $now;
7408: push(@deletions,$file_name."\0".$control_item);
7409: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7410: } else {
7411: $new_control{$control_item} = $$curr_controls{$control_item};
7412: }
7413: }
1.745 raeburn 7414: }
7415: }
7416: }
1.970 raeburn 7417: my ($group);
7418: if (&is_course($domain,$user)) {
7419: ($group,my $file) = split(/\//,$file_name,2);
7420: }
1.749 raeburn 7421: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7422: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7423: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7424: # remove lock
7425: my @del_lock = ($file_name."\0".'locked_access_records');
7426: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7427: my $sqlresult =
1.970 raeburn 7428: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7429: $group);
1.749 raeburn 7430: } else {
7431: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7432: }
1.749 raeburn 7433: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7434: }
7435:
1.827 raeburn 7436: sub make_public_indefinitely {
7437: my ($requrl) = @_;
7438: my $now = time;
7439: my $action = 'activate';
7440: my $aclnum = 0;
7441: if (&is_portfolio_url($requrl)) {
7442: my (undef,$udom,$unum,$file_name,$group) =
7443: &parse_portfolio_url($requrl);
7444: my $current_perms = &get_portfile_permissions($udom,$unum);
7445: my %access_controls = &get_access_controls($current_perms,
7446: $group,$file_name);
7447: foreach my $key (keys(%{$access_controls{$file_name}})) {
7448: my ($num,$scope,$end,$start) =
7449: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7450: if ($scope eq 'public') {
7451: if ($start <= $now && $end == 0) {
7452: $action = 'none';
7453: } else {
7454: $action = 'update';
7455: $aclnum = $num;
7456: }
7457: last;
7458: }
7459: }
7460: if ($action eq 'none') {
7461: return 'ok';
7462: } else {
7463: my %changes;
7464: my $newend = 0;
7465: my $newstart = $now;
7466: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7467: $changes{$action}{$newkey} = {
7468: type => 'public',
7469: time => {
7470: start => $newstart,
7471: end => $newend,
7472: },
7473: };
7474: my ($outcome,$deloutcome,$new_values,$translation) =
7475: &modify_access_controls($file_name,\%changes,$udom,$unum);
7476: return $outcome;
7477: }
7478: } else {
7479: return 'invalid';
7480: }
7481: }
7482:
1.745 raeburn 7483: #------------------------------------------------------Get Marked as Read Only
7484:
7485: sub get_marked_as_readonly {
7486: my ($domain,$user,$what,$group) = @_;
7487: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7488: my @readonly_files;
1.629 banghart 7489: my $cmp1=$what;
7490: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7491: while (my ($file_name,$value) = each(%{$current_permissions})) {
7492: if (defined($group)) {
7493: if ($file_name !~ m-^\Q$group\E/-) {
7494: next;
7495: }
7496: }
1.561 banghart 7497: if (ref($value) eq "ARRAY"){
7498: foreach my $stored_what (@{$value}) {
1.629 banghart 7499: my $cmp2=$stored_what;
1.759 albertel 7500: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7501: $cmp2=join('',@{$stored_what});
1.745 raeburn 7502: }
1.629 banghart 7503: if ($cmp1 eq $cmp2) {
1.561 banghart 7504: push(@readonly_files, $file_name);
1.745 raeburn 7505: last;
1.563 banghart 7506: } elsif (!defined($what)) {
7507: push(@readonly_files, $file_name);
1.745 raeburn 7508: last;
1.561 banghart 7509: }
7510: }
1.745 raeburn 7511: }
1.561 banghart 7512: }
7513: return @readonly_files;
7514: }
1.577 banghart 7515: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7516:
1.577 banghart 7517: sub get_marked_as_readonly_hash {
1.745 raeburn 7518: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7519: my %readonly_files;
1.745 raeburn 7520: while (my ($file_name,$value) = each(%{$current_permissions})) {
7521: if (defined($group)) {
7522: if ($file_name !~ m-^\Q$group\E/-) {
7523: next;
7524: }
7525: }
1.577 banghart 7526: if (ref($value) eq "ARRAY"){
7527: foreach my $stored_what (@{$value}) {
1.745 raeburn 7528: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7529: foreach my $lock_descriptor(@{$stored_what}) {
7530: if ($lock_descriptor eq 'graded') {
7531: $readonly_files{$file_name} = 'graded';
7532: } elsif ($lock_descriptor eq 'handback') {
7533: $readonly_files{$file_name} = 'handback';
7534: } else {
7535: if (!exists($readonly_files{$file_name})) {
7536: $readonly_files{$file_name} = 'locked';
7537: }
7538: }
1.745 raeburn 7539: }
1.750 banghart 7540: }
1.577 banghart 7541: }
7542: }
7543: }
7544: return %readonly_files;
7545: }
1.559 banghart 7546: # ------------------------------------------------------------ Unmark as Read Only
7547:
7548: sub unmark_as_readonly {
1.629 banghart 7549: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7550: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7551: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7552: $file_name = &declutter_portfile($file_name);
1.634 albertel 7553: my $symb_crs = $what;
7554: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7555: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7556: my ($tmp)=keys(%current_permissions);
7557: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7558: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7559: foreach my $file (@readonly_files) {
1.759 albertel 7560: my $clean_file = &declutter_portfile($file);
7561: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7562: my $current_locks = $current_permissions{$file};
1.563 banghart 7563: my @new_locks;
7564: my @del_keys;
7565: if (ref($current_locks) eq "ARRAY"){
7566: foreach my $locker (@{$current_locks}) {
1.632 albertel 7567: my $compare=$locker;
1.749 raeburn 7568: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7569: $compare=join('',@{$locker});
1.746 raeburn 7570: if ($compare ne $symb_crs) {
7571: push(@new_locks, $locker);
7572: }
1.563 banghart 7573: }
7574: }
1.650 albertel 7575: if (scalar(@new_locks) > 0) {
1.563 banghart 7576: $current_permissions{$file} = \@new_locks;
7577: } else {
7578: push(@del_keys, $file);
1.613 albertel 7579: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7580: delete($current_permissions{$file});
1.563 banghart 7581: }
7582: }
1.561 banghart 7583: }
1.613 albertel 7584: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7585: return;
7586: }
1.512 banghart 7587:
1.17 www 7588: # ------------------------------------------------------------ Directory lister
7589:
7590: sub dirlist {
1.955 raeburn 7591: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7592: $uri=~s/^\///;
7593: $uri=~s/\/$//;
1.253 stredwic 7594: my ($udom, $uname);
1.955 raeburn 7595: if ($getuserdir) {
1.253 stredwic 7596: $udom = $userdomain;
7597: $uname = $username;
1.955 raeburn 7598: } else {
7599: (undef,$udom,$uname)=split(/\//,$uri);
7600: if(defined($userdomain)) {
7601: $udom = $userdomain;
7602: }
7603: if(defined($username)) {
7604: $uname = $username;
7605: }
1.253 stredwic 7606: }
1.955 raeburn 7607: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7608:
1.955 raeburn 7609: $dirRoot = $perlvar{'lonDocRoot'};
7610: if (defined($getpropath)) {
7611: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7612: $dirRoot =~ s/\/$//;
1.955 raeburn 7613: } elsif (defined($getuserdir)) {
7614: my $subdir=$uname.'__';
7615: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7616: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7617: ."/$udom/$subdir/$uname";
7618: } elsif (defined($alternateRoot)) {
7619: $dirRoot = $alternateRoot;
1.751 banghart 7620: }
1.253 stredwic 7621:
7622: if($udom) {
7623: if($uname) {
1.955 raeburn 7624: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7625: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7626: .':'.&escape($uname).':'.&escape($udom),
7627: &homeserver($uname,$udom));
7628: if ($listing eq 'unknown_cmd') {
7629: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7630: &homeserver($uname,$udom));
7631: } else {
7632: @listing_results = map { &unescape($_); } split(/:/,$listing);
7633: }
1.605 matthew 7634: if ($listing eq 'unknown_cmd') {
1.800 albertel 7635: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7636: &homeserver($uname,$udom));
1.605 matthew 7637: @listing_results = split(/:/,$listing);
7638: } else {
7639: @listing_results = map { &unescape($_); } split(/:/,$listing);
7640: }
7641: return @listing_results;
1.955 raeburn 7642: } elsif(!$alternateRoot) {
1.800 albertel 7643: my %allusers;
1.841 albertel 7644: my %servers = &get_servers($udom,'library');
1.955 raeburn 7645: foreach my $tryserver (keys(%servers)) {
7646: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7647: &escape($udom),$tryserver);
7648: if ($listing eq 'unknown_cmd') {
7649: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7650: $udom, $tryserver);
7651: } else {
7652: @listing_results = map { &unescape($_); } split(/:/,$listing);
7653: }
1.841 albertel 7654: if ($listing eq 'unknown_cmd') {
7655: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7656: $udom, $tryserver);
7657: @listing_results = split(/:/,$listing);
7658: } else {
7659: @listing_results =
7660: map { &unescape($_); } split(/:/,$listing);
7661: }
7662: if ($listing_results[0] ne 'no_such_dir' &&
7663: $listing_results[0] ne 'empty' &&
7664: $listing_results[0] ne 'con_lost') {
7665: foreach my $line (@listing_results) {
7666: my ($entry) = split(/&/,$line,2);
7667: $allusers{$entry} = 1;
7668: }
7669: }
1.253 stredwic 7670: }
7671: my $alluserstr='';
1.800 albertel 7672: foreach my $user (sort(keys(%allusers))) {
7673: $alluserstr.=$user.'&user:';
1.253 stredwic 7674: }
7675: $alluserstr=~s/:$//;
7676: return split(/:/,$alluserstr);
7677: } else {
1.800 albertel 7678: return ('missing user name');
1.253 stredwic 7679: }
1.955 raeburn 7680: } elsif(!defined($getpropath)) {
1.841 albertel 7681: my @all_domains = sort(&all_domains());
1.955 raeburn 7682: foreach my $domain (@all_domains) {
7683: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7684: }
7685: return @all_domains;
7686: } else {
1.800 albertel 7687: return ('missing domain');
1.275 stredwic 7688: }
7689: }
7690:
7691: # --------------------------------------------- GetFileTimestamp
7692: # This function utilizes dirlist and returns the date stamp for
7693: # when it was last modified. It will also return an error of -1
7694: # if an error occurs
7695:
7696: sub GetFileTimestamp {
1.955 raeburn 7697: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7698: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7699: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7700: my ($fileStat) =
7701: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7702: undef,$getuserdir);
1.275 stredwic 7703: my @stats = split('&', $fileStat);
7704: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7705: # @stats contains first the filename, then the stat output
7706: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7707: } else {
7708: return -1;
1.253 stredwic 7709: }
1.26 www 7710: }
7711:
1.712 albertel 7712: sub stat_file {
7713: my ($uri) = @_;
1.787 albertel 7714: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7715:
1.955 raeburn 7716: my ($udom,$uname,$file);
1.712 albertel 7717: if ($uri =~ m-^/(uploaded|editupload)/-) {
7718: ($udom,$uname,$file) =
1.811 albertel 7719: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7720: $file = 'userfiles/'.$file;
7721: }
7722: if ($uri =~ m-^/res/-) {
7723: ($udom,$uname) =
1.807 albertel 7724: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7725: $file = $uri;
7726: }
7727:
7728: if (!$udom || !$uname || !$file) {
7729: # unable to handle the uri
7730: return ();
7731: }
1.956 raeburn 7732: my $getpropath;
7733: if ($file =~ /^userfiles\//) {
7734: $getpropath = 1;
7735: }
1.955 raeburn 7736: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7737: my @stats = split('&', $result);
1.721 banghart 7738:
1.712 albertel 7739: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7740: shift(@stats); #filename is first
7741: return @stats;
7742: }
7743: return ();
7744: }
7745:
1.26 www 7746: # -------------------------------------------------------- Value of a Condition
7747:
1.713 albertel 7748: # gets the value of a specific preevaluated condition
7749: # stored in the string $env{user.state.<cid>}
7750: # or looks up a condition reference in the bighash and if if hasn't
7751: # already been evaluated recurses into docondval to get the value of
7752: # the condition, then memoizing it to
7753: # $env{user.state.<cid>.<condition>}
1.40 www 7754: sub directcondval {
7755: my $number=shift;
1.620 albertel 7756: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7757: &Apache::lonuserstate::evalstate();
7758: }
1.713 albertel 7759: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7760: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7761: } elsif ($number =~ /^_/) {
7762: my $sub_condition;
7763: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7764: &GDBM_READER(),0640)) {
7765: $sub_condition=$bighash{'conditions'.$number};
7766: untie(%bighash);
7767: }
7768: my $value = &docondval($sub_condition);
1.949 raeburn 7769: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7770: return $value;
7771: }
1.620 albertel 7772: if ($env{'user.state.'.$env{'request.course.id'}}) {
7773: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7774: } else {
7775: return 2;
7776: }
7777: }
7778:
1.713 albertel 7779: # get the collection of conditions for this resource
1.26 www 7780: sub condval {
7781: my $condidx=shift;
1.54 www 7782: my $allpathcond='';
1.713 albertel 7783: foreach my $cond (split(/\|/,$condidx)) {
7784: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7785: $allpathcond.=
7786: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7787: }
1.191 harris41 7788: }
1.54 www 7789: $allpathcond=~s/\|$//;
1.713 albertel 7790: return &docondval($allpathcond);
7791: }
7792:
7793: #evaluates an expression of conditions
7794: sub docondval {
7795: my ($allpathcond) = @_;
7796: my $result=0;
7797: if ($env{'request.course.id'}
7798: && defined($allpathcond)) {
7799: my $operand='|';
7800: my @stack;
7801: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7802: if ($chunk eq '(') {
7803: push @stack,($operand,$result);
7804: } elsif ($chunk eq ')') {
7805: my $before=pop @stack;
7806: if (pop @stack eq '&') {
7807: $result=$result>$before?$before:$result;
7808: } else {
7809: $result=$result>$before?$result:$before;
7810: }
7811: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7812: $operand=$chunk;
7813: } else {
7814: my $new=directcondval($chunk);
7815: if ($operand eq '&') {
7816: $result=$result>$new?$new:$result;
7817: } else {
7818: $result=$result>$new?$result:$new;
7819: }
7820: }
7821: }
1.26 www 7822: }
7823: return $result;
1.421 albertel 7824: }
7825:
7826: # ---------------------------------------------------- Devalidate courseresdata
7827:
7828: sub devalidatecourseresdata {
7829: my ($coursenum,$coursedomain)=@_;
7830: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7831: &devalidate_cache_new('courseres',$hashid);
1.28 www 7832: }
7833:
1.763 www 7834:
1.200 www 7835: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7836: #
7837: # Parameters:
7838: # $coursenum - Number of the course.
7839: # $coursedomain - Domain at which the course was created.
7840: # Returns:
7841: # A hash of the course parameters along (I think) with timestamps
7842: # and version info.
1.877 foxr 7843:
1.624 albertel 7844: sub get_courseresdata {
7845: my ($coursenum,$coursedomain)=@_;
1.200 www 7846: my $coursehom=&homeserver($coursenum,$coursedomain);
7847: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7848: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7849: my %dumpreply;
1.417 albertel 7850: unless (defined($cached)) {
1.624 albertel 7851: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7852: $result=\%dumpreply;
1.251 albertel 7853: my ($tmp) = keys(%dumpreply);
7854: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7855: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7856: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7857: return $tmp;
1.416 albertel 7858: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7859: $result=undef;
1.599 albertel 7860: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7861: }
7862: }
1.624 albertel 7863: return $result;
7864: }
7865:
1.633 albertel 7866: sub devalidateuserresdata {
7867: my ($uname,$udom)=@_;
7868: my $hashid="$udom:$uname";
7869: &devalidate_cache_new('userres',$hashid);
7870: }
7871:
1.624 albertel 7872: sub get_userresdata {
7873: my ($uname,$udom)=@_;
7874: #most student don\'t have any data set, check if there is some data
7875: if (&EXT_cache_status($udom,$uname)) { return undef; }
7876:
7877: my $hashid="$udom:$uname";
7878: my ($result,$cached)=&is_cached_new('userres',$hashid);
7879: if (!defined($cached)) {
7880: my %resourcedata=&dump('resourcedata',$udom,$uname);
7881: $result=\%resourcedata;
7882: &do_cache_new('userres',$hashid,$result,600);
7883: }
7884: my ($tmp)=keys(%$result);
7885: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7886: return $result;
7887: }
7888: #error 2 occurs when the .db doesn't exist
7889: if ($tmp!~/error: 2 /) {
1.672 albertel 7890: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 7891: " Trying to get resource data for ".
7892: $uname." at ".$udom.": ".
7893: $tmp."</font>");
7894: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 7895: #&EXT_cache_set($udom,$uname);
7896: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 7897: undef($tmp); # not really an error so don't send it back
1.624 albertel 7898: }
7899: return $tmp;
7900: }
1.879 foxr 7901: #----------------------------------------------- resdata - return resource data
7902: # Purpose:
7903: # Return resource data for either users or for a course.
7904: # Parameters:
7905: # $name - Course/user name.
7906: # $domain - Name of the domain the user/course is registered on.
7907: # $type - Type of thing $name is (must be 'course' or 'user'
7908: # @which - Array of names of resources desired.
7909: # Returns:
7910: # The value of the first reasource in @which that is found in the
7911: # resource hash.
7912: # Exceptional Conditions:
7913: # If the $type passed in is not valid (not the string 'course' or
7914: # 'user', an undefined reference is returned.
7915: # If none of the resources are found, an undef is returned
1.624 albertel 7916: sub resdata {
7917: my ($name,$domain,$type,@which)=@_;
7918: my $result;
7919: if ($type eq 'course') {
7920: $result=&get_courseresdata($name,$domain);
7921: } elsif ($type eq 'user') {
7922: $result=&get_userresdata($name,$domain);
7923: }
7924: if (!ref($result)) { return $result; }
1.251 albertel 7925: foreach my $item (@which) {
1.927 albertel 7926: if (defined($result->{$item->[0]})) {
7927: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 7928: }
1.250 albertel 7929: }
1.291 albertel 7930: return undef;
1.200 www 7931: }
7932:
1.379 matthew 7933: #
7934: # EXT resource caching routines
7935: #
7936:
7937: sub clear_EXT_cache_status {
1.383 albertel 7938: &delenv('cache.EXT.');
1.379 matthew 7939: }
7940:
7941: sub EXT_cache_status {
7942: my ($target_domain,$target_user) = @_;
1.383 albertel 7943: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 7944: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 7945: # We know already the user has no data
7946: return 1;
7947: } else {
7948: return 0;
7949: }
7950: }
7951:
7952: sub EXT_cache_set {
7953: my ($target_domain,$target_user) = @_;
1.383 albertel 7954: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 7955: #&appenv({$cachename => time});
1.379 matthew 7956: }
7957:
1.28 www 7958: # --------------------------------------------------------- Value of a Variable
1.58 www 7959: sub EXT {
1.715 albertel 7960:
1.395 albertel 7961: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 7962: unless ($varname) { return ''; }
1.218 albertel 7963: #get real user name/domain, courseid and symb
7964: my $courseid;
1.359 albertel 7965: my $publicuser;
1.427 www 7966: if ($symbparm) {
7967: $symbparm=&get_symb_from_alias($symbparm);
7968: }
1.218 albertel 7969: if (!($uname && $udom)) {
1.790 albertel 7970: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 7971: if (!$symbparm) { $symbparm=$cursymb; }
7972: } else {
1.620 albertel 7973: $courseid=$env{'request.course.id'};
1.218 albertel 7974: }
1.48 www 7975: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
7976: my $rest;
1.320 albertel 7977: if (defined($therest[0])) {
1.48 www 7978: $rest=join('.',@therest);
7979: } else {
7980: $rest='';
7981: }
1.320 albertel 7982:
1.57 www 7983: my $qualifierrest=$qualifier;
7984: if ($rest) { $qualifierrest.='.'.$rest; }
7985: my $spacequalifierrest=$space;
7986: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 7987: if ($realm eq 'user') {
1.48 www 7988: # --------------------------------------------------------------- user.resource
7989: if ($space eq 'resource') {
1.651 albertel 7990: if ( (defined($Apache::lonhomework::parsing_a_problem)
7991: || defined($Apache::lonhomework::parsing_a_task))
7992: &&
1.744 albertel 7993: ($symbparm eq &symbread()) ) {
7994: # if we are in the middle of processing the resource the
7995: # get the value we are planning on committing
7996: if (defined($Apache::lonhomework::results{$qualifierrest})) {
7997: return $Apache::lonhomework::results{$qualifierrest};
7998: } else {
7999: return $Apache::lonhomework::history{$qualifierrest};
8000: }
1.335 albertel 8001: } else {
1.359 albertel 8002: my %restored;
1.620 albertel 8003: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8004: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8005: } else {
8006: %restored=&restore($symbparm,$courseid,$udom,$uname);
8007: }
1.335 albertel 8008: return $restored{$qualifierrest};
8009: }
1.48 www 8010: # ----------------------------------------------------------------- user.access
8011: } elsif ($space eq 'access') {
1.218 albertel 8012: # FIXME - not supporting calls for a specific user
1.48 www 8013: return &allowed($qualifier,$rest);
8014: # ------------------------------------------ user.preferences, user.environment
8015: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8016: if (($uname eq $env{'user.name'}) &&
8017: ($udom eq $env{'user.domain'})) {
8018: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8019: } else {
1.359 albertel 8020: my %returnhash;
8021: if (!$publicuser) {
8022: %returnhash=&userenvironment($udom,$uname,
8023: $qualifierrest);
8024: }
1.218 albertel 8025: return $returnhash{$qualifierrest};
8026: }
1.48 www 8027: # ----------------------------------------------------------------- user.course
8028: } elsif ($space eq 'course') {
1.218 albertel 8029: # FIXME - not supporting calls for a specific user
1.620 albertel 8030: return $env{join('.',('request.course',$qualifier))};
1.48 www 8031: # ------------------------------------------------------------------- user.role
8032: } elsif ($space eq 'role') {
1.218 albertel 8033: # FIXME - not supporting calls for a specific user
1.620 albertel 8034: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8035: if ($qualifier eq 'value') {
8036: return $role;
8037: } elsif ($qualifier eq 'extent') {
8038: return $where;
8039: }
8040: # ----------------------------------------------------------------- user.domain
8041: } elsif ($space eq 'domain') {
1.218 albertel 8042: return $udom;
1.48 www 8043: # ------------------------------------------------------------------- user.name
8044: } elsif ($space eq 'name') {
1.218 albertel 8045: return $uname;
1.48 www 8046: # ---------------------------------------------------- Any other user namespace
1.29 www 8047: } else {
1.359 albertel 8048: my %reply;
8049: if (!$publicuser) {
8050: %reply=&get($space,[$qualifierrest],$udom,$uname);
8051: }
8052: return $reply{$qualifierrest};
1.48 www 8053: }
1.236 www 8054: } elsif ($realm eq 'query') {
8055: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8056: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8057: [$spacequalifierrest]);
1.620 albertel 8058: return $env{'form.'.$spacequalifierrest};
1.236 www 8059: } elsif ($realm eq 'request') {
1.48 www 8060: # ------------------------------------------------------------- request.browser
8061: if ($space eq 'browser') {
1.430 www 8062: if ($qualifier eq 'textremote') {
1.676 albertel 8063: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8064: return 1;
8065: } else {
8066: return 0;
8067: }
8068: } else {
1.620 albertel 8069: return $env{'browser.'.$qualifier};
1.430 www 8070: }
1.57 www 8071: # ------------------------------------------------------------ request.filename
8072: } else {
1.620 albertel 8073: return $env{'request.'.$spacequalifierrest};
1.29 www 8074: }
1.28 www 8075: } elsif ($realm eq 'course') {
1.48 www 8076: # ---------------------------------------------------------- course.description
1.620 albertel 8077: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8078: } elsif ($realm eq 'resource') {
1.165 www 8079:
1.620 albertel 8080: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8081: if (!$symbparm) { $symbparm=&symbread(); }
8082: }
1.693 albertel 8083:
8084: if ($space eq 'title') {
8085: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8086: return &gettitle($symbparm);
8087: }
8088:
8089: if ($space eq 'map') {
8090: my ($map) = &decode_symb($symbparm);
8091: return &symbread($map);
8092: }
1.905 albertel 8093: if ($space eq 'filename') {
8094: if ($symbparm) {
8095: return &clutter((&decode_symb($symbparm))[2]);
8096: }
8097: return &hreflocation('',$env{'request.filename'});
8098: }
1.693 albertel 8099:
8100: my ($section, $group, @groups);
1.593 albertel 8101: my ($courselevelm,$courselevel);
1.539 albertel 8102: if ($symbparm && defined($courseid) &&
1.620 albertel 8103: $courseid eq $env{'request.course.id'}) {
1.165 www 8104:
1.218 albertel 8105: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8106:
1.60 www 8107: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8108: my $symbp=$symbparm;
1.735 albertel 8109: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8110:
8111: my $symbparm=$symbp.'.'.$spacequalifierrest;
8112: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8113:
1.620 albertel 8114: if (($env{'user.name'} eq $uname) &&
8115: ($env{'user.domain'} eq $udom)) {
8116: $section=$env{'request.course.sec'};
1.733 raeburn 8117: @groups = split(/:/,$env{'request.course.groups'});
8118: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8119: } else {
1.539 albertel 8120: if (! defined($usection)) {
1.551 albertel 8121: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8122: } else {
8123: $section = $usection;
8124: }
1.733 raeburn 8125: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8126: }
8127:
8128: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8129: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8130: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8131:
1.593 albertel 8132: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8133: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8134: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8135:
1.60 www 8136: # ----------------------------------------------------------- first, check user
1.624 albertel 8137:
8138: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8139: ([$courselevelr,'resource'],
8140: [$courselevelm,'map' ],
8141: [$courselevel, 'course' ]));
1.931 albertel 8142: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8143:
1.594 albertel 8144: # ------------------------------------------------ second, check some of course
1.684 raeburn 8145: my $coursereply;
1.691 raeburn 8146: if (@groups > 0) {
8147: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8148: $mapparm,$spacequalifierrest);
1.927 albertel 8149: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8150: }
1.96 www 8151:
1.684 raeburn 8152: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8153: $env{'course.'.$courseid.'.domain'},
8154: 'course',
8155: ([$seclevelr, 'resource'],
8156: [$seclevelm, 'map' ],
8157: [$seclevel, 'course' ],
8158: [$courselevelr,'resource']));
8159: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8160:
1.60 www 8161: # ------------------------------------------------------ third, check map parms
1.218 albertel 8162: my %parmhash=();
8163: my $thisparm='';
8164: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8165: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8166: &GDBM_READER(),0640)) {
1.218 albertel 8167: $thisparm=$parmhash{$symbparm};
8168: untie(%parmhash);
8169: }
1.927 albertel 8170: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8171: }
1.594 albertel 8172: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8173:
1.218 albertel 8174: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8175: my $filename;
8176: if (!$symbparm) { $symbparm=&symbread(); }
8177: if ($symbparm) {
1.409 www 8178: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8179: } else {
1.620 albertel 8180: $filename=$env{'request.filename'};
1.282 albertel 8181: }
8182: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8183: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8184: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8185: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8186:
1.927 albertel 8187: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8188: if ($symbparm && defined($courseid) &&
1.620 albertel 8189: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8190: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8191: $env{'course.'.$courseid.'.domain'},
8192: 'course',
1.927 albertel 8193: ([$courselevelm,'map' ],
8194: [$courselevel, 'course']));
8195: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8196: }
1.145 www 8197: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8198: unless ($space eq '0') {
1.336 albertel 8199: my @parts=split(/_/,$space);
8200: my $id=pop(@parts);
8201: my $part=join('_',@parts);
8202: if ($part eq '') { $part='0'; }
1.927 albertel 8203: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8204: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8205: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8206: }
1.395 albertel 8207: if ($recurse) { return undef; }
8208: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8209: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8210: # ---------------------------------------------------- Any other user namespace
8211: } elsif ($realm eq 'environment') {
8212: # ----------------------------------------------------------------- environment
1.620 albertel 8213: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8214: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8215: } else {
1.770 albertel 8216: if ($uname eq 'anonymous' && $udom eq '') {
8217: return '';
8218: }
1.219 albertel 8219: my %returnhash=&userenvironment($udom,$uname,
8220: $spacequalifierrest);
8221: return $returnhash{$spacequalifierrest};
8222: }
1.28 www 8223: } elsif ($realm eq 'system') {
1.48 www 8224: # ----------------------------------------------------------------- system.time
8225: if ($space eq 'time') {
8226: return time;
8227: }
1.696 albertel 8228: } elsif ($realm eq 'server') {
8229: # ----------------------------------------------------------------- system.time
8230: if ($space eq 'name') {
8231: return $ENV{'SERVER_NAME'};
8232: }
1.28 www 8233: }
1.48 www 8234: return '';
1.61 www 8235: }
8236:
1.927 albertel 8237: sub get_reply {
8238: my ($reply_value) = @_;
1.940 raeburn 8239: if (ref($reply_value) eq 'ARRAY') {
8240: if (wantarray) {
8241: return @$reply_value;
8242: }
8243: return $reply_value->[0];
8244: } else {
8245: return $reply_value;
1.927 albertel 8246: }
8247: }
8248:
1.691 raeburn 8249: sub check_group_parms {
8250: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8251: my @groupitems = ();
8252: my $resultitem;
1.927 albertel 8253: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8254: foreach my $group (@{$groups}) {
8255: foreach my $level (@levels) {
1.927 albertel 8256: my $item = $courseid.'.['.$group.'].'.$level->[0];
8257: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8258: }
8259: }
8260: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8261: $env{'course.'.$courseid.'.domain'},
8262: 'course',@groupitems);
8263: return $coursereply;
8264: }
8265:
8266: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8267: my ($courseid,@groups) = @_;
8268: @groups = sort(@groups);
1.691 raeburn 8269: return @groups;
8270: }
8271:
1.395 albertel 8272: sub packages_tab_default {
8273: my ($uri,$varname)=@_;
8274: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8275:
8276: my (@extension,@specifics,$do_default);
8277: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8278: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8279: if ($pack_type eq 'default') {
8280: $do_default=1;
8281: } elsif ($pack_type eq 'extension') {
8282: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8283: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8284: # only look at packages defaults for packages that this id is
1.738 albertel 8285: push(@specifics,[$package,$pack_type,$pack_part]);
8286: }
8287: }
8288: # first look for a package that matches the requested part id
8289: foreach my $package (@specifics) {
8290: my (undef,$pack_type,$pack_part)=@{$package};
8291: next if ($pack_part ne $part);
8292: if (defined($packagetab{"$pack_type&$name&default"})) {
8293: return $packagetab{"$pack_type&$name&default"};
8294: }
8295: }
8296: # look for any possible matching non extension_ package
8297: foreach my $package (@specifics) {
8298: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8299: if (defined($packagetab{"$pack_type&$name&default"})) {
8300: return $packagetab{"$pack_type&$name&default"};
8301: }
1.585 albertel 8302: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8303: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8304: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8305: }
8306: }
1.738 albertel 8307: # look for any posible extension_ match
8308: foreach my $package (@extension) {
8309: my ($package,$pack_type)=@{$package};
8310: if (defined($packagetab{"$pack_type&$name&default"})) {
8311: return $packagetab{"$pack_type&$name&default"};
8312: }
8313: if (defined($packagetab{$package."&$name&default"})) {
8314: return $packagetab{$package."&$name&default"};
8315: }
8316: }
8317: # look for a global default setting
8318: if ($do_default && defined($packagetab{"default&$name&default"})) {
8319: return $packagetab{"default&$name&default"};
8320: }
1.395 albertel 8321: return undef;
8322: }
8323:
1.334 albertel 8324: sub add_prefix_and_part {
8325: my ($prefix,$part)=@_;
8326: my $keyroot;
8327: if (defined($prefix) && $prefix !~ /^__/) {
8328: # prefix that has a part already
8329: $keyroot=$prefix;
8330: } elsif (defined($prefix)) {
8331: # prefix that is missing a part
8332: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8333: } else {
8334: # no prefix at all
8335: if (defined($part)) { $keyroot='_'.$part; }
8336: }
8337: return $keyroot;
8338: }
8339:
1.71 www 8340: # ---------------------------------------------------------------- Get metadata
8341:
1.599 albertel 8342: my %metaentry;
1.1070 www 8343: my %importedpartids;
1.71 www 8344: sub metadata {
1.176 www 8345: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8346: $uri=&declutter($uri);
1.288 albertel 8347: # if it is a non metadata possible uri return quickly
1.529 albertel 8348: if (($uri eq '') ||
8349: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8350: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 8351: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
8352: return undef;
8353: }
8354: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8355: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8356: return undef;
1.288 albertel 8357: }
1.73 www 8358: my $filename=$uri;
8359: $uri=~s/\.meta$//;
1.172 www 8360: #
8361: # Is the metadata already cached?
1.177 www 8362: # Look at timestamp of caching
1.172 www 8363: # Everything is cached by the main uri, libraries are never directly cached
8364: #
1.428 albertel 8365: if (!defined($liburi)) {
1.599 albertel 8366: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8367: if (defined($cached)) { return $result->{':'.$what}; }
8368: }
8369: {
1.1069 www 8370: # Imported parts would go here
1.1070 www 8371: my %importedids=();
8372: my @origfileimportpartids=();
1.1069 www 8373: my $importedparts=0;
1.172 www 8374: #
8375: # Is this a recursive call for a library?
8376: #
1.599 albertel 8377: # if (! exists($metacache{$uri})) {
8378: # $metacache{$uri}={};
8379: # }
1.924 albertel 8380: my $cachetime = 60*60;
1.171 www 8381: if ($liburi) {
8382: $liburi=&declutter($liburi);
8383: $filename=$liburi;
1.401 bowersj2 8384: } else {
1.599 albertel 8385: &devalidate_cache_new('meta',$uri);
8386: undef(%metaentry);
1.401 bowersj2 8387: }
1.140 www 8388: my %metathesekeys=();
1.73 www 8389: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8390: my $metastring;
1.924 albertel 8391: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8392: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8393: $metastring =
1.929 albertel 8394: &Apache::lonnet::ssi_body($which,
1.924 albertel 8395: ('grade_target' => 'meta'));
8396: $cachetime = 1; # only want this cached in the child not long term
8397: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8398: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8399: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8400: $metastring=&getfile($file);
1.489 albertel 8401: }
1.208 albertel 8402: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8403: my $token;
1.140 www 8404: undef %metathesekeys;
1.71 www 8405: while ($token=$parser->get_token) {
1.339 albertel 8406: if ($token->[0] eq 'S') {
8407: if (defined($token->[2]->{'package'})) {
1.172 www 8408: #
8409: # This is a package - get package info
8410: #
1.339 albertel 8411: my $package=$token->[2]->{'package'};
8412: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8413: if (defined($token->[2]->{'id'})) {
8414: $keyroot.='_'.$token->[2]->{'id'};
8415: }
1.599 albertel 8416: if ($metaentry{':packages'}) {
8417: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8418: } else {
1.599 albertel 8419: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8420: }
1.736 albertel 8421: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8422: my $part=$keyroot;
8423: $part=~s/^\_//;
1.736 albertel 8424: if ($pack_entry=~/^\Q$package\E\&/ ||
8425: $pack_entry=~/^\Q$package\E_0\&/) {
8426: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8427: # ignore package.tab specified default values
8428: # here &package_tab_default() will fetch those
8429: if ($subp eq 'default') { next; }
1.736 albertel 8430: my $value=$packagetab{$pack_entry};
1.432 albertel 8431: my $unikey;
8432: if ($pack =~ /_0$/) {
8433: $unikey='parameter_0_'.$name;
8434: $part=0;
8435: } else {
8436: $unikey='parameter'.$keyroot.'_'.$name;
8437: }
1.339 albertel 8438: if ($subp eq 'display') {
8439: $value.=' [Part: '.$part.']';
8440: }
1.599 albertel 8441: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8442: $metathesekeys{$unikey}=1;
1.599 albertel 8443: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8444: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8445: }
1.599 albertel 8446: if (defined($metaentry{':'.$unikey.'.default'})) {
8447: $metaentry{':'.$unikey}=
8448: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8449: }
1.339 albertel 8450: }
8451: }
8452: } else {
1.172 www 8453: #
8454: # This is not a package - some other kind of start tag
1.339 albertel 8455: #
8456: my $entry=$token->[1];
1.1068 www 8457: my $unikey='';
1.175 www 8458:
1.339 albertel 8459: if ($entry eq 'import') {
1.175 www 8460: #
8461: # Importing a library here
1.339 albertel 8462: #
1.1067 www 8463: my $location=$parser->get_text('/import');
8464: my $dir=$filename;
8465: $dir=~s|[^/]*$||;
8466: $location=&filelocation($dir,$location);
1.1069 www 8467:
1.1068 www 8468: my $importmode=$token->[2]->{'importmode'};
8469: if ($importmode eq 'problem') {
1.1069 www 8470: # Import as problem/response
1.1068 www 8471: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8472: } elsif ($importmode eq 'part') {
8473: # Import as part(s)
1.1069 www 8474: $importedparts=1;
8475: # We need to get the original file and the imported file to get the part order correct
8476: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
8477: # Load and inspect original file
1.1070 www 8478: if ($#origfileimportpartids<0) {
8479: undef(%importedpartids);
8480: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
8481: my $origfile=&getfile($origfilelocation);
8482: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8483: }
8484:
1.1069 www 8485: # Load and inspect imported file
8486: my $impfile=&getfile($location);
8487: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8488: if ($#impfilepartids>=0) {
8489: # This problem had parts
1.1070 www 8490: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 8491: } else {
8492: # Importing by turning a single problem into a problem part
8493: # It gets the import-tags ID as part-ID
8494: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 8495: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 8496: }
1.1068 www 8497: } else {
8498: # Normal import
8499: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8500: if (defined($token->[2]->{'id'})) {
8501: $unikey.='_'.$token->[2]->{'id'};
8502: }
1.1067 www 8503: }
8504:
1.339 albertel 8505: if ($depthcount<20) {
1.736 albertel 8506: my $metadata =
8507: &metadata($uri,'keys', $location,$unikey,
8508: $depthcount+1);
8509: foreach my $meta (split(',',$metadata)) {
8510: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8511: $metathesekeys{$meta}=1;
1.339 albertel 8512: }
1.1068 www 8513:
8514: }
1.1067 www 8515: } else {
8516: #
8517: # Not importing, some other kind of non-package, non-library start tag
8518: #
8519: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
8520: if (defined($token->[2]->{'id'})) {
8521: $unikey.='_'.$token->[2]->{'id'};
8522: }
1.339 albertel 8523: if (defined($token->[2]->{'name'})) {
8524: $unikey.='_'.$token->[2]->{'name'};
8525: }
8526: $metathesekeys{$unikey}=1;
1.736 albertel 8527: foreach my $param (@{$token->[3]}) {
8528: $metaentry{':'.$unikey.'.'.$param} =
8529: $token->[2]->{$param};
1.339 albertel 8530: }
8531: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8532: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8533: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8534: # only ws inside the tag, and not in default, so use default
8535: # as value
1.599 albertel 8536: $metaentry{':'.$unikey}=$default;
1.908 albertel 8537: } elsif ( $internaltext =~ /\S/ ) {
8538: # something interesting inside the tag
8539: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8540: } else {
1.908 albertel 8541: # no interesting values, don't set a default
1.339 albertel 8542: }
1.172 www 8543: # end of not-a-package not-a-library import
1.339 albertel 8544: }
1.172 www 8545: # end of not-a-package start tag
1.339 albertel 8546: }
1.172 www 8547: # the next is the end of "start tag"
1.339 albertel 8548: }
8549: }
1.483 albertel 8550: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8551: $extension = lc($extension);
8552: if ($extension eq 'htm') { $extension='html'; }
8553:
1.737 albertel 8554: foreach my $key (keys(%packagetab)) {
1.483 albertel 8555: #no specific packages #how's our extension
8556: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8557: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8558: \%metathesekeys);
8559: }
1.883 albertel 8560:
8561: if (!exists($metaentry{':packages'})
8562: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8563: foreach my $key (keys(%packagetab)) {
1.483 albertel 8564: #no specific packages well let's get default then
8565: if ($key!~/^default&/) { next; }
1.488 albertel 8566: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8567: \%metathesekeys);
8568: }
8569: }
1.338 www 8570: # are there custom rights to evaluate
1.599 albertel 8571: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8572:
1.338 www 8573: #
8574: # Importing a rights file here
1.339 albertel 8575: #
8576: unless ($depthcount) {
1.599 albertel 8577: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8578: my $dir=$filename;
8579: $dir=~s|[^/]*$||;
8580: $location=&filelocation($dir,$location);
1.736 albertel 8581: my $rights_metadata =
8582: &metadata($uri,'keys',$location,'_rights',
8583: $depthcount+1);
8584: foreach my $rights (split(',',$rights_metadata)) {
8585: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8586: $metathesekeys{$rights}=1;
1.339 albertel 8587: }
8588: }
8589: }
1.737 albertel 8590: # uniqifiy package listing
8591: my %seen;
8592: my @uniq_packages =
8593: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8594: $metaentry{':packages'} = join(',',@uniq_packages);
8595:
1.1070 www 8596: if ($importedparts) {
8597: # We had imported parts and need to rebuild partorder
8598: $metaentry{':partorder'}='';
8599: $metathesekeys{'partorder'}=1;
8600: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
8601: if ($origfileimportpartids[$index] eq 'part') {
8602: # original part, part of the problem
8603: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
8604: } else {
8605: # we have imported parts at this position
8606: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
8607: }
8608: }
8609: $metaentry{':partorder'}=~s/^\,//;
8610: }
8611:
1.737 albertel 8612: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8613: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8614: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8615: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8616: # this is the end of "was not already recently cached
1.71 www 8617: }
1.599 albertel 8618: return $metaentry{':'.$what};
1.261 albertel 8619: }
8620:
1.488 albertel 8621: sub metadata_create_package_def {
1.483 albertel 8622: my ($uri,$key,$package,$metathesekeys)=@_;
8623: my ($pack,$name,$subp)=split(/\&/,$key);
8624: if ($subp eq 'default') { next; }
8625:
1.599 albertel 8626: if (defined($metaentry{':packages'})) {
8627: $metaentry{':packages'}.=','.$package;
1.483 albertel 8628: } else {
1.599 albertel 8629: $metaentry{':packages'}=$package;
1.483 albertel 8630: }
8631: my $value=$packagetab{$key};
8632: my $unikey;
8633: $unikey='parameter_0_'.$name;
1.599 albertel 8634: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8635: $$metathesekeys{$unikey}=1;
1.599 albertel 8636: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8637: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8638: }
1.599 albertel 8639: if (defined($metaentry{':'.$unikey.'.default'})) {
8640: $metaentry{':'.$unikey}=
8641: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8642: }
8643: }
8644:
1.261 albertel 8645: sub metadata_generate_part0 {
8646: my ($metadata,$metacache,$uri) = @_;
8647: my %allnames;
1.737 albertel 8648: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8649: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8650: my $part=$$metacache{':'.$metakey.'.part'};
8651: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8652: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8653: $allnames{$name}=$part;
8654: }
8655: }
8656: }
8657: foreach my $name (keys(%allnames)) {
8658: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8659: my $key=":parameter_0_$name";
1.261 albertel 8660: $$metacache{"$key.part"}='0';
8661: $$metacache{"$key.name"}=$name;
1.428 albertel 8662: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8663: $allnames{$name}.'_'.$name.
8664: '.type'};
1.428 albertel 8665: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8666: '.display'};
1.644 www 8667: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8668: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8669: $$metacache{"$key.display"}=$olddis;
8670: }
1.71 www 8671: }
8672:
1.764 albertel 8673: # ------------------------------------------------------ Devalidate title cache
8674:
8675: sub devalidate_title_cache {
8676: my ($url)=@_;
8677: if (!$env{'request.course.id'}) { return; }
8678: my $symb=&symbread($url);
8679: if (!$symb) { return; }
8680: my $key=$env{'request.course.id'}."\0".$symb;
8681: &devalidate_cache_new('title',$key);
8682: }
8683:
1.1014 droeschl 8684: # ------------------------------------------------- Get the title of a course
8685:
8686: sub current_course_title {
8687: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8688: }
1.301 www 8689: # ------------------------------------------------- Get the title of a resource
8690:
8691: sub gettitle {
8692: my $urlsymb=shift;
8693: my $symb=&symbread($urlsymb);
1.534 albertel 8694: if ($symb) {
1.620 albertel 8695: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8696: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8697: if (defined($cached)) {
8698: return $result;
8699: }
1.534 albertel 8700: my ($map,$resid,$url)=&decode_symb($symb);
8701: my $title='';
1.907 albertel 8702: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8703: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8704: } else {
8705: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8706: &GDBM_READER(),0640)) {
8707: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8708: $title=$bighash{'title_'.$mapid.'.'.$resid};
8709: untie(%bighash);
8710: }
1.534 albertel 8711: }
8712: $title=~s/\&colon\;/\:/gs;
8713: if ($title) {
1.599 albertel 8714: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8715: }
8716: $urlsymb=$url;
8717: }
8718: my $title=&metadata($urlsymb,'title');
8719: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8720: return $title;
1.301 www 8721: }
1.613 albertel 8722:
1.614 albertel 8723: sub get_slot {
8724: my ($which,$cnum,$cdom)=@_;
8725: if (!$cnum || !$cdom) {
1.790 albertel 8726: (undef,my $courseid)=&whichuser();
1.620 albertel 8727: $cdom=$env{'course.'.$courseid.'.domain'};
8728: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8729: }
1.703 albertel 8730: my $key=join("\0",'slots',$cdom,$cnum,$which);
8731: my %slotinfo;
8732: if (exists($remembered{$key})) {
8733: $slotinfo{$which} = $remembered{$key};
8734: } else {
8735: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8736: &Apache::lonhomework::showhash(%slotinfo);
8737: my ($tmp)=keys(%slotinfo);
8738: if ($tmp=~/^error:/) { return (); }
8739: $remembered{$key} = $slotinfo{$which};
8740: }
1.616 albertel 8741: if (ref($slotinfo{$which}) eq 'HASH') {
8742: return %{$slotinfo{$which}};
8743: }
8744: return $slotinfo{$which};
1.614 albertel 8745: }
1.31 www 8746: # ------------------------------------------------- Update symbolic store links
8747:
8748: sub symblist {
8749: my ($mapname,%newhash)=@_;
1.438 www 8750: $mapname=&deversion(&declutter($mapname));
1.31 www 8751: my %hash;
1.620 albertel 8752: if (($env{'request.course.fn'}) && (%newhash)) {
8753: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8754: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8755: foreach my $url (keys(%newhash)) {
1.711 albertel 8756: next if ($url eq 'last_known'
8757: && $env{'form.no_update_last_known'});
8758: $hash{declutter($url)}=&encode_symb($mapname,
8759: $newhash{$url}->[1],
8760: $newhash{$url}->[0]);
1.191 harris41 8761: }
1.31 www 8762: if (untie(%hash)) {
8763: return 'ok';
8764: }
8765: }
8766: }
8767: return 'error';
1.212 www 8768: }
8769:
8770: # --------------------------------------------------------------- Verify a symb
8771:
8772: sub symbverify {
1.510 www 8773: my ($symb,$thisurl)=@_;
8774: my $thisfn=$thisurl;
1.439 www 8775: $thisfn=&declutter($thisfn);
1.215 www 8776: # direct jump to resource in page or to a sequence - will construct own symbs
8777: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8778: # check URL part
1.409 www 8779: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8780:
1.431 www 8781: unless ($url eq $thisfn) { return 0; }
1.213 www 8782:
1.216 www 8783: $symb=&symbclean($symb);
1.510 www 8784: $thisurl=&deversion($thisurl);
1.439 www 8785: $thisfn=&deversion($thisfn);
1.213 www 8786:
8787: my %bighash;
8788: my $okay=0;
1.431 www 8789:
1.620 albertel 8790: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8791: &GDBM_READER(),0640)) {
1.1032 raeburn 8792: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8793: $thisurl =~ s/\?.+$//;
8794: }
1.510 www 8795: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8796: unless ($ids) {
1.510 www 8797: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8798: }
8799: if ($ids) {
8800: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8801: foreach my $id (split(/\,/,$ids)) {
8802: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8803: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8804: $symb =~ s/\?.+$//;
8805: }
1.216 www 8806: if (
8807: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8808: eq $symb) {
1.620 albertel 8809: if (($env{'request.role.adv'}) ||
1.800 albertel 8810: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8811: $okay=1;
8812: }
8813: }
1.216 www 8814: }
8815: }
1.213 www 8816: untie(%bighash);
8817: }
8818: return $okay;
1.31 www 8819: }
8820:
1.210 www 8821: # --------------------------------------------------------------- Clean-up symb
8822:
8823: sub symbclean {
8824: my $symb=shift;
1.568 albertel 8825: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8826: # remove version from map
8827: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8828:
1.210 www 8829: # remove version from URL
8830: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8831:
1.507 www 8832: # remove wrapper
8833:
1.510 www 8834: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8835: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8836: return $symb;
1.409 www 8837: }
8838:
8839: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8840:
8841: sub encode_symb {
8842: my ($map,$resid,$url)=@_;
8843: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8844: }
1.409 www 8845:
8846: sub decode_symb {
1.568 albertel 8847: my $symb=shift;
8848: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8849: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8850: return (&fixversion($map),$resid,&fixversion($url));
8851: }
8852:
8853: sub fixversion {
8854: my $fn=shift;
1.609 banghart 8855: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8856: my %bighash;
8857: my $uri=&clutter($fn);
1.620 albertel 8858: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8859: # is this cached?
1.599 albertel 8860: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8861: if (defined($cached)) { return $result; }
8862: # unfortunately not cached, or expired
1.620 albertel 8863: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8864: &GDBM_READER(),0640)) {
8865: if ($bighash{'version_'.$uri}) {
8866: my $version=$bighash{'version_'.$uri};
1.444 www 8867: unless (($version eq 'mostrecent') ||
8868: ($version==&getversion($uri))) {
1.440 www 8869: $uri=~s/\.(\w+)$/\.$version\.$1/;
8870: }
8871: }
8872: untie %bighash;
1.413 www 8873: }
1.599 albertel 8874: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8875: }
8876:
8877: sub deversion {
8878: my $url=shift;
8879: $url=~s/\.\d+\.(\w+)$/\.$1/;
8880: return $url;
1.210 www 8881: }
8882:
1.31 www 8883: # ------------------------------------------------------ Return symb list entry
8884:
8885: sub symbread {
1.249 www 8886: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8887: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8888: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 8889: # no filename provided? try from environment
1.44 www 8890: unless ($thisfn) {
1.620 albertel 8891: if ($env{'request.symb'}) {
8892: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 8893: }
1.620 albertel 8894: $thisfn=$env{'request.filename'};
1.44 www 8895: }
1.569 albertel 8896: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 8897: # is that filename actually a symb? Verify, clean, and return
8898: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 8899: if (&symbverify($thisfn,$1)) {
1.620 albertel 8900: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 8901: }
1.242 www 8902: }
1.44 www 8903: $thisfn=declutter($thisfn);
1.31 www 8904: my %hash;
1.37 www 8905: my %bighash;
8906: my $syval='';
1.620 albertel 8907: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 8908: my $targetfn = $thisfn;
1.609 banghart 8909: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 8910: $targetfn = 'adm/wrapper/'.$thisfn;
8911: }
1.687 albertel 8912: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8913: $targetfn=$1;
8914: }
1.620 albertel 8915: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8916: &GDBM_READER(),0640)) {
1.481 raeburn 8917: $syval=$hash{$targetfn};
1.37 www 8918: untie(%hash);
8919: }
8920: # ---------------------------------------------------------- There was an entry
8921: if ($syval) {
1.601 albertel 8922: #unless ($syval=~/\_\d+$/) {
1.620 albertel 8923: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 8924: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8925: #return $env{$cache_str}='';
1.601 albertel 8926: #}
8927: #$syval.=$1;
8928: #}
1.37 www 8929: } else {
8930: # ------------------------------------------------------- Was not in symb table
1.620 albertel 8931: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8932: &GDBM_READER(),0640)) {
1.37 www 8933: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 8934: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 8935: unless ($ids) {
8936: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 8937: }
8938: unless ($ids) {
8939: # alias?
8940: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 8941: }
1.37 www 8942: if ($ids) {
8943: # ------------------------------------------------------------------- Has ID(s)
8944: my @possibilities=split(/\,/,$ids);
1.39 www 8945: if ($#possibilities==0) {
8946: # ----------------------------------------------- There is only one possibility
1.37 www 8947: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 8948: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8949: $resid,$thisfn);
1.249 www 8950: } elsif (!$donotrecurse) {
1.39 www 8951: # ------------------------------------------ There is more than one possibility
8952: my $realpossible=0;
1.800 albertel 8953: foreach my $id (@possibilities) {
8954: my $file=$bighash{'src_'.$id};
1.39 www 8955: if (&allowed('bre',$file)) {
1.800 albertel 8956: my ($mapid,$resid)=split(/\./,$id);
1.39 www 8957: if ($bighash{'map_type_'.$mapid} ne 'page') {
8958: $realpossible++;
1.626 albertel 8959: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8960: $resid,$thisfn);
1.39 www 8961: }
8962: }
1.191 harris41 8963: }
1.39 www 8964: if ($realpossible!=1) { $syval=''; }
1.249 www 8965: } else {
8966: $syval='';
1.37 www 8967: }
8968: }
8969: untie(%bighash)
1.481 raeburn 8970: }
1.31 www 8971: }
1.62 www 8972: if ($syval) {
1.620 albertel 8973: return $env{$cache_str}=$syval;
1.62 www 8974: }
1.31 www 8975: }
1.949 raeburn 8976: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 8977: return $env{$cache_str}='';
1.31 www 8978: }
8979:
8980: # ---------------------------------------------------------- Return random seed
8981:
1.32 www 8982: sub numval {
8983: my $txt=shift;
8984: $txt=~tr/A-J/0-9/;
8985: $txt=~tr/a-j/0-9/;
8986: $txt=~tr/K-T/0-9/;
8987: $txt=~tr/k-t/0-9/;
8988: $txt=~tr/U-Z/0-5/;
8989: $txt=~tr/u-z/0-5/;
8990: $txt=~s/\D//g;
1.564 albertel 8991: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 8992: return int($txt);
1.368 albertel 8993: }
8994:
1.484 albertel 8995: sub numval2 {
8996: my $txt=shift;
8997: $txt=~tr/A-J/0-9/;
8998: $txt=~tr/a-j/0-9/;
8999: $txt=~tr/K-T/0-9/;
9000: $txt=~tr/k-t/0-9/;
9001: $txt=~tr/U-Z/0-5/;
9002: $txt=~tr/u-z/0-5/;
9003: $txt=~s/\D//g;
9004: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9005: my $total;
9006: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9007: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9008: return int($total);
9009: }
9010:
1.575 albertel 9011: sub numval3 {
9012: use integer;
9013: my $txt=shift;
9014: $txt=~tr/A-J/0-9/;
9015: $txt=~tr/a-j/0-9/;
9016: $txt=~tr/K-T/0-9/;
9017: $txt=~tr/k-t/0-9/;
9018: $txt=~tr/U-Z/0-5/;
9019: $txt=~tr/u-z/0-5/;
9020: $txt=~s/\D//g;
9021: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9022: my $total;
9023: foreach my $val (@txts) { $total+=$val; }
9024: if ($_64bit) { $total=(($total<<32)>>32); }
9025: return $total;
9026: }
9027:
1.675 albertel 9028: sub digest {
9029: my ($data)=@_;
9030: my $digest=&Digest::MD5::md5($data);
9031: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9032: my ($e,$f);
9033: {
9034: use integer;
9035: $e=($a+$b);
9036: $f=($c+$d);
9037: if ($_64bit) {
9038: $e=(($e<<32)>>32);
9039: $f=(($f<<32)>>32);
9040: }
9041: }
9042: if (wantarray) {
9043: return ($e,$f);
9044: } else {
9045: my $g;
9046: {
9047: use integer;
9048: $g=($e+$f);
9049: if ($_64bit) {
9050: $g=(($g<<32)>>32);
9051: }
9052: }
9053: return $g;
9054: }
9055: }
9056:
1.368 albertel 9057: sub latest_rnd_algorithm_id {
1.675 albertel 9058: return '64bit5';
1.366 albertel 9059: }
1.32 www 9060:
1.503 albertel 9061: sub get_rand_alg {
9062: my ($courseid)=@_;
1.790 albertel 9063: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9064: if ($courseid) {
1.620 albertel 9065: return $env{"course.$courseid.rndseed"};
1.503 albertel 9066: }
9067: return &latest_rnd_algorithm_id();
9068: }
9069:
1.562 albertel 9070: sub validCODE {
9071: my ($CODE)=@_;
9072: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9073: return 0;
9074: }
9075:
1.491 albertel 9076: sub getCODE {
1.620 albertel 9077: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9078: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9079: defined($Apache::lonhomework::parsing_a_task) ) &&
9080: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9081: return $Apache::lonhomework::history{'resource.CODE'};
9082: }
9083: return undef;
9084: }
9085:
1.31 www 9086: sub rndseed {
1.155 albertel 9087: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9088: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9089: if (!defined($symb)) {
1.366 albertel 9090: unless ($symb=$wsymb) { return time; }
9091: }
9092: if (!$courseid) { $courseid=$wcourseid; }
9093: if (!$domain) { $domain=$wdomain; }
9094: if (!$username) { $username=$wusername }
1.503 albertel 9095: my $which=&get_rand_alg();
1.803 albertel 9096:
1.491 albertel 9097: if (defined(&getCODE())) {
1.675 albertel 9098: if ($which eq '64bit5') {
9099: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9100: } elsif ($which eq '64bit4') {
1.575 albertel 9101: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9102: } else {
9103: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9104: }
1.675 albertel 9105: } elsif ($which eq '64bit5') {
9106: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9107: } elsif ($which eq '64bit4') {
9108: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9109: } elsif ($which eq '64bit3') {
9110: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9111: } elsif ($which eq '64bit2') {
9112: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9113: } elsif ($which eq '64bit') {
9114: return &rndseed_64bit($symb,$courseid,$domain,$username);
9115: }
9116: return &rndseed_32bit($symb,$courseid,$domain,$username);
9117: }
9118:
9119: sub rndseed_32bit {
9120: my ($symb,$courseid,$domain,$username)=@_;
9121: {
9122: use integer;
9123: my $symbchck=unpack("%32C*",$symb) << 27;
9124: my $symbseed=numval($symb) << 22;
9125: my $namechck=unpack("%32C*",$username) << 17;
9126: my $nameseed=numval($username) << 12;
9127: my $domainseed=unpack("%32C*",$domain) << 7;
9128: my $courseseed=unpack("%32C*",$courseid);
9129: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9130: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9131: #&logthis("rndseed :$num:$symb");
1.564 albertel 9132: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9133: return $num;
9134: }
9135: }
9136:
9137: sub rndseed_64bit {
9138: my ($symb,$courseid,$domain,$username)=@_;
9139: {
9140: use integer;
9141: my $symbchck=unpack("%32S*",$symb) << 21;
9142: my $symbseed=numval($symb) << 10;
9143: my $namechck=unpack("%32S*",$username);
9144:
9145: my $nameseed=numval($username) << 21;
9146: my $domainseed=unpack("%32S*",$domain) << 10;
9147: my $courseseed=unpack("%32S*",$courseid);
9148:
9149: my $num1=$symbchck+$symbseed+$namechck;
9150: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9151: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9152: #&logthis("rndseed :$num:$symb");
1.564 albertel 9153: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9154: return "$num1,$num2";
1.155 albertel 9155: }
1.366 albertel 9156: }
9157:
1.443 albertel 9158: sub rndseed_64bit2 {
9159: my ($symb,$courseid,$domain,$username)=@_;
9160: {
9161: use integer;
9162: # strings need to be an even # of cahracters long, it it is odd the
9163: # last characters gets thrown away
9164: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9165: my $symbseed=numval($symb) << 10;
9166: my $namechck=unpack("%32S*",$username.' ');
9167:
9168: my $nameseed=numval($username) << 21;
1.501 albertel 9169: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9170: my $courseseed=unpack("%32S*",$courseid.' ');
9171:
9172: my $num1=$symbchck+$symbseed+$namechck;
9173: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9174: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9175: #&logthis("rndseed :$num:$symb");
1.803 albertel 9176: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9177: return "$num1,$num2";
9178: }
9179: }
9180:
9181: sub rndseed_64bit3 {
9182: my ($symb,$courseid,$domain,$username)=@_;
9183: {
9184: use integer;
9185: # strings need to be an even # of cahracters long, it it is odd the
9186: # last characters gets thrown away
9187: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9188: my $symbseed=numval2($symb) << 10;
9189: my $namechck=unpack("%32S*",$username.' ');
9190:
9191: my $nameseed=numval2($username) << 21;
1.443 albertel 9192: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9193: my $courseseed=unpack("%32S*",$courseid.' ');
9194:
9195: my $num1=$symbchck+$symbseed+$namechck;
9196: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9197: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9198: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9199: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9200:
1.503 albertel 9201: return "$num1:$num2";
1.443 albertel 9202: }
9203: }
9204:
1.575 albertel 9205: sub rndseed_64bit4 {
9206: my ($symb,$courseid,$domain,$username)=@_;
9207: {
9208: use integer;
9209: # strings need to be an even # of cahracters long, it it is odd the
9210: # last characters gets thrown away
9211: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9212: my $symbseed=numval3($symb) << 10;
9213: my $namechck=unpack("%32S*",$username.' ');
9214:
9215: my $nameseed=numval3($username) << 21;
9216: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9217: my $courseseed=unpack("%32S*",$courseid.' ');
9218:
9219: my $num1=$symbchck+$symbseed+$namechck;
9220: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9221: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9222: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9223: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9224:
9225: return "$num1:$num2";
9226: }
9227: }
9228:
1.675 albertel 9229: sub rndseed_64bit5 {
9230: my ($symb,$courseid,$domain,$username)=@_;
9231: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9232: return "$num1:$num2";
9233: }
9234:
1.366 albertel 9235: sub rndseed_CODE_64bit {
9236: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9237: {
1.366 albertel 9238: use integer;
1.443 albertel 9239: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9240: my $symbseed=numval2($symb);
1.491 albertel 9241: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9242: my $CODEseed=numval(&getCODE());
1.443 albertel 9243: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9244: my $num1=$symbseed+$CODEchck;
9245: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9246: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9247: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9248: if ($_64bit) { $num1=(($num1<<32)>>32); }
9249: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9250: return "$num1:$num2";
1.366 albertel 9251: }
9252: }
9253:
1.575 albertel 9254: sub rndseed_CODE_64bit4 {
9255: my ($symb,$courseid,$domain,$username)=@_;
9256: {
9257: use integer;
9258: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9259: my $symbseed=numval3($symb);
9260: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9261: my $CODEseed=numval3(&getCODE());
9262: my $courseseed=unpack("%32S*",$courseid.' ');
9263: my $num1=$symbseed+$CODEchck;
9264: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9265: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9266: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9267: if ($_64bit) { $num1=(($num1<<32)>>32); }
9268: if ($_64bit) { $num2=(($num2<<32)>>32); }
9269: return "$num1:$num2";
9270: }
9271: }
9272:
1.675 albertel 9273: sub rndseed_CODE_64bit5 {
9274: my ($symb,$courseid,$domain,$username)=@_;
9275: my $code = &getCODE();
9276: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9277: return "$num1:$num2";
9278: }
9279:
1.366 albertel 9280: sub setup_random_from_rndseed {
9281: my ($rndseed)=@_;
1.503 albertel 9282: if ($rndseed =~/([,:])/) {
9283: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9284: &Math::Random::random_set_seed(abs($num1),abs($num2));
9285: } else {
9286: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9287: }
1.36 albertel 9288: }
9289:
1.474 albertel 9290: sub latest_receipt_algorithm_id {
1.835 albertel 9291: return 'receipt3';
1.474 albertel 9292: }
9293:
1.480 www 9294: sub recunique {
9295: my $fucourseid=shift;
9296: my $unique;
1.835 albertel 9297: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9298: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9299: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9300: } else {
9301: $unique=$perlvar{'lonReceipt'};
9302: }
9303: return unpack("%32C*",$unique);
9304: }
9305:
9306: sub recprefix {
9307: my $fucourseid=shift;
9308: my $prefix;
1.835 albertel 9309: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9310: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9311: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9312: } else {
9313: $prefix=$perlvar{'lonHostID'};
9314: }
9315: return unpack("%32C*",$prefix);
9316: }
9317:
1.76 www 9318: sub ireceipt {
1.474 albertel 9319: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9320:
9321: my $return =&recprefix($fucourseid).'-';
9322:
9323: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9324: $env{'request.state'} eq 'construct') {
9325: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9326: return $return;
9327: }
9328:
1.76 www 9329: my $cuname=unpack("%32C*",$funame);
9330: my $cudom=unpack("%32C*",$fudom);
9331: my $cucourseid=unpack("%32C*",$fucourseid);
9332: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9333: my $cunique=&recunique($fucourseid);
1.474 albertel 9334: my $cpart=unpack("%32S*",$part);
1.835 albertel 9335: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9336:
1.790 albertel 9337: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9338:
9339: $return.= ($cunique%$cuname+
9340: $cunique%$cudom+
9341: $cusymb%$cuname+
9342: $cusymb%$cudom+
9343: $cucourseid%$cuname+
9344: $cucourseid%$cudom+
9345: $cpart%$cuname+
9346: $cpart%$cudom);
9347: } else {
9348: $return.= ($cunique%$cuname+
9349: $cunique%$cudom+
9350: $cusymb%$cuname+
9351: $cusymb%$cudom+
9352: $cucourseid%$cuname+
9353: $cucourseid%$cudom);
9354: }
9355: return $return;
1.76 www 9356: }
9357:
9358: sub receipt {
1.474 albertel 9359: my ($part)=@_;
1.790 albertel 9360: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9361: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9362: }
1.260 ng 9363:
1.790 albertel 9364: sub whichuser {
9365: my ($passedsymb)=@_;
9366: my ($symb,$courseid,$domain,$name,$publicuser);
9367: if (defined($env{'form.grade_symb'})) {
9368: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9369: my $allowed=&allowed('vgr',$tmp_courseid);
9370: if (!$allowed &&
9371: exists($env{'request.course.sec'}) &&
9372: $env{'request.course.sec'} !~ /^\s*$/) {
9373: $allowed=&allowed('vgr',$tmp_courseid.
9374: '/'.$env{'request.course.sec'});
9375: }
9376: if ($allowed) {
9377: ($symb)=&get_env_multiple('form.grade_symb');
9378: $courseid=$tmp_courseid;
9379: ($domain)=&get_env_multiple('form.grade_domain');
9380: ($name)=&get_env_multiple('form.grade_username');
9381: return ($symb,$courseid,$domain,$name,$publicuser);
9382: }
9383: }
9384: if (!$passedsymb) {
9385: $symb=&symbread();
9386: } else {
9387: $symb=$passedsymb;
9388: }
9389: $courseid=$env{'request.course.id'};
9390: $domain=$env{'user.domain'};
9391: $name=$env{'user.name'};
9392: if ($name eq 'public' && $domain eq 'public') {
9393: if (!defined($env{'form.username'})) {
9394: $env{'form.username'}.=time.rand(10000000);
9395: }
9396: $name.=$env{'form.username'};
9397: }
9398: return ($symb,$courseid,$domain,$name,$publicuser);
9399:
9400: }
9401:
1.36 albertel 9402: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9403: # returns either the contents of the file or
9404: # -1 if the file doesn't exist
1.481 raeburn 9405: #
9406: # if the target is a file that was uploaded via DOCS,
9407: # a check will be made to see if a current copy exists on the local server,
9408: # if it does this will be served, otherwise a copy will be retrieved from
9409: # the home server for the course and stored in /home/httpd/html/userfiles on
9410: # the local server.
1.472 albertel 9411:
1.36 albertel 9412: sub getfile {
1.538 albertel 9413: my ($file) = @_;
1.609 banghart 9414: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9415: &repcopy($file);
9416: return &readfile($file);
9417: }
9418:
9419: sub repcopy_userfile {
9420: my ($file)=@_;
1.609 banghart 9421: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9422: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9423: my ($cdom,$cnum,$filename) =
1.811 albertel 9424: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9425: my $uri="/uploaded/$cdom/$cnum/$filename";
9426: if (-e "$file") {
1.828 www 9427: # we already have a local copy, check it out
1.538 albertel 9428: my @fileinfo = stat($file);
1.828 www 9429: my $rtncode;
9430: my $info;
1.538 albertel 9431: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9432: if ($lwpresp ne 'ok') {
1.828 www 9433: # there is no such file anymore, even though we had a local copy
1.482 albertel 9434: if ($rtncode eq '404') {
1.538 albertel 9435: unlink($file);
1.482 albertel 9436: }
9437: return -1;
9438: }
9439: if ($info < $fileinfo[9]) {
1.828 www 9440: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9441: return 'ok';
1.828 www 9442: } else {
9443: # the file is outdated, get rid of it
9444: unlink($file);
1.482 albertel 9445: }
1.828 www 9446: }
9447: # one way or the other, at this point, we don't have the file
9448: # construct the correct path for the file
9449: my @parts = ($cdom,$cnum);
9450: if ($filename =~ m|^(.+)/[^/]+$|) {
9451: push @parts, split(/\//,$1);
9452: }
9453: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9454: foreach my $part (@parts) {
9455: $path .= '/'.$part;
9456: if (!-e $path) {
9457: mkdir($path,0770);
1.482 albertel 9458: }
9459: }
1.828 www 9460: # now the path exists for sure
9461: # get a user agent
9462: my $ua=new LWP::UserAgent;
9463: my $transferfile=$file.'.in.transfer';
9464: # FIXME: this should flock
9465: if (-e $transferfile) { return 'ok'; }
9466: my $request;
9467: $uri=~s/^\///;
1.980 raeburn 9468: my $homeserver = &homeserver($cnum,$cdom);
9469: my $protocol = $protocol{$homeserver};
9470: $protocol = 'http' if ($protocol ne 'https');
9471: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9472: my $response=$ua->request($request,$transferfile);
9473: # did it work?
9474: if ($response->is_error()) {
9475: unlink($transferfile);
9476: &logthis("Userfile repcopy failed for $uri");
9477: return -1;
9478: }
9479: # worked, rename the transfer file
9480: rename($transferfile,$file);
1.607 raeburn 9481: return 'ok';
1.481 raeburn 9482: }
9483:
1.517 albertel 9484: sub tokenwrapper {
9485: my $uri=shift;
1.980 raeburn 9486: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9487: $uri=~s|^/||;
1.620 albertel 9488: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9489: my $token=$1;
1.552 albertel 9490: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9491: if ($udom && $uname && $file) {
9492: $file=~s|(\?\.*)*$||;
1.949 raeburn 9493: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9494: my $homeserver = &homeserver($uname,$udom);
9495: my $protocol = $protocol{$homeserver};
9496: $protocol = 'http' if ($protocol ne 'https');
9497: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9498: (($uri=~/\?/)?'&':'?').'token='.$token.
9499: '&tokenissued='.$perlvar{'lonHostID'};
9500: } else {
9501: return '/adm/notfound.html';
9502: }
9503: }
9504:
1.828 www 9505: # call with reqtype HEAD: get last modification time
9506: # call with reqtype GET: get the file contents
9507: # Do not call this with reqtype GET for large files! It loads everything into memory
9508: #
1.481 raeburn 9509: sub getuploaded {
9510: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9511: $uri=~s/^\///;
1.980 raeburn 9512: my $homeserver = &homeserver($cnum,$cdom);
9513: my $protocol = $protocol{$homeserver};
9514: $protocol = 'http' if ($protocol ne 'https');
9515: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9516: my $ua=new LWP::UserAgent;
9517: my $request=new HTTP::Request($reqtype,$uri);
9518: my $response=$ua->request($request);
9519: $$rtncode = $response->code;
1.482 albertel 9520: if (! $response->is_success()) {
9521: return 'failed';
9522: }
9523: if ($reqtype eq 'HEAD') {
1.486 www 9524: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9525: } elsif ($reqtype eq 'GET') {
9526: $$info = $response->content;
1.472 albertel 9527: }
1.482 albertel 9528: return 'ok';
1.36 albertel 9529: }
9530:
1.481 raeburn 9531: sub readfile {
9532: my $file = shift;
9533: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9534: my $fh;
9535: open($fh,"<$file");
9536: my $a='';
1.800 albertel 9537: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9538: return $a;
9539: }
9540:
1.36 albertel 9541: sub filelocation {
1.590 banghart 9542: my ($dir,$file) = @_;
9543: my $location;
9544: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9545:
9546: if ($file =~ m-^/adm/-) {
9547: $file=~s-^/adm/wrapper/-/-;
9548: $file=~s-^/adm/coursedocs/showdoc/-/-;
9549: }
1.882 albertel 9550:
1.590 banghart 9551: if ($file=~m:^/~:) { # is a contruction space reference
9552: $location = $file;
9553: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9554: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9555: # is a correct contruction space reference
9556: $location = $file;
1.956 raeburn 9557: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9558: $location = $file;
1.609 banghart 9559: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9560: my ($udom,$uname,$filename)=
1.811 albertel 9561: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9562: my $home=&homeserver($uname,$udom);
9563: my $is_me=0;
9564: my @ids=¤t_machine_ids();
9565: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9566: if ($is_me) {
1.955 raeburn 9567: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9568: } else {
9569: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9570: $udom.'/'.$uname.'/'.$filename;
9571: }
1.882 albertel 9572: } elsif ($file =~ m-^/adm/-) {
9573: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9574: } else {
9575: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9576: $file=~s:^/res/:/:;
9577: if ( !( $file =~ m:^/:) ) {
9578: $location = $dir. '/'.$file;
9579: } else {
9580: $location = '/home/httpd/html/res'.$file;
9581: }
1.59 albertel 9582: }
1.590 banghart 9583: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9584: while ($location=~m{/\.\./}) {
9585: if ($location =~ m{/[^/]+/\.\./}) {
9586: $location=~ s{/[^/]+/\.\./}{/}g;
9587: } else {
9588: $location=~ s{/\.\./}{/}g;
9589: }
9590: } #remove dir/..
1.590 banghart 9591: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9592: return $location;
1.46 www 9593: }
1.36 albertel 9594:
1.46 www 9595: sub hreflocation {
9596: my ($dir,$file)=@_;
1.980 raeburn 9597: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9598: $file=filelocation($dir,$file);
1.700 albertel 9599: } elsif ($file=~m-^/adm/-) {
9600: $file=~s-^/adm/wrapper/-/-;
9601: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9602: }
9603: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9604: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9605: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9606: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9607: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9608: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9609: -/uploaded/$1/$2/-x;
1.46 www 9610: }
1.913 albertel 9611: if ($file=~ m{^/userfiles/}) {
9612: $file =~ s{^/userfiles/}{/uploaded/};
9613: }
1.462 albertel 9614: return $file;
1.465 albertel 9615: }
9616:
9617: sub current_machine_domains {
1.853 albertel 9618: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9619: }
9620:
9621: sub machine_domains {
9622: my ($hostname) = @_;
1.465 albertel 9623: my @domains;
1.838 albertel 9624: my %hostname = &all_hostnames();
1.465 albertel 9625: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9626: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9627: if ($hostname eq $name) {
1.844 albertel 9628: push(@domains,&host_domain($id));
1.465 albertel 9629: }
9630: }
9631: return @domains;
9632: }
9633:
9634: sub current_machine_ids {
1.853 albertel 9635: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9636: }
9637:
9638: sub machine_ids {
9639: my ($hostname) = @_;
9640: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9641: my @ids;
1.888 albertel 9642: my %name_to_host = &all_names();
1.889 albertel 9643: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9644: return @{ $name_to_host{$hostname} };
9645: }
9646: return;
1.31 www 9647: }
9648:
1.824 raeburn 9649: sub additional_machine_domains {
9650: my @domains;
9651: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9652: while( my $line = <$fh>) {
9653: $line =~ s/\s//g;
9654: push(@domains,$line);
9655: }
9656: return @domains;
9657: }
9658:
9659: sub default_login_domain {
9660: my $domain = $perlvar{'lonDefDomain'};
9661: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9662: foreach my $posdom (¤t_machine_domains(),
9663: &additional_machine_domains()) {
9664: if (lc($posdom) eq lc($testdomain)) {
9665: $domain=$posdom;
9666: last;
9667: }
9668: }
9669: return $domain;
9670: }
9671:
1.31 www 9672: # ------------------------------------------------------------- Declutters URLs
9673:
9674: sub declutter {
9675: my $thisfn=shift;
1.569 albertel 9676: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9677: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9678: $thisfn=~s/^\///;
1.697 albertel 9679: $thisfn=~s|^adm/wrapper/||;
9680: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9681: $thisfn=~s/^res\///;
1.1032 raeburn 9682: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9683: $thisfn=~s/\?.+$//;
9684: }
1.268 www 9685: return $thisfn;
9686: }
9687:
9688: # ------------------------------------------------------------- Clutter up URLs
9689:
9690: sub clutter {
9691: my $thisfn='/'.&declutter(shift);
1.887 albertel 9692: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9693: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9694: $thisfn='/res'.$thisfn;
9695: }
1.1031 raeburn 9696: if ($thisfn !~m|^/adm|) {
9697: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9698: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9699: } else {
9700: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9701: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9702: if ($embstyle eq 'ssi'
9703: || ($embstyle eq 'hdn')
9704: || ($embstyle eq 'rat')
9705: || ($embstyle eq 'prv')
9706: || ($embstyle eq 'ign')) {
9707: #do nothing with these
9708: } elsif (($embstyle eq 'img')
1.695 albertel 9709: || ($embstyle eq 'emb')
9710: || ($embstyle eq 'wrp')) {
9711: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9712: } elsif ($embstyle eq 'unk'
9713: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9714: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9715: } else {
1.718 www 9716: # &logthis("Got a blank emb style");
1.695 albertel 9717: }
1.694 albertel 9718: }
9719: }
1.31 www 9720: return $thisfn;
1.12 www 9721: }
9722:
1.787 albertel 9723: sub clutter_with_no_wrapper {
9724: my $uri = &clutter(shift);
9725: if ($uri =~ m-^/adm/-) {
9726: $uri =~ s-^/adm/wrapper/-/-;
9727: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9728: }
9729: return $uri;
9730: }
9731:
1.557 albertel 9732: sub freeze_escape {
9733: my ($value)=@_;
9734: if (ref($value)) {
9735: $value=&nfreeze($value);
9736: return '__FROZEN__'.&escape($value);
9737: }
9738: return &escape($value);
9739: }
9740:
1.11 www 9741:
1.557 albertel 9742: sub thaw_unescape {
9743: my ($value)=@_;
9744: if ($value =~ /^__FROZEN__/) {
9745: substr($value,0,10,undef);
9746: $value=&unescape($value);
9747: return &thaw($value);
9748: }
9749: return &unescape($value);
9750: }
9751:
1.436 albertel 9752: sub correct_line_ends {
9753: my ($result)=@_;
9754: $$result =~s/\r\n/\n/mg;
9755: $$result =~s/\r/\n/mg;
1.415 albertel 9756: }
1.1 albertel 9757: # ================================================================ Main Program
9758:
1.184 www 9759: sub goodbye {
1.204 albertel 9760: &logthis("Starting Shut down");
1.443 albertel 9761: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9762: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9763: #converted
1.599 albertel 9764: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9765: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9766: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9767: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9768: #1.1 only
1.870 albertel 9769: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9770: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9771: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9772: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9773: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9774: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9775: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9776: &flushcourselogs();
9777: &logthis("Shutting down");
9778: }
9779:
1.852 albertel 9780: sub get_dns {
1.869 albertel 9781: my ($url,$func,$ignore_cache) = @_;
9782: if (!$ignore_cache) {
9783: my ($content,$cached)=
9784: &Apache::lonnet::is_cached_new('dns',$url);
9785: if ($cached) {
9786: &$func($content);
9787: return;
9788: }
9789: }
9790:
9791: my %alldns;
1.852 albertel 9792: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9793: foreach my $dns (<$config>) {
9794: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9795: my $line = $1;
9796: my ($host,$protocol) = split(/:/,$line);
9797: if ($protocol ne 'https') {
9798: $protocol = 'http';
9799: }
9800: $alldns{$host} = $protocol;
1.869 albertel 9801: }
9802: while (%alldns) {
9803: my ($dns) = keys(%alldns);
1.852 albertel 9804: my $ua=new LWP::UserAgent;
1.979 raeburn 9805: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9806: my $response=$ua->request($request);
1.979 raeburn 9807: delete($alldns{$dns});
1.852 albertel 9808: next if ($response->is_error());
9809: my @content = split("\n",$response->content);
1.869 albertel 9810: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9811: &$func(\@content);
1.869 albertel 9812: return;
1.852 albertel 9813: }
9814: close($config);
1.871 albertel 9815: my $which = (split('/',$url))[3];
9816: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9817: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9818: my @content = <$config>;
9819: &$func(\@content);
9820: return;
1.852 albertel 9821: }
1.327 albertel 9822: # ------------------------------------------------------------ Read domain file
9823: {
1.852 albertel 9824: my $loaded;
1.846 albertel 9825: my %domain;
9826:
1.852 albertel 9827: sub parse_domain_tab {
9828: my ($lines) = @_;
9829: foreach my $line (@$lines) {
9830: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9831:
1.846 albertel 9832: chomp($line);
1.852 albertel 9833: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9834: my %this_domain;
9835: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9836: 'lang_def', 'city', 'longi', 'lati',
9837: 'primary') {
9838: $this_domain{$field} = shift(@elements);
9839: }
9840: $domain{$name} = \%this_domain;
1.852 albertel 9841: }
9842: }
1.864 albertel 9843:
9844: sub reset_domain_info {
9845: undef($loaded);
9846: undef(%domain);
9847: }
9848:
1.852 albertel 9849: sub load_domain_tab {
1.869 albertel 9850: my ($ignore_cache) = @_;
9851: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9852: my $fh;
9853: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9854: my @lines = <$fh>;
9855: &parse_domain_tab(\@lines);
1.448 albertel 9856: }
1.852 albertel 9857: close($fh);
9858: $loaded = 1;
1.327 albertel 9859: }
1.846 albertel 9860:
9861: sub domain {
1.852 albertel 9862: &load_domain_tab() if (!$loaded);
9863:
1.846 albertel 9864: my ($name,$what) = @_;
9865: return if ( !exists($domain{$name}) );
9866:
9867: if (!$what) {
9868: return $domain{$name}{'description'};
9869: }
9870: return $domain{$name}{$what};
9871: }
1.974 raeburn 9872:
9873: sub domain_info {
9874: &load_domain_tab() if (!$loaded);
9875: return %domain;
9876: }
9877:
1.327 albertel 9878: }
9879:
9880:
1.1 albertel 9881: # ------------------------------------------------------------- Read hosts file
9882: {
1.838 albertel 9883: my %hostname;
1.844 albertel 9884: my %hostdom;
1.845 albertel 9885: my %libserv;
1.852 albertel 9886: my $loaded;
1.888 albertel 9887: my %name_to_host;
1.1074 raeburn 9888: my %internetdom;
1.852 albertel 9889:
9890: sub parse_hosts_tab {
9891: my ($file) = @_;
9892: foreach my $configline (@$file) {
9893: next if ($configline =~ /^(\#|\s*$ )/x);
9894: next if ($configline =~ /^\^/);
9895: chomp($configline);
1.1074 raeburn 9896: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 9897: $name=~s/\s//g;
9898: if ($id && $domain && $role && $name) {
9899: $hostname{$id}=$name;
1.888 albertel 9900: push(@{$name_to_host{$name}}, $id);
1.852 albertel 9901: $hostdom{$id}=$domain;
9902: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 9903: if (defined($protocol)) {
9904: if ($protocol eq 'https') {
9905: $protocol{$id} = $protocol;
9906: } else {
9907: $protocol{$id} = 'http';
9908: }
1.968 raeburn 9909: } else {
1.969 raeburn 9910: $protocol{$id} = 'http';
1.968 raeburn 9911: }
1.1074 raeburn 9912: if (defined($intdom)) {
9913: $internetdom{$id} = $intdom;
9914: }
1.852 albertel 9915: }
9916: }
9917: }
1.864 albertel 9918:
9919: sub reset_hosts_info {
1.897 albertel 9920: &purge_remembered();
1.864 albertel 9921: &reset_domain_info();
9922: &reset_hosts_ip_info();
1.892 albertel 9923: undef(%name_to_host);
1.864 albertel 9924: undef(%hostname);
9925: undef(%hostdom);
9926: undef(%libserv);
9927: undef($loaded);
9928: }
1.1 albertel 9929:
1.852 albertel 9930: sub load_hosts_tab {
1.869 albertel 9931: my ($ignore_cache) = @_;
9932: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 9933: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9934: my @config = <$config>;
9935: &parse_hosts_tab(\@config);
9936: close($config);
9937: $loaded=1;
1.1 albertel 9938: }
1.852 albertel 9939:
1.838 albertel 9940: sub hostname {
1.852 albertel 9941: &load_hosts_tab() if (!$loaded);
9942:
1.838 albertel 9943: my ($lonid) = @_;
9944: return $hostname{$lonid};
9945: }
1.845 albertel 9946:
1.838 albertel 9947: sub all_hostnames {
1.852 albertel 9948: &load_hosts_tab() if (!$loaded);
9949:
1.838 albertel 9950: return %hostname;
9951: }
1.845 albertel 9952:
1.888 albertel 9953: sub all_names {
9954: &load_hosts_tab() if (!$loaded);
9955:
9956: return %name_to_host;
9957: }
9958:
1.974 raeburn 9959: sub all_host_domain {
9960: &load_hosts_tab() if (!$loaded);
9961: return %hostdom;
9962: }
9963:
1.845 albertel 9964: sub is_library {
1.852 albertel 9965: &load_hosts_tab() if (!$loaded);
9966:
1.845 albertel 9967: return exists($libserv{$_[0]});
9968: }
9969:
9970: sub all_library {
1.852 albertel 9971: &load_hosts_tab() if (!$loaded);
9972:
1.845 albertel 9973: return %libserv;
9974: }
9975:
1.1062 droeschl 9976: sub unique_library {
9977: #2x reverse removes all hostnames that appear more than once
9978: my %unique = reverse &all_library();
9979: return reverse %unique;
9980: }
9981:
1.841 albertel 9982: sub get_servers {
1.852 albertel 9983: &load_hosts_tab() if (!$loaded);
9984:
1.841 albertel 9985: my ($domain,$type) = @_;
9986: my %possible_hosts = ($type eq 'library') ? %libserv
9987: : %hostname;
9988: my %result;
1.842 albertel 9989: if (ref($domain) eq 'ARRAY') {
9990: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 9991: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 9992: $result{$host} = $hostname;
9993: }
9994: }
9995: } else {
9996: while ( my ($host,$hostname) = each(%possible_hosts)) {
9997: if ($hostdom{$host} eq $domain) {
9998: $result{$host} = $hostname;
9999: }
1.841 albertel 10000: }
10001: }
10002: return %result;
10003: }
1.845 albertel 10004:
1.1062 droeschl 10005: sub get_unique_servers {
10006: my %unique = reverse &get_servers(@_);
10007: return reverse %unique;
10008: }
10009:
1.844 albertel 10010: sub host_domain {
1.852 albertel 10011: &load_hosts_tab() if (!$loaded);
10012:
1.844 albertel 10013: my ($lonid) = @_;
10014: return $hostdom{$lonid};
10015: }
10016:
1.841 albertel 10017: sub all_domains {
1.852 albertel 10018: &load_hosts_tab() if (!$loaded);
10019:
1.841 albertel 10020: my %seen;
10021: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10022: return @uniq;
10023: }
1.1074 raeburn 10024:
10025: sub internet_dom {
10026: &load_hosts_tab() if (!$loaded);
10027:
10028: my ($lonid) = @_;
10029: return $internetdom{$lonid};
10030: }
1.1 albertel 10031: }
10032:
1.847 albertel 10033: {
10034: my %iphost;
1.856 albertel 10035: my %name_to_ip;
10036: my %lonid_to_ip;
1.869 albertel 10037:
1.847 albertel 10038: sub get_hosts_from_ip {
10039: my ($ip) = @_;
10040: my %iphosts = &get_iphost();
10041: if (ref($iphosts{$ip})) {
10042: return @{$iphosts{$ip}};
10043: }
10044: return;
1.839 albertel 10045: }
1.864 albertel 10046:
10047: sub reset_hosts_ip_info {
10048: undef(%iphost);
10049: undef(%name_to_ip);
10050: undef(%lonid_to_ip);
10051: }
1.856 albertel 10052:
10053: sub get_host_ip {
10054: my ($lonid) = @_;
10055: if (exists($lonid_to_ip{$lonid})) {
10056: return $lonid_to_ip{$lonid};
10057: }
10058: my $name=&hostname($lonid);
10059: my $ip = gethostbyname($name);
10060: return if (!$ip || length($ip) ne 4);
10061: $ip=inet_ntoa($ip);
10062: $name_to_ip{$name} = $ip;
10063: $lonid_to_ip{$lonid} = $ip;
10064: return $ip;
10065: }
1.847 albertel 10066:
10067: sub get_iphost {
1.869 albertel 10068: my ($ignore_cache) = @_;
1.894 albertel 10069:
1.869 albertel 10070: if (!$ignore_cache) {
10071: if (%iphost) {
10072: return %iphost;
10073: }
10074: my ($ip_info,$cached)=
10075: &Apache::lonnet::is_cached_new('iphost','iphost');
10076: if ($cached) {
10077: %iphost = %{$ip_info->[0]};
10078: %name_to_ip = %{$ip_info->[1]};
10079: %lonid_to_ip = %{$ip_info->[2]};
10080: return %iphost;
10081: }
10082: }
1.894 albertel 10083:
10084: # get yesterday's info for fallback
10085: my %old_name_to_ip;
10086: my ($ip_info,$cached)=
10087: &Apache::lonnet::is_cached_new('iphost','iphost');
10088: if ($cached) {
10089: %old_name_to_ip = %{$ip_info->[1]};
10090: }
10091:
1.888 albertel 10092: my %name_to_host = &all_names();
10093: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10094: my $ip;
10095: if (!exists($name_to_ip{$name})) {
10096: $ip = gethostbyname($name);
10097: if (!$ip || length($ip) ne 4) {
1.894 albertel 10098: if (defined($old_name_to_ip{$name})) {
10099: $ip = $old_name_to_ip{$name};
10100: &logthis("Can't find $name defaulting to old $ip");
10101: } else {
10102: &logthis("Name $name no IP found");
10103: next;
10104: }
10105: } else {
10106: $ip=inet_ntoa($ip);
1.847 albertel 10107: }
10108: $name_to_ip{$name} = $ip;
10109: } else {
10110: $ip = $name_to_ip{$name};
1.653 albertel 10111: }
1.888 albertel 10112: foreach my $id (@{ $name_to_host{$name} }) {
10113: $lonid_to_ip{$id} = $ip;
10114: }
10115: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10116: }
1.869 albertel 10117: &Apache::lonnet::do_cache_new('iphost','iphost',
10118: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10119: 48*60*60);
1.869 albertel 10120:
1.847 albertel 10121: return %iphost;
1.598 albertel 10122: }
10123:
1.992 raeburn 10124: #
10125: # Given a DNS returns the loncapa host name for that DNS
10126: #
10127: sub host_from_dns {
10128: my ($dns) = @_;
10129: my @hosts;
10130: my $ip;
10131:
1.993 raeburn 10132: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10133: $ip = $name_to_ip{$dns};
10134: }
10135: if (!$ip) {
10136: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10137: if (length($ip) == 4) {
10138: $ip = &IO::Socket::inet_ntoa($ip);
10139: }
10140: }
10141: if ($ip) {
10142: @hosts = get_hosts_from_ip($ip);
10143: return $hosts[0];
10144: }
10145: return undef;
1.986 foxr 10146: }
1.992 raeburn 10147:
1.1074 raeburn 10148: sub get_internet_names {
10149: my ($lonid) = @_;
10150: return if ($lonid eq '');
10151: my ($idnref,$cached)=
10152: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10153: if ($cached) {
10154: return $idnref;
10155: }
10156: my $ip = &get_host_ip($lonid);
10157: my @hosts = &get_hosts_from_ip($ip);
10158: my %iphost = &get_iphost();
10159: my (@idns,%seen);
10160: foreach my $id (@hosts) {
10161: my $dom = &host_domain($id);
10162: my $prim_id = &domain($dom,'primary');
10163: my $prim_ip = &get_host_ip($prim_id);
10164: next if ($seen{$prim_ip});
10165: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10166: foreach my $id (@{$iphost{$prim_ip}}) {
10167: my $intdom = &internet_dom($id);
10168: unless (grep(/^\Q$intdom\E$/,@idns)) {
10169: push(@idns,$intdom);
10170: }
10171: }
10172: }
10173: $seen{$prim_ip} = 1;
10174: }
10175: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10176: }
10177:
1.986 foxr 10178: }
10179:
1.1079 raeburn 10180: sub all_loncaparevs {
10181: 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);
10182: }
10183:
1.862 albertel 10184: BEGIN {
10185:
10186: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10187: unless ($readit) {
10188: {
10189: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10190: %perlvar = (%perlvar,%{$configvars});
10191: }
10192:
10193:
1.1 albertel 10194: # ------------------------------------------------------ Read spare server file
10195: {
1.448 albertel 10196: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10197:
10198: while (my $configline=<$config>) {
10199: chomp($configline);
1.284 matthew 10200: if ($configline) {
1.784 albertel 10201: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10202: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10203: push(@{ $spareid{$type} }, $host);
1.1 albertel 10204: }
10205: }
1.448 albertel 10206: close($config);
1.1 albertel 10207: }
1.11 www 10208: # ------------------------------------------------------------ Read permissions
10209: {
1.448 albertel 10210: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10211:
10212: while (my $configline=<$config>) {
1.448 albertel 10213: chomp($configline);
10214: if ($configline) {
10215: my ($role,$perm)=split(/ /,$configline);
10216: if ($perm ne '') { $pr{$role}=$perm; }
10217: }
1.11 www 10218: }
1.448 albertel 10219: close($config);
1.11 www 10220: }
10221:
10222: # -------------------------------------------- Read plain texts for permissions
10223: {
1.448 albertel 10224: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10225:
10226: while (my $configline=<$config>) {
1.448 albertel 10227: chomp($configline);
10228: if ($configline) {
1.742 raeburn 10229: my ($short,@plain)=split(/:/,$configline);
10230: %{$prp{$short}} = ();
10231: if (@plain > 0) {
10232: $prp{$short}{'std'} = $plain[0];
10233: for (my $i=1; $i<@plain; $i++) {
10234: $prp{$short}{'alt'.$i} = $plain[$i];
10235: }
10236: }
1.448 albertel 10237: }
1.135 www 10238: }
1.448 albertel 10239: close($config);
1.135 www 10240: }
10241:
10242: # ---------------------------------------------------------- Read package table
10243: {
1.448 albertel 10244: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10245:
10246: while (my $configline=<$config>) {
1.483 albertel 10247: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10248: chomp($configline);
10249: my ($short,$plain)=split(/:/,$configline);
10250: my ($pack,$name)=split(/\&/,$short);
10251: if ($plain ne '') {
10252: $packagetab{$pack.'&'.$name.'&name'}=$name;
10253: $packagetab{$short}=$plain;
10254: }
1.11 www 10255: }
1.448 albertel 10256: close($config);
1.329 matthew 10257: }
10258:
1.1073 raeburn 10259: # ---------------------------------------------------------- Read loncaparev table
10260: {
10261: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10262: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10263: while (my $configline=<$config>) {
10264: chomp($configline);
10265: my ($hostid,$loncaparev)=split(/:/,$configline);
10266: $loncaparevs{$hostid}=$loncaparev;
10267: }
10268: close($config);
10269: }
10270: }
10271: }
10272:
1.1074 raeburn 10273: # ---------------------------------------------------------- Read serverhostID table
10274: {
10275: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10276: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10277: while (my $configline=<$config>) {
10278: chomp($configline);
10279: my ($name,$id)=split(/:/,$configline);
10280: $serverhomeIDs{$name}=$id;
10281: }
10282: close($config);
10283: }
10284: }
10285: }
10286:
1.1079 raeburn 10287: {
10288: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10289: if (-e $file) {
10290: my $parser = HTML::LCParser->new($file);
10291: while (my $token = $parser->get_token()) {
10292: if ($token->[0] eq 'S') {
10293: my $item = $token->[1];
10294: my $name = $token->[2]{'name'};
10295: my $value = $token->[2]{'value'};
10296: if ($item ne '' && $name ne '' && $value ne '') {
10297: my $release = $parser->get_text();
10298: $release =~ s/(^\s*|\s*$ )//gx;
10299: $needsrelease{$item.':'.$name.':'.$value} = $release;
10300: }
10301: }
10302: }
10303: }
1.1073 raeburn 10304: }
10305:
1.329 matthew 10306: # ------------- set up temporary directory
10307: {
10308: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10309:
1.11 www 10310: }
10311:
1.794 albertel 10312: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10313: 'compress_threshold'=> 20_000,
10314: });
1.185 www 10315:
1.281 www 10316: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10317: $dumpcount=0;
1.958 www 10318: $locknum=0;
1.22 www 10319:
1.163 harris41 10320: &logtouch();
1.672 albertel 10321: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10322: $readit=1;
1.564 albertel 10323: {
10324: use integer;
10325: my $test=(2**32)+1;
1.568 albertel 10326: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10327: &logthis(" Detected 64bit platform ($_64bit)");
10328: }
1.195 www 10329: }
1.1 albertel 10330: }
1.179 www 10331:
1.1 albertel 10332: 1;
1.191 harris41 10333: __END__
10334:
1.243 albertel 10335: =pod
10336:
1.191 harris41 10337: =head1 NAME
10338:
1.243 albertel 10339: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10340:
10341: =head1 SYNOPSIS
10342:
1.243 albertel 10343: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10344:
10345: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10346:
1.243 albertel 10347: Common parameters:
10348:
10349: =over 4
10350:
10351: =item *
10352:
10353: $uname : an internal username (if $cname expecting a course Id specifically)
10354:
10355: =item *
10356:
10357: $udom : a domain (if $cdom expecting a course's domain specifically)
10358:
10359: =item *
10360:
10361: $symb : a resource instance identifier
10362:
10363: =item *
10364:
10365: $namespace : the name of a .db file that contains the data needed or
10366: being set.
10367:
10368: =back
10369:
1.394 bowersj2 10370: =head1 OVERVIEW
1.191 harris41 10371:
1.394 bowersj2 10372: lonnet provides subroutines which interact with the
10373: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10374: about classes, users, and resources.
1.243 albertel 10375:
10376: For many of these objects you can also use this to store data about
10377: them or modify them in various ways.
1.191 harris41 10378:
1.394 bowersj2 10379: =head2 Symbs
1.191 harris41 10380:
1.394 bowersj2 10381: To identify a specific instance of a resource, LON-CAPA uses symbols
10382: or "symbs"X<symb>. These identifiers are built from the URL of the
10383: map, the resource number of the resource in the map, and the URL of
10384: the resource itself. The latter is somewhat redundant, but might help
10385: if maps change.
10386:
10387: An example is
10388:
10389: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10390:
10391: The respective map entry is
10392:
10393: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10394: title="Problem 2">
10395: </resource>
10396:
10397: Symbs are used by the random number generator, as well as to store and
10398: restore data specific to a certain instance of for example a problem.
10399:
10400: =head2 Storing And Retrieving Data
10401:
10402: X<store()>X<cstore()>X<restore()>Three of the most important functions
10403: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10404: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10405: is is the non-critical message twin of cstore. These functions are for
10406: handlers to store a perl hash to a user's permanent data space in an
10407: easy manner, and to retrieve it again on another call. It is expected
10408: that a handler would use this once at the beginning to retrieve data,
10409: and then again once at the end to send only the new data back.
10410:
10411: The data is stored in the user's data directory on the user's
10412: homeserver under the ID of the course.
10413:
10414: The hash that is returned by restore will have all of the previous
10415: value for all of the elements of the hash.
10416:
10417: Example:
10418:
10419: #creating a hash
10420: my %hash;
10421: $hash{'foo'}='bar';
10422:
10423: #storing it
10424: &Apache::lonnet::cstore(\%hash);
10425:
10426: #changing a value
10427: $hash{'foo'}='notbar';
10428:
10429: #adding a new value
10430: $hash{'bar'}='foo';
10431: &Apache::lonnet::cstore(\%hash);
10432:
10433: #retrieving the hash
10434: my %history=&Apache::lonnet::restore();
10435:
10436: #print the hash
10437: foreach my $key (sort(keys(%history))) {
10438: print("\%history{$key} = $history{$key}");
10439: }
10440:
10441: Will print out:
1.191 harris41 10442:
1.394 bowersj2 10443: %history{1:foo} = bar
10444: %history{1:keys} = foo:timestamp
10445: %history{1:timestamp} = 990455579
10446: %history{2:bar} = foo
10447: %history{2:foo} = notbar
10448: %history{2:keys} = foo:bar:timestamp
10449: %history{2:timestamp} = 990455580
10450: %history{bar} = foo
10451: %history{foo} = notbar
10452: %history{timestamp} = 990455580
10453: %history{version} = 2
10454:
10455: Note that the special hash entries C<keys>, C<version> and
10456: C<timestamp> were added to the hash. C<version> will be equal to the
10457: total number of versions of the data that have been stored. The
10458: C<timestamp> attribute will be the UNIX time the hash was
10459: stored. C<keys> is available in every historical section to list which
10460: keys were added or changed at a specific historical revision of a
10461: hash.
10462:
10463: B<Warning>: do not store the hash that restore returns directly. This
10464: will cause a mess since it will restore the historical keys as if the
10465: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10466:
1.394 bowersj2 10467: Calling convention:
1.191 harris41 10468:
1.394 bowersj2 10469: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10470: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10471:
1.394 bowersj2 10472: For more detailed information, see lonnet specific documentation.
1.191 harris41 10473:
1.394 bowersj2 10474: =head1 RETURN MESSAGES
1.191 harris41 10475:
1.394 bowersj2 10476: =over 4
1.191 harris41 10477:
1.394 bowersj2 10478: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10479:
1.394 bowersj2 10480: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10481: when the connection is brought back up
1.191 harris41 10482:
1.394 bowersj2 10483: =item * B<con_failed>: unable to contact remote host and unable to save message
10484: for later delivery
1.191 harris41 10485:
1.967 bisitz 10486: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10487:
1.394 bowersj2 10488: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10489: that was requested
1.191 harris41 10490:
1.243 albertel 10491: =back
1.191 harris41 10492:
1.243 albertel 10493: =head1 PUBLIC SUBROUTINES
1.191 harris41 10494:
1.243 albertel 10495: =head2 Session Environment Functions
1.191 harris41 10496:
1.243 albertel 10497: =over 4
1.191 harris41 10498:
1.394 bowersj2 10499: =item *
10500: X<appenv()>
1.949 raeburn 10501: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10502: the user envirnoment file, and will be restored for each access this
1.620 albertel 10503: user makes during this session, also modifies the %env for the current
1.949 raeburn 10504: process. Optional rolesarrayref - if defined contains a reference to an array
10505: of roles which are exempt from the restriction on modifying user.role entries
10506: in the user's environment.db and in %env.
1.191 harris41 10507:
10508: =item *
1.394 bowersj2 10509: X<delenv()>
1.987 raeburn 10510: B<delenv($delthis,$regexp)>: removes all items from the session
10511: environment file that begin with $delthis. If the
10512: optional second arg - $regexp - is true, $delthis is treated as a
10513: regular expression, otherwise \Q$delthis\E is used.
10514: The values are also deleted from the current processes %env.
1.191 harris41 10515:
1.795 albertel 10516: =item * get_env_multiple($name)
10517:
10518: gets $name from the %env hash, it seemlessly handles the cases where multiple
10519: values may be defined and end up as an array ref.
10520:
10521: returns an array of values
10522:
1.243 albertel 10523: =back
10524:
10525: =head2 User Information
1.191 harris41 10526:
1.243 albertel 10527: =over 4
1.191 harris41 10528:
10529: =item *
1.394 bowersj2 10530: X<queryauthenticate()>
10531: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10532: authentication scheme
10533:
10534: =item *
1.394 bowersj2 10535: X<authenticate()>
1.1073 raeburn 10536: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10537: authenticate user from domain's lib servers (first use the current
10538: one). C<$upass> should be the users password.
1.1073 raeburn 10539: $checkdefauth is optional (value is 1 if a check should be made to
10540: authenticate user using default authentication method, and allow
10541: account creation if username does not have account in the domain).
10542: $clientcancheckhost is optional (value is 1 if checking whether the
10543: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10544:
10545: =item *
1.394 bowersj2 10546: X<homeserver()>
10547: B<homeserver($uname,$udom)>: find the server which has
10548: the user's directory and files (there must be only one), this caches
10549: the answer, and also caches if there is a borken connection.
1.191 harris41 10550:
10551: =item *
1.394 bowersj2 10552: X<idget()>
10553: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10554: (IDs are a unique resource in a domain, there must be only 1 ID per
10555: username, and only 1 username per ID in a specific domain) (returns
10556: hash: id=>name,id=>name)
1.191 harris41 10557:
10558: =item *
1.394 bowersj2 10559: X<idrget()>
10560: B<idrget($udom,@unames)>: find the IDs behind a list of
10561: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10562:
10563: =item *
1.394 bowersj2 10564: X<idput()>
10565: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10566:
10567: =item *
1.394 bowersj2 10568: X<rolesinit()>
10569: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10570:
10571: =item *
1.551 albertel 10572: X<getsection()>
10573: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10574: course $cname, return section name/number or '' for "not in course"
10575: and '-1' for "no section"
10576:
10577: =item *
1.394 bowersj2 10578: X<userenvironment()>
10579: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10580: passed in @what from the requested user's environment, returns a hash
10581:
1.858 raeburn 10582: =item *
10583: X<userlog_query()>
1.859 albertel 10584: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10585: activity.log file. %filters defines filters applied when parsing the
10586: log file. These can be start or end timestamps, or the type of action
10587: - log to look for Login or Logout events, check for Checkin or
10588: Checkout, role for role selection. The response is in the form
10589: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10590: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10591:
1.243 albertel 10592: =back
10593:
10594: =head2 User Roles
10595:
10596: =over 4
10597:
10598: =item *
10599:
1.810 raeburn 10600: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10601: F: full access
10602: U,I,K: authentication modes (cxx only)
10603: '': forbidden
10604: 1: user needs to choose course
10605: 2: browse allowed
1.766 albertel 10606: A: passphrase authentication needed
1.243 albertel 10607:
10608: =item *
10609:
10610: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10611: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10612: and course level
10613:
10614: =item *
10615:
1.988 raeburn 10616: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10617: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10618: $type is Course (default) or Community.
1.988 raeburn 10619: If $forcedefault evaluates to true, text returned will be default
10620: text for $type. Otherwise, if this is a course, the text returned
10621: will be a custom name for the role (if defined in the course's
10622: environment). If no custom name is defined the default is returned.
10623:
1.832 raeburn 10624: =item *
10625:
1.935 raeburn 10626: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10627: All arguments are optional. Returns a hash of a roles, either for
10628: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10629: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10630: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10631: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10632: For each key, value is set to colon-separated start and end times for
10633: the role. If no username and domain are specified, will default to
1.934 raeburn 10634: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10635: of role statuses (active, future or previous), roles
10636: (e.g., cc,in, st etc.) and domains of the roles which can be used
10637: to restrict the list of roles reported. If no array ref is
10638: provided for types, will default to return only active roles.
1.834 albertel 10639:
1.243 albertel 10640: =back
10641:
10642: =head2 User Modification
10643:
10644: =over 4
10645:
10646: =item *
10647:
1.957 raeburn 10648: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10649: user for the level given by URL. Optional start and end dates (leave empty
10650: string or zero for "no date")
1.191 harris41 10651:
10652: =item *
10653:
1.243 albertel 10654: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10655: change a users, password, possible return values are: ok,
10656: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10657: refused
1.191 harris41 10658:
10659: =item *
10660:
1.243 albertel 10661: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10662:
10663: =item *
10664:
1.1058 raeburn 10665: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10666: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10667:
10668: will update user information (firstname,middlename,lastname,generation,
10669: permanentemail), and if forceid is true, student/employee ID also.
10670: A user's institutional affiliation(s) can also be updated.
10671: User information fields will not be overwritten with empty entries
10672: unless the field is included in the $candelete array reference.
10673: This array is included when a single user is modified via "Manage Users",
10674: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10675:
10676: =item *
10677:
1.286 matthew 10678: modifystudent
10679:
1.957 raeburn 10680: modify a student's enrollment and identification information.
1.286 matthew 10681: The course id is resolved based on the current users environment.
10682: This means the envoking user must be a course coordinator or otherwise
10683: associated with a course.
10684:
1.297 matthew 10685: This call is essentially a wrapper for lonnet::modifyuser and
10686: lonnet::modify_student_enrollment
1.286 matthew 10687:
10688: Inputs:
10689:
10690: =over 4
10691:
1.957 raeburn 10692: =item B<$udom> Student's loncapa domain
1.286 matthew 10693:
1.957 raeburn 10694: =item B<$uname> Student's loncapa login name
1.286 matthew 10695:
1.964 bisitz 10696: =item B<$uid> Student/Employee ID
1.286 matthew 10697:
1.957 raeburn 10698: =item B<$umode> Student's authentication mode
1.286 matthew 10699:
1.957 raeburn 10700: =item B<$upass> Student's password
1.286 matthew 10701:
1.957 raeburn 10702: =item B<$first> Student's first name
1.286 matthew 10703:
1.957 raeburn 10704: =item B<$middle> Student's middle name
1.286 matthew 10705:
1.957 raeburn 10706: =item B<$last> Student's last name
1.286 matthew 10707:
1.957 raeburn 10708: =item B<$gene> Student's generation
1.286 matthew 10709:
1.957 raeburn 10710: =item B<$usec> Student's section in course
1.286 matthew 10711:
10712: =item B<$end> Unix time of the roles expiration
10713:
10714: =item B<$start> Unix time of the roles start date
10715:
10716: =item B<$forceid> If defined, allow $uid to be changed
10717:
10718: =item B<$desiredhome> server to use as home server for student
10719:
1.957 raeburn 10720: =item B<$email> Student's permanent e-mail address
10721:
10722: =item B<$type> Type of enrollment (auto or manual)
10723:
1.963 raeburn 10724: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10725:
10726: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10727:
1.963 raeburn 10728: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10729:
1.963 raeburn 10730: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10731:
1.963 raeburn 10732: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10733:
1.286 matthew 10734: =back
1.297 matthew 10735:
10736: =item *
10737:
10738: modify_student_enrollment
10739:
10740: Change a students enrollment status in a class. The environment variable
10741: 'role.request.course' must be defined for this function to proceed.
10742:
10743: Inputs:
10744:
10745: =over 4
10746:
10747: =item $udom, students domain
10748:
10749: =item $uname, students name
10750:
10751: =item $uid, students user id
10752:
10753: =item $first, students first name
10754:
10755: =item $middle
10756:
10757: =item $last
10758:
10759: =item $gene
10760:
10761: =item $usec
10762:
10763: =item $end
10764:
10765: =item $start
10766:
1.957 raeburn 10767: =item $type
10768:
10769: =item $locktype
10770:
10771: =item $cid
10772:
10773: =item $selfenroll
10774:
10775: =item $context
10776:
1.297 matthew 10777: =back
10778:
1.191 harris41 10779:
10780: =item *
10781:
1.243 albertel 10782: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10783: custom role; give a custom role to a user for the level given by URL. Specify
10784: name and domain of role author, and role name
1.191 harris41 10785:
10786: =item *
10787:
1.243 albertel 10788: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10789:
10790: =item *
10791:
1.243 albertel 10792: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10793:
10794: =back
10795:
10796: =head2 Course Infomation
10797:
10798: =over 4
1.191 harris41 10799:
10800: =item *
10801:
1.631 albertel 10802: coursedescription($courseid) : returns a hash of information about the
10803: specified course id, including all environment settings for the
10804: course, the description of the course will be in the hash under the
10805: key 'description'
1.191 harris41 10806:
10807: =item *
10808:
1.624 albertel 10809: resdata($name,$domain,$type,@which) : request for current parameter
10810: setting for a specific $type, where $type is either 'course' or 'user',
10811: @what should be a list of parameters to ask about. This routine caches
10812: answers for 5 minutes.
1.243 albertel 10813:
1.877 foxr 10814: =item *
10815:
10816: get_courseresdata($courseid, $domain) : dump the entire course resource
10817: data base, returning a hash that is keyed by the resource name and has
10818: values that are the resource value. I believe that the timestamps and
10819: versions are also returned.
10820:
10821:
1.243 albertel 10822: =back
10823:
10824: =head2 Course Modification
10825:
10826: =over 4
1.191 harris41 10827:
10828: =item *
10829:
1.243 albertel 10830: writecoursepref($courseid,%prefs) : write preferences (environment
10831: database) for a course
1.191 harris41 10832:
10833: =item *
10834:
1.1011 raeburn 10835: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10836:
10837: =item *
10838:
1.1038 raeburn 10839: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10840:
10841: =back
10842:
10843: =head2 Resource Subroutines
10844:
10845: =over 4
1.191 harris41 10846:
10847: =item *
10848:
1.243 albertel 10849: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10850:
10851: =item *
10852:
1.243 albertel 10853: repcopy($filename) : subscribes to the requested file, and attempts to
10854: replicate from the owning library server, Might return
1.607 raeburn 10855: 'unavailable', 'not_found', 'forbidden', 'ok', or
10856: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10857: resource. Expects the local filesystem pathname
10858: (/home/httpd/html/res/....)
10859:
10860: =back
10861:
10862: =head2 Resource Information
10863:
10864: =over 4
1.191 harris41 10865:
10866: =item *
10867:
1.243 albertel 10868: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10869: a vairety of different possible values, $varname should be a request
10870: string, and the other parameters can be used to specify who and what
10871: one is asking about.
10872:
10873: Possible values for $varname are environment.lastname (or other item
10874: from the envirnment hash), user.name (or someother aspect about the
10875: user), resource.0.maxtries (or some other part and parameter of a
10876: resource)
1.204 albertel 10877:
10878: =item *
10879:
1.243 albertel 10880: directcondval($number) : get current value of a condition; reads from a state
10881: string
1.204 albertel 10882:
10883: =item *
10884:
1.243 albertel 10885: condval($condidx) : value of condition index based on state
1.204 albertel 10886:
10887: =item *
10888:
1.243 albertel 10889: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10890: resource's metadata, $what should be either a specific key, or either
10891: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10892: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10893:
10894: this function automatically caches all requests
1.191 harris41 10895:
10896: =item *
10897:
1.243 albertel 10898: metadata_query($query,$custom,$customshow) : make a metadata query against the
10899: network of library servers; returns file handle of where SQL and regex results
10900: will be stored for query
1.191 harris41 10901:
10902: =item *
10903:
1.243 albertel 10904: symbread($filename) : return symbolic list entry (filename argument optional);
10905: returns the data handle
1.191 harris41 10906:
10907: =item *
10908:
1.243 albertel 10909: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 10910: a possible symb for the URL in $thisfn, and if is an encryypted
10911: resource that the user accessed using /enc/ returns a 1 on success, 0
10912: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 10913: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 10914:
1.191 harris41 10915:
10916: =item *
10917:
1.243 albertel 10918: symbclean($symb) : removes versions numbers from a symb, returns the
10919: cleaned symb
1.191 harris41 10920:
10921: =item *
10922:
1.243 albertel 10923: is_on_map($uri) : checks if the $uri is somewhere on the current
10924: course map, user must be in a course for it to work.
1.191 harris41 10925:
10926: =item *
10927:
1.243 albertel 10928: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 10929:
10930: =item *
10931:
1.243 albertel 10932: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10933: a random seed, all arguments are optional, if they aren't sent it uses the
10934: environment to derive them. Note: if symb isn't sent and it can't get one
10935: from &symbread it will use the current time as its return value
1.191 harris41 10936:
10937: =item *
10938:
1.243 albertel 10939: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10940: unfakeable, receipt
1.191 harris41 10941:
10942: =item *
10943:
1.620 albertel 10944: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 10945:
10946: =item *
10947:
1.243 albertel 10948: countacc($url) : count the number of accesses to a given URL
1.191 harris41 10949:
10950: =item *
10951:
1.243 albertel 10952: 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
1.191 harris41 10953:
10954: =item *
10955:
1.243 albertel 10956: 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)
1.191 harris41 10957:
10958: =item *
10959:
1.243 albertel 10960: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 10961:
10962: =item *
10963:
1.243 albertel 10964: devalidate($symb) : devalidate temporary spreadsheet calculations,
10965: forcing spreadsheet to reevaluate the resource scores next time.
10966:
10967: =back
10968:
10969: =head2 Storing/Retreiving Data
10970:
10971: =over 4
1.191 harris41 10972:
10973: =item *
10974:
1.243 albertel 10975: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10976: for this url; hashref needs to be given and should be a \%hashname; the
10977: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 10978: be derived from the env
1.191 harris41 10979:
10980: =item *
10981:
1.243 albertel 10982: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10983: uses critical subroutine
1.191 harris41 10984:
10985: =item *
10986:
1.243 albertel 10987: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10988: all args are optional
1.191 harris41 10989:
10990: =item *
10991:
1.717 albertel 10992: dumpstore($namespace,$udom,$uname,$regexp,$range) :
10993: dumps the complete (or key matching regexp) namespace into a hash
10994: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10995: normally &store()ed into
10996:
10997: $range should be either an integer '100' (give me the first 100
10998: matching records)
10999: or be two integers sperated by a - with no spaces
11000: '30-50' (give me the 30th through the 50th matching
11001: records)
11002:
11003:
11004: =item *
11005:
11006: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11007: replaces a &store() version of data with a replacement set of data
11008: for a particular resource in a namespace passed in the $storehash hash
11009: reference
11010:
11011: =item *
11012:
1.243 albertel 11013: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11014: works very similar to store/cstore, but all data is stored in a
11015: temporary location and can be reset using tmpreset, $storehash should
11016: be a hash reference, returns nothing on success
1.191 harris41 11017:
11018: =item *
11019:
1.243 albertel 11020: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11021: similar to restore, but all data is stored in a temporary location and
11022: can be reset using tmpreset. Returns a hash of values on success,
11023: error string otherwise.
1.191 harris41 11024:
11025: =item *
11026:
1.243 albertel 11027: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11028: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11029:
11030: =item *
11031:
1.243 albertel 11032: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11033: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11034:
11035: =item *
11036:
1.243 albertel 11037: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11038: namesp ($udom and $uname are optional)
1.191 harris41 11039:
11040: =item *
11041:
1.702 albertel 11042: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11043: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11044: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11045:
1.702 albertel 11046: $range should be either an integer '100' (give me the first 100
11047: matching records)
11048: or be two integers sperated by a - with no spaces
11049: '30-50' (give me the 30th through the 50th matching
11050: records)
1.449 matthew 11051: =item *
11052:
11053: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11054: $store can be a scalar, an array reference, or if the amount to be
11055: incremented is > 1, a hash reference.
11056:
11057: ($udom and $uname are optional)
1.191 harris41 11058:
11059: =item *
11060:
1.243 albertel 11061: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11062: ($udom and $uname are optional)
1.191 harris41 11063:
11064: =item *
11065:
1.243 albertel 11066: cput($namespace,$storehash,$udom,$uname) : critical put
11067: ($udom and $uname are optional)
1.191 harris41 11068:
11069: =item *
11070:
1.748 albertel 11071: newput($namespace,$storehash,$udom,$uname) :
11072:
11073: Attempts to store the items in the $storehash, but only if they don't
11074: currently exist, if this succeeds you can be certain that you have
11075: successfully created a new key value pair in the $namespace db.
11076:
11077:
11078: Args:
11079: $namespace: name of database to store values to
11080: $storehash: hashref to store to the db
11081: $udom: (optional) domain of user containing the db
11082: $uname: (optional) name of user caontaining the db
11083:
11084: Returns:
11085: 'ok' -> succeeded in storing all keys of $storehash
11086: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11087: least <key> already existed in the db (other
11088: requested keys may also already exist)
1.967 bisitz 11089: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11090: 'con_lost' -> unable to contact request server
11091: 'refused' -> action was not allowed by remote machine
11092:
11093:
11094: =item *
11095:
1.243 albertel 11096: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11097: reference filled in from namesp (encrypts the return communication)
11098: ($udom and $uname are optional)
1.191 harris41 11099:
11100: =item *
11101:
1.243 albertel 11102: log($udom,$name,$home,$message) : write to permanent log for user; use
11103: critical subroutine
11104:
1.806 raeburn 11105: =item *
11106:
1.860 raeburn 11107: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11108: array reference filled in from namespace found in domain level on either
11109: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11110:
11111: =item *
11112:
1.860 raeburn 11113: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11114: domain level either on specified domain server ($uhome) or primary domain
11115: server ($udom and $uhome are optional)
1.806 raeburn 11116:
1.943 raeburn 11117: =item *
11118:
11119: get_domain_defaults($target_domain) : returns hash with defaults for
11120: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11121: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11122: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11123: Values are retrieved from cache (if current), or from domain's configuration.db
11124: (if available), or lastly from values in lonTabs/dns_domain,tab,
11125: or lonTabs/domain.tab.
11126:
11127: %domdefaults = &get_auth_defaults($target_domain);
11128:
1.243 albertel 11129: =back
11130:
11131: =head2 Network Status Functions
11132:
11133: =over 4
1.191 harris41 11134:
11135: =item *
11136:
11137: dirlist($uri) : return directory list based on URI
11138:
11139: =item *
11140:
1.243 albertel 11141: spareserver() : find server with least workload from spare.tab
11142:
1.986 foxr 11143:
11144: =item *
11145:
11146: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11147: if there is no corresponding loncapa host.
11148:
1.243 albertel 11149: =back
11150:
1.986 foxr 11151:
1.243 albertel 11152: =head2 Apache Request
11153:
11154: =over 4
1.191 harris41 11155:
11156: =item *
11157:
1.243 albertel 11158: ssi($url,%hash) : server side include, does a complete request cycle on url to
11159: localhost, posts hash
11160:
11161: =back
11162:
11163: =head2 Data to String to Data
11164:
11165: =over 4
1.191 harris41 11166:
11167: =item *
11168:
1.243 albertel 11169: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11170: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11171:
11172: =item *
11173:
1.243 albertel 11174: hashref2str($hashref) : convert a hashref into a string complete with
11175: escaping and '=' and '&' separators, supports elements that are
11176: arrayrefs and hashrefs
1.191 harris41 11177:
11178: =item *
11179:
1.243 albertel 11180: arrayref2str($arrayref) : convert an arrayref into a string complete
11181: with escaping and '&' separators, supports elements that are arrayrefs
11182: and hashrefs
1.191 harris41 11183:
11184: =item *
11185:
1.243 albertel 11186: str2hash($string) : convert string to hash using unescaping and
11187: splitting on '=' and '&', supports elements that are arrayrefs and
11188: hashrefs
1.191 harris41 11189:
11190: =item *
11191:
1.243 albertel 11192: str2array($string) : convert string to hash using unescaping and
11193: splitting on '&', supports elements that are arrayrefs and hashrefs
11194:
11195: =back
11196:
11197: =head2 Logging Routines
11198:
11199: =over 4
11200:
11201: These routines allow one to make log messages in the lonnet.log and
11202: lonnet.perm logfiles.
1.191 harris41 11203:
11204: =item *
11205:
1.243 albertel 11206: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11207:
11208: =item *
11209:
1.243 albertel 11210: logthis() : append message to the normal lonnet.log file, it gets
11211: preiodically rolled over and deleted.
1.191 harris41 11212:
11213: =item *
11214:
1.243 albertel 11215: logperm() : append a permanent message to lonnet.perm.log, this log
11216: file never gets deleted by any automated portion of the system, only
11217: messages of critical importance should go in here.
11218:
11219: =back
11220:
11221: =head2 General File Helper Routines
11222:
11223: =over 4
1.191 harris41 11224:
11225: =item *
11226:
1.481 raeburn 11227: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11228: (a) files in /uploaded
11229: (i) If a local copy of the file exists -
11230: compares modification date of local copy with last-modified date for
11231: definitive version stored on home server for course. If local copy is
11232: stale, requests a new version from the home server and stores it.
11233: If the original has been removed from the home server, then local copy
11234: is unlinked.
11235: (ii) If local copy does not exist -
11236: requests the file from the home server and stores it.
11237:
11238: If $caller is 'uploadrep':
11239: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11240: for request for files originally uploaded via DOCS.
11241: - returns 'ok' if fresh local copy now available, -1 otherwise.
11242:
11243: Otherwise:
11244: This indicates a call from the content generation phase of the request.
11245: - returns the entire contents of the file or -1.
11246:
11247: (b) files in /res
11248: - returns the entire contents of a file or -1;
11249: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11250:
1.712 albertel 11251:
11252: =item *
11253:
11254: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11255: reference
11256:
11257: returns either a stat() list of data about the file or an empty list
11258: if the file doesn't exist or couldn't find out about it (connection
11259: problems or user unknown)
11260:
1.191 harris41 11261: =item *
11262:
1.243 albertel 11263: filelocation($dir,$file) : returns file system location of a file
11264: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11265: directory that relative $file lookups are to looked in ($dir of /a/dir
11266: and a file of ../bob will become /a/bob)
1.191 harris41 11267:
11268: =item *
11269:
11270: hreflocation($dir,$file) : returns file system location or a URL; same as
11271: filelocation except for hrefs
11272:
11273: =item *
11274:
11275: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11276:
1.243 albertel 11277: =back
11278:
1.608 albertel 11279: =head2 Usererfile file routines (/uploaded*)
11280:
11281: =over 4
11282:
11283: =item *
11284:
11285: userfileupload(): main rotine for putting a file in a user or course's
11286: filespace, arguments are,
11287:
1.620 albertel 11288: formname - required - this is the name of the element in $env where the
1.608 albertel 11289: filename, and the contents of the file to create/modifed exist
1.620 albertel 11290: the filename is in $env{'form.'.$formname.'.filename'} and the
11291: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 11292: coursedoc - if true, store the file in the course of the active role
11293: of the current user
11294: subdir - required - subdirectory to put the file in under ../userfiles/
11295: if undefined, it will be placed in "unknown"
11296:
11297: (This routine calls clean_filename() to remove any dangerous
11298: characters from the filename, and then calls finuserfileupload() to
11299: complete the transaction)
11300:
11301: returns either the url of the uploaded file (/uploaded/....) if successful
11302: and /adm/notfound.html if unsuccessful
11303:
11304: =item *
11305:
11306: clean_filename(): routine for cleaing a filename up for storage in
11307: userfile space, argument is:
11308:
11309: filename - proposed filename
11310:
11311: returns: the new clean filename
11312:
11313: =item *
11314:
11315: finishuserfileupload(): routine that creaes and sends the file to
11316: userspace, probably shouldn't be called directly
11317:
11318: docuname: username or courseid of destination for the file
11319: docudom: domain of user/course of destination for the file
11320: formname: same as for userfileupload()
11321: fname: filename (inculding subdirectories) for the file
11322:
11323: returns either the url of the uploaded file (/uploaded/....) if successful
11324: and /adm/notfound.html if unsuccessful
11325:
11326: =item *
11327:
11328: renameuserfile(): renames an existing userfile to a new name
11329:
11330: Args:
11331: docuname: username or courseid of destination for the file
11332: docudom: domain of user/course of destination for the file
11333: old: current file name (including any subdirs under userfiles)
11334: new: desired file name (including any subdirs under userfiles)
11335:
11336: =item *
11337:
11338: mkdiruserfile(): creates a directory is a userfiles dir
11339:
11340: Args:
11341: docuname: username or courseid of destination for the file
11342: docudom: domain of user/course of destination for the file
11343: dir: dir to create (including any subdirs under userfiles)
11344:
11345: =item *
11346:
11347: removeuserfile(): removes a file that exists in userfiles
11348:
11349: Args:
11350: docuname: username or courseid of destination for the file
11351: docudom: domain of user/course of destination for the file
11352: fname: filname to delete (including any subdirs under userfiles)
11353:
11354: =item *
11355:
11356: removeuploadedurl(): convience function for removeuserfile()
11357:
11358: Args:
11359: url: a full /uploaded/... url to delete
11360:
1.747 albertel 11361: =item *
11362:
11363: get_portfile_permissions():
11364: Args:
11365: domain: domain of user or course contain the portfolio files
11366: user: name of user or num of course contain the portfolio files
11367: Returns:
11368: hashref of a dump of the proper file_permissions.db
11369:
11370:
11371: =item *
11372:
11373: get_access_controls():
11374:
11375: Args:
11376: current_permissions: the hash ref returned from get_portfile_permissions()
11377: group: (optional) the group you want the files associated with
11378: file: (optional) the file you want access info on
11379:
11380: Returns:
1.749 raeburn 11381: a hash (keys are file names) of hashes containing
11382: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11383: values are XML containing access control settings (see below)
1.747 albertel 11384:
11385: Internal notes:
11386:
1.749 raeburn 11387: access controls are stored in file_permissions.db as key=value pairs.
11388: key -> path to file/file_name\0uniqueID:scope_end_start
11389: where scope -> public,guest,course,group,domains or users.
11390: end -> UNIX time for end of access (0 -> no end date)
11391: start -> UNIX time for start of access
11392:
11393: value -> XML description of access control
11394: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11395: <start></start>
11396: <end></end>
11397:
11398: <password></password> for scope type = guest
11399:
11400: <domain></domain> for scope type = course or group
11401: <number></number>
11402: <roles id="">
11403: <role></role>
11404: <access></access>
11405: <section></section>
11406: <group></group>
11407: </roles>
11408:
11409: <dom></dom> for scope type = domains
11410:
11411: <users> for scope type = users
11412: <user>
11413: <uname></uname>
11414: <udom></udom>
11415: </user>
11416: </users>
11417: </scope>
11418:
11419: Access data is also aggregated for each file in an additional key=value pair:
11420: key -> path to file/file_name\0accesscontrol
11421: value -> reference to hash
11422: hash contains key = value pairs
11423: where key = uniqueID:scope_end_start
11424: value = UNIX time record was last updated
11425:
11426: Used to improve speed of look-ups of access controls for each file.
11427:
11428: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11429:
11430: modify_access_controls():
11431:
11432: Modifies access controls for a portfolio file
11433: Args
11434: 1. file name
11435: 2. reference to hash of required changes,
11436: 3. domain
11437: 4. username
11438: where domain,username are the domain of the portfolio owner
11439: (either a user or a course)
11440:
11441: Returns:
11442: 1. result of additions or updates ('ok' or 'error', with error message).
11443: 2. result of deletions ('ok' or 'error', with error message).
11444: 3. reference to hash of any new or updated access controls.
11445: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11446: key = integer (inbound ID)
11447: value = uniqueID
1.747 albertel 11448:
1.608 albertel 11449: =back
11450:
1.243 albertel 11451: =head2 HTTP Helper Routines
11452:
11453: =over 4
11454:
1.191 harris41 11455: =item *
11456:
11457: escape() : unpack non-word characters into CGI-compatible hex codes
11458:
11459: =item *
11460:
11461: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11462:
1.243 albertel 11463: =back
11464:
11465: =head1 PRIVATE SUBROUTINES
11466:
11467: =head2 Underlying communication routines (Shouldn't call)
11468:
11469: =over 4
11470:
11471: =item *
11472:
11473: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11474:
11475: =item *
11476:
11477: reply() : uses subreply to send a message to remote machine, logs all failures
11478:
11479: =item *
11480:
11481: critical() : passes a critical message to another server; if cannot
11482: get through then place message in connection buffer directory and
11483: returns con_delayed, if incapable of saving message, returns
11484: con_failed
11485:
11486: =item *
11487:
11488: reconlonc() : tries to reconnect lonc client processes.
11489:
11490: =back
11491:
11492: =head2 Resource Access Logging
11493:
11494: =over 4
11495:
11496: =item *
11497:
11498: flushcourselogs() : flush (save) buffer logs and access logs
11499:
11500: =item *
11501:
11502: courselog($what) : save message for course in hash
11503:
11504: =item *
11505:
11506: courseacclog($what) : save message for course using &courselog(). Perform
11507: special processing for specific resource types (problems, exams, quizzes, etc).
11508:
1.191 harris41 11509: =item *
11510:
11511: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11512: as a PerlChildExitHandler
1.243 albertel 11513:
11514: =back
11515:
11516: =head2 Other
11517:
11518: =over 4
11519:
11520: =item *
11521:
11522: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11523:
11524: =back
11525:
11526: =cut
1.877 foxr 11527:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>