Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1056.4.8
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1056.4.8! raeburn 4: # $Id: lonnet.pm,v 1.1056.4.7 2010/08/18 12:22:39 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.1056.4.5 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.1056.4.3 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.1056.4.3 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.1056.4.7 raeburn 225: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3 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.1056.4.8! raeburn 233: $ua->timeout(4);
1.1056.4.3 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.1056.4.7 raeburn 241: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1056.4.3 raeburn 242: $loncaparev = $1;
243: }
244: }
245: } else {
246: $loncaparev = $loncaparevs{$lonhost};
247: }
1.1056.4.7 raeburn 248: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3 raeburn 249: $loncaparev = $1;
250: }
251: }
252: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
253: }
254: }
255:
256: sub get_server_homeID {
257: my ($hostname,$ignore_cache,$caller) = @_;
258: unless ($ignore_cache) {
259: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
1.993 raeburn 260: if (defined($cached)) {
1.1056.4.3 raeburn 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: }
1.993 raeburn 274: }
1.1056.4.3 raeburn 275: if ($serverhomeID eq '') {
276: $serverhomeID = $machine_ids[-1];
277: }
278: } else {
279: $serverhomeID = $serverhomeIDs{$hostname};
1.993 raeburn 280: }
1.1056.4.3 raeburn 281: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
1.993 raeburn 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:
727: # ------------------------------------------ Fight off request when overloaded
728:
729: sub overloaderror {
730: my ($r,$checkserver)=@_;
731: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
732: my $loadavg;
733: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 734: open(my $loadfile,'/proc/loadavg');
1.283 www 735: $loadavg=<$loadfile>;
736: $loadavg =~ s/\s.*//g;
1.285 matthew 737: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 738: close($loadfile);
1.283 www 739: } else {
740: $loadavg=&reply('load',$checkserver);
741: }
1.285 matthew 742: my $overload=$loadavg-100;
1.283 www 743: if ($overload>0) {
1.285 matthew 744: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 745: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 746: return 413;
1.283 www 747: }
748: return '';
1.5 www 749: }
1.1 albertel 750:
751: # ------------------------------ Find server with least workload from spare.tab
1.11 www 752:
1.1 albertel 753: sub spareserver {
1.670 albertel 754: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 755: my $spare_server;
1.370 albertel 756: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 757: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
758: : $userloadpercent;
1.1056.4.8! raeburn 759: my ($uint_dom,$remotesessions);
! 760: if ($env{'user.domain'}) {
! 761: my $uprimary_id = &Apache::lonnet::domain($env{'user.domain'},'primary');
! 762: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
! 763: my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
! 764: $remotesessions = $udomdefaults{'remotesessions'};
! 765: }
1.784 albertel 766: foreach my $try_server (@{ $spareid{'primary'} }) {
1.1056.4.8! raeburn 767: if ($uint_dom) {
! 768: next unless (&spare_can_host($env{'user.domain'},$uint_dom,
! 769: $remotesessions,$try_server));
! 770: }
1.784 albertel 771: ($spare_server, $lowest_load) =
772: &compare_server_load($try_server, $spare_server, $lowest_load);
773: }
774:
775: my $found_server = ($spare_server ne '' && $lowest_load < 100);
776:
777: if (!$found_server) {
778: foreach my $try_server (@{ $spareid{'default'} }) {
1.1056.4.8! raeburn 779: if ($uint_dom) {
! 780: next unless (&spare_can_host($env{'user.domain'},$uint_dom,
! 781: $remotesessions,$try_server));
! 782: }
1.784 albertel 783: ($spare_server, $lowest_load) =
784: &compare_server_load($try_server, $spare_server, $lowest_load);
785: }
786: }
787:
788: if (!$want_server_name) {
1.968 raeburn 789: my $protocol = 'http';
790: if ($protocol{$spare_server} eq 'https') {
791: $protocol = $protocol{$spare_server};
792: }
1.1001 raeburn 793: if (defined($spare_server)) {
794: my $hostname = &hostname($spare_server);
1.1056.4.8! raeburn 795: if (defined($hostname)) {
1.1001 raeburn 796: $spare_server = $protocol.'://'.$hostname;
797: }
798: }
1.784 albertel 799: }
800: return $spare_server;
801: }
802:
803: sub compare_server_load {
804: my ($try_server, $spare_server, $lowest_load) = @_;
805:
806: my $loadans = &reply('load', $try_server);
807: my $userloadans = &reply('userload',$try_server);
808:
809: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1056.4.3 raeburn 810: return; #didn't get a number from the server
1.784 albertel 811: }
812:
813: my $load;
814: if ($loadans =~ /\d/) {
815: if ($userloadans =~ /\d/) {
816: #both are numbers, pick the bigger one
817: $load = ($loadans > $userloadans) ? $loadans
818: : $userloadans;
1.411 albertel 819: } else {
1.784 albertel 820: $load = $loadans;
1.411 albertel 821: }
1.784 albertel 822: } else {
823: $load = $userloadans;
824: }
825:
826: if (($load =~ /\d/) && ($load < $lowest_load)) {
827: $spare_server = $try_server;
828: $lowest_load = $load;
1.370 albertel 829: }
1.784 albertel 830: return ($spare_server,$lowest_load);
1.202 matthew 831: }
1.914 albertel 832:
833: # --------------------------- ask offload servers if user already has a session
834: sub find_existing_session {
835: my ($udom,$uname) = @_;
836: foreach my $try_server (@{ $spareid{'primary'} },
837: @{ $spareid{'default'} }) {
838: return $try_server if (&has_user_session($try_server, $udom, $uname));
839: }
840: return;
841: }
842:
843: # -------------------------------- ask if server already has a session for user
844: sub has_user_session {
845: my ($lonid,$udom,$uname) = @_;
846: my $result = &reply(join(':','userhassession',
847: map {&escape($_)} ($udom,$uname)),$lonid);
848: return 1 if ($result eq 'ok');
849:
850: return 0;
851: }
852:
1.1056.4.3 raeburn 853: # --------- determine least loaded server in a user's domain which allows login
854:
855: sub choose_server {
856: my ($udom) = @_;
857: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
858: my %servers = &get_servers($udom);
859: my $lowest_load = 30000;
860: my ($login_host,$hostname);
861: foreach my $lonhost (keys(%servers)) {
862: my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
863: if ($loginvia eq '') {
864: ($login_host, $lowest_load) =
865: &compare_server_load($lonhost, $login_host, $lowest_load);
866: }
867: }
868: if ($login_host ne '') {
869: $hostname = $servers{$login_host};
870: }
871: return ($login_host,$hostname);
872: }
873:
1.202 matthew 874: # --------------------------------------------- Try to change a user's password
875:
876: sub changepass {
1.799 raeburn 877: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 878: $currentpass = &escape($currentpass);
879: $newpass = &escape($newpass);
1.1030 raeburn 880: my $lonhost = $perlvar{'lonHostID'};
881: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 882: $server);
883: if (! $answer) {
884: &logthis("No reply on password change request to $server ".
885: "by $uname in domain $udom.");
886: } elsif ($answer =~ "^ok") {
887: &logthis("$uname in $udom successfully changed their password ".
888: "on $server.");
889: } elsif ($answer =~ "^pwchange_failure") {
890: &logthis("$uname in $udom was unable to change their password ".
891: "on $server. The action was blocked by either lcpasswd ".
892: "or pwchange");
893: } elsif ($answer =~ "^non_authorized") {
894: &logthis("$uname in $udom did not get their password correct when ".
895: "attempting to change it on $server.");
896: } elsif ($answer =~ "^auth_mode_error") {
897: &logthis("$uname in $udom attempted to change their password despite ".
898: "not being locally or internally authenticated on $server.");
899: } elsif ($answer =~ "^unknown_user") {
900: &logthis("$uname in $udom attempted to change their password ".
901: "on $server but were unable to because $server is not ".
902: "their home server.");
903: } elsif ($answer =~ "^refused") {
904: &logthis("$server refused to change $uname in $udom password because ".
905: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 906: } elsif ($answer =~ "invalid_client") {
907: &logthis("$server refused to change $uname in $udom password because ".
908: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 909: }
910: return $answer;
1.1 albertel 911: }
912:
1.169 harris41 913: # ----------------------- Try to determine user's current authentication scheme
914:
915: sub queryauthenticate {
916: my ($uname,$udom)=@_;
1.456 albertel 917: my $uhome=&homeserver($uname,$udom);
918: if (!$uhome) {
919: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
920: return 'no_host';
921: }
922: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
923: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
924: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 925: }
1.456 albertel 926: return $answer;
1.169 harris41 927: }
928:
1.1 albertel 929: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 930:
1.1 albertel 931: sub authenticate {
1.1056.4.3 raeburn 932: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 933: $upass=&escape($upass);
934: $uname= &LONCAPA::clean_username($uname);
1.836 www 935: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 936: my $newhome;
1.836 www 937: if ((!$uhome) || ($uhome eq 'no_host')) {
938: # Maybe the machine was offline and only re-appeared again recently?
939: &reconlonc();
940: # One more
1.952 raeburn 941: $uhome=&homeserver($uname,$udom,1);
942: if (($uhome eq 'no_host') && $checkdefauth) {
943: if (defined(&domain($udom,'primary'))) {
944: $newhome=&domain($udom,'primary');
945: }
946: if ($newhome ne '') {
947: $uhome = $newhome;
948: }
949: }
1.836 www 950: if ((!$uhome) || ($uhome eq 'no_host')) {
951: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 952: return 'no_host';
953: }
1.1 albertel 954: }
1.1056.4.3 raeburn 955: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 956: if ($answer eq 'authorized') {
1.952 raeburn 957: if ($newhome) {
958: &logthis("User $uname at $udom authorized by $uhome, but needs account");
959: return 'no_account_on_host';
960: } else {
961: &logthis("User $uname at $udom authorized by $uhome");
962: return $uhome;
963: }
1.471 albertel 964: }
965: if ($answer eq 'non_authorized') {
966: &logthis("User $uname at $udom rejected by $uhome");
967: return 'no_host';
1.9 www 968: }
1.471 albertel 969: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 970: return 'no_host';
971: }
972:
1.1056.4.3 raeburn 973: sub can_host_session {
974: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
975: my $canhost = 1;
976: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
977: if (ref($remotesessions) eq 'HASH') {
978: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
979: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
980: $canhost = 0;
981: } else {
982: $canhost = 1;
983: }
984: }
985: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
986: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
987: $canhost = 1;
988: } else {
989: $canhost = 0;
990: }
991: }
992: if ($canhost) {
993: if ($remotesessions->{'version'} ne '') {
994: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
995: if ($reqmajor ne '' && $reqminor ne '') {
996: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
997: my $major = $1;
998: my $minor = $2;
999: if (($major < $reqmajor ) ||
1000: (($major == $reqmajor) && ($minor < $reqminor))) {
1001: $canhost = 0;
1002: }
1003: } else {
1004: $canhost = 0;
1005: }
1006: }
1007: }
1008: }
1009: }
1010: if ($canhost) {
1011: if (ref($hostedsessions) eq 'HASH') {
1012: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1013: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
1014: $canhost = 0;
1015: } else {
1016: $canhost = 1;
1017: }
1018: }
1019: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1020: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
1021: $canhost = 1;
1022: } else {
1023: $canhost = 0;
1024: }
1025: }
1026: }
1027: }
1028: return $canhost;
1029: }
1030:
1.1056.4.8! raeburn 1031: sub spare_can_host {
! 1032: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
! 1033: my $canhost=1;
! 1034: my @intdoms;
! 1035: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
! 1036: if (ref($internet_names) eq 'ARRAY') {
! 1037: @intdoms = @{$internet_names};
! 1038: }
! 1039: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
! 1040: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
! 1041: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
! 1042: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
! 1043: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
! 1044: $canhost = &can_host_session($udom,$try_server,$remoterev,
! 1045: $remotesessions,
! 1046: $defdomdefaults{'hostedsessions'});
! 1047: }
! 1048: return $canhost;
! 1049: }
! 1050:
1.1 albertel 1051: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1052:
1.599 albertel 1053: my %homecache;
1.1 albertel 1054: sub homeserver {
1.230 stredwic 1055: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1056: my $index="$uname:$udom";
1.426 albertel 1057:
1.599 albertel 1058: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1059:
1060: my %servers = &get_servers($udom,'library');
1061: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1062: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1063: exists($badServerCache{$tryserver}));
1.841 albertel 1064:
1065: my $answer=reply("home:$udom:$uname",$tryserver);
1066: if ($answer eq 'found') {
1067: delete($badServerCache{$tryserver});
1068: return $homecache{$index}=$tryserver;
1069: } elsif ($answer eq 'no_host') {
1070: $badServerCache{$tryserver}=1;
1071: }
1.1 albertel 1072: }
1073: return 'no_host';
1.70 www 1074: }
1075:
1076: # ------------------------------------- Find the usernames behind a list of IDs
1077:
1078: sub idget {
1079: my ($udom,@ids)=@_;
1080: my %returnhash=();
1081:
1.841 albertel 1082: my %servers = &get_servers($udom,'library');
1083: foreach my $tryserver (keys(%servers)) {
1084: my $idlist=join('&',@ids);
1085: $idlist=~tr/A-Z/a-z/;
1086: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1087: my @answer=();
1088: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1089: @answer=split(/\&/,$reply);
1090: } ;
1091: my $i;
1092: for ($i=0;$i<=$#ids;$i++) {
1093: if ($answer[$i]) {
1094: $returnhash{$ids[$i]}=$answer[$i];
1095: }
1096: }
1097: }
1.70 www 1098: return %returnhash;
1099: }
1100:
1101: # ------------------------------------- Find the IDs behind a list of usernames
1102:
1103: sub idrget {
1104: my ($udom,@unames)=@_;
1105: my %returnhash=();
1.800 albertel 1106: foreach my $uname (@unames) {
1107: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1108: }
1.70 www 1109: return %returnhash;
1110: }
1111:
1112: # ------------------------------- Store away a list of names and associated IDs
1113:
1114: sub idput {
1115: my ($udom,%ids)=@_;
1116: my %servers=();
1.800 albertel 1117: foreach my $uname (keys(%ids)) {
1118: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1119: my $uhom=&homeserver($uname,$udom);
1.70 www 1120: if ($uhom ne 'no_host') {
1.800 albertel 1121: my $id=&escape($ids{$uname});
1.70 www 1122: $id=~tr/A-Z/a-z/;
1.800 albertel 1123: my $esc_unam=&escape($uname);
1.70 www 1124: if ($servers{$uhom}) {
1.800 albertel 1125: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1126: } else {
1.800 albertel 1127: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1128: }
1129: }
1.191 harris41 1130: }
1.800 albertel 1131: foreach my $server (keys(%servers)) {
1132: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1133: }
1.344 www 1134: }
1135:
1.1023 raeburn 1136: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1137: sub dump_dom {
1.1023 raeburn 1138: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1139: if (!$udom) {
1140: $udom=$env{'user.domain'};
1141: }
1142: my %returnhash;
1.1023 raeburn 1143: if ($udom) {
1144: my $uname = &get_domainconfiguser($udom);
1145: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1146: }
1147: return %returnhash;
1148: }
1149:
1.1023 raeburn 1150: # ------------------------------------------ get items from domain db files
1.806 raeburn 1151:
1152: sub get_dom {
1.860 raeburn 1153: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1154: my $items='';
1155: foreach my $item (@$storearr) {
1156: $items.=&escape($item).'&';
1157: }
1158: $items=~s/\&$//;
1.860 raeburn 1159: if (!$udom) {
1160: $udom=$env{'user.domain'};
1161: if (defined(&domain($udom,'primary'))) {
1162: $uhome=&domain($udom,'primary');
1163: } else {
1.874 albertel 1164: undef($uhome);
1.860 raeburn 1165: }
1166: } else {
1167: if (!$uhome) {
1168: if (defined(&domain($udom,'primary'))) {
1169: $uhome=&domain($udom,'primary');
1170: }
1171: }
1172: }
1173: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1174: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1175: my %returnhash;
1.875 albertel 1176: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1177: return %returnhash;
1178: }
1.806 raeburn 1179: my @pairs=split(/\&/,$rep);
1180: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1181: return @pairs;
1182: }
1183: my $i=0;
1184: foreach my $item (@$storearr) {
1185: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1186: $i++;
1187: }
1188: return %returnhash;
1189: } else {
1.880 banghart 1190: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1191: }
1192: }
1193:
1194: # -------------------------------------------- put items in domain db files
1195:
1196: sub put_dom {
1.860 raeburn 1197: my ($namespace,$storehash,$udom,$uhome)=@_;
1198: if (!$udom) {
1199: $udom=$env{'user.domain'};
1200: if (defined(&domain($udom,'primary'))) {
1201: $uhome=&domain($udom,'primary');
1202: } else {
1.874 albertel 1203: undef($uhome);
1.860 raeburn 1204: }
1205: } else {
1206: if (!$uhome) {
1207: if (defined(&domain($udom,'primary'))) {
1208: $uhome=&domain($udom,'primary');
1209: }
1210: }
1211: }
1212: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1213: my $items='';
1214: foreach my $item (keys(%$storehash)) {
1215: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1216: }
1217: $items=~s/\&$//;
1218: return &reply("putdom:$udom:$namespace:$items",$uhome);
1219: } else {
1.860 raeburn 1220: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1221: }
1222: }
1223:
1.1023 raeburn 1224: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1225: sub newput_dom {
1.1023 raeburn 1226: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1227: my $result;
1228: if (!$udom) {
1229: $udom=$env{'user.domain'};
1230: }
1.1023 raeburn 1231: if ($udom) {
1232: my $uname = &get_domainconfiguser($udom);
1233: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1234: }
1235: return $result;
1236: }
1237:
1.1023 raeburn 1238: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1239: sub del_dom {
1.1023 raeburn 1240: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1241: if (ref($storearr) eq 'ARRAY') {
1242: if (!$udom) {
1243: $udom=$env{'user.domain'};
1244: }
1.1023 raeburn 1245: if ($udom) {
1246: my $uname = &get_domainconfiguser($udom);
1247: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1248: }
1249: }
1250: }
1251:
1.1023 raeburn 1252: # ----------------------------------construct domainconfig user for a domain
1253: sub get_domainconfiguser {
1254: my ($udom) = @_;
1255: return $udom.'-domainconfig';
1256: }
1257:
1.837 raeburn 1258: sub retrieve_inst_usertypes {
1259: my ($udom) = @_;
1260: my (%returnhash,@order);
1.989 raeburn 1261: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1262: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1263: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1264: %returnhash = %{$domdefs{'inststatustypes'}};
1265: @order = @{$domdefs{'inststatusorder'}};
1266: } else {
1267: if (defined(&domain($udom,'primary'))) {
1268: my $uhome=&domain($udom,'primary');
1269: my $rep=&reply("inst_usertypes:$udom",$uhome);
1270: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1271: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1272: return (\%returnhash,\@order);
1273: }
1274: my ($hashitems,$orderitems) = split(/:/,$rep);
1275: my @pairs=split(/\&/,$hashitems);
1276: foreach my $item (@pairs) {
1277: my ($key,$value)=split(/=/,$item,2);
1278: $key = &unescape($key);
1279: next if ($key =~ /^error: 2 /);
1280: $returnhash{$key}=&thaw_unescape($value);
1281: }
1282: my @esc_order = split(/\&/,$orderitems);
1283: foreach my $item (@esc_order) {
1284: push(@order,&unescape($item));
1285: }
1286: } else {
1287: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1288: }
1289: }
1290: return (\%returnhash,\@order);
1291: }
1292:
1.868 raeburn 1293: sub is_domainimage {
1294: my ($url) = @_;
1295: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1296: if (&domain($1) ne '') {
1297: return '1';
1298: }
1299: }
1300: return;
1301: }
1302:
1.899 raeburn 1303: sub inst_directory_query {
1304: my ($srch) = @_;
1305: my $udom = $srch->{'srchdomain'};
1306: my %results;
1307: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1308: my $outcome;
1.899 raeburn 1309: if ($homeserver ne '') {
1.904 albertel 1310: my $queryid=&reply("querysend:instdirsearch:".
1311: &escape($srch->{'srchby'}).':'.
1312: &escape($srch->{'srchterm'}).':'.
1313: &escape($srch->{'srchtype'}),$homeserver);
1314: my $host=&hostname($homeserver);
1315: if ($queryid !~/^\Q$host\E\_/) {
1316: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1317: return;
1318: }
1319: my $response = &get_query_reply($queryid);
1320: my $maxtries = 5;
1321: my $tries = 1;
1322: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1323: $response = &get_query_reply($queryid);
1324: $tries ++;
1325: }
1326:
1327: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1328: if ($response eq 'unavailable') {
1329: $outcome = $response;
1330: } else {
1331: $outcome = 'ok';
1332: my @matches = split(/\n/,$response);
1333: foreach my $match (@matches) {
1334: my ($key,$value) = split(/=/,$match);
1335: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1336: }
1.899 raeburn 1337: }
1338: }
1339: }
1.909 raeburn 1340: return ($outcome,%results);
1.899 raeburn 1341: }
1342:
1343: sub usersearch {
1344: my ($srch) = @_;
1345: my $dom = $srch->{'srchdomain'};
1346: my %results;
1347: my %libserv = &all_library();
1348: my $query = 'usersearch';
1349: foreach my $tryserver (keys(%libserv)) {
1350: if (&host_domain($tryserver) eq $dom) {
1351: my $host=&hostname($tryserver);
1352: my $queryid=
1.911 raeburn 1353: &reply("querysend:".&escape($query).':'.
1354: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1355: &escape($srch->{'srchtype'}).':'.
1356: &escape($srch->{'srchterm'}),$tryserver);
1357: if ($queryid !~/^\Q$host\E\_/) {
1358: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1359: next;
1.899 raeburn 1360: }
1361: my $reply = &get_query_reply($queryid);
1362: my $maxtries = 1;
1363: my $tries = 1;
1364: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1365: $reply = &get_query_reply($queryid);
1366: $tries ++;
1367: }
1368: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1369: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1370: } else {
1.911 raeburn 1371: my @matches;
1372: if ($reply =~ /\n/) {
1373: @matches = split(/\n/,$reply);
1374: } else {
1375: @matches = split(/\&/,$reply);
1376: }
1.899 raeburn 1377: foreach my $match (@matches) {
1378: my ($uname,$udom,%userhash);
1.911 raeburn 1379: foreach my $entry (split(/:/,$match)) {
1380: my ($key,$value) =
1381: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1382: $userhash{$key} = $value;
1383: if ($key eq 'username') {
1384: $uname = $value;
1385: } elsif ($key eq 'domain') {
1386: $udom = $value;
1.911 raeburn 1387: }
1.899 raeburn 1388: }
1389: $results{$uname.':'.$udom} = \%userhash;
1390: }
1391: }
1392: }
1393: }
1394: return %results;
1395: }
1396:
1.912 raeburn 1397: sub get_instuser {
1398: my ($udom,$uname,$id) = @_;
1399: my $homeserver = &domain($udom,'primary');
1400: my ($outcome,%results);
1401: if ($homeserver ne '') {
1402: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1403: &escape($id).':'.&escape($udom),$homeserver);
1404: my $host=&hostname($homeserver);
1405: if ($queryid !~/^\Q$host\E\_/) {
1406: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1407: return;
1408: }
1409: my $response = &get_query_reply($queryid);
1410: my $maxtries = 5;
1411: my $tries = 1;
1412: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1413: $response = &get_query_reply($queryid);
1414: $tries ++;
1415: }
1416: if (!&error($response) && $response ne 'refused') {
1417: if ($response eq 'unavailable') {
1418: $outcome = $response;
1419: } else {
1420: $outcome = 'ok';
1421: my @matches = split(/\n/,$response);
1422: foreach my $match (@matches) {
1423: my ($key,$value) = split(/=/,$match);
1424: $results{&unescape($key)} = &thaw_unescape($value);
1425: }
1426: }
1427: }
1428: }
1429: my %userinfo;
1430: if (ref($results{$uname}) eq 'HASH') {
1431: %userinfo = %{$results{$uname}};
1432: }
1433: return ($outcome,%userinfo);
1434: }
1435:
1436: sub inst_rulecheck {
1.923 raeburn 1437: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1438: my %returnhash;
1439: if ($udom ne '') {
1440: if (ref($rules) eq 'ARRAY') {
1441: @{$rules} = map {&escape($_);} (@{$rules});
1442: my $rulestr = join(':',@{$rules});
1443: my $homeserver=&domain($udom,'primary');
1444: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1445: my $response;
1446: if ($item eq 'username') {
1447: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1448: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1449: $homeserver));
1.923 raeburn 1450: } elsif ($item eq 'id') {
1451: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1452: ':'.&escape($id).':'.$rulestr,
1453: $homeserver));
1.945 raeburn 1454: } elsif ($item eq 'selfcreate') {
1455: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1456: &escape($udom).':'.&escape($uname).
1457: ':'.$rulestr,$homeserver));
1.923 raeburn 1458: }
1.912 raeburn 1459: if ($response ne 'refused') {
1460: my @pairs=split(/\&/,$response);
1461: foreach my $item (@pairs) {
1462: my ($key,$value)=split(/=/,$item,2);
1463: $key = &unescape($key);
1464: next if ($key =~ /^error: 2 /);
1465: $returnhash{$key}=&thaw_unescape($value);
1466: }
1467: }
1468: }
1469: }
1470: }
1471: return %returnhash;
1472: }
1473:
1474: sub inst_userrules {
1.923 raeburn 1475: my ($udom,$check) = @_;
1.912 raeburn 1476: my (%ruleshash,@ruleorder);
1477: if ($udom ne '') {
1478: my $homeserver=&domain($udom,'primary');
1479: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1480: my $response;
1481: if ($check eq 'id') {
1482: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1483: $homeserver);
1.943 raeburn 1484: } elsif ($check eq 'email') {
1485: $response=&reply('instemailrules:'.&escape($udom),
1486: $homeserver);
1.923 raeburn 1487: } else {
1488: $response=&reply('instuserrules:'.&escape($udom),
1489: $homeserver);
1490: }
1.912 raeburn 1491: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1492: ($response ne 'unknown_cmd') &&
1.912 raeburn 1493: ($response ne 'no_such_host')) {
1494: my ($hashitems,$orderitems) = split(/:/,$response);
1495: my @pairs=split(/\&/,$hashitems);
1496: foreach my $item (@pairs) {
1497: my ($key,$value)=split(/=/,$item,2);
1498: $key = &unescape($key);
1499: next if ($key =~ /^error: 2 /);
1500: $ruleshash{$key}=&thaw_unescape($value);
1501: }
1502: my @esc_order = split(/\&/,$orderitems);
1503: foreach my $item (@esc_order) {
1504: push(@ruleorder,&unescape($item));
1505: }
1506: }
1507: }
1508: }
1509: return (\%ruleshash,\@ruleorder);
1510: }
1511:
1.976 raeburn 1512: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1513:
1514: sub get_domain_defaults {
1515: my ($domain) = @_;
1516: my $cachetime = 60*60*24;
1517: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1518: if (defined($cached)) {
1519: if (ref($result) eq 'HASH') {
1520: return %{$result};
1521: }
1522: }
1523: my %domdefaults;
1524: my %domconfig =
1.989 raeburn 1525: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1526: 'requestcourses','inststatus',
1.1056.4.3 raeburn 1527: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1528: if (ref($domconfig{'defaults'}) eq 'HASH') {
1529: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1530: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1531: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1532: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1533: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1534: } else {
1535: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1536: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1537: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1538: }
1.976 raeburn 1539: if (ref($domconfig{'quotas'}) eq 'HASH') {
1540: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1541: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1542: } else {
1543: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1544: }
1545: my @usertools = ('aboutme','blog','portfolio');
1546: foreach my $item (@usertools) {
1547: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1548: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1549: }
1550: }
1551: }
1.985 raeburn 1552: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1553: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1554: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1555: }
1556: }
1.989 raeburn 1557: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1558: foreach my $item ('inststatustypes','inststatusorder') {
1559: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1560: }
1561: }
1.1047 raeburn 1562: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1563: foreach my $item ('canuse_pdfforms') {
1564: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1565: }
1566: }
1.1056.4.3 raeburn 1567: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1568: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1569: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1570: }
1571: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1572: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1573: }
1574: }
1.943 raeburn 1575: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1576: $cachetime);
1577: return %domdefaults;
1578: }
1579:
1.344 www 1580: # --------------------------------------------------- Assign a key to a student
1581:
1582: sub assign_access_key {
1.364 www 1583: #
1584: # a valid key looks like uname:udom#comments
1585: # comments are being appended
1586: #
1.498 www 1587: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1588: $kdom=
1.620 albertel 1589: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1590: $knum=
1.620 albertel 1591: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1592: $cdom=
1.620 albertel 1593: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1594: $cnum=
1.620 albertel 1595: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1596: $udom=$env{'user.name'} unless (defined($udom));
1597: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1598: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1599: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1600: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1601: # assigned to this person
1602: # - this should not happen,
1.345 www 1603: # unless something went wrong
1604: # the first time around
1605: # ready to assign
1.364 www 1606: $logentry=$1.'; '.$logentry;
1.496 www 1607: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1608: $kdom,$knum) eq 'ok') {
1.345 www 1609: # key now belongs to user
1.346 www 1610: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1611: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1612: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1613: return 'ok';
1614: } else {
1615: return
1616: 'error: Count not permanently assign key, will need to be re-entered later.';
1617: }
1618: } else {
1619: return 'error: Could not assign key, try again later.';
1620: }
1.364 www 1621: } elsif (!$existing{$ckey}) {
1.345 www 1622: # the key does not exist
1623: return 'error: The key does not exist';
1624: } else {
1625: # the key is somebody else's
1626: return 'error: The key is already in use';
1627: }
1.344 www 1628: }
1629:
1.364 www 1630: # ------------------------------------------ put an additional comment on a key
1631:
1632: sub comment_access_key {
1633: #
1634: # a valid key looks like uname:udom#comments
1635: # comments are being appended
1636: #
1637: my ($ckey,$cdom,$cnum,$logentry)=@_;
1638: $cdom=
1.620 albertel 1639: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1640: $cnum=
1.620 albertel 1641: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1642: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1643: if ($existing{$ckey}) {
1644: $existing{$ckey}.='; '.$logentry;
1645: # ready to assign
1.367 www 1646: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1647: $cdom,$cnum) eq 'ok') {
1648: return 'ok';
1649: } else {
1650: return 'error: Count not store comment.';
1651: }
1652: } else {
1653: # the key does not exist
1654: return 'error: The key does not exist';
1655: }
1656: }
1657:
1.344 www 1658: # ------------------------------------------------------ Generate a set of keys
1659:
1660: sub generate_access_keys {
1.364 www 1661: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1662: $cdom=
1.620 albertel 1663: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1664: $cnum=
1.620 albertel 1665: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1666: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1667: unless (($cdom) && ($cnum)) { return 0; }
1668: if ($number>10000) { return 0; }
1669: sleep(2); # make sure don't get same seed twice
1670: srand(time()^($$+($$<<15))); # from "Programming Perl"
1671: my $total=0;
1672: for (my $i=1;$i<=$number;$i++) {
1673: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1674: sprintf("%lx",int(100000*rand)).'-'.
1675: sprintf("%lx",int(100000*rand));
1676: $newkey=~s/1/g/g; # folks mix up 1 and l
1677: $newkey=~s/0/h/g; # and also 0 and O
1678: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1679: if ($existing{$newkey}) {
1680: $i--;
1681: } else {
1.364 www 1682: if (&put('accesskeys',
1683: { $newkey => '# generated '.localtime().
1.620 albertel 1684: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1685: '; '.$logentry },
1686: $cdom,$cnum) eq 'ok') {
1.344 www 1687: $total++;
1688: }
1689: }
1690: }
1.620 albertel 1691: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1692: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1693: return $total;
1694: }
1695:
1696: # ------------------------------------------------------- Validate an accesskey
1697:
1698: sub validate_access_key {
1699: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1700: $cdom=
1.620 albertel 1701: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1702: $cnum=
1.620 albertel 1703: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1704: $udom=$env{'user.domain'} unless (defined($udom));
1705: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1706: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1707: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1708: }
1709:
1710: # ------------------------------------- Find the section of student in a course
1.652 albertel 1711: sub devalidate_getsection_cache {
1712: my ($udom,$unam,$courseid)=@_;
1713: my $hashid="$udom:$unam:$courseid";
1714: &devalidate_cache_new('getsection',$hashid);
1715: }
1.298 matthew 1716:
1.815 albertel 1717: sub courseid_to_courseurl {
1718: my ($courseid) = @_;
1719: #already url style courseid
1720: return $courseid if ($courseid =~ m{^/});
1721:
1722: if (exists($env{'course.'.$courseid.'.num'})) {
1723: my $cnum = $env{'course.'.$courseid.'.num'};
1724: my $cdom = $env{'course.'.$courseid.'.domain'};
1725: return "/$cdom/$cnum";
1726: }
1727:
1728: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1729: if (exists($courseinfo{'num'})) {
1730: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1731: }
1732:
1733: return undef;
1734: }
1735:
1.298 matthew 1736: sub getsection {
1737: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1738: my $cachetime=1800;
1.551 albertel 1739:
1740: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1741: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1742: if (defined($cached)) { return $result; }
1743:
1.298 matthew 1744: my %Pending;
1745: my %Expired;
1746: #
1747: # Each role can either have not started yet (pending), be active,
1748: # or have expired.
1749: #
1750: # If there is an active role, we are done.
1751: #
1752: # If there is more than one role which has not started yet,
1753: # choose the one which will start sooner
1754: # If there is one role which has not started yet, return it.
1755: #
1756: # If there is more than one expired role, choose the one which ended last.
1757: # If there is a role which has expired, return it.
1758: #
1.815 albertel 1759: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1760: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1761: foreach my $key (keys(%roleshash)) {
1.479 albertel 1762: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1763: my $section=$1;
1764: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1765: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1766: my $now=time;
1.548 albertel 1767: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1768: $Expired{$end}=$section;
1769: next;
1770: }
1.548 albertel 1771: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1772: $Pending{$start}=$section;
1773: next;
1774: }
1.599 albertel 1775: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1776: }
1777: #
1778: # Presumedly there will be few matching roles from the above
1779: # loop and the sorting time will be negligible.
1780: if (scalar(keys(%Pending))) {
1781: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1782: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1783: }
1784: if (scalar(keys(%Expired))) {
1785: my @sorted = sort {$a <=> $b} keys(%Expired);
1786: my $time = pop(@sorted);
1.599 albertel 1787: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1788: }
1.599 albertel 1789: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1790: }
1.70 www 1791:
1.599 albertel 1792: sub save_cache {
1793: &purge_remembered();
1.722 albertel 1794: #&Apache::loncommon::validate_page();
1.620 albertel 1795: undef(%env);
1.780 albertel 1796: undef($env_loaded);
1.599 albertel 1797: }
1.452 albertel 1798:
1.599 albertel 1799: my $to_remember=-1;
1800: my %remembered;
1801: my %accessed;
1802: my $kicks=0;
1803: my $hits=0;
1.849 albertel 1804: sub make_key {
1805: my ($name,$id) = @_;
1.872 albertel 1806: if (length($id) > 65
1807: && length(&escape($id)) > 200) {
1808: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1809: }
1.849 albertel 1810: return &escape($name.':'.$id);
1811: }
1812:
1.599 albertel 1813: sub devalidate_cache_new {
1814: my ($name,$id,$debug) = @_;
1815: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1816: $id=&make_key($name,$id);
1.599 albertel 1817: $memcache->delete($id);
1818: delete($remembered{$id});
1819: delete($accessed{$id});
1820: }
1821:
1822: sub is_cached_new {
1823: my ($name,$id,$debug) = @_;
1.849 albertel 1824: $id=&make_key($name,$id);
1.599 albertel 1825: if (exists($remembered{$id})) {
1826: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1827: $accessed{$id}=[&gettimeofday()];
1828: $hits++;
1829: return ($remembered{$id},1);
1830: }
1831: my $value = $memcache->get($id);
1832: if (!(defined($value))) {
1833: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1834: return (undef,undef);
1.416 albertel 1835: }
1.599 albertel 1836: if ($value eq '__undef__') {
1837: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1838: $value=undef;
1839: }
1840: &make_room($id,$value,$debug);
1841: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1842: return ($value,1);
1843: }
1844:
1845: sub do_cache_new {
1846: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1847: $id=&make_key($name,$id);
1.599 albertel 1848: my $setvalue=$value;
1849: if (!defined($setvalue)) {
1850: $setvalue='__undef__';
1851: }
1.623 albertel 1852: if (!defined($time) ) {
1853: $time=600;
1854: }
1.599 albertel 1855: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1856: my $result = $memcache->set($id,$setvalue,$time);
1857: if (! $result) {
1.872 albertel 1858: &logthis("caching of id -> $id failed");
1.910 albertel 1859: $memcache->disconnect_all();
1.872 albertel 1860: }
1.600 albertel 1861: # need to make a copy of $value
1.919 albertel 1862: &make_room($id,$value,$debug);
1.599 albertel 1863: return $value;
1864: }
1865:
1866: sub make_room {
1867: my ($id,$value,$debug)=@_;
1.919 albertel 1868:
1869: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1870: : $value;
1.599 albertel 1871: if ($to_remember<0) { return; }
1872: $accessed{$id}=[&gettimeofday()];
1873: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1874: my $to_kick;
1875: my $max_time=0;
1876: foreach my $other (keys(%accessed)) {
1877: if (&tv_interval($accessed{$other}) > $max_time) {
1878: $to_kick=$other;
1879: $max_time=&tv_interval($accessed{$other});
1880: }
1881: }
1882: delete($remembered{$to_kick});
1883: delete($accessed{$to_kick});
1884: $kicks++;
1885: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1886: return;
1887: }
1888:
1.599 albertel 1889: sub purge_remembered {
1.604 albertel 1890: #&logthis("Tossing ".scalar(keys(%remembered)));
1891: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1892: undef(%remembered);
1893: undef(%accessed);
1.428 albertel 1894: }
1.70 www 1895: # ------------------------------------- Read an entry from a user's environment
1896:
1897: sub userenvironment {
1898: my ($udom,$unam,@what)=@_;
1.976 raeburn 1899: my $items;
1900: foreach my $item (@what) {
1901: $items.=&escape($item).'&';
1902: }
1903: $items=~s/\&$//;
1.70 www 1904: my %returnhash=();
1.1009 raeburn 1905: my $uhome = &homeserver($unam,$udom);
1906: unless ($uhome eq 'no_host') {
1907: my @answer=split(/\&/,
1908: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1909: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1910: return %returnhash;
1911: }
1.1009 raeburn 1912: my $i;
1913: for ($i=0;$i<=$#what;$i++) {
1914: $returnhash{$what[$i]}=&unescape($answer[$i]);
1915: }
1.70 www 1916: }
1917: return %returnhash;
1.1 albertel 1918: }
1919:
1.617 albertel 1920: # ---------------------------------------------------------- Get a studentphoto
1921: sub studentphoto {
1922: my ($udom,$unam,$ext) = @_;
1923: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1924: if (defined($env{'request.course.id'})) {
1.708 raeburn 1925: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1926: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1927: return(&retrievestudentphoto($udom,$unam,$ext));
1928: } else {
1929: my ($result,$perm_reqd)=
1.707 albertel 1930: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1931: if ($result eq 'ok') {
1932: if (!($perm_reqd eq 'yes')) {
1933: return(&retrievestudentphoto($udom,$unam,$ext));
1934: }
1935: }
1936: }
1937: }
1938: } else {
1939: my ($result,$perm_reqd) =
1.707 albertel 1940: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1941: if ($result eq 'ok') {
1942: if (!($perm_reqd eq 'yes')) {
1943: return(&retrievestudentphoto($udom,$unam,$ext));
1944: }
1945: }
1946: }
1947: return '/adm/lonKaputt/lonlogo_broken.gif';
1948: }
1949:
1950: sub retrievestudentphoto {
1951: my ($udom,$unam,$ext,$type) = @_;
1952: my $home=&Apache::lonnet::homeserver($unam,$udom);
1953: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1954: if ($ret eq 'ok') {
1955: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1956: if ($type eq 'thumbnail') {
1957: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1958: }
1959: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1960: return $tokenurl;
1961: } else {
1962: if ($type eq 'thumbnail') {
1963: return '/adm/lonKaputt/genericstudent_tn.gif';
1964: } else {
1965: return '/adm/lonKaputt/lonlogo_broken.gif';
1966: }
1.617 albertel 1967: }
1968: }
1969:
1.263 www 1970: # -------------------------------------------------------------------- New chat
1971:
1972: sub chatsend {
1.724 raeburn 1973: my ($newentry,$anon,$group)=@_;
1.620 albertel 1974: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1975: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1976: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1977: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1978: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1979: &escape($newentry)).':'.$group,$chome);
1.292 www 1980: }
1981:
1982: # ------------------------------------------ Find current version of a resource
1983:
1984: sub getversion {
1985: my $fname=&clutter(shift);
1986: unless ($fname=~/^\/res\//) { return -1; }
1987: return ¤tversion(&filelocation('',$fname));
1988: }
1989:
1990: sub currentversion {
1991: my $fname=shift;
1.599 albertel 1992: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1993: if (defined($cached)) { return $result; }
1.292 www 1994: my $author=$fname;
1995: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1996: my ($udom,$uname)=split(/\//,$author);
1997: my $home=homeserver($uname,$udom);
1998: if ($home eq 'no_host') {
1999: return -1;
2000: }
2001: my $answer=reply("currentversion:$fname",$home);
2002: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2003: return -1;
2004: }
1.599 albertel 2005: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 2006: }
2007:
1.1 albertel 2008: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2009:
1.1 albertel 2010: sub subscribe {
2011: my $fname=shift;
1.761 raeburn 2012: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2013: $fname=~s/[\n\r]//g;
1.1 albertel 2014: my $author=$fname;
2015: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2016: my ($udom,$uname)=split(/\//,$author);
2017: my $home=homeserver($uname,$udom);
1.335 albertel 2018: if ($home eq 'no_host') {
2019: return 'not_found';
1.1 albertel 2020: }
2021: my $answer=reply("sub:$fname",$home);
1.64 www 2022: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2023: $answer.=' by '.$home;
2024: }
1.1 albertel 2025: return $answer;
2026: }
2027:
1.8 www 2028: # -------------------------------------------------------------- Replicate file
2029:
2030: sub repcopy {
2031: my $filename=shift;
1.23 www 2032: $filename=~s/\/+/\//g;
1.607 raeburn 2033: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2034: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2035: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2036: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2037: return &repcopy_userfile($filename);
2038: }
1.532 albertel 2039: $filename=~s/[\n\r]//g;
1.8 www 2040: my $transname="$filename.in.transfer";
1.828 www 2041: # FIXME: this should flock
1.607 raeburn 2042: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2043: my $remoteurl=subscribe($filename);
1.64 www 2044: if ($remoteurl =~ /^con_lost by/) {
2045: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2046: return 'unavailable';
1.8 www 2047: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2048: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2049: return 'not_found';
1.64 www 2050: } elsif ($remoteurl =~ /^rejected by/) {
2051: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2052: return 'forbidden';
1.20 www 2053: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2054: return 'ok';
1.8 www 2055: } else {
1.290 www 2056: my $author=$filename;
2057: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2058: my ($udom,$uname)=split(/\//,$author);
2059: my $home=homeserver($uname,$udom);
2060: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2061: my @parts=split(/\//,$filename);
2062: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2063: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2064: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2065: return 'bad_request';
1.8 www 2066: }
2067: my $count;
2068: for ($count=5;$count<$#parts;$count++) {
2069: $path.="/$parts[$count]";
2070: if ((-e $path)!=1) {
2071: mkdir($path,0777);
2072: }
2073: }
2074: my $ua=new LWP::UserAgent;
2075: my $request=new HTTP::Request('GET',"$remoteurl");
2076: my $response=$ua->request($request,$transname);
2077: if ($response->is_error()) {
2078: unlink($transname);
2079: my $message=$response->status_line;
1.672 albertel 2080: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2081: ." LWP get: $message: $filename</font>");
1.607 raeburn 2082: return 'unavailable';
1.8 www 2083: } else {
1.16 www 2084: if ($remoteurl!~/\.meta$/) {
2085: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2086: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2087: if ($mresponse->is_error()) {
2088: unlink($filename.'.meta');
2089: &logthis(
1.672 albertel 2090: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2091: }
2092: }
1.8 www 2093: rename($transname,$filename);
1.607 raeburn 2094: return 'ok';
1.8 www 2095: }
1.290 www 2096: }
1.8 www 2097: }
1.330 www 2098: }
2099:
2100: # ------------------------------------------------ Get server side include body
2101: sub ssi_body {
1.381 albertel 2102: my ($filelink,%form)=@_;
1.606 matthew 2103: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2104: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2105: }
1.953 www 2106: my $output='';
2107: my $response;
1.980 raeburn 2108: if ($filelink=~/^https?\:/) {
1.954 raeburn 2109: ($output,$response)=&externalssi($filelink);
1.953 www 2110: } else {
1.1004 droeschl 2111: $filelink .= $filelink=~/\?/ ? '&' : '?';
2112: $filelink .= 'inhibitmenu=yes';
1.953 www 2113: ($output,$response)=&ssi($filelink,%form);
2114: }
1.778 albertel 2115: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2116: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2117: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2118: if (wantarray) {
2119: return ($output, $response);
2120: } else {
2121: return $output;
2122: }
1.8 www 2123: }
2124:
1.15 www 2125: # --------------------------------------------------------- Server Side Include
2126:
1.782 albertel 2127: sub absolute_url {
2128: my ($host_name) = @_;
2129: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2130: if ($host_name eq '') {
2131: $host_name = $ENV{'SERVER_NAME'};
2132: }
2133: return $protocol.$host_name;
2134: }
2135:
1.942 foxr 2136: #
2137: # Server side include.
2138: # Parameters:
2139: # fn Possibly encrypted resource name/id.
2140: # form Hash that describes how the rendering should be done
2141: # and other things.
1.944 foxr 2142: # Returns:
1.950 raeburn 2143: # Scalar context: The content of the response.
2144: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2145: #
1.15 www 2146: sub ssi {
2147:
1.944 foxr 2148: my ($fn,%form)=@_;
1.15 www 2149: my $ua=new LWP::UserAgent;
1.23 www 2150: my $request;
1.711 albertel 2151:
2152: $form{'no_update_last_known'}=1;
1.895 albertel 2153: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2154: if (%form) {
1.782 albertel 2155: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2156: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2157: } else {
1.782 albertel 2158: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2159: }
2160:
1.15 www 2161: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2162: my $response=$ua->request($request);
2163:
1.944 foxr 2164: if (wantarray) {
2165: return ($response->content, $response);
2166: } else {
2167: return $response->content;
1.942 foxr 2168: }
1.324 www 2169: }
2170:
2171: sub externalssi {
2172: my ($url)=@_;
2173: my $ua=new LWP::UserAgent;
2174: my $request=new HTTP::Request('GET',$url);
2175: my $response=$ua->request($request);
1.954 raeburn 2176: if (wantarray) {
2177: return ($response->content, $response);
2178: } else {
2179: return $response->content;
2180: }
1.15 www 2181: }
1.254 www 2182:
1.492 albertel 2183: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2184:
2185: sub allowuploaded {
2186: my ($srcurl,$url)=@_;
2187: $url=&clutter(&declutter($url));
2188: my $dir=$url;
2189: $dir=~s/\/[^\/]+$//;
2190: my %httpref=();
2191: my $httpurl=&hreflocation('',$url);
2192: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2193: &Apache::lonnet::appenv(\%httpref);
1.254 www 2194: }
1.477 raeburn 2195:
1.478 albertel 2196: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2197: # input: action, courseID, current domain, intended
1.637 raeburn 2198: # path to file, source of file, instruction to parse file for objects,
2199: # ref to hash for embedded objects,
2200: # ref to hash for codebase of java objects.
2201: #
1.485 raeburn 2202: # output: url to file (if action was uploaddoc),
2203: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2204: #
1.478 albertel 2205: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2206: # course.
1.477 raeburn 2207: #
1.478 albertel 2208: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2209: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2210: # course's home server.
1.477 raeburn 2211: #
1.478 albertel 2212: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2213: # be copied from $source (current location) to
2214: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2215: # and will then be copied to
2216: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2217: # course's home server.
1.485 raeburn 2218: #
1.481 raeburn 2219: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2220: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2221: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2222: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2223: # in course's home server.
1.637 raeburn 2224: #
1.477 raeburn 2225:
2226: sub process_coursefile {
1.638 albertel 2227: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2228: my $fetchresult;
1.638 albertel 2229: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2230: if ($action eq 'propagate') {
1.638 albertel 2231: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2232: $home);
1.481 raeburn 2233: } else {
1.477 raeburn 2234: my $fpath = '';
2235: my $fname = $file;
1.478 albertel 2236: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2237: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2238: my $filepath = &build_filepath($fpath);
1.481 raeburn 2239: if ($action eq 'copy') {
2240: if ($source eq '') {
2241: $fetchresult = 'no source file';
2242: return $fetchresult;
2243: } else {
2244: my $destination = $filepath.'/'.$fname;
2245: rename($source,$destination);
2246: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2247: $home);
1.481 raeburn 2248: }
2249: } elsif ($action eq 'uploaddoc') {
2250: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2251: print $fh $env{'form.'.$source};
1.481 raeburn 2252: close($fh);
1.637 raeburn 2253: if ($parser eq 'parse') {
1.1024 raeburn 2254: my $mm = new File::MMagic;
2255: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2256: if ($mime_type eq 'text/html') {
2257: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2258: unless ($parse_result eq 'ok') {
2259: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2260: }
1.637 raeburn 2261: }
2262: }
1.477 raeburn 2263: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2264: $home);
1.481 raeburn 2265: if ($fetchresult eq 'ok') {
2266: return '/uploaded/'.$fpath.'/'.$fname;
2267: } else {
2268: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2269: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2270: return '/adm/notfound.html';
2271: }
1.477 raeburn 2272: }
2273: }
1.485 raeburn 2274: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2275: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2276: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2277: }
2278: return $fetchresult;
2279: }
2280:
1.637 raeburn 2281: sub build_filepath {
2282: my ($fpath) = @_;
2283: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2284: unless ($fpath eq '') {
2285: my @parts=split('/',$fpath);
2286: foreach my $part (@parts) {
2287: $filepath.= '/'.$part;
2288: if ((-e $filepath)!=1) {
2289: mkdir($filepath,0777);
2290: }
2291: }
2292: }
2293: return $filepath;
2294: }
2295:
2296: sub store_edited_file {
1.638 albertel 2297: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2298: my $file = $primary_url;
2299: $file =~ s#^/uploaded/$docudom/$docuname/##;
2300: my $fpath = '';
2301: my $fname = $file;
2302: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2303: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2304: my $filepath = &build_filepath($fpath);
2305: open(my $fh,'>'.$filepath.'/'.$fname);
2306: print $fh $content;
2307: close($fh);
1.638 albertel 2308: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2309: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2310: $home);
1.637 raeburn 2311: if ($$fetchresult eq 'ok') {
2312: return '/uploaded/'.$fpath.'/'.$fname;
2313: } else {
1.638 albertel 2314: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2315: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2316: return '/adm/notfound.html';
2317: }
2318: }
2319:
1.531 albertel 2320: sub clean_filename {
1.831 albertel 2321: my ($fname,$args)=@_;
1.315 www 2322: # Replace Windows backslashes by forward slashes
1.257 www 2323: $fname=~s/\\/\//g;
1.831 albertel 2324: if (!$args->{'keep_path'}) {
2325: # Get rid of everything but the actual filename
2326: $fname=~s/^.*\/([^\/]+)$/$1/;
2327: }
1.315 www 2328: # Replace spaces by underscores
2329: $fname=~s/\s+/\_/g;
2330: # Replace all other weird characters by nothing
1.831 albertel 2331: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2332: # Replace all .\d. sequences with _\d. so they no longer look like version
2333: # numbers
2334: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2335: return $fname;
2336: }
1.1051 raeburn 2337: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2338: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2339: # image with the same aspect ratio as the original, but with dimensions which do
2340: # not exceed $resizewidth and $resizeheight.
2341:
1.984 neumanie 2342: sub resizeImage {
1.1051 raeburn 2343: my ($img_path,$resizewidth,$resizeheight) = @_;
2344: my $ima = Image::Magick->new;
2345: my $resized;
2346: if (-e $img_path) {
2347: $ima->Read($img_path);
2348: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2349: my $width = $ima->Get('width');
2350: my $height = $ima->Get('height');
2351: if ($width > $resizewidth) {
2352: my $factor = $width/$resizewidth;
2353: my $newheight = $height/$factor;
2354: $ima->Scale(width=>$resizewidth,height=>$newheight);
2355: $resized = 1;
2356: }
2357: }
2358: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2359: my $width = $ima->Get('width');
2360: my $height = $ima->Get('height');
2361: if ($height > $resizeheight) {
2362: my $factor = $height/$resizeheight;
2363: my $newwidth = $width/$factor;
2364: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2365: $resized = 1;
2366: }
2367: }
2368: if ($resized) {
2369: $ima->Write($img_path);
2370: }
2371: }
2372: return;
1.977 amueller 2373: }
2374:
1.608 albertel 2375: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2376: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 2377: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 2378: # $coursedoc - if true up to the current course
2379: # if false
2380: # $subdir - directory in userfile to store the file into
1.858 raeburn 2381: # $parser - instruction to parse file for objects ($parser = parse)
2382: # $allfiles - reference to hash for embedded objects
2383: # $codebase - reference to hash for codebase of java objects
2384: # $desuname - username for permanent storage of uploaded file
2385: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2386: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2387: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2388: # $resizewidth - width (pixels) to which to resize uploaded image
2389: # $resizeheight - height (pixels) to which to resize uploaded image
1.858 raeburn 2390: #
1.686 albertel 2391: # output: url of file in userspace, or error: <message>
2392: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2393:
1.531 albertel 2394: sub userfileupload {
1.860 raeburn 2395: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051 raeburn 2396: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531 albertel 2397: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2398: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2399: $fname=&clean_filename($fname);
1.315 www 2400: # See if there is anything left
1.257 www 2401: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2402: chop($env{'form.'.$formname});
1.523 raeburn 2403: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2404: my $now = time;
2405: my $filepath = 'tmp/helprequests/'.$now;
2406: my @parts=split(/\//,$filepath);
2407: my $fullpath = $perlvar{'lonDaemons'};
2408: for (my $i=0;$i<@parts;$i++) {
2409: $fullpath .= '/'.$parts[$i];
2410: if ((-e $fullpath)!=1) {
2411: mkdir($fullpath,0777);
2412: }
2413: }
2414: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 2415: print $fh $env{'form.'.$formname};
1.523 raeburn 2416: close($fh);
1.741 raeburn 2417: return $fullpath.'/'.$fname;
2418: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2419: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2420: '_'.$env{'user.domain'}.'/pending';
2421: my @parts=split(/\//,$filepath);
2422: my $fullpath = $perlvar{'lonDaemons'};
2423: for (my $i=0;$i<@parts;$i++) {
2424: $fullpath .= '/'.$parts[$i];
2425: if ((-e $fullpath)!=1) {
2426: mkdir($fullpath,0777);
2427: }
2428: }
2429: open(my $fh,'>'.$fullpath.'/'.$fname);
2430: print $fh $env{'form.'.$formname};
2431: close($fh);
2432: return $fullpath.'/'.$fname;
1.523 raeburn 2433: }
1.995 raeburn 2434: if ($subdir eq 'scantron') {
2435: $fname = 'scantron_orig_'.$fname;
2436: } else {
1.258 www 2437: # Create the directory if not present
1.995 raeburn 2438: $fname="$subdir/$fname";
2439: }
1.259 www 2440: if ($coursedoc) {
1.638 albertel 2441: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2442: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2443: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2444: return &finishuserfileupload($docuname,$docudom,
2445: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2446: $codebase,$thumbwidth,$thumbheight,
2447: $resizewidth,$resizeheight);
1.481 raeburn 2448: } else {
1.620 albertel 2449: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2450: return &process_coursefile('uploaddoc',$docuname,$docudom,
2451: $fname,$formname,$parser,
2452: $allfiles,$codebase);
1.481 raeburn 2453: }
1.719 banghart 2454: } elsif (defined($destuname)) {
2455: my $docuname=$destuname;
2456: my $docudom=$destudom;
1.860 raeburn 2457: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2458: $parser,$allfiles,$codebase,
1.1051 raeburn 2459: $thumbwidth,$thumbheight,
2460: $resizewidth,$resizeheight);
1.719 banghart 2461:
1.259 www 2462: } else {
1.638 albertel 2463: my $docuname=$env{'user.name'};
2464: my $docudom=$env{'user.domain'};
1.714 raeburn 2465: if (exists($env{'form.group'})) {
2466: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2467: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2468: }
1.860 raeburn 2469: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2470: $parser,$allfiles,$codebase,
1.1051 raeburn 2471: $thumbwidth,$thumbheight,
2472: $resizewidth,$resizeheight);
1.259 www 2473: }
1.271 www 2474: }
2475:
2476: sub finishuserfileupload {
1.860 raeburn 2477: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1051 raeburn 2478: $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
1.477 raeburn 2479: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2480: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2481:
1.860 raeburn 2482: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2483: $file=$fname;
2484: if ($fname=~m|/|) {
2485: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2486: $path.=$fnamepath.'/';
2487: }
1.259 www 2488: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2489: my $count;
2490: for ($count=4;$count<=$#parts;$count++) {
2491: $filepath.="/$parts[$count]";
2492: if ((-e $filepath)!=1) {
2493: mkdir($filepath,0777);
2494: }
2495: }
1.984 neumanie 2496:
1.258 www 2497: # Save the file
2498: {
1.701 albertel 2499: if (!open(FH,'>'.$filepath.'/'.$file)) {
2500: &logthis('Failed to create '.$filepath.'/'.$file);
2501: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2502: return '/adm/notfound.html';
2503: }
2504: if (!print FH ($env{'form.'.$formname})) {
2505: &logthis('Failed to write to '.$filepath.'/'.$file);
2506: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2507: return '/adm/notfound.html';
2508: }
1.570 albertel 2509: close(FH);
1.1051 raeburn 2510: if ($resizewidth && $resizeheight) {
2511: my $mm = new File::MMagic;
2512: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2513: if ($mime_type =~ m{^image/}) {
2514: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2515: }
1.977 amueller 2516: }
1.258 www 2517: }
1.637 raeburn 2518: if ($parser eq 'parse') {
1.1024 raeburn 2519: my $mm = new File::MMagic;
2520: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2521: if ($mime_type eq 'text/html') {
2522: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2523: $allfiles,$codebase);
2524: unless ($parse_result eq 'ok') {
2525: &logthis('Failed to parse '.$filepath.$file.
2526: ' for embedded media: '.$parse_result);
2527: }
1.637 raeburn 2528: }
2529: }
1.860 raeburn 2530: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2531: my $input = $filepath.'/'.$file;
2532: my $output = $filepath.'/'.'tn-'.$file;
2533: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2534: system("convert -sample $thumbsize $input $output");
2535: if (-e $filepath.'/'.'tn-'.$file) {
2536: $fetchthumb = 1;
2537: }
2538: }
1.858 raeburn 2539:
1.259 www 2540: # Notify homeserver to grep it
2541: #
1.984 neumanie 2542: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2543: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2544: if ($fetchresult eq 'ok') {
1.860 raeburn 2545: if ($fetchthumb) {
2546: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2547: if ($thumbresult ne 'ok') {
2548: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2549: $docuhome.': '.$thumbresult);
2550: }
2551: }
1.259 www 2552: #
1.258 www 2553: # Return the URL to it
1.494 albertel 2554: return '/uploaded/'.$path.$file;
1.263 www 2555: } else {
1.494 albertel 2556: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2557: ': '.$fetchresult);
1.263 www 2558: return '/adm/notfound.html';
1.858 raeburn 2559: }
1.493 albertel 2560: }
2561:
1.637 raeburn 2562: sub extract_embedded_items {
1.961 raeburn 2563: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2564: my @state = ();
2565: my %javafiles = (
2566: codebase => '',
2567: code => '',
2568: archive => ''
2569: );
2570: my %mediafiles = (
2571: src => '',
2572: movie => '',
2573: );
1.648 raeburn 2574: my $p;
2575: if ($content) {
2576: $p = HTML::LCParser->new($content);
2577: } else {
1.961 raeburn 2578: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2579: }
1.641 albertel 2580: while (my $t=$p->get_token()) {
1.640 albertel 2581: if ($t->[0] eq 'S') {
2582: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2583: push(@state, $tagname);
1.648 raeburn 2584: if (lc($tagname) eq 'allow') {
2585: &add_filetype($allfiles,$attr->{'src'},'src');
2586: }
1.640 albertel 2587: if (lc($tagname) eq 'img') {
2588: &add_filetype($allfiles,$attr->{'src'},'src');
2589: }
1.886 albertel 2590: if (lc($tagname) eq 'a') {
2591: &add_filetype($allfiles,$attr->{'href'},'href');
2592: }
1.645 raeburn 2593: if (lc($tagname) eq 'script') {
2594: if ($attr->{'archive'} =~ /\.jar$/i) {
2595: &add_filetype($allfiles,$attr->{'archive'},'archive');
2596: } else {
2597: &add_filetype($allfiles,$attr->{'src'},'src');
2598: }
2599: }
2600: if (lc($tagname) eq 'link') {
2601: if (lc($attr->{'rel'}) eq 'stylesheet') {
2602: &add_filetype($allfiles,$attr->{'href'},'href');
2603: }
2604: }
1.640 albertel 2605: if (lc($tagname) eq 'object' ||
2606: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2607: foreach my $item (keys(%javafiles)) {
2608: $javafiles{$item} = '';
2609: }
2610: }
2611: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2612: my $name = lc($attr->{'name'});
2613: foreach my $item (keys(%javafiles)) {
2614: if ($name eq $item) {
2615: $javafiles{$item} = $attr->{'value'};
2616: last;
2617: }
2618: }
2619: foreach my $item (keys(%mediafiles)) {
2620: if ($name eq $item) {
2621: &add_filetype($allfiles, $attr->{'value'}, 'value');
2622: last;
2623: }
2624: }
2625: }
2626: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2627: foreach my $item (keys(%javafiles)) {
2628: if ($attr->{$item}) {
2629: $javafiles{$item} = $attr->{$item};
2630: last;
2631: }
2632: }
2633: foreach my $item (keys(%mediafiles)) {
2634: if ($attr->{$item}) {
2635: &add_filetype($allfiles,$attr->{$item},$item);
2636: last;
2637: }
2638: }
2639: }
2640: } elsif ($t->[0] eq 'E') {
2641: my ($tagname) = ($t->[1]);
2642: if ($javafiles{'codebase'} ne '') {
2643: $javafiles{'codebase'} .= '/';
2644: }
2645: if (lc($tagname) eq 'applet' ||
2646: lc($tagname) eq 'object' ||
2647: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2648: ) {
2649: foreach my $item (keys(%javafiles)) {
2650: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2651: my $file=$javafiles{'codebase'}.$javafiles{$item};
2652: &add_filetype($allfiles,$file,$item);
2653: }
2654: }
2655: }
2656: pop @state;
2657: }
2658: }
1.637 raeburn 2659: return 'ok';
2660: }
2661:
1.639 albertel 2662: sub add_filetype {
2663: my ($allfiles,$file,$type)=@_;
2664: if (exists($allfiles->{$file})) {
2665: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2666: push(@{$allfiles->{$file}}, &escape($type));
2667: }
2668: } else {
2669: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2670: }
2671: }
2672:
1.493 albertel 2673: sub removeuploadedurl {
1.984 neumanie 2674: my ($url)=@_;
2675: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2676: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2677: }
2678:
2679: sub removeuserfile {
2680: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2681: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2682: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2683: if ($result eq 'ok') {
1.798 raeburn 2684: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2685: my $metafile = $fname.'.meta';
2686: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2687: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2688: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2689: my $sqlresult =
1.823 albertel 2690: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2691: 'portfolio_metadata',$group,
2692: 'delete');
1.798 raeburn 2693: }
2694: }
2695: return $result;
1.257 www 2696: }
1.15 www 2697:
1.530 albertel 2698: sub mkdiruserfile {
2699: my ($docuname,$docudom,$dir)=@_;
2700: my $home=&homeserver($docuname,$docudom);
2701: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2702: }
2703:
1.531 albertel 2704: sub renameuserfile {
2705: my ($docuname,$docudom,$old,$new)=@_;
2706: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2707: my $result = &reply("renameuserfile:$docudom:$docuname:".
2708: &escape("$old").':'.&escape("$new"),$home);
2709: if ($result eq 'ok') {
2710: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2711: my $oldmeta = $old.'.meta';
2712: my $newmeta = $new.'.meta';
2713: my $metaresult =
2714: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2715: my $url = "/uploaded/$docudom/$docuname/$old";
2716: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2717: my $sqlresult =
1.823 albertel 2718: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2719: 'portfolio_metadata',$group,
2720: 'delete');
1.798 raeburn 2721: }
2722: }
2723: return $result;
1.531 albertel 2724: }
2725:
1.14 www 2726: # ------------------------------------------------------------------------- Log
2727:
2728: sub log {
2729: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2730: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2731: }
2732:
2733: # ------------------------------------------------------------------ Course Log
1.352 www 2734: #
2735: # This routine flushes several buffers of non-mission-critical nature
2736: #
1.157 www 2737:
2738: sub flushcourselogs {
1.352 www 2739: &logthis('Flushing log buffers');
2740: #
2741: # course logs
2742: # This is a log of all transactions in a course, which can be used
2743: # for data mining purposes
2744: #
2745: # It also collects the courseid database, which lists last transaction
2746: # times and course titles for all courseids
2747: #
2748: my %courseidbuffer=();
1.921 raeburn 2749: foreach my $crsid (keys(%courselogs)) {
1.352 www 2750: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2751: &escape($courselogs{$crsid}),
2752: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2753: delete $courselogs{$crsid};
2754: } else {
2755: &logthis('Failed to flush log buffer for '.$crsid);
2756: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2757: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2758: " exceeded maximum size, deleting.</font>");
2759: delete $courselogs{$crsid};
2760: }
1.352 www 2761: }
1.920 raeburn 2762: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2763: 'description' => $coursedescrbuf{$crsid},
2764: 'inst_code' => $courseinstcodebuf{$crsid},
2765: 'type' => $coursetypebuf{$crsid},
2766: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2767: };
1.191 harris41 2768: }
1.352 www 2769: #
2770: # Write course id database (reverse lookup) to homeserver of courses
2771: # Is used in pickcourse
2772: #
1.840 albertel 2773: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2774: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2775: $courseidbuffer{$crs_home},
2776: $crs_home,'timeonly');
1.352 www 2777: }
2778: #
2779: # File accesses
2780: # Writes to the dynamic metadata of resources to get hit counts, etc.
2781: #
1.449 matthew 2782: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2783: if ($entry =~ /___count$/) {
2784: my ($dom,$name);
1.807 albertel 2785: ($dom,$name,undef)=
1.811 albertel 2786: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2787: if (! defined($dom) || $dom eq '' ||
2788: ! defined($name) || $name eq '') {
1.620 albertel 2789: my $cid = $env{'request.course.id'};
2790: $dom = $env{'request.'.$cid.'.domain'};
2791: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2792: }
1.450 matthew 2793: my $value = $accesshash{$entry};
2794: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2795: my %temphash=($url => $value);
1.449 matthew 2796: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2797: if ($result eq 'ok') {
2798: delete $accesshash{$entry};
2799: } elsif ($result eq 'unknown_cmd') {
2800: # Target server has old code running on it.
1.450 matthew 2801: my %temphash=($entry => $value);
1.449 matthew 2802: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2803: delete $accesshash{$entry};
2804: }
2805: }
2806: } else {
1.811 albertel 2807: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2808: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2809: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2810: delete $accesshash{$entry};
2811: }
1.185 www 2812: }
1.191 harris41 2813: }
1.352 www 2814: #
2815: # Roles
2816: # Reverse lookup of user roles for course faculty/staff and co-authorship
2817: #
1.800 albertel 2818: foreach my $entry (keys(%userrolehash)) {
1.351 www 2819: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2820: split(/\:/,$entry);
2821: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2822: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2823: $rudom,$runame) eq 'ok') {
2824: delete $userrolehash{$entry};
2825: }
2826: }
1.662 raeburn 2827: #
2828: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2829: #
2830: my %domrolebuffer = ();
1.1000 raeburn 2831: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2832: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2833: if ($domrolebuffer{$rudom}) {
2834: $domrolebuffer{$rudom}.='&'.&escape($entry).
2835: '='.&escape($domainrolehash{$entry});
2836: } else {
2837: $domrolebuffer{$rudom}.=&escape($entry).
2838: '='.&escape($domainrolehash{$entry});
2839: }
2840: delete $domainrolehash{$entry};
2841: }
2842: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2843: my %servers = &get_servers($dom,'library');
2844: foreach my $tryserver (keys(%servers)) {
2845: unless (&reply('domroleput:'.$dom.':'.
2846: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2847: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2848: }
1.662 raeburn 2849: }
2850: }
1.186 www 2851: $dumpcount++;
1.157 www 2852: }
2853:
2854: sub courselog {
2855: my $what=shift;
1.158 www 2856: $what=time.':'.$what;
1.620 albertel 2857: unless ($env{'request.course.id'}) { return ''; }
2858: $coursedombuf{$env{'request.course.id'}}=
2859: $env{'course.'.$env{'request.course.id'}.'.domain'};
2860: $coursenumbuf{$env{'request.course.id'}}=
2861: $env{'course.'.$env{'request.course.id'}.'.num'};
2862: $coursehombuf{$env{'request.course.id'}}=
2863: $env{'course.'.$env{'request.course.id'}.'.home'};
2864: $coursedescrbuf{$env{'request.course.id'}}=
2865: $env{'course.'.$env{'request.course.id'}.'.description'};
2866: $courseinstcodebuf{$env{'request.course.id'}}=
2867: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2868: $courseownerbuf{$env{'request.course.id'}}=
2869: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2870: $coursetypebuf{$env{'request.course.id'}}=
2871: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2872: if (defined $courselogs{$env{'request.course.id'}}) {
2873: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2874: } else {
1.620 albertel 2875: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2876: }
1.620 albertel 2877: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2878: &flushcourselogs();
2879: }
1.158 www 2880: }
2881:
2882: sub courseacclog {
2883: my $fnsymb=shift;
1.620 albertel 2884: unless ($env{'request.course.id'}) { return ''; }
2885: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2886: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2887: $what.=':POST';
1.583 matthew 2888: # FIXME: Probably ought to escape things....
1.800 albertel 2889: foreach my $key (keys(%env)) {
2890: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2891: my $formitem = $1;
2892: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2893: $what.=':'.$formitem.'='.$env{$key};
2894: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2895: $what.=':'.$formitem.'='.$env{$key};
2896: }
1.158 www 2897: }
1.191 harris41 2898: }
1.583 matthew 2899: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2900: # FIXME: We should not be depending on a form parameter that someone
2901: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2902: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2903: $what.= ':POST';
2904: # FIXME: Probably ought to escape things....
2905: foreach my $element ('courseexp','crsfulltext','crsrelated',
2906: 'crsdiscuss') {
1.620 albertel 2907: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2908: }
2909: }
1.158 www 2910: }
2911: &courselog($what);
1.149 www 2912: }
2913:
1.185 www 2914: sub countacc {
2915: my $url=&declutter(shift);
1.458 matthew 2916: return if (! defined($url) || $url eq '');
1.620 albertel 2917: unless ($env{'request.course.id'}) { return ''; }
2918: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2919: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2920: $accesshash{$key}++;
1.185 www 2921: }
1.349 www 2922:
1.361 www 2923: sub linklog {
2924: my ($from,$to)=@_;
2925: $from=&declutter($from);
2926: $to=&declutter($to);
2927: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2928: $accesshash{$to.'___'.$from.'___goto'}=1;
2929: }
2930:
1.349 www 2931: sub userrolelog {
2932: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2933: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2934: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2935: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2936: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2937: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2938: $userrolehash
2939: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2940: =$tend.':'.$tstart;
1.662 raeburn 2941: }
1.898 albertel 2942: if (($env{'request.role'} =~ /dc\./) &&
2943: (($trole=~/^au/) || ($trole=~/^in/) ||
2944: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2945: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2946: ($trole=~/^co/))) {
1.898 albertel 2947: $userrolehash
2948: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2949: =$tend.':'.$tstart;
2950: }
1.662 raeburn 2951: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2952: ($trole=~/^li/) || ($trole=~/^li/) ||
2953: ($trole=~/^au/) || ($trole=~/^dg/) ||
2954: ($trole=~/^sc/)) {
2955: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2956: $domainrolehash
2957: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2958: = $tend.':'.$tstart;
2959: }
1.351 www 2960: }
2961:
1.957 raeburn 2962: sub courserolelog {
2963: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2964: if (($trole eq 'cc') || ($trole eq 'in') ||
2965: ($trole eq 'ep') || ($trole eq 'ad') ||
2966: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 2967: ($trole=~/^cr/) || ($trole eq 'gr') ||
2968: ($trole eq 'co')) {
1.957 raeburn 2969: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2970: my $cdom = $1;
2971: my $cnum = $2;
2972: my $sec = $3;
2973: my $namespace = 'rolelog';
2974: my %storehash = (
2975: role => $trole,
2976: start => $tstart,
2977: end => $tend,
2978: selfenroll => $selfenroll,
2979: context => $context,
2980: );
2981: if ($trole eq 'gr') {
2982: $namespace = 'groupslog';
2983: $storehash{'group'} = $sec;
2984: } else {
2985: $storehash{'section'} = $sec;
2986: }
2987: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 2988: if (($trole ne 'st') || ($sec ne '')) {
2989: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2990: }
1.957 raeburn 2991: }
2992: }
2993: return;
2994: }
2995:
1.351 www 2996: sub get_course_adv_roles {
1.948 raeburn 2997: my ($cid,$codes) = @_;
1.620 albertel 2998: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2999: my %coursehash=&coursedescription($cid);
1.988 raeburn 3000: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3001: my %nothide=();
1.800 albertel 3002: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3003: if ($user !~ /:/) {
3004: $nothide{join(':',split(/[\@]/,$user))}=1;
3005: } else {
3006: $nothide{$user}=1;
3007: }
1.470 www 3008: }
1.351 www 3009: my %returnhash=();
3010: my %dumphash=
3011: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3012: my $now=time;
1.997 raeburn 3013: my %privileged;
1.1000 raeburn 3014: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3015: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3016: if (($tstart) && ($tstart<0)) { next; }
3017: if (($tend) && ($tend<$now)) { next; }
3018: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3019: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3020: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3021: unless (ref($privileged{$domain}) eq 'HASH') {
3022: my %dompersonnel =
1.998 raeburn 3023: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3024: $privileged{$domain} = {};
3025: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3026: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3027: foreach my $user (keys(%{$dompersonnel{$server}})) {
3028: my ($trole,$uname,$udom) = split(/:/,$user);
3029: $privileged{$udom}{$uname} = 1;
3030: }
3031: }
3032: }
3033: }
3034: if ((exists($privileged{$domain}{$username})) &&
3035: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3036: if ($role eq 'cr') { next; }
1.948 raeburn 3037: if ($codes) {
3038: if ($section) { $role .= ':'.$section; }
3039: if ($returnhash{$role}) {
3040: $returnhash{$role}.=','.$username.':'.$domain;
3041: } else {
3042: $returnhash{$role}=$username.':'.$domain;
3043: }
1.351 www 3044: } else {
1.988 raeburn 3045: my $key=&plaintext($role,$crstype);
1.973 bisitz 3046: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3047: if ($returnhash{$key}) {
3048: $returnhash{$key}.=','.$username.':'.$domain;
3049: } else {
3050: $returnhash{$key}=$username.':'.$domain;
3051: }
1.351 www 3052: }
1.948 raeburn 3053: }
1.400 www 3054: return %returnhash;
3055: }
3056:
3057: sub get_my_roles {
1.937 raeburn 3058: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3059: unless (defined($uname)) { $uname=$env{'user.name'}; }
3060: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3061: my (%dumphash,%nothide);
1.858 raeburn 3062: if ($context eq 'userroles') {
3063: %dumphash = &dump('roles',$udom,$uname);
3064: } else {
3065: %dumphash=
1.400 www 3066: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3067: if ($hidepriv) {
3068: my %coursehash=&coursedescription($udom.'_'.$uname);
3069: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3070: if ($user !~ /:/) {
3071: $nothide{join(':',split(/[\@]/,$user))} = 1;
3072: } else {
3073: $nothide{$user} = 1;
3074: }
3075: }
3076: }
1.858 raeburn 3077: }
1.400 www 3078: my %returnhash=();
3079: my $now=time;
1.999 raeburn 3080: my %privileged;
1.800 albertel 3081: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3082: my ($role,$tend,$tstart);
3083: if ($context eq 'userroles') {
3084: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3085: } else {
3086: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3087: }
1.400 www 3088: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3089: my $status = 'active';
1.939 raeburn 3090: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3091: $status = 'previous';
3092: }
3093: if (($tstart) && ($now<$tstart)) {
3094: $status = 'future';
3095: }
3096: if (ref($types) eq 'ARRAY') {
3097: if (!grep(/^\Q$status\E$/,@{$types})) {
3098: next;
3099: }
3100: } else {
3101: if ($status ne 'active') {
3102: next;
3103: }
3104: }
1.867 raeburn 3105: my ($rolecode,$username,$domain,$section,$area);
3106: if ($context eq 'userroles') {
3107: ($area,$rolecode) = split(/_/,$entry);
3108: (undef,$domain,$username,$section) = split(/\//,$area);
3109: } else {
3110: ($role,$username,$domain,$section) = split(/\:/,$entry);
3111: }
1.832 raeburn 3112: if (ref($roledoms) eq 'ARRAY') {
3113: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3114: next;
3115: }
3116: }
3117: if (ref($roles) eq 'ARRAY') {
3118: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3119: if ($role =~ /^cr\//) {
3120: if (!grep(/^cr$/,@{$roles})) {
3121: next;
3122: }
3123: } else {
3124: next;
3125: }
1.832 raeburn 3126: }
1.867 raeburn 3127: }
1.937 raeburn 3128: if ($hidepriv) {
1.999 raeburn 3129: if ($context eq 'userroles') {
3130: if ((&privileged($username,$domain)) &&
3131: (!$nothide{$username.':'.$domain})) {
3132: next;
3133: }
3134: } else {
3135: unless (ref($privileged{$domain}) eq 'HASH') {
3136: my %dompersonnel =
3137: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3138: $privileged{$domain} = {};
3139: if (keys(%dompersonnel)) {
3140: foreach my $server (keys(%dompersonnel)) {
3141: if (ref($dompersonnel{$server}) eq 'HASH') {
3142: foreach my $user (keys(%{$dompersonnel{$server}})) {
3143: my ($trole,$uname,$udom) = split(/:/,$user);
3144: $privileged{$udom}{$uname} = $trole;
3145: }
3146: }
3147: }
3148: }
3149: }
3150: if (exists($privileged{$domain}{$username})) {
3151: if (!$nothide{$username.':'.$domain}) {
3152: next;
3153: }
3154: }
1.937 raeburn 3155: }
3156: }
1.933 raeburn 3157: if ($withsec) {
3158: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3159: $tstart.':'.$tend;
3160: } else {
3161: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3162: }
1.832 raeburn 3163: }
1.373 www 3164: return %returnhash;
1.399 www 3165: }
3166:
3167: # ----------------------------------------------------- Frontpage Announcements
3168: #
3169: #
3170:
3171: sub postannounce {
3172: my ($server,$text)=@_;
1.844 albertel 3173: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3174: unless ($text=~/\w/) { $text=''; }
3175: return &reply('setannounce:'.&escape($text),$server);
3176: }
3177:
3178: sub getannounce {
1.448 albertel 3179:
3180: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3181: my $announcement='';
1.800 albertel 3182: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3183: close($fh);
1.399 www 3184: if ($announcement=~/\w/) {
3185: return
3186: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3187: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3188: } else {
3189: return '';
3190: }
3191: } else {
3192: return '';
3193: }
1.351 www 3194: }
1.353 www 3195:
3196: # ---------------------------------------------------------- Course ID routines
3197: # Deal with domain's nohist_courseid.db files
3198: #
3199:
3200: sub courseidput {
1.921 raeburn 3201: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3202: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3203: my $outcome;
3204: if ($caller eq 'timeonly') {
3205: my $cids = '';
3206: foreach my $item (keys(%$storehash)) {
3207: $cids.=&escape($item).'&';
3208: }
3209: $cids=~s/\&$//;
3210: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3211: $coursehome);
3212: } else {
3213: my $items = '';
3214: foreach my $item (keys(%$storehash)) {
3215: $items.= &escape($item).'='.
3216: &freeze_escape($$storehash{$item}).'&';
3217: }
3218: $items=~s/\&$//;
3219: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3220: $coursehome);
1.918 raeburn 3221: }
3222: if ($outcome eq 'unknown_cmd') {
3223: my $what;
3224: foreach my $cid (keys(%$storehash)) {
3225: $what .= &escape($cid).'=';
1.921 raeburn 3226: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3227: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3228: }
3229: $what =~ s/\:$/&/;
3230: }
3231: $what =~ s/\&$//;
3232: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3233: } else {
3234: return $outcome;
3235: }
1.353 www 3236: }
3237:
3238: sub courseiddump {
1.921 raeburn 3239: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3240: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3241: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3 raeburn 3242: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3243: my $as_hash = 1;
3244: my %returnhash;
3245: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3246: my %libserv = &all_library();
3247: foreach my $tryserver (keys(%libserv)) {
3248: if ( ( $hostidflag == 1
3249: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3250: || (!defined($hostidflag)) ) {
3251:
1.918 raeburn 3252: if (($domfilter eq '') ||
3253: (&host_domain($tryserver) eq $domfilter)) {
3254: my $rep =
3255: &reply('courseiddump:'.&host_domain($tryserver).':'.
3256: $sincefilter.':'.&escape($descfilter).':'.
3257: &escape($instcodefilter).':'.&escape($ownerfilter).
3258: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3259: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3260: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3261: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3262: &escape($cc_clone).':'.$cloneonly.':'.
3263: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3 raeburn 3264: &escape($creationcontext).':'.$domcloner,
3265: $tryserver);
1.918 raeburn 3266: my @pairs=split(/\&/,$rep);
3267: foreach my $item (@pairs) {
3268: my ($key,$value)=split(/\=/,$item,2);
3269: $key = &unescape($key);
3270: next if ($key =~ /^error: 2 /);
3271: my $result = &thaw_unescape($value);
3272: if (ref($result) eq 'HASH') {
3273: $returnhash{$key}=$result;
3274: } else {
1.921 raeburn 3275: my @responses = split(/:/,$value);
3276: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3277: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3278: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3279: }
1.1008 raeburn 3280: }
1.353 www 3281: }
3282: }
3283: }
3284: }
3285: return %returnhash;
3286: }
3287:
1.1055 raeburn 3288: sub courselastaccess {
3289: my ($cdom,$cnum,$hostidref) = @_;
3290: my %returnhash;
3291: if ($cdom && $cnum) {
3292: my $chome = &homeserver($cnum,$cdom);
3293: if ($chome ne 'no_host') {
3294: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3295: &extract_lastaccess(\%returnhash,$rep);
3296: }
3297: } else {
3298: if (!$cdom) { $cdom=''; }
3299: my %libserv = &all_library();
3300: foreach my $tryserver (keys(%libserv)) {
3301: if (ref($hostidref) eq 'ARRAY') {
3302: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3303: }
3304: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3305: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3306: &extract_lastaccess(\%returnhash,$rep);
3307: }
3308: }
3309: }
3310: return %returnhash;
3311: }
3312:
3313: sub extract_lastaccess {
3314: my ($returnhash,$rep) = @_;
3315: if (ref($returnhash) eq 'HASH') {
3316: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3317: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3318: $rep eq '') {
3319: my @pairs=split(/\&/,$rep);
3320: foreach my $item (@pairs) {
3321: my ($key,$value)=split(/\=/,$item,2);
3322: $key = &unescape($key);
3323: next if ($key =~ /^error: 2 /);
3324: $returnhash->{$key} = &thaw_unescape($value);
3325: }
3326: }
3327: }
3328: return;
3329: }
3330:
1.658 raeburn 3331: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3332:
3333: sub dcmailput {
1.685 raeburn 3334: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3335: my $status = &Apache::lonnet::critical(
1.740 www 3336: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3337: &escape($message),$server);
1.662 raeburn 3338: return $status;
3339: }
3340:
1.658 raeburn 3341: sub dcmaildump {
3342: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3343: my %returnhash=();
1.846 albertel 3344:
3345: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3346: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3347: &escape($enddate).':';
3348: my @esc_senders=map { &escape($_)} @$senders;
3349: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3350: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3351: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3352: if (($key) && ($value)) {
3353: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3354: }
3355: }
3356: }
3357: return %returnhash;
3358: }
1.662 raeburn 3359: # ---------------------------------------------------------- Domain roles
3360:
3361: sub get_domain_roles {
3362: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3363: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3364: $startdate = '.';
3365: }
1.1018 raeburn 3366: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3367: $enddate = '.';
3368: }
1.922 raeburn 3369: my $rolelist;
3370: if (ref($roles) eq 'ARRAY') {
3371: $rolelist = join(':',@{$roles});
3372: }
1.662 raeburn 3373: my %personnel = ();
1.841 albertel 3374:
3375: my %servers = &get_servers($dom,'library');
3376: foreach my $tryserver (keys(%servers)) {
3377: %{$personnel{$tryserver}}=();
3378: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3379: &escape($startdate).':'.
3380: &escape($enddate).':'.
3381: &escape($rolelist), $tryserver))) {
3382: my ($key,$value) = split(/\=/,$line,2);
3383: if (($key) && ($value)) {
3384: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3385: }
3386: }
1.662 raeburn 3387: }
3388: return %personnel;
3389: }
1.658 raeburn 3390:
1.149 www 3391: # ----------------------------------------------------------- Check out an item
3392:
1.504 albertel 3393: sub get_first_access {
3394: my ($type,$argsymb)=@_;
1.790 albertel 3395: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3396: if ($argsymb) { $symb=$argsymb; }
3397: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3398: if ($type eq 'course') {
3399: $res='course';
3400: } elsif ($type eq 'map') {
1.588 albertel 3401: $res=&symbread($map);
3402: } else {
3403: $res=$symb;
3404: }
3405: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3406: return $times{"$courseid\0$res"};
1.504 albertel 3407: }
3408:
3409: sub set_first_access {
3410: my ($type)=@_;
1.790 albertel 3411: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3412: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3413: if ($type eq 'course') {
3414: $res='course';
3415: } elsif ($type eq 'map') {
1.588 albertel 3416: $res=&symbread($map);
3417: } else {
3418: $res=$symb;
3419: }
3420: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3421: if (!$firstaccess) {
1.588 albertel 3422: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3423: }
3424: return 'already_set';
1.504 albertel 3425: }
3426:
1.149 www 3427: sub checkout {
3428: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3429: my $now=time;
3430: my $lonhost=$perlvar{'lonHostID'};
3431: my $infostr=&escape(
1.234 www 3432: 'CHECKOUTTOKEN&'.
1.149 www 3433: $tuname.'&'.
3434: $tudom.'&'.
3435: $tcrsid.'&'.
3436: $symb.'&'.
3437: $now.'&'.$ENV{'REMOTE_ADDR'});
3438: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3439: if ($token=~/^error\:/) {
1.672 albertel 3440: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3441: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3442: "</font>");
3443: return '';
3444: }
3445:
1.149 www 3446: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3447: $token=~tr/a-z/A-Z/;
3448:
1.153 www 3449: my %infohash=('resource.0.outtoken' => $token,
3450: 'resource.0.checkouttime' => $now,
3451: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3452:
3453: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3454: return '';
1.151 www 3455: } else {
1.672 albertel 3456: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3457: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3458: "</font>");
1.149 www 3459: }
3460:
3461: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3462: &escape('Checkout '.$infostr.' - '.
3463: $token)) ne 'ok') {
3464: return '';
1.151 www 3465: } else {
1.672 albertel 3466: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3467: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3468: "</font>");
1.149 www 3469: }
1.151 www 3470: return $token;
1.149 www 3471: }
3472:
3473: # ------------------------------------------------------------ Check in an item
3474:
3475: sub checkin {
3476: my $token=shift;
1.150 www 3477: my $now=time;
3478: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3479: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3480: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3481: $dtoken=~s/\W/\_/g;
1.234 www 3482: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3483: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3484:
1.154 www 3485: unless (($tuname) && ($tudom)) {
3486: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3487: return '';
3488: }
3489:
3490: unless (&allowed('mgr',$tcrsid)) {
3491: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3492: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3493: return '';
3494: }
3495:
1.153 www 3496: my %infohash=('resource.0.intoken' => $token,
3497: 'resource.0.checkintime' => $now,
3498: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3499:
3500: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3501: return '';
3502: }
3503:
3504: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3505: &escape('Checkin - '.$token)) ne 'ok') {
3506: return '';
3507: }
3508:
3509: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3510: }
3511:
3512: # --------------------------------------------- Set Expire Date for Spreadsheet
3513:
3514: sub expirespread {
3515: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3516: my $cid=$env{'request.course.id'};
1.110 www 3517: if ($cid) {
3518: my $now=time;
3519: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3520: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3521: $env{'course.'.$cid.'.num'}.
1.110 www 3522: ':nohist_expirationdates:'.
3523: &escape($key).'='.$now,
1.620 albertel 3524: $env{'course.'.$cid.'.home'})
1.110 www 3525: }
3526: return 'ok';
1.14 www 3527: }
3528:
1.109 www 3529: # ----------------------------------------------------- Devalidate Spreadsheets
3530:
3531: sub devalidate {
1.325 www 3532: my ($symb,$uname,$udom)=@_;
1.620 albertel 3533: my $cid=$env{'request.course.id'};
1.109 www 3534: if ($cid) {
1.391 matthew 3535: # delete the stored spreadsheets for
3536: # - the student level sheet of this user in course's homespace
3537: # - the assessment level sheet for this resource
3538: # for this user in user's homespace
1.553 albertel 3539: # - current conditional state info
1.325 www 3540: my $key=$uname.':'.$udom.':';
1.109 www 3541: my $status=
1.299 matthew 3542: &del('nohist_calculatedsheets',
1.391 matthew 3543: [$key.'studentcalc:'],
1.620 albertel 3544: $env{'course.'.$cid.'.domain'},
3545: $env{'course.'.$cid.'.num'})
1.133 albertel 3546: .' '.
3547: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3548: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3549: unless ($status eq 'ok ok') {
3550: &logthis('Could not devalidate spreadsheet '.
1.325 www 3551: $uname.' at '.$udom.' for '.
1.109 www 3552: $symb.': '.$status);
1.133 albertel 3553: }
1.553 albertel 3554: &delenv('user.state.'.$cid);
1.109 www 3555: }
3556: }
3557:
1.265 albertel 3558: sub get_scalar {
3559: my ($string,$end) = @_;
3560: my $value;
3561: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3562: $value = $1;
3563: } elsif ($$string =~ s/^([^&]*?)&//) {
3564: $value = $1;
3565: }
3566: return &unescape($value);
3567: }
3568:
3569: sub array2str {
3570: my (@array) = @_;
3571: my $result=&arrayref2str(\@array);
3572: $result=~s/^__ARRAY_REF__//;
3573: $result=~s/__END_ARRAY_REF__$//;
3574: return $result;
3575: }
3576:
1.204 albertel 3577: sub arrayref2str {
3578: my ($arrayref) = @_;
1.265 albertel 3579: my $result='__ARRAY_REF__';
1.204 albertel 3580: foreach my $elem (@$arrayref) {
1.265 albertel 3581: if(ref($elem) eq 'ARRAY') {
3582: $result.=&arrayref2str($elem).'&';
3583: } elsif(ref($elem) eq 'HASH') {
3584: $result.=&hashref2str($elem).'&';
3585: } elsif(ref($elem)) {
3586: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3587: } else {
3588: $result.=&escape($elem).'&';
3589: }
3590: }
3591: $result=~s/\&$//;
1.265 albertel 3592: $result .= '__END_ARRAY_REF__';
1.204 albertel 3593: return $result;
3594: }
3595:
1.168 albertel 3596: sub hash2str {
1.204 albertel 3597: my (%hash) = @_;
3598: my $result=&hashref2str(\%hash);
1.265 albertel 3599: $result=~s/^__HASH_REF__//;
3600: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3601: return $result;
3602: }
3603:
3604: sub hashref2str {
3605: my ($hashref)=@_;
1.265 albertel 3606: my $result='__HASH_REF__';
1.800 albertel 3607: foreach my $key (sort(keys(%$hashref))) {
3608: if (ref($key) eq 'ARRAY') {
3609: $result.=&arrayref2str($key).'=';
3610: } elsif (ref($key) eq 'HASH') {
3611: $result.=&hashref2str($key).'=';
3612: } elsif (ref($key)) {
1.265 albertel 3613: $result.='=';
1.800 albertel 3614: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3615: } else {
1.800 albertel 3616: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3617: }
3618:
1.800 albertel 3619: if(ref($hashref->{$key}) eq 'ARRAY') {
3620: $result.=&arrayref2str($hashref->{$key}).'&';
3621: } elsif(ref($hashref->{$key}) eq 'HASH') {
3622: $result.=&hashref2str($hashref->{$key}).'&';
3623: } elsif(ref($hashref->{$key})) {
1.265 albertel 3624: $result.='&';
1.800 albertel 3625: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3626: } else {
1.800 albertel 3627: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3628: }
3629: }
1.168 albertel 3630: $result=~s/\&$//;
1.265 albertel 3631: $result .= '__END_HASH_REF__';
1.168 albertel 3632: return $result;
3633: }
3634:
3635: sub str2hash {
1.265 albertel 3636: my ($string)=@_;
3637: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3638: return %$hash;
3639: }
3640:
3641: sub str2hashref {
1.168 albertel 3642: my ($string) = @_;
1.265 albertel 3643:
3644: my %hash;
3645:
3646: if($string !~ /^__HASH_REF__/) {
3647: if (! ($string eq '' || !defined($string))) {
3648: $hash{'error'}='Not hash reference';
3649: }
3650: return (\%hash, $string);
3651: }
3652:
3653: $string =~ s/^__HASH_REF__//;
3654:
3655: while($string !~ /^__END_HASH_REF__/) {
3656: #key
3657: my $key='';
3658: if($string =~ /^__HASH_REF__/) {
3659: ($key, $string)=&str2hashref($string);
3660: if(defined($key->{'error'})) {
3661: $hash{'error'}='Bad data';
3662: return (\%hash, $string);
3663: }
3664: } elsif($string =~ /^__ARRAY_REF__/) {
3665: ($key, $string)=&str2arrayref($string);
3666: if($key->[0] eq 'Array reference error') {
3667: $hash{'error'}='Bad data';
3668: return (\%hash, $string);
3669: }
3670: } else {
3671: $string =~ s/^(.*?)=//;
1.267 albertel 3672: $key=&unescape($1);
1.265 albertel 3673: }
3674: $string =~ s/^=//;
3675:
3676: #value
3677: my $value='';
3678: if($string =~ /^__HASH_REF__/) {
3679: ($value, $string)=&str2hashref($string);
3680: if(defined($value->{'error'})) {
3681: $hash{'error'}='Bad data';
3682: return (\%hash, $string);
3683: }
3684: } elsif($string =~ /^__ARRAY_REF__/) {
3685: ($value, $string)=&str2arrayref($string);
3686: if($value->[0] eq 'Array reference error') {
3687: $hash{'error'}='Bad data';
3688: return (\%hash, $string);
3689: }
3690: } else {
3691: $value=&get_scalar(\$string,'__END_HASH_REF__');
3692: }
3693: $string =~ s/^&//;
3694:
3695: $hash{$key}=$value;
1.204 albertel 3696: }
1.265 albertel 3697:
3698: $string =~ s/^__END_HASH_REF__//;
3699:
3700: return (\%hash, $string);
1.204 albertel 3701: }
3702:
3703: sub str2array {
1.265 albertel 3704: my ($string)=@_;
3705: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3706: return @$array;
3707: }
3708:
3709: sub str2arrayref {
1.204 albertel 3710: my ($string) = @_;
1.265 albertel 3711: my @array;
3712:
3713: if($string !~ /^__ARRAY_REF__/) {
3714: if (! ($string eq '' || !defined($string))) {
3715: $array[0]='Array reference error';
3716: }
3717: return (\@array, $string);
3718: }
3719:
3720: $string =~ s/^__ARRAY_REF__//;
3721:
3722: while($string !~ /^__END_ARRAY_REF__/) {
3723: my $value='';
3724: if($string =~ /^__HASH_REF__/) {
3725: ($value, $string)=&str2hashref($string);
3726: if(defined($value->{'error'})) {
3727: $array[0] ='Array reference error';
3728: return (\@array, $string);
3729: }
3730: } elsif($string =~ /^__ARRAY_REF__/) {
3731: ($value, $string)=&str2arrayref($string);
3732: if($value->[0] eq 'Array reference error') {
3733: $array[0] ='Array reference error';
3734: return (\@array, $string);
3735: }
3736: } else {
3737: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3738: }
3739: $string =~ s/^&//;
3740:
3741: push(@array, $value);
1.191 harris41 3742: }
1.265 albertel 3743:
3744: $string =~ s/^__END_ARRAY_REF__//;
3745:
3746: return (\@array, $string);
1.168 albertel 3747: }
3748:
1.167 albertel 3749: # -------------------------------------------------------------------Temp Store
3750:
1.168 albertel 3751: sub tmpreset {
3752: my ($symb,$namespace,$domain,$stuname) = @_;
3753: if (!$symb) {
3754: $symb=&symbread();
1.620 albertel 3755: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3756: }
3757: $symb=escape($symb);
3758:
1.620 albertel 3759: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3760: $namespace=~s/\//\_/g;
3761: $namespace=~s/\W//g;
3762:
1.620 albertel 3763: if (!$domain) { $domain=$env{'user.domain'}; }
3764: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3765: if ($domain eq 'public' && $stuname eq 'public') {
3766: $stuname=$ENV{'REMOTE_ADDR'};
3767: }
1.168 albertel 3768: my $path=$perlvar{'lonDaemons'}.'/tmp';
3769: my %hash;
3770: if (tie(%hash,'GDBM_File',
3771: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3772: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3773: foreach my $key (keys(%hash)) {
1.180 albertel 3774: if ($key=~ /:$symb/) {
1.168 albertel 3775: delete($hash{$key});
3776: }
3777: }
3778: }
3779: }
3780:
1.167 albertel 3781: sub tmpstore {
1.168 albertel 3782: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3783:
3784: if (!$symb) {
3785: $symb=&symbread();
1.620 albertel 3786: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3787: }
3788: $symb=escape($symb);
3789:
3790: if (!$namespace) {
3791: # I don't think we would ever want to store this for a course.
3792: # it seems this will only be used if we don't have a course.
1.620 albertel 3793: #$namespace=$env{'request.course.id'};
1.168 albertel 3794: #if (!$namespace) {
1.620 albertel 3795: $namespace=$env{'request.state'};
1.168 albertel 3796: #}
3797: }
3798: $namespace=~s/\//\_/g;
3799: $namespace=~s/\W//g;
1.620 albertel 3800: if (!$domain) { $domain=$env{'user.domain'}; }
3801: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3802: if ($domain eq 'public' && $stuname eq 'public') {
3803: $stuname=$ENV{'REMOTE_ADDR'};
3804: }
1.168 albertel 3805: my $now=time;
3806: my %hash;
3807: my $path=$perlvar{'lonDaemons'}.'/tmp';
3808: if (tie(%hash,'GDBM_File',
3809: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3810: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3811: $hash{"version:$symb"}++;
3812: my $version=$hash{"version:$symb"};
3813: my $allkeys='';
3814: foreach my $key (keys(%$storehash)) {
3815: $allkeys.=$key.':';
1.591 albertel 3816: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3817: }
3818: $hash{"$version:$symb:timestamp"}=$now;
3819: $allkeys.='timestamp';
3820: $hash{"$version:keys:$symb"}=$allkeys;
3821: if (untie(%hash)) {
3822: return 'ok';
3823: } else {
3824: return "error:$!";
3825: }
3826: } else {
3827: return "error:$!";
3828: }
3829: }
1.167 albertel 3830:
1.168 albertel 3831: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3832:
1.168 albertel 3833: sub tmprestore {
3834: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3835:
1.168 albertel 3836: if (!$symb) {
3837: $symb=&symbread();
1.620 albertel 3838: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3839: }
3840: $symb=escape($symb);
3841:
1.620 albertel 3842: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3843:
1.620 albertel 3844: if (!$domain) { $domain=$env{'user.domain'}; }
3845: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3846: if ($domain eq 'public' && $stuname eq 'public') {
3847: $stuname=$ENV{'REMOTE_ADDR'};
3848: }
1.168 albertel 3849: my %returnhash;
3850: $namespace=~s/\//\_/g;
3851: $namespace=~s/\W//g;
3852: my %hash;
3853: my $path=$perlvar{'lonDaemons'}.'/tmp';
3854: if (tie(%hash,'GDBM_File',
3855: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3856: &GDBM_READER(),0640)) {
1.168 albertel 3857: my $version=$hash{"version:$symb"};
3858: $returnhash{'version'}=$version;
3859: my $scope;
3860: for ($scope=1;$scope<=$version;$scope++) {
3861: my $vkeys=$hash{"$scope:keys:$symb"};
3862: my @keys=split(/:/,$vkeys);
3863: my $key;
3864: $returnhash{"$scope:keys"}=$vkeys;
3865: foreach $key (@keys) {
1.591 albertel 3866: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3867: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3868: }
3869: }
1.168 albertel 3870: if (!(untie(%hash))) {
3871: return "error:$!";
3872: }
3873: } else {
3874: return "error:$!";
3875: }
3876: return %returnhash;
1.167 albertel 3877: }
3878:
1.9 www 3879: # ----------------------------------------------------------------------- Store
3880:
3881: sub store {
1.124 www 3882: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3883: my $home='';
3884:
1.168 albertel 3885: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3886:
1.213 www 3887: $symb=&symbclean($symb);
1.122 albertel 3888: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3889:
1.620 albertel 3890: if (!$domain) { $domain=$env{'user.domain'}; }
3891: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3892:
3893: &devalidate($symb,$stuname,$domain);
1.109 www 3894:
3895: $symb=escape($symb);
1.187 www 3896: if (!$namespace) {
1.620 albertel 3897: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3898: return '';
3899: }
3900: }
1.620 albertel 3901: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3902:
3903: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3904: $$storehash{'host'}=$perlvar{'lonHostID'};
3905:
1.12 www 3906: my $namevalue='';
1.800 albertel 3907: foreach my $key (keys(%$storehash)) {
3908: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3909: }
1.12 www 3910: $namevalue=~s/\&$//;
1.187 www 3911: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3912: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3913: }
3914:
1.47 www 3915: # -------------------------------------------------------------- Critical Store
3916:
3917: sub cstore {
1.124 www 3918: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3919: my $home='';
3920:
1.168 albertel 3921: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3922:
1.213 www 3923: $symb=&symbclean($symb);
1.122 albertel 3924: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3925:
1.620 albertel 3926: if (!$domain) { $domain=$env{'user.domain'}; }
3927: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3928:
3929: &devalidate($symb,$stuname,$domain);
1.109 www 3930:
3931: $symb=escape($symb);
1.187 www 3932: if (!$namespace) {
1.620 albertel 3933: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3934: return '';
3935: }
3936: }
1.620 albertel 3937: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3938:
3939: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3940: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3941:
1.47 www 3942: my $namevalue='';
1.800 albertel 3943: foreach my $key (keys(%$storehash)) {
3944: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3945: }
1.47 www 3946: $namevalue=~s/\&$//;
1.187 www 3947: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3948: return critical
3949: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3950: }
3951:
1.9 www 3952: # --------------------------------------------------------------------- Restore
3953:
3954: sub restore {
1.124 www 3955: my ($symb,$namespace,$domain,$stuname) = @_;
3956: my $home='';
3957:
1.168 albertel 3958: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3959:
1.122 albertel 3960: if (!$symb) {
3961: unless ($symb=escape(&symbread())) { return ''; }
3962: } else {
1.213 www 3963: $symb=&escape(&symbclean($symb));
1.122 albertel 3964: }
1.188 www 3965: if (!$namespace) {
1.620 albertel 3966: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3967: return '';
3968: }
3969: }
1.620 albertel 3970: if (!$domain) { $domain=$env{'user.domain'}; }
3971: if (!$stuname) { $stuname=$env{'user.name'}; }
3972: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3973: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3974:
1.12 www 3975: my %returnhash=();
1.800 albertel 3976: foreach my $line (split(/\&/,$answer)) {
3977: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3978: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3979: }
1.75 www 3980: my $version;
3981: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3982: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3983: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3984: }
1.75 www 3985: }
1.13 www 3986: return %returnhash;
1.34 www 3987: }
3988:
3989: # ---------------------------------------------------------- Course Description
3990:
3991: sub coursedescription {
1.731 albertel 3992: my ($courseid,$args)=@_;
1.34 www 3993: $courseid=~s/^\///;
1.49 www 3994: $courseid=~s/\_/\//g;
1.34 www 3995: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3996: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3997: my $normalid=$cdomain.'_'.$cnum;
3998: # need to always cache even if we get errors otherwise we keep
3999: # trying and trying and trying to get the course description.
4000: my %envhash=();
4001: my %returnhash=();
1.731 albertel 4002:
4003: my $expiretime=600;
4004: if ($env{'request.course.id'} eq $normalid) {
4005: $expiretime=120;
4006: }
4007:
4008: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4009: if (!$args->{'freshen_cache'}
4010: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4011: foreach my $key (keys(%env)) {
4012: next if ($key !~ /^\Q$prefix\E(.*)/);
4013: my ($setting) = $1;
4014: $returnhash{$setting} = $env{$key};
4015: }
4016: return %returnhash;
4017: }
4018:
4019: # get the data agin
4020: if (!$args->{'one_time'}) {
4021: $envhash{'course.'.$normalid.'.last_cache'}=time;
4022: }
1.811 albertel 4023:
1.34 www 4024: if ($chome ne 'no_host') {
1.302 albertel 4025: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4026: if (!exists($returnhash{'con_lost'})) {
4027: $returnhash{'home'}= $chome;
4028: $returnhash{'domain'} = $cdomain;
4029: $returnhash{'num'} = $cnum;
1.741 raeburn 4030: if (!defined($returnhash{'type'})) {
4031: $returnhash{'type'} = 'Course';
4032: }
1.130 albertel 4033: while (my ($name,$value) = each %returnhash) {
1.53 www 4034: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4035: }
1.270 www 4036: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 4037: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 4038: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 4039: $envhash{'course.'.$normalid.'.home'}=$chome;
4040: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4041: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4042: }
4043: }
1.731 albertel 4044: if (!$args->{'one_time'}) {
1.949 raeburn 4045: &appenv(\%envhash);
1.731 albertel 4046: }
1.302 albertel 4047: return %returnhash;
1.461 www 4048: }
4049:
1.1056.4.5 raeburn 4050: sub update_released_required {
4051: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4052: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4053: $cid = $env{'request.course.id'};
4054: $cdom = $env{'course.'.$cid.'.domain'};
4055: $cnum = $env{'course.'.$cid.'.num'};
4056: $chome = $env{'course.'.$cid.'.home'};
4057: }
4058: if ($needsrelease) {
4059: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4060: my $needsupdate;
4061: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4062: $needsupdate = 1;
4063: } else {
4064: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4065: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4066: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4067: $needsupdate = 1;
4068: }
4069: }
4070: if ($needsupdate) {
4071: my %needshash = (
4072: 'internal.releaserequired' => $needsrelease,
4073: );
4074: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4075: if ($putresult eq 'ok') {
4076: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4077: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4078: if (ref($crsinfo{$cid}) eq 'HASH') {
4079: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4080: &courseidput($cdom,\%crsinfo,$chome,'notime');
4081: }
4082: }
4083: }
4084: }
4085: return;
4086: }
4087:
1.461 www 4088: # -------------------------------------------------See if a user is privileged
4089:
4090: sub privileged {
4091: my ($username,$domain)=@_;
4092: my $rolesdump=&reply("dump:$domain:$username:roles",
4093: &homeserver($username,$domain));
1.1033 raeburn 4094: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4095: ($rolesdump =~ /^error:/)) {
4096: return 0;
4097: }
1.461 www 4098: my $now=time;
4099: if ($rolesdump ne '') {
1.800 albertel 4100: foreach my $entry (split(/&/,$rolesdump)) {
4101: if ($entry!~/^rolesdef_/) {
4102: my ($area,$role)=split(/=/,$entry);
1.461 www 4103: $area=~s/\_\w\w$//;
4104: my ($trole,$tend,$tstart)=split(/_/,$role);
4105: if (($trole eq 'dc') || ($trole eq 'su')) {
4106: my $active=1;
4107: if ($tend) {
4108: if ($tend<$now) { $active=0; }
4109: }
4110: if ($tstart) {
4111: if ($tstart>$now) { $active=0; }
4112: }
4113: if ($active) { return 1; }
4114: }
4115: }
4116: }
4117: }
4118: return 0;
1.9 www 4119: }
1.1 albertel 4120:
1.103 harris41 4121: # -------------------------------------------------------- Get user privileges
1.11 www 4122:
4123: sub rolesinit {
4124: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4125: my $now=time;
4126: my %userroles = ('user.login.time' => $now);
1.1056.4.3 raeburn 4127: my $extra = &freeze_escape({'clientcheckrole' => 1});
4128: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4129: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1056.4.3 raeburn 4130: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4131: return \%userroles;
4132: }
1.11 www 4133: my %allroles=();
1.678 raeburn 4134: my %allgroups=();
4135: my $group_privs;
1.11 www 4136:
4137: if ($rolesdump ne '') {
1.800 albertel 4138: foreach my $entry (split(/&/,$rolesdump)) {
4139: if ($entry!~/^rolesdef_/) {
4140: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4141: $area=~s/\_\w\w$//;
1.678 raeburn 4142: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4143: if ($role=~/^cr/) {
1.807 albertel 4144: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4145: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4146: ($tend,$tstart)=split('_',$trest);
4147: } else {
4148: $trole=$role;
4149: }
1.678 raeburn 4150: } elsif ($role =~ m|^gr/|) {
4151: ($trole,$tend,$tstart) = split(/_/,$role);
4152: ($trole,$group_privs) = split(/\//,$trole);
4153: $group_privs = &unescape($group_privs);
1.587 albertel 4154: } else {
4155: ($trole,$tend,$tstart)=split(/_/,$role);
4156: }
1.743 albertel 4157: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4158: $username);
4159: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4160: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4161: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4162: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4163: my $spec=$trole.'.'.$area;
4164: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4165: if ($trole =~ /^cr\//) {
1.567 raeburn 4166: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4167: } elsif ($trole eq 'gr') {
4168: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4169: } else {
1.567 raeburn 4170: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4171: }
1.12 www 4172: }
1.662 raeburn 4173: }
1.191 harris41 4174: }
1.743 albertel 4175: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4176: $userroles{'user.adv'} = $adv;
4177: $userroles{'user.author'} = $author;
1.620 albertel 4178: $env{'user.adv'}=$adv;
1.11 www 4179: }
1.743 albertel 4180: return \%userroles;
1.11 www 4181: }
4182:
1.567 raeburn 4183: sub set_arearole {
4184: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4185: # log the associated role with the area
4186: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4187: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4188: }
4189:
4190: sub custom_roleprivs {
4191: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4192: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4193: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4194: if (&hostname($homsvr) ne '') {
1.567 raeburn 4195: my ($rdummy,$roledef)=
4196: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4197: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4198: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4199: if (defined($syspriv)) {
1.1043 raeburn 4200: if ($trest =~ /^$match_community$/) {
4201: $syspriv =~ s/bre\&S//;
4202: }
1.567 raeburn 4203: $$allroles{'cm./'}.=':'.$syspriv;
4204: $$allroles{$spec.'./'}.=':'.$syspriv;
4205: }
4206: if ($tdomain ne '') {
4207: if (defined($dompriv)) {
4208: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4209: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4210: }
4211: if (($trest ne '') && (defined($coursepriv))) {
4212: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4213: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4214: }
4215: }
4216: }
4217: }
4218: }
4219:
1.678 raeburn 4220: sub group_roleprivs {
4221: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4222: my $access = 1;
4223: my $now = time;
4224: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4225: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4226: if ($access) {
1.811 albertel 4227: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4228: $$allgroups{$course}{$group} .=':'.$group_privs;
4229: }
4230: }
1.567 raeburn 4231:
4232: sub standard_roleprivs {
4233: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4234: if (defined($pr{$trole.':s'})) {
4235: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4236: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4237: }
4238: if ($tdomain ne '') {
4239: if (defined($pr{$trole.':d'})) {
4240: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4241: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4242: }
4243: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4244: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4245: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4246: }
4247: }
4248: }
4249:
4250: sub set_userprivs {
1.1056.4.2 raeburn 4251: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4252: my $author=0;
4253: my $adv=0;
1.678 raeburn 4254: my %grouproles = ();
4255: if (keys(%{$allgroups}) > 0) {
1.1056.4.2 raeburn 4256: my @groupkeys;
1.1000 raeburn 4257: foreach my $role (keys(%{$allroles})) {
1.1056.4.2 raeburn 4258: push(@groupkeys,$role);
4259: }
4260: if (ref($groups_roles) eq 'HASH') {
4261: foreach my $key (keys(%{$groups_roles})) {
4262: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4263: push(@groupkeys,$key);
4264: }
4265: }
4266: }
4267: if (@groupkeys > 0) {
4268: foreach my $role (@groupkeys) {
4269: my ($trole,$area,$sec,$extendedarea);
4270: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4271: $trole = $1;
4272: $area = $2;
4273: $sec = $3;
4274: $extendedarea = $area.$sec;
4275: if (exists($$allgroups{$area})) {
4276: foreach my $group (keys(%{$$allgroups{$area}})) {
4277: my $spec = $trole.'.'.$extendedarea;
4278: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4279: $$allgroups{$area}{$group};
1.1056.4.2 raeburn 4280: }
1.678 raeburn 4281: }
4282: }
4283: }
4284: }
4285: }
1.800 albertel 4286: foreach my $group (keys(%grouproles)) {
4287: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4288: }
1.800 albertel 4289: foreach my $role (keys(%{$allroles})) {
4290: my %thesepriv;
1.941 raeburn 4291: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4292: foreach my $item (split(/:/,$$allroles{$role})) {
4293: if ($item ne '') {
4294: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4295: if ($restrictions eq '') {
4296: $thesepriv{$privilege}='F';
4297: } elsif ($thesepriv{$privilege} ne 'F') {
4298: $thesepriv{$privilege}.=$restrictions;
4299: }
4300: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4301: }
4302: }
4303: my $thesestr='';
1.800 albertel 4304: foreach my $priv (keys(%thesepriv)) {
4305: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4306: }
4307: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4308: }
4309: return ($author,$adv);
4310: }
4311:
1.994 raeburn 4312: sub role_status {
1.1002 raeburn 4313: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4314: my @pwhere = ();
4315: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4316: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4317: unless (!defined($$role) || $$role eq '') {
4318: $$where=join('.',@pwhere);
4319: $$trolecode=$$role.'.'.$$where;
4320: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4321: $$tstatus='is';
4322: if ($$tstart && $$tstart>$then) {
4323: $$tstatus='future';
1.1034 raeburn 4324: if ($$tstart<$now) {
4325: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4326: if (($$where ne '') && ($$role ne '')) {
1.1056.4.2 raeburn 4327: my (%allroles,%allgroups,$group_privs,
4328: %groups_roles,@rolecodes);
1.1002 raeburn 4329: my %userroles = (
4330: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4331: );
1.1056.4.2 raeburn 4332: @rolecodes = ('cm');
1.1002 raeburn 4333: my $spec=$$role.'.'.$$where;
4334: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4335: if ($$role =~ /^cr\//) {
4336: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2 raeburn 4337: push(@rolecodes,'cr');
1.1002 raeburn 4338: } elsif ($$role eq 'gr') {
1.1056.4.2 raeburn 4339: push(@rolecodes,$$role);
1.1002 raeburn 4340: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4341: $env{'user.name'});
1.1056.4.2 raeburn 4342: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4343: (undef,my $group_privs) = split(/\//,$trole);
4344: $group_privs = &unescape($group_privs);
4345: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2 raeburn 4346: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4347: if (keys(%course_roles) > 0) {
4348: my ($tnum) = ($trest =~ /^($match_courseid)/);
4349: if ($tdomain ne '' && $tnum ne '') {
4350: foreach my $key (keys(%course_roles)) {
4351: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4352: my $crsrole = $1;
4353: my $crssec = $2;
4354: if ($crsrole =~ /^cr/) {
4355: unless (grep(/^cr$/,@rolecodes)) {
4356: push(@rolecodes,'cr');
4357: }
4358: } else {
4359: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4360: push(@rolecodes,$crsrole);
4361: }
4362: }
4363: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4364: if ($crssec ne '') {
4365: $rolekey .= '/'.$crssec;
4366: }
4367: $rolekey .= './';
4368: $groups_roles{$rolekey} = \@rolecodes;
4369: }
4370: }
4371: }
4372: }
1.1002 raeburn 4373: } else {
1.1056.4.2 raeburn 4374: push(@rolecodes,$$role);
1.1002 raeburn 4375: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4376: }
1.1056.4.2 raeburn 4377: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4378: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4379: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4380: }
4381: }
1.1034 raeburn 4382: $$tstatus = 'is';
1.1002 raeburn 4383: }
1.994 raeburn 4384: }
4385: if ($$tend) {
4386: if ($$tend<$then) {
4387: $$tstatus='expired';
4388: } elsif ($$tend<$now) {
4389: $$tstatus='will_not';
4390: }
4391: }
4392: }
4393: }
4394: }
4395:
4396: sub check_adhoc_privs {
1.1002 raeburn 4397: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
1.994 raeburn 4398: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4399: if ($env{$cckey}) {
4400: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4401: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4402: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4403: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4404: }
4405: } else {
4406: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4407: }
4408: }
4409:
4410: sub set_adhoc_privileges {
4411: # role can be cc or ca
4412: my ($dcdom,$pickedcourse,$role) = @_;
4413: my $area = '/'.$dcdom.'/'.$pickedcourse;
4414: my $spec = $role.'.'.$area;
4415: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4416: $env{'user.name'});
4417: my %ccrole = ();
4418: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4419: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4420: &appenv(\%userroles,[$role,'cm']);
4421: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4422: &appenv( {'request.role' => $spec,
4423: 'request.role.domain' => $dcdom,
4424: 'request.course.sec' => ''
4425: }
4426: );
4427: my $tadv=0;
4428: if (&allowed('adv') eq 'F') { $tadv=1; }
4429: &appenv({'request.role.adv' => $tadv});
4430: }
4431:
1.12 www 4432: # --------------------------------------------------------------- get interface
4433:
4434: sub get {
1.131 albertel 4435: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4436: my $items='';
1.800 albertel 4437: foreach my $item (@$storearr) {
4438: $items.=&escape($item).'&';
1.191 harris41 4439: }
1.12 www 4440: $items=~s/\&$//;
1.620 albertel 4441: if (!$udomain) { $udomain=$env{'user.domain'}; }
4442: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4443: my $uhome=&homeserver($uname,$udomain);
4444:
1.133 albertel 4445: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4446: my @pairs=split(/\&/,$rep);
1.273 albertel 4447: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4448: return @pairs;
4449: }
1.15 www 4450: my %returnhash=();
1.42 www 4451: my $i=0;
1.800 albertel 4452: foreach my $item (@$storearr) {
4453: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4454: $i++;
1.191 harris41 4455: }
1.15 www 4456: return %returnhash;
1.27 www 4457: }
4458:
4459: # --------------------------------------------------------------- del interface
4460:
4461: sub del {
1.133 albertel 4462: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4463: my $items='';
1.800 albertel 4464: foreach my $item (@$storearr) {
4465: $items.=&escape($item).'&';
1.191 harris41 4466: }
1.984 neumanie 4467:
1.27 www 4468: $items=~s/\&$//;
1.620 albertel 4469: if (!$udomain) { $udomain=$env{'user.domain'}; }
4470: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4471: my $uhome=&homeserver($uname,$udomain);
4472: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4473: }
4474:
4475: # -------------------------------------------------------------- dump interface
4476:
4477: sub dump {
1.755 albertel 4478: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4479: if (!$udomain) { $udomain=$env{'user.domain'}; }
4480: if (!$uname) { $uname=$env{'user.name'}; }
4481: my $uhome=&homeserver($uname,$udomain);
4482: if ($regexp) {
4483: $regexp=&escape($regexp);
4484: } else {
4485: $regexp='.';
4486: }
4487: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4488: my @pairs=split(/\&/,$rep);
4489: my %returnhash=();
4490: foreach my $item (@pairs) {
4491: my ($key,$value)=split(/=/,$item,2);
4492: $key = &unescape($key);
4493: next if ($key =~ /^error: 2 /);
4494: $returnhash{$key}=&thaw_unescape($value);
4495: }
4496: return %returnhash;
1.407 www 4497: }
4498:
1.717 albertel 4499: # --------------------------------------------------------- dumpstore interface
4500:
4501: sub dumpstore {
4502: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4503: if (!$udomain) { $udomain=$env{'user.domain'}; }
4504: if (!$uname) { $uname=$env{'user.name'}; }
4505: my $uhome=&homeserver($uname,$udomain);
4506: if ($regexp) {
4507: $regexp=&escape($regexp);
4508: } else {
4509: $regexp='.';
4510: }
4511: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4512: my @pairs=split(/\&/,$rep);
4513: my %returnhash=();
4514: foreach my $item (@pairs) {
4515: my ($key,$value)=split(/=/,$item,2);
4516: next if ($key =~ /^error: 2 /);
4517: $returnhash{$key}=&thaw_unescape($value);
4518: }
4519: return %returnhash;
1.717 albertel 4520: }
4521:
1.407 www 4522: # -------------------------------------------------------------- keys interface
4523:
4524: sub getkeys {
4525: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4526: if (!$udomain) { $udomain=$env{'user.domain'}; }
4527: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4528: my $uhome=&homeserver($uname,$udomain);
4529: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4530: my @keyarray=();
1.800 albertel 4531: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4532: next if ($key =~ /^error: 2 /);
1.800 albertel 4533: push(@keyarray,&unescape($key));
1.407 www 4534: }
4535: return @keyarray;
1.318 matthew 4536: }
4537:
1.319 matthew 4538: # --------------------------------------------------------------- currentdump
4539: sub currentdump {
1.328 matthew 4540: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4541: $courseid = $env{'request.course.id'} if (! defined($courseid));
4542: $sdom = $env{'user.domain'} if (! defined($sdom));
4543: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4544: my $uhome = &homeserver($sname,$sdom);
4545: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4546: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4547: #
1.318 matthew 4548: my %returnhash=();
1.319 matthew 4549: #
4550: if ($rep eq "unknown_cmd") {
4551: # an old lond will not know currentdump
4552: # Do a dump and make it look like a currentdump
1.822 albertel 4553: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4554: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4555: my %hash = @tmp;
4556: @tmp=();
1.424 matthew 4557: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4558: } else {
4559: my @pairs=split(/\&/,$rep);
1.800 albertel 4560: foreach my $pair (@pairs) {
4561: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4562: my ($symb,$param) = split(/:/,$key);
4563: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4564: &thaw_unescape($value);
1.319 matthew 4565: }
1.191 harris41 4566: }
1.12 www 4567: return %returnhash;
1.424 matthew 4568: }
4569:
4570: sub convert_dump_to_currentdump{
4571: my %hash = %{shift()};
4572: my %returnhash;
4573: # Code ripped from lond, essentially. The only difference
4574: # here is the unescaping done by lonnet::dump(). Conceivably
4575: # we might run in to problems with parameter names =~ /^v\./
4576: while (my ($key,$value) = each(%hash)) {
4577: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4578: $symb = &unescape($symb);
4579: $param = &unescape($param);
1.424 matthew 4580: next if ($v eq 'version' || $symb eq 'keys');
4581: next if (exists($returnhash{$symb}) &&
4582: exists($returnhash{$symb}->{$param}) &&
4583: $returnhash{$symb}->{'v.'.$param} > $v);
4584: $returnhash{$symb}->{$param}=$value;
4585: $returnhash{$symb}->{'v.'.$param}=$v;
4586: }
4587: #
4588: # Remove all of the keys in the hashes which keep track of
4589: # the version of the parameter.
4590: while (my ($symb,$param_hash) = each(%returnhash)) {
4591: # use a foreach because we are going to delete from the hash.
4592: foreach my $key (keys(%$param_hash)) {
4593: delete($param_hash->{$key}) if ($key =~ /^v\./);
4594: }
4595: }
4596: return \%returnhash;
1.12 www 4597: }
4598:
1.627 albertel 4599: # ------------------------------------------------------ critical inc interface
4600:
4601: sub cinc {
4602: return &inc(@_,'critical');
4603: }
4604:
1.449 matthew 4605: # --------------------------------------------------------------- inc interface
4606:
4607: sub inc {
1.627 albertel 4608: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4609: if (!$udomain) { $udomain=$env{'user.domain'}; }
4610: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4611: my $uhome=&homeserver($uname,$udomain);
4612: my $items='';
4613: if (! ref($store)) {
4614: # got a single value, so use that instead
4615: $items = &escape($store).'=&';
4616: } elsif (ref($store) eq 'SCALAR') {
4617: $items = &escape($$store).'=&';
4618: } elsif (ref($store) eq 'ARRAY') {
4619: $items = join('=&',map {&escape($_);} @{$store});
4620: } elsif (ref($store) eq 'HASH') {
4621: while (my($key,$value) = each(%{$store})) {
4622: $items.= &escape($key).'='.&escape($value).'&';
4623: }
4624: }
4625: $items=~s/\&$//;
1.627 albertel 4626: if ($critical) {
4627: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4628: } else {
4629: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4630: }
1.449 matthew 4631: }
4632:
1.12 www 4633: # --------------------------------------------------------------- put interface
4634:
4635: sub put {
1.134 albertel 4636: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4637: if (!$udomain) { $udomain=$env{'user.domain'}; }
4638: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4639: my $uhome=&homeserver($uname,$udomain);
1.12 www 4640: my $items='';
1.800 albertel 4641: foreach my $item (keys(%$storehash)) {
4642: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4643: }
1.12 www 4644: $items=~s/\&$//;
1.134 albertel 4645: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4646: }
4647:
1.631 albertel 4648: # ------------------------------------------------------------ newput interface
4649:
4650: sub newput {
4651: my ($namespace,$storehash,$udomain,$uname)=@_;
4652: if (!$udomain) { $udomain=$env{'user.domain'}; }
4653: if (!$uname) { $uname=$env{'user.name'}; }
4654: my $uhome=&homeserver($uname,$udomain);
4655: my $items='';
4656: foreach my $key (keys(%$storehash)) {
4657: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4658: }
4659: $items=~s/\&$//;
4660: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4661: }
4662:
4663: # --------------------------------------------------------- putstore interface
4664:
1.524 raeburn 4665: sub putstore {
1.715 albertel 4666: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4667: if (!$udomain) { $udomain=$env{'user.domain'}; }
4668: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4669: my $uhome=&homeserver($uname,$udomain);
4670: my $items='';
1.715 albertel 4671: foreach my $key (keys(%$storehash)) {
4672: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4673: }
1.715 albertel 4674: $items=~s/\&$//;
1.716 albertel 4675: my $esc_symb=&escape($symb);
4676: my $esc_v=&escape($version);
1.715 albertel 4677: my $reply =
1.716 albertel 4678: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4679: $uhome);
4680: if ($reply eq 'unknown_cmd') {
1.716 albertel 4681: # gfall back to way things use to be done
1.715 albertel 4682: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4683: $uname);
1.524 raeburn 4684: }
1.715 albertel 4685: return $reply;
4686: }
4687:
4688: sub old_putstore {
1.716 albertel 4689: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4690: if (!$udomain) { $udomain=$env{'user.domain'}; }
4691: if (!$uname) { $uname=$env{'user.name'}; }
4692: my $uhome=&homeserver($uname,$udomain);
4693: my %newstorehash;
1.800 albertel 4694: foreach my $item (keys(%$storehash)) {
4695: my $key = $version.':'.&escape($symb).':'.$item;
4696: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4697: }
4698: my $items='';
4699: my %allitems = ();
1.800 albertel 4700: foreach my $item (keys(%newstorehash)) {
4701: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4702: my $key = $1.':keys:'.$2;
4703: $allitems{$key} .= $3.':';
4704: }
1.800 albertel 4705: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4706: }
1.800 albertel 4707: foreach my $item (keys(%allitems)) {
4708: $allitems{$item} =~ s/\:$//;
4709: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4710: }
4711: $items=~s/\&$//;
4712: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4713: }
4714:
1.47 www 4715: # ------------------------------------------------------ critical put interface
4716:
4717: sub cput {
1.134 albertel 4718: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4719: if (!$udomain) { $udomain=$env{'user.domain'}; }
4720: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4721: my $uhome=&homeserver($uname,$udomain);
1.47 www 4722: my $items='';
1.800 albertel 4723: foreach my $item (keys(%$storehash)) {
4724: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4725: }
1.47 www 4726: $items=~s/\&$//;
1.134 albertel 4727: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4728: }
4729:
4730: # -------------------------------------------------------------- eget interface
4731:
4732: sub eget {
1.133 albertel 4733: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4734: my $items='';
1.800 albertel 4735: foreach my $item (@$storearr) {
4736: $items.=&escape($item).'&';
1.191 harris41 4737: }
1.12 www 4738: $items=~s/\&$//;
1.620 albertel 4739: if (!$udomain) { $udomain=$env{'user.domain'}; }
4740: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4741: my $uhome=&homeserver($uname,$udomain);
4742: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4743: my @pairs=split(/\&/,$rep);
4744: my %returnhash=();
1.42 www 4745: my $i=0;
1.800 albertel 4746: foreach my $item (@$storearr) {
4747: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4748: $i++;
1.191 harris41 4749: }
1.12 www 4750: return %returnhash;
4751: }
4752:
1.667 albertel 4753: # ------------------------------------------------------------ tmpput interface
4754: sub tmpput {
1.802 raeburn 4755: my ($storehash,$server,$context)=@_;
1.667 albertel 4756: my $items='';
1.800 albertel 4757: foreach my $item (keys(%$storehash)) {
4758: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4759: }
4760: $items=~s/\&$//;
1.802 raeburn 4761: if (defined($context)) {
4762: $items .= ':'.&escape($context);
4763: }
1.667 albertel 4764: return &reply("tmpput:$items",$server);
4765: }
4766:
4767: # ------------------------------------------------------------ tmpget interface
4768: sub tmpget {
1.688 albertel 4769: my ($token,$server)=@_;
4770: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4771: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4772: my %returnhash;
4773: foreach my $item (split(/\&/,$rep)) {
4774: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4775: next if ($key =~ /^error: 2 /);
1.667 albertel 4776: $returnhash{&unescape($key)}=&thaw_unescape($value);
4777: }
4778: return %returnhash;
4779: }
4780:
1.688 albertel 4781: # ------------------------------------------------------------ tmpget interface
4782: sub tmpdel {
4783: my ($token,$server)=@_;
4784: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4785: return &reply("tmpdel:$token",$server);
4786: }
4787:
1.765 albertel 4788: # -------------------------------------------------- portfolio access checking
4789:
4790: sub portfolio_access {
1.766 albertel 4791: my ($requrl) = @_;
1.765 albertel 4792: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4793: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4794: if ($result) {
4795: my %setters;
4796: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4797: my ($startblock,$endblock) =
4798: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4799: if ($startblock && $endblock) {
4800: return 'B';
4801: }
4802: } else {
4803: my ($startblock,$endblock) =
4804: &Apache::loncommon::blockcheck(\%setters,'port');
4805: if ($startblock && $endblock) {
4806: return 'B';
4807: }
4808: }
4809: }
1.765 albertel 4810: if ($result eq 'ok') {
1.766 albertel 4811: return 'F';
1.765 albertel 4812: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4813: return 'A';
1.765 albertel 4814: }
1.766 albertel 4815: return '';
1.765 albertel 4816: }
4817:
4818: sub get_portfolio_access {
1.767 albertel 4819: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4820:
4821: if (!ref($access_hash)) {
4822: my $current_perms = &get_portfile_permissions($udom,$unum);
4823: my %access_controls = &get_access_controls($current_perms,$group,
4824: $file_name);
4825: $access_hash = $access_controls{$file_name};
4826: }
4827:
1.765 albertel 4828: my ($public,$guest,@domains,@users,@courses,@groups);
4829: my $now = time;
4830: if (ref($access_hash) eq 'HASH') {
4831: foreach my $key (keys(%{$access_hash})) {
4832: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4833: if ($start > $now) {
4834: next;
4835: }
4836: if ($end && $end<$now) {
4837: next;
4838: }
4839: if ($scope eq 'public') {
4840: $public = $key;
4841: last;
4842: } elsif ($scope eq 'guest') {
4843: $guest = $key;
4844: } elsif ($scope eq 'domains') {
4845: push(@domains,$key);
4846: } elsif ($scope eq 'users') {
4847: push(@users,$key);
4848: } elsif ($scope eq 'course') {
4849: push(@courses,$key);
4850: } elsif ($scope eq 'group') {
4851: push(@groups,$key);
4852: }
4853: }
4854: if ($public) {
4855: return 'ok';
4856: }
4857: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4858: if ($guest) {
4859: return $guest;
4860: }
4861: } else {
4862: if (@domains > 0) {
4863: foreach my $domkey (@domains) {
4864: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4865: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4866: return 'ok';
4867: }
4868: }
4869: }
4870: }
4871: if (@users > 0) {
4872: foreach my $userkey (@users) {
1.865 raeburn 4873: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4874: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4875: if (ref($item) eq 'HASH') {
4876: if (($item->{'uname'} eq $env{'user.name'}) &&
4877: ($item->{'udom'} eq $env{'user.domain'})) {
4878: return 'ok';
4879: }
4880: }
4881: }
4882: }
1.765 albertel 4883: }
4884: }
4885: my %roleshash;
4886: my @courses_and_groups = @courses;
4887: push(@courses_and_groups,@groups);
4888: if (@courses_and_groups > 0) {
4889: my (%allgroups,%allroles);
4890: my ($start,$end,$role,$sec,$group);
4891: foreach my $envkey (%env) {
1.1056.4.1 raeburn 4892: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4893: my $cid = $2.'_'.$3;
4894: if ($1 eq 'gr') {
4895: $group = $4;
4896: $allgroups{$cid}{$group} = $env{$envkey};
4897: } else {
4898: if ($4 eq '') {
4899: $sec = 'none';
4900: } else {
4901: $sec = $4;
4902: }
4903: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4904: }
1.811 albertel 4905: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4906: my $cid = $2.'_'.$3;
4907: if ($4 eq '') {
4908: $sec = 'none';
4909: } else {
4910: $sec = $4;
4911: }
4912: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4913: }
4914: }
4915: if (keys(%allroles) == 0) {
4916: return;
4917: }
4918: foreach my $key (@courses_and_groups) {
4919: my %content = %{$$access_hash{$key}};
4920: my $cnum = $content{'number'};
4921: my $cdom = $content{'domain'};
4922: my $cid = $cdom.'_'.$cnum;
4923: if (!exists($allroles{$cid})) {
4924: next;
4925: }
4926: foreach my $role_id (keys(%{$content{'roles'}})) {
4927: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4928: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4929: my @status = @{$content{'roles'}{$role_id}{'access'}};
4930: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4931: foreach my $role (keys(%{$allroles{$cid}})) {
4932: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4933: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4934: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4935: if (grep/^all$/,@sections) {
4936: return 'ok';
4937: } else {
4938: if (grep/^$sec$/,@sections) {
4939: return 'ok';
4940: }
4941: }
4942: }
4943: }
4944: if (keys(%{$allgroups{$cid}}) == 0) {
4945: if (grep/^none$/,@groups) {
4946: return 'ok';
4947: }
4948: } else {
4949: if (grep/^all$/,@groups) {
4950: return 'ok';
4951: }
4952: foreach my $group (keys(%{$allgroups{$cid}})) {
4953: if (grep/^$group$/,@groups) {
4954: return 'ok';
4955: }
4956: }
4957: }
4958: }
4959: }
4960: }
4961: }
4962: }
4963: if ($guest) {
4964: return $guest;
4965: }
4966: }
4967: }
4968: return;
4969: }
4970:
4971: sub course_group_datechecker {
4972: my ($dates,$now,$status) = @_;
4973: my ($start,$end) = split(/\./,$dates);
4974: if (!$start && !$end) {
4975: return 'ok';
4976: }
4977: if (grep/^active$/,@{$status}) {
4978: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4979: return 'ok';
4980: }
4981: }
4982: if (grep/^previous$/,@{$status}) {
4983: if ($end > $now ) {
4984: return 'ok';
4985: }
4986: }
4987: if (grep/^future$/,@{$status}) {
4988: if ($start > $now) {
4989: return 'ok';
4990: }
4991: }
4992: return;
4993: }
4994:
4995: sub parse_portfolio_url {
4996: my ($url) = @_;
4997:
4998: my ($type,$udom,$unum,$group,$file_name);
4999:
1.823 albertel 5000: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5001: $type = 1;
5002: $udom = $1;
5003: $unum = $2;
5004: $file_name = $3;
1.823 albertel 5005: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5006: $type = 2;
5007: $udom = $1;
5008: $unum = $2;
5009: $group = $3;
5010: $file_name = $3.'/'.$4;
5011: }
5012: if (wantarray) {
5013: return ($type,$udom,$unum,$file_name,$group);
5014: }
5015: return $type;
5016: }
5017:
5018: sub is_portfolio_url {
5019: my ($url) = @_;
5020: return scalar(&parse_portfolio_url($url));
5021: }
5022:
1.798 raeburn 5023: sub is_portfolio_file {
5024: my ($file) = @_;
1.820 raeburn 5025: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5026: return 1;
5027: }
5028: return;
5029: }
5030:
1.976 raeburn 5031: sub usertools_access {
1.985 raeburn 5032: my ($uname,$udom,$tool,$action,$context) = @_;
5033: my ($access,%tools);
5034: if ($context eq '') {
5035: $context = 'tools';
5036: }
5037: if ($context eq 'requestcourses') {
5038: %tools = (
5039: official => 1,
5040: unofficial => 1,
1.1006 raeburn 5041: community => 1,
1.985 raeburn 5042: );
5043: } else {
5044: %tools = (
5045: aboutme => 1,
5046: blog => 1,
5047: portfolio => 1,
5048: );
5049: }
1.976 raeburn 5050: return if (!defined($tools{$tool}));
5051:
5052: if ((!defined($udom)) || (!defined($uname))) {
5053: $udom = $env{'user.domain'};
5054: $uname = $env{'user.name'};
5055: }
5056:
1.978 raeburn 5057: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5058: if ($action ne 'reload') {
1.985 raeburn 5059: if ($context eq 'requestcourses') {
5060: return $env{'environment.canrequest.'.$tool};
5061: } else {
5062: return $env{'environment.availabletools.'.$tool};
5063: }
5064: }
1.976 raeburn 5065: }
5066:
5067: my ($toolstatus,$inststatus);
5068:
1.985 raeburn 5069: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5070: ($action ne 'reload')) {
5071: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5072: $inststatus = $env{'environment.inststatus'};
5073: } else {
1.1025 raeburn 5074: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
1.985 raeburn 5075: $toolstatus = $userenv{$context.'.'.$tool};
1.976 raeburn 5076: $inststatus = $userenv{'inststatus'};
5077: }
5078:
5079: if ($toolstatus ne '') {
5080: if ($toolstatus) {
5081: $access = 1;
5082: } else {
5083: $access = 0;
5084: }
5085: return $access;
5086: }
5087:
5088: my $is_adv = &is_advanced_user($udom,$uname);
5089: my %domdef = &get_domain_defaults($udom);
5090: if (ref($domdef{$tool}) eq 'HASH') {
5091: if ($is_adv) {
5092: if ($domdef{$tool}{'_LC_adv'} ne '') {
5093: if ($domdef{$tool}{'_LC_adv'}) {
5094: $access = 1;
5095: } else {
5096: $access = 0;
5097: }
5098: return $access;
5099: }
5100: }
5101: if ($inststatus ne '') {
5102: my ($hasaccess,$hasnoaccess);
5103: foreach my $affiliation (split(/:/,$inststatus)) {
5104: if ($domdef{$tool}{$affiliation} ne '') {
5105: if ($domdef{$tool}{$affiliation}) {
5106: $hasaccess = 1;
5107: } else {
5108: $hasnoaccess = 1;
5109: }
5110: }
5111: }
5112: if ($hasaccess || $hasnoaccess) {
5113: if ($hasaccess) {
5114: $access = 1;
5115: } elsif ($hasnoaccess) {
5116: $access = 0;
5117: }
5118: return $access;
5119: }
5120: } else {
5121: if ($domdef{$tool}{'default'} ne '') {
5122: if ($domdef{$tool}{'default'}) {
5123: $access = 1;
5124: } elsif ($domdef{$tool}{'default'} == 0) {
5125: $access = 0;
5126: }
5127: return $access;
5128: }
5129: }
5130: } else {
1.985 raeburn 5131: if ($context eq 'tools') {
5132: $access = 1;
5133: } else {
5134: $access = 0;
5135: }
1.976 raeburn 5136: return $access;
5137: }
5138: }
5139:
1.1050 raeburn 5140: sub is_course_owner {
5141: my ($cdom,$cnum,$udom,$uname) = @_;
5142: if (($udom eq '') || ($uname eq '')) {
5143: $udom = $env{'user.domain'};
5144: $uname = $env{'user.name'};
5145: }
5146: unless (($udom eq '') || ($uname eq '')) {
5147: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5148: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5149: return 1;
5150: } else {
5151: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5152: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5153: return 1;
5154: }
5155: }
5156: }
5157: }
5158: return;
5159: }
5160:
1.976 raeburn 5161: sub is_advanced_user {
5162: my ($udom,$uname) = @_;
5163: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5164: my %allroles;
5165: my $is_adv;
5166: foreach my $role (keys(%roleshash)) {
5167: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5168: my $area = '/'.$tdomain.'/'.$trest;
5169: if ($sec ne '') {
5170: $area .= '/'.$sec;
5171: }
5172: if (($area ne '') && ($trole ne '')) {
5173: my $spec=$trole.'.'.$area;
5174: if ($trole =~ /^cr\//) {
5175: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5176: } elsif ($trole ne 'gr') {
5177: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5178: }
5179: }
5180: }
5181: foreach my $role (keys(%allroles)) {
5182: last if ($is_adv);
5183: foreach my $item (split(/:/,$allroles{$role})) {
5184: if ($item ne '') {
5185: my ($privilege,$restrictions)=split(/&/,$item);
5186: if ($privilege eq 'adv') {
5187: $is_adv = 1;
5188: last;
5189: }
5190: }
5191: }
5192: }
5193: return $is_adv;
5194: }
1.798 raeburn 5195:
1.1035 raeburn 5196: sub check_can_request {
1.1036 raeburn 5197: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5198: my $canreq = 0;
5199: my ($types,$typename) = &Apache::loncommon::course_types();
5200: my @options = ('approval','validate','autolimit');
5201: my $optregex = join('|',@options);
5202: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5203: foreach my $type (@{$types}) {
5204: if (&usertools_access($env{'user.name'},
5205: $env{'user.domain'},
5206: $type,undef,'requestcourses')) {
5207: $canreq ++;
1.1036 raeburn 5208: if (ref($request_domains) eq 'HASH') {
5209: push(@{$request_domains->{$type}},$env{'user.domain'});
5210: }
1.1035 raeburn 5211: if ($dom eq $env{'user.domain'}) {
5212: $can_request->{$type} = 1;
5213: }
5214: }
5215: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5216: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5217: if (@curr > 0) {
1.1036 raeburn 5218: foreach my $item (@curr) {
5219: if (ref($request_domains) eq 'HASH') {
5220: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5221: if ($otherdom ne '') {
5222: if (ref($request_domains->{$type}) eq 'ARRAY') {
5223: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5224: push(@{$request_domains->{$type}},$otherdom);
5225: }
5226: } else {
5227: push(@{$request_domains->{$type}},$otherdom);
5228: }
5229: }
5230: }
5231: }
5232: unless($dom eq $env{'user.domain'}) {
5233: $canreq ++;
1.1035 raeburn 5234: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5235: $can_request->{$type} = 1;
5236: }
5237: }
5238: }
5239: }
5240: }
5241: }
5242: return $canreq;
5243: }
5244:
1.341 www 5245: # ---------------------------------------------- Custom access rule evaluation
5246:
5247: sub customaccess {
5248: my ($priv,$uri)=@_;
1.807 albertel 5249: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5250: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5251: $udom = &LONCAPA::clean_domain($udom);
5252: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5253: my $access=0;
1.800 albertel 5254: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5255: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5256: if ($type eq 'user') {
5257: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5258: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5259: if ($tdom) {
5260: if ($tdom ne $env{'user.domain'}) { next; }
5261: }
1.896 albertel 5262: if ($tuname) {
5263: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5264: }
5265: $access=($effect eq 'allow');
5266: last;
5267: }
5268: } else {
5269: if ($role) {
5270: if ($role ne $urole) { next; }
5271: }
5272: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5273: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5274: if ($tdom) {
5275: if ($tdom ne $udom) { next; }
5276: }
5277: if ($tcrs) {
5278: if ($tcrs ne $ucrs) { next; }
5279: }
5280: if ($tsec) {
5281: if ($tsec ne $usec) { next; }
5282: }
5283: $access=($effect eq 'allow');
5284: last;
5285: }
5286: if ($realm eq '' && $role eq '') {
5287: $access=($effect eq 'allow');
5288: }
1.402 bowersj2 5289: }
1.341 www 5290: }
5291: return $access;
5292: }
5293:
1.103 harris41 5294: # ------------------------------------------------- Check for a user privilege
1.12 www 5295:
5296: sub allowed {
1.810 raeburn 5297: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5298: my $ver_orguri=$uri;
1.439 www 5299: $uri=&deversion($uri);
1.152 www 5300: my $orguri=$uri;
1.52 www 5301: $uri=&declutter($uri);
1.809 raeburn 5302:
1.810 raeburn 5303: if ($priv eq 'evb') {
5304: # Evade communication block restrictions for specified role in a course
5305: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5306: return $1;
5307: } else {
5308: return;
5309: }
5310: }
5311:
1.620 albertel 5312: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5313: # Free bre access to adm and meta resources
1.775 albertel 5314: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5315: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5316: && ($priv eq 'bre')) {
1.14 www 5317: return 'F';
1.159 www 5318: }
5319:
1.545 banghart 5320: # Free bre access to user's own portfolio contents
1.714 raeburn 5321: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5322: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5323: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5324: my %setters;
5325: my ($startblock,$endblock) =
5326: &Apache::loncommon::blockcheck(\%setters,'port');
5327: if ($startblock && $endblock) {
5328: return 'B';
5329: } else {
5330: return 'F';
5331: }
1.545 banghart 5332: }
5333:
1.762 raeburn 5334: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5335: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5336: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5337: if (exists($env{'request.course.id'})) {
5338: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5339: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5340: if (($domain eq $cdom) && ($name eq $cnum)) {
5341: my $courseprivid=$env{'request.course.id'};
5342: $courseprivid=~s/\_/\//;
5343: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5344: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5345: return $1;
1.762 raeburn 5346: } else {
5347: if ($env{'request.course.sec'}) {
5348: $courseprivid.='/'.$env{'request.course.sec'};
5349: }
5350: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5351: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5352: return $2;
5353: }
1.714 raeburn 5354: }
5355: }
5356: }
5357: }
5358:
1.159 www 5359: # Free bre to public access
5360:
5361: if ($priv eq 'bre') {
1.238 www 5362: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5363: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5364: return 'F';
5365: }
1.238 www 5366: if ($copyright eq 'priv') {
5367: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5368: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5369: return '';
5370: }
5371: }
5372: if ($copyright eq 'domain') {
5373: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5374: unless (($env{'user.domain'} eq $1) ||
5375: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5376: return '';
5377: }
1.262 matthew 5378: }
1.620 albertel 5379: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5380: # Library role, so allow browsing of resources in this domain.
5381: return 'F';
1.238 www 5382: }
1.341 www 5383: if ($copyright eq 'custom') {
5384: unless (&customaccess($priv,$uri)) { return ''; }
5385: }
1.14 www 5386: }
1.264 matthew 5387: # Domain coordinator is trying to create a course
1.620 albertel 5388: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5389: # uri is the requested domain in this case.
5390: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5391: # a role of dc for the domain in question.
1.620 albertel 5392: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5393: }
1.29 www 5394:
1.52 www 5395: my $thisallowed='';
5396: my $statecond=0;
5397: my $courseprivid='';
5398:
1.1039 raeburn 5399: my $ownaccess;
1.1043 raeburn 5400: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5401: if (($priv eq 'bro') && ($env{'user.author'})) {
5402: if ($uri eq '') {
5403: $ownaccess = 1;
5404: } else {
5405: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5406: my $udom = $env{'user.domain'};
5407: my $uname = $env{'user.name'};
5408: if ($uri =~ m{^\Q$udom\E/?$}) {
5409: $ownaccess = 1;
1.1040 raeburn 5410: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5411: unless ($uri =~ m{\.\./}) {
5412: $ownaccess = 1;
5413: }
5414: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5415: my $now = time;
5416: if ($uri =~ m{^([^/]+)/?$}) {
5417: my $adom = $1;
5418: foreach my $key (keys(%env)) {
1.1042 raeburn 5419: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5420: my ($start,$end) = split('.',$env{$key});
5421: if (($now >= $start) && (!$end || $end < $now)) {
5422: $ownaccess = 1;
5423: last;
5424: }
5425: }
5426: }
5427: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5428: my $adom = $1;
5429: my $aname = $2;
1.1042 raeburn 5430: foreach my $role ('ca','aa') {
5431: if ($env{"user.role.$role./$adom/$aname"}) {
5432: my ($start,$end) =
5433: split('.',$env{"user.role.$role./$adom/$aname"});
5434: if (($now >= $start) && (!$end || $end < $now)) {
5435: $ownaccess = 1;
5436: last;
5437: }
1.1039 raeburn 5438: }
5439: }
5440: }
5441: }
5442: }
5443: }
5444: }
5445:
1.52 www 5446: # Course
5447:
1.620 albertel 5448: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5449: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5450: $thisallowed.=$1;
5451: }
1.52 www 5452: }
1.29 www 5453:
1.52 www 5454: # Domain
5455:
1.620 albertel 5456: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5457: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5458: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5459: $thisallowed.=$1;
5460: }
1.12 www 5461: }
1.52 www 5462:
5463: # Course: uri itself is a course
1.66 www 5464: my $courseuri=$uri;
5465: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5466: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5467:
1.620 albertel 5468: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5469: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5470: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5471: $thisallowed.=$1;
5472: }
1.12 www 5473: }
1.29 www 5474:
1.665 albertel 5475: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5476: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5477: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5478: $thisallowed='';
1.671 raeburn 5479: my ($match)=&is_on_map($uri);
5480: if ($match) {
5481: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5482: =~/\Q$priv\E\&([^\:]*)/) {
5483: $thisallowed.=$1;
5484: }
5485: } else {
1.705 albertel 5486: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5487: if ($refuri) {
5488: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5489: $thisallowed='F';
1.671 raeburn 5490: } else {
5491: $refuri=&declutter($refuri);
5492: my ($match) = &is_on_map($refuri);
5493: if ($match) {
5494: $thisallowed='F';
5495: }
1.669 raeburn 5496: }
1.671 raeburn 5497: }
5498: }
1.314 www 5499: }
1.492 albertel 5500:
1.766 albertel 5501: if ($priv eq 'bre'
5502: && $thisallowed ne 'F'
5503: && $thisallowed ne '2'
5504: && &is_portfolio_url($uri)) {
5505: $thisallowed = &portfolio_access($uri);
5506: }
5507:
1.52 www 5508: # Full access at system, domain or course-wide level? Exit.
1.29 www 5509: if ($thisallowed=~/F/) {
5510: return 'F';
5511: }
5512:
1.52 www 5513: # If this is generating or modifying users, exit with special codes
1.29 www 5514:
1.643 www 5515: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5516: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5517: my ($audom,$auname)=split('/',$uri);
1.643 www 5518: # no author name given, so this just checks on the general right to make a co-author in this domain
5519: unless ($auname) { return $thisallowed; }
5520: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5521: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5522: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5523: ($audom ne $env{'request.role.domain'}))) { return ''; }
5524: }
1.52 www 5525: return $thisallowed;
5526: }
5527: #
1.103 harris41 5528: # Gathered so far: system, domain and course wide privileges
1.52 www 5529: #
5530: # Course: See if uri or referer is an individual resource that is part of
5531: # the course
5532:
1.620 albertel 5533: if ($env{'request.course.id'}) {
1.232 www 5534:
1.620 albertel 5535: $courseprivid=$env{'request.course.id'};
5536: if ($env{'request.course.sec'}) {
5537: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5538: }
5539: $courseprivid=~s/\_/\//;
5540: my $checkreferer=1;
1.232 www 5541: my ($match,$cond)=&is_on_map($uri);
5542: if ($match) {
5543: $statecond=$cond;
1.620 albertel 5544: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5545: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5546: $thisallowed.=$1;
5547: $checkreferer=0;
5548: }
1.29 www 5549: }
1.83 www 5550:
1.148 www 5551: if ($checkreferer) {
1.620 albertel 5552: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5553: unless ($refuri) {
1.800 albertel 5554: foreach my $key (keys(%env)) {
5555: if ($key=~/^httpref\..*\*/) {
5556: my $pattern=$key;
1.156 www 5557: $pattern=~s/^httpref\.\/res\///;
1.148 www 5558: $pattern=~s/\*/\[\^\/\]\+/g;
5559: $pattern=~s/\//\\\//g;
1.152 www 5560: if ($orguri=~/$pattern/) {
1.800 albertel 5561: $refuri=$env{$key};
1.148 www 5562: }
5563: }
1.191 harris41 5564: }
1.148 www 5565: }
1.232 www 5566:
1.148 www 5567: if ($refuri) {
1.152 www 5568: $refuri=&declutter($refuri);
1.232 www 5569: my ($match,$cond)=&is_on_map($refuri);
5570: if ($match) {
5571: my $refstatecond=$cond;
1.620 albertel 5572: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5573: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5574: $thisallowed.=$1;
1.53 www 5575: $uri=$refuri;
5576: $statecond=$refstatecond;
1.52 www 5577: }
5578: }
1.148 www 5579: }
1.29 www 5580: }
1.52 www 5581: }
1.29 www 5582:
1.52 www 5583: #
1.103 harris41 5584: # Gathered now: all privileges that could apply, and condition number
1.52 www 5585: #
5586: #
5587: # Full or no access?
5588: #
1.29 www 5589:
1.52 www 5590: if ($thisallowed=~/F/) {
5591: return 'F';
5592: }
1.29 www 5593:
1.52 www 5594: unless ($thisallowed) {
5595: return '';
5596: }
1.29 www 5597:
1.52 www 5598: # Restrictions exist, deal with them
5599: #
5600: # C:according to course preferences
5601: # R:according to resource settings
5602: # L:unless locked
5603: # X:according to user session state
5604: #
5605:
5606: # Possibly locked functionality, check all courses
1.54 www 5607: # Locks might take effect only after 10 minutes cache expiration for other
5608: # courses, and 2 minutes for current course
1.52 www 5609:
5610: my $envkey;
5611: if ($thisallowed=~/L/) {
1.1000 raeburn 5612: foreach $envkey (keys(%env)) {
1.54 www 5613: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5614: my $courseid=$2;
5615: my $roleid=$1.'.'.$2;
1.92 www 5616: $courseid=~s/^\///;
1.54 www 5617: my $expiretime=600;
1.620 albertel 5618: if ($env{'request.role'} eq $roleid) {
1.54 www 5619: $expiretime=120;
5620: }
5621: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5622: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5623: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5624: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5625: }
1.620 albertel 5626: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5627: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5628: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5629: &log($env{'user.domain'},$env{'user.name'},
5630: $env{'user.home'},
1.57 www 5631: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5632: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5633: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5634: return '';
5635: }
5636: }
1.620 albertel 5637: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5638: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5639: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5640: &log($env{'user.domain'},$env{'user.name'},
5641: $env{'user.home'},
1.57 www 5642: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5643: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5644: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5645: return '';
5646: }
5647: }
5648: }
1.29 www 5649: }
1.52 www 5650: }
5651:
5652: #
5653: # Rest of the restrictions depend on selected course
5654: #
5655:
1.620 albertel 5656: unless ($env{'request.course.id'}) {
1.766 albertel 5657: if ($thisallowed eq 'A') {
5658: return 'A';
1.814 raeburn 5659: } elsif ($thisallowed eq 'B') {
5660: return 'B';
1.766 albertel 5661: } else {
5662: return '1';
5663: }
1.52 www 5664: }
1.29 www 5665:
1.52 www 5666: #
5667: # Now user is definitely in a course
5668: #
1.53 www 5669:
5670:
5671: # Course preferences
5672:
5673: if ($thisallowed=~/C/) {
1.620 albertel 5674: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5675: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5676: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5677: =~/\Q$rolecode\E/) {
1.689 albertel 5678: if ($priv ne 'pch') {
5679: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5680: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5681: $env{'request.course.id'});
5682: }
1.237 www 5683: return '';
5684: }
5685:
1.620 albertel 5686: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5687: =~/\Q$unamedom\E/) {
1.689 albertel 5688: if ($priv ne 'pch') {
5689: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5690: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5691: $env{'request.course.id'});
5692: }
1.54 www 5693: return '';
5694: }
1.53 www 5695: }
5696:
5697: # Resource preferences
5698:
5699: if ($thisallowed=~/R/) {
1.620 albertel 5700: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5701: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5702: if ($priv ne 'pch') {
5703: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5704: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5705: }
5706: return '';
1.54 www 5707: }
1.53 www 5708: }
1.30 www 5709:
1.246 www 5710: # Restricted by state or randomout?
1.30 www 5711:
1.52 www 5712: if ($thisallowed=~/X/) {
1.620 albertel 5713: if ($env{'acc.randomout'}) {
1.579 albertel 5714: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5715: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5716: return '';
5717: }
1.247 www 5718: }
5719: if (&condval($statecond)) {
1.52 www 5720: return '2';
5721: } else {
5722: return '';
5723: }
5724: }
1.30 www 5725:
1.766 albertel 5726: if ($thisallowed eq 'A') {
5727: return 'A';
1.814 raeburn 5728: } elsif ($thisallowed eq 'B') {
5729: return 'B';
1.766 albertel 5730: }
1.52 www 5731: return 'F';
1.232 www 5732: }
5733:
1.710 albertel 5734: sub split_uri_for_cond {
5735: my $uri=&deversion(&declutter(shift));
5736: my @uriparts=split(/\//,$uri);
5737: my $filename=pop(@uriparts);
5738: my $pathname=join('/',@uriparts);
5739: return ($pathname,$filename);
5740: }
1.232 www 5741: # --------------------------------------------------- Is a resource on the map?
5742:
5743: sub is_on_map {
1.710 albertel 5744: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5745: #Trying to find the conditional for the file
1.620 albertel 5746: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5747: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5748: if ($match) {
1.289 bowersj2 5749: return (1,$1);
5750: } else {
1.434 www 5751: return (0,0);
1.289 bowersj2 5752: }
1.12 www 5753: }
5754:
1.427 www 5755: # --------------------------------------------------------- Get symb from alias
5756:
5757: sub get_symb_from_alias {
5758: my $symb=shift;
5759: my ($map,$resid,$url)=&decode_symb($symb);
5760: # Already is a symb
5761: if ($url) { return $symb; }
5762: # Must be an alias
5763: my $aliassymb='';
5764: my %bighash;
1.620 albertel 5765: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5766: &GDBM_READER(),0640)) {
5767: my $rid=$bighash{'mapalias_'.$symb};
5768: if ($rid) {
5769: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5770: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5771: $resid,$bighash{'src_'.$rid});
1.427 www 5772: }
5773: untie %bighash;
5774: }
5775: return $aliassymb;
5776: }
5777:
1.12 www 5778: # ----------------------------------------------------------------- Define Role
5779:
5780: sub definerole {
5781: if (allowed('mcr','/')) {
5782: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5783: foreach my $role (split(':',$sysrole)) {
5784: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5785: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5786: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5787: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5788: return "refused:s:$crole&$cqual";
5789: }
5790: }
1.191 harris41 5791: }
1.800 albertel 5792: foreach my $role (split(':',$domrole)) {
5793: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5794: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5795: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5796: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5797: return "refused:d:$crole&$cqual";
5798: }
5799: }
1.191 harris41 5800: }
1.800 albertel 5801: foreach my $role (split(':',$courole)) {
5802: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5803: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5804: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5805: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5806: return "refused:c:$crole&$cqual";
5807: }
5808: }
1.191 harris41 5809: }
1.620 albertel 5810: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5811: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5812: "rolesdef_$rolename=".
5813: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5814: return reply($command,$env{'user.home'});
1.12 www 5815: } else {
5816: return 'refused';
5817: }
1.105 harris41 5818: }
5819:
5820: # ---------------- Make a metadata query against the network of library servers
5821:
5822: sub metadata_query {
1.244 matthew 5823: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5824: my %rhash;
1.845 albertel 5825: my %libserv = &all_library();
1.244 matthew 5826: my @server_list = (defined($server_array) ? @$server_array
5827: : keys(%libserv) );
5828: for my $server (@server_list) {
1.118 harris41 5829: unless ($custom or $customshow) {
5830: my $reply=&reply("querysend:".&escape($query),$server);
5831: $rhash{$server}=$reply;
5832: }
5833: else {
5834: my $reply=&reply("querysend:".&escape($query).':'.
5835: &escape($custom).':'.&escape($customshow),
5836: $server);
5837: $rhash{$server}=$reply;
5838: }
1.112 harris41 5839: }
1.118 harris41 5840: return \%rhash;
1.240 www 5841: }
5842:
5843: # ----------------------------------------- Send log queries and wait for reply
5844:
5845: sub log_query {
5846: my ($uname,$udom,$query,%filters)=@_;
5847: my $uhome=&homeserver($uname,$udom);
5848: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5849: my $uhost=&hostname($uhome);
1.800 albertel 5850: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5851: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5852: $uhome);
1.479 albertel 5853: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5854: return get_query_reply($queryid);
5855: }
5856:
1.818 raeburn 5857: # -------------------------- Update MySQL table for portfolio file
5858:
5859: sub update_portfolio_table {
1.821 raeburn 5860: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5861: if ($group ne '') {
5862: $file_name =~s /^\Q$group\E//;
5863: }
1.818 raeburn 5864: my $homeserver = &homeserver($uname,$udom);
5865: my $queryid=
1.821 raeburn 5866: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5867: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5868: my $reply = &get_query_reply($queryid);
5869: return $reply;
5870: }
5871:
1.899 raeburn 5872: # -------------------------- Update MySQL allusers table
5873:
5874: sub update_allusers_table {
5875: my ($uname,$udom,$names) = @_;
5876: my $homeserver = &homeserver($uname,$udom);
5877: my $queryid=
5878: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5879: 'lastname='.&escape($names->{'lastname'}).'%%'.
5880: 'firstname='.&escape($names->{'firstname'}).'%%'.
5881: 'middlename='.&escape($names->{'middlename'}).'%%'.
5882: 'generation='.&escape($names->{'generation'}).'%%'.
5883: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5884: 'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4 raeburn 5885: return;
1.899 raeburn 5886: }
5887:
1.508 raeburn 5888: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5889:
5890: sub fetch_enrollment_query {
1.511 raeburn 5891: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5892: my $homeserver;
1.547 raeburn 5893: my $maxtries = 1;
1.508 raeburn 5894: if ($context eq 'automated') {
5895: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5896: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5897: } else {
5898: $homeserver = &homeserver($cnum,$dom);
5899: }
1.838 albertel 5900: my $host=&hostname($homeserver);
1.506 raeburn 5901: my $cmd = '';
1.1000 raeburn 5902: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5903: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5904: }
5905: $cmd =~ s/%%$//;
5906: $cmd = &escape($cmd);
5907: my $query = 'fetchenrollment';
1.620 albertel 5908: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5909: unless ($queryid=~/^\Q$host\E\_/) {
5910: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5911: return 'error: '.$queryid;
5912: }
1.506 raeburn 5913: my $reply = &get_query_reply($queryid);
1.547 raeburn 5914: my $tries = 1;
5915: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5916: $reply = &get_query_reply($queryid);
5917: $tries ++;
5918: }
1.526 raeburn 5919: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5920: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5921: } else {
1.901 albertel 5922: my @responses = split(/:/,$reply);
1.515 raeburn 5923: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5924: foreach my $line (@responses) {
5925: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5926: $$replyref{$key} = $value;
5927: }
5928: } else {
1.506 raeburn 5929: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5930: foreach my $line (@responses) {
5931: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5932: $$replyref{$key} = $value;
5933: if ($value > 0) {
1.800 albertel 5934: foreach my $item (@{$$affiliatesref{$key}}) {
5935: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5936: my $destname = $pathname.'/'.$filename;
5937: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5938: if ($xml_classlist =~ /^error/) {
5939: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5940: } else {
1.506 raeburn 5941: if ( open(FILE,">$destname") ) {
5942: print FILE &unescape($xml_classlist);
5943: close(FILE);
1.526 raeburn 5944: } else {
5945: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5946: }
5947: }
5948: }
5949: }
5950: }
5951: }
5952: return 'ok';
5953: }
5954: return 'error';
5955: }
5956:
1.242 www 5957: sub get_query_reply {
5958: my $queryid=shift;
1.240 www 5959: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5960: my $reply='';
5961: for (1..100) {
5962: sleep 2;
5963: if (-e $replyfile.'.end') {
1.448 albertel 5964: if (open(my $fh,$replyfile)) {
1.904 albertel 5965: $reply = join('',<$fh>);
5966: close($fh);
1.240 www 5967: } else { return 'error: reply_file_error'; }
1.242 www 5968: return &unescape($reply);
5969: }
1.240 www 5970: }
1.242 www 5971: return 'timeout:'.$queryid;
1.240 www 5972: }
5973:
5974: sub courselog_query {
1.241 www 5975: #
5976: # possible filters:
5977: # url: url or symb
5978: # username
5979: # domain
5980: # action: view, submit, grade
5981: # start: timestamp
5982: # end: timestamp
5983: #
1.240 www 5984: my (%filters)=@_;
1.620 albertel 5985: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5986: if ($filters{'url'}) {
5987: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5988: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5989: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5990: }
1.620 albertel 5991: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5992: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5993: return &log_query($cname,$cdom,'courselog',%filters);
5994: }
5995:
5996: sub userlog_query {
1.858 raeburn 5997: #
5998: # possible filters:
5999: # action: log check role
6000: # start: timestamp
6001: # end: timestamp
6002: #
1.240 www 6003: my ($uname,$udom,%filters)=@_;
6004: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6005: }
6006:
1.506 raeburn 6007: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6008:
6009: sub auto_run {
1.508 raeburn 6010: my ($cnum,$cdom) = @_;
1.876 raeburn 6011: my $response = 0;
6012: my $settings;
6013: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6014: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6015: $settings = $domconfig{'autoenroll'};
6016: if ($settings->{'run'} eq '1') {
6017: $response = 1;
6018: }
6019: } else {
1.934 raeburn 6020: my $homeserver;
6021: if (&is_course($cdom,$cnum)) {
6022: $homeserver = &homeserver($cnum,$cdom);
6023: } else {
6024: $homeserver = &domain($cdom,'primary');
6025: }
6026: if ($homeserver ne 'no_host') {
6027: $response = &reply('autorun:'.$cdom,$homeserver);
6028: }
1.876 raeburn 6029: }
1.506 raeburn 6030: return $response;
6031: }
1.776 albertel 6032:
1.506 raeburn 6033: sub auto_get_sections {
1.508 raeburn 6034: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6035: my $homeserver;
6036: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6037: $homeserver = &homeserver($cnum,$cdom);
6038: }
6039: if (!defined($homeserver)) {
6040: if ($cdom =~ /^$match_domain$/) {
6041: $homeserver = &domain($cdom,'primary');
6042: }
6043: }
6044: my @secs;
6045: if (defined($homeserver)) {
6046: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6047: unless ($response eq 'refused') {
6048: @secs = split(/:/,$response);
6049: }
1.506 raeburn 6050: }
6051: return @secs;
6052: }
1.776 albertel 6053:
1.506 raeburn 6054: sub auto_new_course {
1.508 raeburn 6055: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
6056: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 6057: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 6058: return $response;
6059: }
1.776 albertel 6060:
1.506 raeburn 6061: sub auto_validate_courseID {
1.508 raeburn 6062: my ($cnum,$cdom,$inst_course_id) = @_;
6063: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6064: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6065: return $response;
6066: }
1.776 albertel 6067:
1.1007 raeburn 6068: sub auto_validate_instcode {
1.1020 raeburn 6069: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6070: my ($homeserver,$response);
6071: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6072: $homeserver = &homeserver($cnum,$cdom);
6073: }
6074: if (!defined($homeserver)) {
6075: if ($cdom =~ /^$match_domain$/) {
6076: $homeserver = &domain($cdom,'primary');
6077: }
6078: }
1.1056.4.2 raeburn 6079: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6080: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6081: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6082: return ($outcome,$description);
1.1007 raeburn 6083: }
6084:
1.506 raeburn 6085: sub auto_create_password {
1.873 raeburn 6086: my ($cnum,$cdom,$authparam,$udom) = @_;
6087: my ($homeserver,$response);
1.506 raeburn 6088: my $create_passwd = 0;
6089: my $authchk = '';
1.873 raeburn 6090: if ($udom =~ /^$match_domain$/) {
6091: $homeserver = &domain($udom,'primary');
6092: }
6093: if ($homeserver eq '') {
6094: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6095: $homeserver = &homeserver($cnum,$cdom);
6096: }
6097: }
6098: if ($homeserver eq '') {
6099: $authchk = 'nodomain';
1.506 raeburn 6100: } else {
1.873 raeburn 6101: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6102: if ($response eq 'refused') {
6103: $authchk = 'refused';
6104: } else {
1.901 albertel 6105: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6106: }
1.506 raeburn 6107: }
6108: return ($authparam,$create_passwd,$authchk);
6109: }
6110:
1.706 raeburn 6111: sub auto_photo_permission {
6112: my ($cnum,$cdom,$students) = @_;
6113: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6114: my ($outcome,$perm_reqd,$conditions) =
6115: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6116: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6117: return (undef,undef);
6118: }
1.706 raeburn 6119: return ($outcome,$perm_reqd,$conditions);
6120: }
6121:
6122: sub auto_checkphotos {
6123: my ($uname,$udom,$pid) = @_;
6124: my $homeserver = &homeserver($uname,$udom);
6125: my ($result,$resulttype);
6126: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6127: &escape($uname).':'.&escape($pid),
6128: $homeserver));
1.709 albertel 6129: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6130: return (undef,undef);
6131: }
1.706 raeburn 6132: if ($outcome) {
6133: ($result,$resulttype) = split(/:/,$outcome);
6134: }
6135: return ($result,$resulttype);
6136: }
6137:
6138: sub auto_photochoice {
6139: my ($cnum,$cdom) = @_;
6140: my $homeserver = &homeserver($cnum,$cdom);
6141: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6142: &escape($cdom),
6143: $homeserver)));
1.709 albertel 6144: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6145: return (undef,undef);
6146: }
1.706 raeburn 6147: return ($update,$comment);
6148: }
6149:
6150: sub auto_photoupdate {
6151: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6152: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6153: my $host=&hostname($homeserver);
1.706 raeburn 6154: my $cmd = '';
6155: my $maxtries = 1;
1.800 albertel 6156: foreach my $affiliate (keys(%{$affiliatesref})) {
6157: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6158: }
6159: $cmd =~ s/%%$//;
6160: $cmd = &escape($cmd);
6161: my $query = 'institutionalphotos';
6162: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6163: unless ($queryid=~/^\Q$host\E\_/) {
6164: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6165: return 'error: '.$queryid;
6166: }
6167: my $reply = &get_query_reply($queryid);
6168: my $tries = 1;
6169: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6170: $reply = &get_query_reply($queryid);
6171: $tries ++;
6172: }
6173: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6174: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6175: } else {
6176: my @responses = split(/:/,$reply);
6177: my $outcome = shift(@responses);
6178: foreach my $item (@responses) {
6179: my ($key,$value) = split(/=/,$item);
6180: $$photo{$key} = $value;
6181: }
6182: return $outcome;
6183: }
6184: return 'error';
6185: }
6186:
1.521 raeburn 6187: sub auto_instcode_format {
1.793 albertel 6188: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6189: $cat_order) = @_;
1.521 raeburn 6190: my $courses = '';
1.772 raeburn 6191: my @homeservers;
1.521 raeburn 6192: if ($caller eq 'global') {
1.841 albertel 6193: my %servers = &get_servers($codedom,'library');
6194: foreach my $tryserver (keys(%servers)) {
6195: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6196: push(@homeservers,$tryserver);
6197: }
1.584 raeburn 6198: }
1.1022 raeburn 6199: } elsif ($caller eq 'requests') {
6200: if ($codedom =~ /^$match_domain$/) {
6201: my $chome = &domain($codedom,'primary');
6202: unless ($chome eq 'no_host') {
6203: push(@homeservers,$chome);
6204: }
6205: }
1.521 raeburn 6206: } else {
1.772 raeburn 6207: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6208: }
1.793 albertel 6209: foreach my $code (keys(%{$instcodes})) {
6210: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6211: }
6212: chop($courses);
1.772 raeburn 6213: my $ok_response = 0;
6214: my $response;
6215: while (@homeservers > 0 && $ok_response == 0) {
6216: my $server = shift(@homeservers);
6217: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6218: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6219: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6220: split(/:/,$response);
1.772 raeburn 6221: %{$codes} = (%{$codes},&str2hash($codes_str));
6222: push(@{$codetitles},&str2array($codetitles_str));
6223: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6224: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6225: $ok_response = 1;
6226: }
6227: }
6228: if ($ok_response) {
1.521 raeburn 6229: return 'ok';
1.772 raeburn 6230: } else {
6231: return $response;
1.521 raeburn 6232: }
6233: }
6234:
1.792 raeburn 6235: sub auto_instcode_defaults {
6236: my ($domain,$returnhash,$code_order) = @_;
6237: my @homeservers;
1.841 albertel 6238:
6239: my %servers = &get_servers($domain,'library');
6240: foreach my $tryserver (keys(%servers)) {
6241: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6242: push(@homeservers,$tryserver);
6243: }
1.792 raeburn 6244: }
1.841 albertel 6245:
1.792 raeburn 6246: my $response;
1.841 albertel 6247: foreach my $server (@homeservers) {
1.792 raeburn 6248: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6249: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6250:
6251: foreach my $pair (split(/\&/,$response)) {
6252: my ($name,$value)=split(/\=/,$pair);
6253: if ($name eq 'code_order') {
6254: @{$code_order} = split(/\&/,&unescape($value));
6255: } else {
6256: $returnhash->{&unescape($name)}=&unescape($value);
6257: }
6258: }
6259: return 'ok';
1.792 raeburn 6260: }
1.841 albertel 6261:
6262: return $response;
1.1003 raeburn 6263: }
6264:
6265: sub auto_possible_instcodes {
1.1007 raeburn 6266: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6267: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6268: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6269: return;
6270: }
1.1003 raeburn 6271: my (@homeservers,$uhome);
6272: if (defined(&domain($domain,'primary'))) {
6273: $uhome=&domain($domain,'primary');
6274: push(@homeservers,&domain($domain,'primary'));
6275: } else {
6276: my %servers = &get_servers($domain,'library');
6277: foreach my $tryserver (keys(%servers)) {
6278: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6279: push(@homeservers,$tryserver);
6280: }
6281: }
6282: }
6283: my $response;
6284: foreach my $server (@homeservers) {
6285: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6286: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6287: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6288: split(':',$response);
6289: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6290: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6291: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6292: my ($name,$value)=split('=',$item);
6293: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6294: }
6295: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6296: my ($name,$value)=split('=',$item);
6297: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6298: }
6299: return 'ok';
6300: }
6301: return $response;
6302: }
1.792 raeburn 6303:
1.1010 raeburn 6304: sub auto_courserequest_checks {
6305: my ($dom) = @_;
1.1020 raeburn 6306: my ($homeserver,%validations);
6307: if ($dom =~ /^$match_domain$/) {
6308: $homeserver = &domain($dom,'primary');
6309: }
6310: unless ($homeserver eq 'no_host') {
6311: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6312: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6313: my @items = split(/&/,$response);
6314: foreach my $item (@items) {
6315: my ($key,$value) = split('=',$item);
6316: $validations{&unescape($key)} = &thaw_unescape($value);
6317: }
6318: }
6319: }
1.1010 raeburn 6320: return %validations;
6321: }
6322:
1.1020 raeburn 6323: sub auto_courserequest_validation {
6324: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6325: my ($homeserver,$response);
6326: if ($dom =~ /^$match_domain$/) {
6327: $homeserver = &domain($dom,'primary');
6328: }
6329: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6330:
1.1020 raeburn 6331: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6332: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6333: ':'.&escape($instcode).':'.&escape($instseclist),
6334: $homeserver));
6335: }
6336: return $response;
6337: }
6338:
1.777 albertel 6339: sub auto_validate_class_sec {
1.918 raeburn 6340: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6341: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6342: my $ownerlist;
6343: if (ref($owners) eq 'ARRAY') {
6344: $ownerlist = join(',',@{$owners});
6345: } else {
6346: $ownerlist = $owners;
6347: }
1.773 raeburn 6348: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6349: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6350: return $response;
6351: }
6352:
1.679 raeburn 6353: # ------------------------------------------------------- Course Group routines
6354:
6355: sub get_coursegroups {
1.809 raeburn 6356: my ($cdom,$cnum,$group,$namespace) = @_;
6357: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6358: }
6359:
1.679 raeburn 6360: sub modify_coursegroup {
6361: my ($cdom,$cnum,$groupsettings) = @_;
6362: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6363: }
6364:
1.809 raeburn 6365: sub toggle_coursegroup_status {
6366: my ($cdom,$cnum,$group,$action) = @_;
6367: my ($from_namespace,$to_namespace);
6368: if ($action eq 'delete') {
6369: $from_namespace = 'coursegroups';
6370: $to_namespace = 'deleted_groups';
6371: } else {
6372: $from_namespace = 'deleted_groups';
6373: $to_namespace = 'coursegroups';
6374: }
6375: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6376: if (my $tmp = &error(%curr_group)) {
6377: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6378: return ('read error',$tmp);
6379: } else {
6380: my %savedsettings = %curr_group;
1.809 raeburn 6381: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6382: my $deloutcome;
6383: if ($result eq 'ok') {
1.809 raeburn 6384: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6385: } else {
6386: return ('write error',$result);
6387: }
6388: if ($deloutcome eq 'ok') {
6389: return 'ok';
6390: } else {
6391: return ('delete error',$deloutcome);
6392: }
6393: }
6394: }
6395:
1.679 raeburn 6396: sub modify_group_roles {
1.957 raeburn 6397: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6398: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6399: my $role = 'gr/'.&escape($userprivs);
6400: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6401: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6402: if ($result eq 'ok') {
6403: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6404: }
1.679 raeburn 6405: return $result;
6406: }
6407:
6408: sub modify_coursegroup_membership {
6409: my ($cdom,$cnum,$membership) = @_;
6410: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6411: return $result;
6412: }
6413:
1.682 raeburn 6414: sub get_active_groups {
6415: my ($udom,$uname,$cdom,$cnum) = @_;
6416: my $now = time;
6417: my %groups = ();
6418: foreach my $key (keys(%env)) {
1.811 albertel 6419: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6420: my ($start,$end) = split(/\./,$env{$key});
6421: if (($end!=0) && ($end<$now)) { next; }
6422: if (($start!=0) && ($start>$now)) { next; }
6423: if ($1 eq $cdom && $2 eq $cnum) {
6424: $groups{$3} = $env{$key} ;
6425: }
6426: }
6427: }
6428: return %groups;
6429: }
6430:
1.683 raeburn 6431: sub get_group_membership {
6432: my ($cdom,$cnum,$group) = @_;
6433: return(&dump('groupmembership',$cdom,$cnum,$group));
6434: }
6435:
6436: sub get_users_groups {
6437: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6438: my @usersgroups;
1.683 raeburn 6439: my $cachetime=1800;
6440:
6441: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6442: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6443: if (defined($cached)) {
1.734 albertel 6444: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6445: } else {
6446: $grouplist = '';
1.816 raeburn 6447: my $courseurl = &courseid_to_courseurl($courseid);
6448: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 6449: my $access_end = $env{'course.'.$courseid.
6450: '.default_enrollment_end_date'};
6451: my $now = time;
6452: foreach my $key (keys(%roleshash)) {
6453: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6454: my $group = $1;
6455: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6456: my $start = $2;
6457: my $end = $1;
6458: if ($start == -1) { next; } # deleted from group
6459: if (($start!=0) && ($start>$now)) { next; }
6460: if (($end!=0) && ($end<$now)) {
6461: if ($access_end && $access_end < $now) {
6462: if ($access_end - $end < 86400) {
6463: push(@usersgroups,$group);
1.733 raeburn 6464: }
6465: }
1.817 raeburn 6466: next;
1.733 raeburn 6467: }
1.817 raeburn 6468: push(@usersgroups,$group);
1.683 raeburn 6469: }
6470: }
6471: }
1.817 raeburn 6472: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6473: $grouplist = join(':',@usersgroups);
6474: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6475: }
1.733 raeburn 6476: return @usersgroups;
1.683 raeburn 6477: }
6478:
6479: sub devalidate_getgroups_cache {
6480: my ($udom,$uname,$cdom,$cnum)=@_;
6481: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6482:
1.683 raeburn 6483: my $hashid="$udom:$uname:$courseid";
6484: &devalidate_cache_new('getgroups',$hashid);
6485: }
6486:
1.12 www 6487: # ------------------------------------------------------------------ Plain Text
6488:
6489: sub plaintext {
1.988 raeburn 6490: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6491: if ($short =~ m{^cr/}) {
1.758 albertel 6492: return (split('/',$short))[-1];
6493: }
1.742 raeburn 6494: if (!defined($cid)) {
6495: $cid = $env{'request.course.id'};
6496: }
6497: my %rolenames = (
1.1008 raeburn 6498: Course => 'std',
6499: Community => 'alt1',
1.742 raeburn 6500: );
1.1037 raeburn 6501: if ($cid ne '') {
6502: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6503: unless ($forcedefault) {
6504: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6505: &Apache::lonlocal::mt_escape(\$roletext);
6506: return &Apache::lonlocal::mt($roletext);
6507: }
6508: }
6509: }
6510: if ((defined($type)) && (defined($rolenames{$type})) &&
6511: (defined($rolenames{$type})) &&
6512: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6513: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6514: } elsif ($cid ne '') {
6515: my $crstype = $env{'course.'.$cid.'.type'};
6516: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6517: (defined($prp{$short}{$rolenames{$crstype}}))) {
6518: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6519: }
1.742 raeburn 6520: }
1.1037 raeburn 6521: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6522: }
6523:
6524: # ----------------------------------------------------------------- Assign Role
6525:
6526: sub assignrole {
1.957 raeburn 6527: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6528: $context)=@_;
1.21 www 6529: my $mrole;
6530: if ($role =~ /^cr\//) {
1.393 www 6531: my $cwosec=$url;
1.811 albertel 6532: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6533: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6534: my $refused = 1;
6535: if ($context eq 'requestcourses') {
6536: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6537: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6538: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6539: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6540: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6541: if ($crsenv{'internal.courseowner'} eq
6542: $env{'user.name'}.':'.$env{'user.domain'}) {
6543: $refused = '';
6544: }
6545: }
6546: }
6547: }
6548: }
6549: if ($refused) {
6550: &logthis('Refused custom assignrole: '.
6551: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6552: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6553: return 'refused';
6554: }
1.104 www 6555: }
1.21 www 6556: $mrole='cr';
1.678 raeburn 6557: } elsif ($role =~ /^gr\//) {
6558: my $cwogrp=$url;
1.811 albertel 6559: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6560: unless (&allowed('mdg',$cwogrp)) {
6561: &logthis('Refused group assignrole: '.
6562: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6563: $env{'user.name'}.' at '.$env{'user.domain'});
6564: return 'refused';
6565: }
6566: $mrole='gr';
1.21 www 6567: } else {
1.82 www 6568: my $cwosec=$url;
1.811 albertel 6569: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6570: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6571: my $refused;
6572: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6573: if (!(&allowed('c'.$role,$url))) {
6574: $refused = 1;
6575: }
6576: } else {
6577: $refused = 1;
6578: }
1.947 raeburn 6579: if ($refused) {
1.1045 raeburn 6580: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6581: if (!$selfenroll && $context eq 'course') {
6582: my %crsenv;
6583: if ($role eq 'cc' || $role eq 'co') {
6584: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6585: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6586: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6587: if ($crsenv{'internal.courseowner'} eq
6588: $env{'user.name'}.':'.$env{'user.domain'}) {
6589: $refused = '';
6590: }
6591: }
6592: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6593: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6594: if ($crsenv{'internal.courseowner'} eq
6595: $env{'user.name'}.':'.$env{'user.domain'}) {
6596: $refused = '';
6597: }
6598: }
6599: }
6600: }
6601: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6602: $refused = '';
1.1017 raeburn 6603: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6604: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6605: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6606: my $wrongcc;
6607: if ($cnum =~ /^$match_community$/) {
6608: $wrongcc = 1 if ($role eq 'cc');
6609: } else {
6610: $wrongcc = 1 if ($role eq 'co');
6611: }
6612: unless ($wrongcc) {
6613: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6614: if ($crsenv{'internal.courseowner'} eq
6615: $env{'user.name'}.':'.$env{'user.domain'}) {
6616: $refused = '';
6617: }
1.1017 raeburn 6618: }
6619: }
6620: }
6621: if ($refused) {
1.947 raeburn 6622: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6623: ' '.$role.' '.$end.' '.$start.' by '.
6624: $env{'user.name'}.' at '.$env{'user.domain'});
6625: return 'refused';
6626: }
1.932 raeburn 6627: }
1.104 www 6628: }
1.21 www 6629: $mrole=$role;
6630: }
1.620 albertel 6631: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6632: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6633: if ($end) { $command.='_'.$end; }
1.21 www 6634: if ($start) {
6635: if ($end) {
1.81 www 6636: $command.='_'.$start;
1.21 www 6637: } else {
1.81 www 6638: $command.='_0_'.$start;
1.21 www 6639: }
6640: }
1.739 raeburn 6641: my $origstart = $start;
6642: my $origend = $end;
1.957 raeburn 6643: my $delflag;
1.357 www 6644: # actually delete
6645: if ($deleteflag) {
1.373 www 6646: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6647: # modify command to delete the role
1.620 albertel 6648: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6649: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6650: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6651: # set start and finish to negative values for userrolelog
6652: $start=-1;
6653: $end=-1;
1.957 raeburn 6654: $delflag = 1;
1.357 www 6655: }
6656: }
6657: # send command
1.349 www 6658: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6659: # log new user role if status is ok
1.349 www 6660: if ($answer eq 'ok') {
1.663 raeburn 6661: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6662: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6663: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6664: unless ($role =~ /^gr/) {
6665: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6666: $origstart,$selfenroll,$context);
1.739 raeburn 6667: }
1.1053 raeburn 6668: if ($role eq 'cc') {
6669: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6670: }
1.349 www 6671: }
6672: return $answer;
1.169 harris41 6673: }
6674:
1.1053 raeburn 6675: sub autoupdate_coowners {
6676: my ($url,$end,$start,$uname,$udom) = @_;
6677: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6678: if (($cdom ne '') && ($cnum ne '')) {
6679: my $now = time;
6680: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6681: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6682: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6683: my $instcode = $coursehash{'internal.coursecode'};
6684: if ($instcode ne '') {
1.1056 raeburn 6685: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6686: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6687: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6688: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6689: if ($result eq 'valid') {
6690: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6691: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6692: push(@newcoowners,$coowner);
6693: }
6694: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6695: push(@newcoowners,$uname.':'.$udom);
6696: }
6697: @newcoowners = sort(@newcoowners);
6698: } else {
6699: push(@newcoowners,$uname.':'.$udom);
6700: }
6701: } else {
6702: if ($coursehash{'internal.co-owners'}) {
6703: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6704: unless ($coowner eq $uname.':'.$udom) {
6705: push(@newcoowners,$coowner);
6706: }
6707: }
6708: unless (@newcoowners > 0) {
6709: $delcoowners = 1;
6710: $coowners = '';
6711: }
6712: }
6713: }
6714: if (@newcoowners || $delcoowners) {
6715: &store_coowners($cdom,$cnum,$coursehash{'home'},
6716: $delcoowners,@newcoowners);
6717: }
6718: }
6719: }
6720: }
6721: }
6722: }
6723: }
6724:
6725: sub store_coowners {
6726: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6727: my $cid = $cdom.'_'.$cnum;
6728: my ($coowners,$delresult,$putresult);
6729: if (@newcoowners) {
6730: $coowners = join(',',@newcoowners);
6731: my %coownershash = (
6732: 'internal.co-owners' => $coowners,
6733: );
6734: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6735: if ($putresult eq 'ok') {
6736: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6737: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6738: }
6739: }
6740: }
6741: if ($delcoowners) {
6742: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6743: if ($delresult eq 'ok') {
6744: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6745: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6746: }
6747: }
6748: }
6749: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6750: my %crsinfo =
6751: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6752: if (ref($crsinfo{$cid}) eq 'HASH') {
6753: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6754: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6755: }
6756: }
6757: }
6758:
1.169 harris41 6759: # -------------------------------------------------- Modify user authentication
1.197 www 6760: # Overrides without validation
6761:
1.169 harris41 6762: sub modifyuserauth {
6763: my ($udom,$uname,$umode,$upass)=@_;
6764: my $uhome=&homeserver($uname,$udom);
1.197 www 6765: unless (&allowed('mau',$udom)) { return 'refused'; }
6766: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6767: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6768: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6769: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6770: &escape($upass),$uhome);
1.620 albertel 6771: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6772: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6773: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6774: &log($udom,,$uname,$uhome,
1.620 albertel 6775: 'Authentication changed by '.$env{'user.domain'}.', '.
6776: $env{'user.name'}.', '.$umode.
1.197 www 6777: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6778: unless ($reply eq 'ok') {
1.197 www 6779: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6780: return 'error: '.$reply;
6781: }
1.170 harris41 6782: return 'ok';
1.80 www 6783: }
6784:
1.81 www 6785: # --------------------------------------------------------------- Modify a user
1.80 www 6786:
1.81 www 6787: sub modifyuser {
1.206 matthew 6788: my ($udom, $uname, $uid,
6789: $umode, $upass, $first,
6790: $middle, $last, $gene,
1.1056.4.1 raeburn 6791: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6792: $udom= &LONCAPA::clean_domain($udom);
6793: $uname=&LONCAPA::clean_username($uname);
1.1056.4.1 raeburn 6794: my $showcandelete = 'none';
6795: if (ref($candelete) eq 'ARRAY') {
6796: if (@{$candelete} > 0) {
6797: $showcandelete = join(', ',@{$candelete});
6798: }
6799: }
1.81 www 6800: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6801: $umode.', '.$first.', '.$middle.', '.
1.1056.4.1 raeburn 6802: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6803: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6804: ' desiredhome not specified').
1.620 albertel 6805: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6806: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6807: my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4 raeburn 6808: my $newuser;
6809: if ($uhome eq 'no_host') {
6810: $newuser = 1;
6811: }
1.80 www 6812: # ----------------------------------------------------------------- Create User
1.406 albertel 6813: if (($uhome eq 'no_host') &&
6814: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6815: my $unhome='';
1.844 albertel 6816: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6817: $unhome = $desiredhome;
1.620 albertel 6818: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6819: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6820: } else { # load balancing routine for determining $unhome
1.81 www 6821: my $loadm=10000000;
1.841 albertel 6822: my %servers = &get_servers($udom,'library');
6823: foreach my $tryserver (keys(%servers)) {
6824: my $answer=reply('load',$tryserver);
6825: if (($answer=~/\d+/) && ($answer<$loadm)) {
6826: $loadm=$answer;
6827: $unhome=$tryserver;
6828: }
1.80 www 6829: }
6830: }
6831: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6832: return 'error: unable to find a home server for '.$uname.
6833: ' in domain '.$udom;
1.80 www 6834: }
6835: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6836: &escape($upass),$unhome);
6837: unless ($reply eq 'ok') {
6838: return 'error: '.$reply;
6839: }
1.230 stredwic 6840: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6841: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6842: return 'error: unable verify users home machine.';
1.80 www 6843: }
1.209 matthew 6844: } # End of creation of new user
1.80 www 6845: # ---------------------------------------------------------------------- Add ID
6846: if ($uid) {
6847: $uid=~tr/A-Z/a-z/;
6848: my %uidhash=&idrget($udom,$uname);
1.196 www 6849: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6850: && (!$forceid)) {
1.80 www 6851: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6852: return 'error: user id "'.$uid.'" does not match '.
6853: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6854: }
6855: } else {
6856: &idput($udom,($uname => $uid));
6857: }
6858: }
6859: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6860: my @tmp=&get('environment',
1.899 raeburn 6861: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6862: 'permanentemail','inststatus'],
1.134 albertel 6863: $udom,$uname);
1.1056.4.4 raeburn 6864: my (%names,%oldnames);
1.313 matthew 6865: if ($tmp[0] =~ m/^error:.*/) {
6866: %names=();
6867: } else {
6868: %names = @tmp;
1.1056.4.4 raeburn 6869: %oldnames = %names;
1.313 matthew 6870: }
1.1056.4.6 raeburn 6871: #
1.1056.4.1 raeburn 6872: # If name, email and/or uid are blank (e.g., because an uploaded file
6873: # of users did not contain them), do not overwrite existing values
6874: # unless field is in $candelete array ref.
6875: #
6876:
6877: my @fields = ('firstname','middlename','lastname','generation',
6878: 'permanentemail','id');
6879: my %newvalues;
6880: if (ref($candelete) eq 'ARRAY') {
6881: foreach my $field (@fields) {
6882: if (grep(/^\Q$field\E$/,@{$candelete})) {
6883: if ($field eq 'firstname') {
6884: $names{$field} = $first;
6885: } elsif ($field eq 'middlename') {
6886: $names{$field} = $middle;
6887: } elsif ($field eq 'lastname') {
6888: $names{$field} = $last;
6889: } elsif ($field eq 'generation') {
6890: $names{$field} = $gene;
6891: } elsif ($field eq 'permanentemail') {
6892: $names{$field} = $email;
6893: } elsif ($field eq 'id') {
6894: $names{$field} = $uid;
6895: }
6896: }
6897: }
6898: }
1.388 www 6899: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6900: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6901: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6902: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6903: if ($email) {
6904: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6905: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6906: }
1.899 raeburn 6907: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6908: if (defined($inststatus)) {
6909: $names{'inststatus'} = '';
6910: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6911: if (ref($usertypes) eq 'HASH') {
6912: my @okstatuses;
6913: foreach my $item (split(/:/,$inststatus)) {
6914: if (defined($usertypes->{$item})) {
6915: push(@okstatuses,$item);
6916: }
6917: }
6918: if (@okstatuses) {
6919: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6920: }
6921: }
6922: }
1.1056.4.4 raeburn 6923: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 6924: $umode.', '.$first.', '.$middle.', '.
1.1056.4.4 raeburn 6925: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 6926: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6927: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6928: } else {
6929: $logmsg .= ' during self creation';
6930: }
1.1056.4.4 raeburn 6931: my $changed;
6932: if ($newuser) {
6933: $changed = 1;
6934: } else {
6935: foreach my $field (@fields) {
6936: if ($names{$field} ne $oldnames{$field}) {
6937: $changed = 1;
6938: last;
6939: }
6940: }
6941: }
6942: unless ($changed) {
6943: $logmsg = 'No changes in user information needed for: '.$logmsg;
6944: &logthis($logmsg);
6945: return 'ok';
6946: }
6947: my $reply = &put('environment', \%names, $udom,$uname);
6948: if ($reply ne 'ok') {
6949: return 'error: '.$reply;
6950: }
6951: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
6952: &devalidate_cache_new('namescache',$uname.':'.$udom);
6953: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 6954: &logthis($logmsg);
1.134 albertel 6955: return 'ok';
1.80 www 6956: }
6957:
1.81 www 6958: # -------------------------------------------------------------- Modify student
1.80 www 6959:
1.81 www 6960: sub modifystudent {
6961: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6962: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6963: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6964: if (!$cid) {
1.620 albertel 6965: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6966: return 'not_in_class';
6967: }
1.80 www 6968: }
6969: # --------------------------------------------------------------- Make the user
1.81 www 6970: my $reply=&modifyuser
1.209 matthew 6971: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6972: $desiredhome,$email,$inststatus);
1.80 www 6973: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6974: # This will cause &modify_student_enrollment to get the uid from the
6975: # students environment
6976: $uid = undef if (!$forceid);
1.455 albertel 6977: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6978: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6979: return $reply;
6980: }
6981:
6982: sub modify_student_enrollment {
1.957 raeburn 6983: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6984: my ($cdom,$cnum,$chome);
6985: if (!$cid) {
1.620 albertel 6986: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6987: return 'not_in_class';
6988: }
1.620 albertel 6989: $cdom=$env{'course.'.$cid.'.domain'};
6990: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6991: } else {
6992: ($cdom,$cnum)=split(/_/,$cid);
6993: }
1.620 albertel 6994: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6995: if (!$chome) {
1.457 raeburn 6996: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6997: }
1.455 albertel 6998: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6999: # Make sure the user exists
1.81 www 7000: my $uhome=&homeserver($uname,$udom);
7001: if (($uhome eq '') || ($uhome eq 'no_host')) {
7002: return 'error: no such user';
7003: }
1.297 matthew 7004: # Get student data if we were not given enough information
7005: if (!defined($first) || $first eq '' ||
7006: !defined($last) || $last eq '' ||
7007: !defined($uid) || $uid eq '' ||
7008: !defined($middle) || $middle eq '' ||
7009: !defined($gene) || $gene eq '') {
1.294 matthew 7010: # They did not supply us with enough data to enroll the student, so
7011: # we need to pick up more information.
1.297 matthew 7012: my %tmp = &get('environment',
1.294 matthew 7013: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7014: ,$udom,$uname);
7015:
1.800 albertel 7016: #foreach my $key (keys(%tmp)) {
7017: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7018: #}
1.294 matthew 7019: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7020: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7021: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7022: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7023: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7024: }
1.556 albertel 7025: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 7026: my $reply=cput('classlist',
7027: {"$uname:$udom" =>
1.515 raeburn 7028: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7029: $cdom,$cnum);
1.81 www 7030: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7031: return 'error: '.$reply;
1.652 albertel 7032: } else {
7033: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 7034: }
1.297 matthew 7035: # Add student role to user
1.83 www 7036: my $uurl='/'.$cid;
1.81 www 7037: $uurl=~s/\_/\//g;
7038: if ($usec) {
7039: $uurl.='/'.$usec;
7040: }
1.957 raeburn 7041: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 7042: }
7043:
1.556 albertel 7044: sub format_name {
7045: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7046: my $name;
7047: if ($first ne 'lastname') {
7048: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7049: } else {
7050: if ($lastname=~/\S/) {
7051: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7052: $name=~s/\s+,/,/;
7053: } else {
7054: $name.= $firstname.' '.$middlename.' '.$generation;
7055: }
7056: }
7057: $name=~s/^\s+//;
7058: $name=~s/\s+$//;
7059: $name=~s/\s+/ /g;
7060: return $name;
7061: }
7062:
1.84 www 7063: # ------------------------------------------------- Write to course preferences
7064:
7065: sub writecoursepref {
7066: my ($courseid,%prefs)=@_;
7067: $courseid=~s/^\///;
7068: $courseid=~s/\_/\//g;
7069: my ($cdomain,$cnum)=split(/\//,$courseid);
7070: my $chome=homeserver($cnum,$cdomain);
7071: if (($chome eq '') || ($chome eq 'no_host')) {
7072: return 'error: no such course';
7073: }
7074: my $cstring='';
1.800 albertel 7075: foreach my $pref (keys(%prefs)) {
7076: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7077: }
1.84 www 7078: $cstring=~s/\&$//;
7079: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7080: }
7081:
7082: # ---------------------------------------------------------- Make/modify course
7083:
7084: sub createcourse {
1.741 raeburn 7085: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7086: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7087: $url=&declutter($url);
7088: my $cid='';
1.1028 raeburn 7089: if ($context eq 'requestcourses') {
7090: my $can_create = 0;
7091: my ($ownername,$ownerdom) = split(':',$course_owner);
7092: if ($udom eq $ownerdom) {
7093: if (&usertools_access($ownername,$ownerdom,$category,undef,
7094: $context)) {
7095: $can_create = 1;
7096: }
7097: } else {
7098: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7099: $category);
7100: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7101: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7102: if (@curr > 0) {
7103: my @options = qw(approval validate autolimit);
7104: my $optregex = join('|',@options);
7105: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7106: $can_create = 1;
7107: }
7108: }
7109: }
7110: }
7111: if ($can_create) {
7112: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7113: unless (&allowed('ccc',$udom)) {
7114: return 'refused';
7115: }
1.1017 raeburn 7116: }
7117: } else {
7118: return 'refused';
7119: }
1.1028 raeburn 7120: } elsif (!&allowed('ccc',$udom)) {
7121: return 'refused';
1.84 www 7122: }
1.1011 raeburn 7123: # --------------------------------------------------------------- Get Unique ID
7124: my $uname;
7125: if ($cnum =~ /^$match_courseid$/) {
7126: my $chome=&homeserver($cnum,$udom,'true');
7127: if (($chome eq '') || ($chome eq 'no_host')) {
7128: $uname = $cnum;
7129: } else {
1.1038 raeburn 7130: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7131: }
7132: } else {
1.1038 raeburn 7133: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7134: }
7135: return $uname if ($uname =~ /^error/);
7136: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7137: if (!defined($course_server)) {
7138: if (defined(&domain($udom,'primary'))) {
7139: $course_server = &domain($udom,'primary');
7140: } else {
7141: $course_server = $env{'user.home'};
7142: }
7143: }
7144: my %host_servers =
7145: &Apache::lonnet::get_servers($udom,'library');
7146: unless ($host_servers{$course_server}) {
7147: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7148: }
1.84 www 7149: # ------------------------------------------------------------- Make the course
7150: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7151: $course_server);
1.84 www 7152: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7153: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7154: if (($uhome eq '') || ($uhome eq 'no_host')) {
7155: return 'error: no such course';
7156: }
1.271 www 7157: # ----------------------------------------------------------------- Course made
1.516 raeburn 7158: # log existence
1.1029 raeburn 7159: my $now = time;
1.918 raeburn 7160: my $newcourse = {
7161: $udom.'_'.$uname => {
1.921 raeburn 7162: description => $description,
7163: inst_code => $inst_code,
7164: owner => $course_owner,
7165: type => $crstype,
1.1029 raeburn 7166: creator => $env{'user.name'}.':'.
7167: $env{'user.domain'},
7168: created => $now,
7169: context => $context,
1.918 raeburn 7170: },
7171: };
1.921 raeburn 7172: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7173: # set toplevel url
1.271 www 7174: my $topurl=$url;
7175: unless ($nonstandard) {
7176: # ------------------------------------------ For standard courses, make top url
7177: my $mapurl=&clutter($url);
1.278 www 7178: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7179: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7180: <map>
7181: <resource id="1" type="start"></resource>
7182: <resource id="2" src="$mapurl"></resource>
7183: <resource id="3" type="finish"></resource>
7184: <link index="1" from="1" to="2"></link>
7185: <link index="2" from="2" to="3"></link>
7186: </map>
7187: ENDINITMAP
7188: $topurl=&declutter(
1.638 albertel 7189: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7190: );
7191: }
7192: # ----------------------------------------------------------- Write preferences
1.84 www 7193: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7194: ('description' => $description,
7195: 'url' => $topurl,
7196: 'internal.creator' => $env{'user.name'}.':'.
7197: $env{'user.domain'},
7198: 'internal.created' => $now,
7199: 'internal.creationcontext' => $context)
7200: );
1.84 www 7201: return '/'.$udom.'/'.$uname;
7202: }
7203:
1.1011 raeburn 7204: # ------------------------------------------------------------------- Create ID
7205: sub generate_coursenum {
1.1038 raeburn 7206: my ($udom,$crstype) = @_;
1.1011 raeburn 7207: my $domdesc = &domain($udom);
7208: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7209: my $first;
7210: if ($crstype eq 'Community') {
7211: $first = '0';
7212: } else {
7213: $first = int(1+rand(9));
7214: }
7215: my $uname=$first.
1.1011 raeburn 7216: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7217: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7218: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7219: # ----------------------------------------------- Make sure that does not exist
7220: my $uhome=&homeserver($uname,$udom,'true');
7221: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7222: if ($crstype eq 'Community') {
7223: $first = '0';
7224: } else {
7225: $first = int(1+rand(9));
7226: }
7227: $uname=$first.
1.1011 raeburn 7228: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7229: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7230: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7231: $uhome=&homeserver($uname,$udom,'true');
7232: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7233: return 'error: unable to generate unique course-ID';
7234: }
7235: }
7236: return $uname;
7237: }
7238:
1.813 albertel 7239: sub is_course {
7240: my ($cdom,$cnum) = @_;
7241: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7242: undef,'.');
1.813 albertel 7243: if (exists($courses{$cdom.'_'.$cnum})) {
7244: return 1;
7245: }
7246: return 0;
7247: }
7248:
1.1015 raeburn 7249: sub store_userdata {
7250: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7251: my $result;
1.1016 raeburn 7252: if ($datakey ne '') {
1.1013 raeburn 7253: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7254: if ($udom eq '' || $uname eq '') {
7255: $udom = $env{'user.domain'};
7256: $uname = $env{'user.name'};
7257: }
7258: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7259: if (($uhome eq '') || ($uhome eq 'no_host')) {
7260: $result = 'error: no_host';
7261: } else {
7262: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7263: $storehash->{'host'} = $perlvar{'lonHostID'};
7264:
7265: my $namevalue='';
7266: foreach my $key (keys(%{$storehash})) {
7267: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7268: }
7269: $namevalue=~s/\&$//;
7270: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 7271: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 7272: }
7273: } else {
7274: $result = 'error: data to store was not a hash reference';
7275: }
7276: } else {
7277: $result= 'error: invalid requestkey';
7278: }
7279: return $result;
7280: }
7281:
1.21 www 7282: # ---------------------------------------------------------- Assign Custom Role
7283:
7284: sub assigncustomrole {
1.957 raeburn 7285: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7286: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7287: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7288: }
7289:
7290: # ----------------------------------------------------------------- Revoke Role
7291:
7292: sub revokerole {
1.957 raeburn 7293: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7294: my $now=time;
1.965 raeburn 7295: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7296: }
7297:
7298: # ---------------------------------------------------------- Revoke Custom Role
7299:
7300: sub revokecustomrole {
1.957 raeburn 7301: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7302: my $now=time;
1.357 www 7303: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7304: $deleteflag,$selfenroll,$context);
1.17 www 7305: }
7306:
1.533 banghart 7307: # ------------------------------------------------------------ Disk usage
1.535 albertel 7308: sub diskusage {
1.955 raeburn 7309: my ($udom,$uname,$directorypath,$getpropath)=@_;
7310: $directorypath =~ s/\/$//;
7311: my $listing=&reply('du2:'.&escape($directorypath).':'
7312: .&escape($getpropath).':'.&escape($uname).':'
7313: .&escape($udom),homeserver($uname,$udom));
7314: if ($listing eq 'unknown_cmd') {
7315: if ($getpropath) {
7316: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7317: }
7318: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7319: }
1.514 albertel 7320: return $listing;
1.512 banghart 7321: }
7322:
1.566 banghart 7323: sub is_locked {
7324: my ($file_name, $domain, $user) = @_;
7325: my @check;
7326: my $is_locked;
7327: push @check, $file_name;
1.613 albertel 7328: my %locked = &get('file_permissions',\@check,
1.620 albertel 7329: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7330: my ($tmp)=keys(%locked);
7331: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7332:
1.566 banghart 7333: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7334: $is_locked = 'false';
7335: foreach my $entry (@{$locked{$file_name}}) {
7336: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7337: $is_locked = 'true';
7338: last;
1.745 raeburn 7339: }
7340: }
1.566 banghart 7341: } else {
7342: $is_locked = 'false';
7343: }
7344: }
7345:
1.759 albertel 7346: sub declutter_portfile {
7347: my ($file) = @_;
1.833 albertel 7348: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7349: return $file;
7350: }
7351:
1.559 banghart 7352: # ------------------------------------------------------------- Mark as Read Only
7353:
7354: sub mark_as_readonly {
7355: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7356: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7357: my ($tmp)=keys(%current_permissions);
7358: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7359: foreach my $file (@{$files}) {
1.759 albertel 7360: $file = &declutter_portfile($file);
1.561 banghart 7361: push(@{$current_permissions{$file}},$what);
1.559 banghart 7362: }
1.613 albertel 7363: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7364: return;
7365: }
7366:
1.572 banghart 7367: # ------------------------------------------------------------Save Selected Files
7368:
7369: sub save_selected_files {
7370: my ($user, $path, @files) = @_;
7371: my $filename = $user."savedfiles";
1.573 banghart 7372: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7373: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7374: foreach my $file (@files) {
1.620 albertel 7375: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7376: }
7377: foreach my $file (@other_files) {
1.574 banghart 7378: print (OUT $file."\n");
1.572 banghart 7379: }
1.574 banghart 7380: close (OUT);
1.572 banghart 7381: return 'ok';
7382: }
7383:
1.574 banghart 7384: sub clear_selected_files {
7385: my ($user) = @_;
7386: my $filename = $user."savedfiles";
7387: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7388: print (OUT undef);
7389: close (OUT);
7390: return ("ok");
7391: }
7392:
1.572 banghart 7393: sub files_in_path {
7394: my ($user, $path) = @_;
7395: my $filename = $user."savedfiles";
7396: my %return_files;
1.574 banghart 7397: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7398: while (my $line_in = <IN>) {
1.574 banghart 7399: chomp ($line_in);
7400: my @paths_and_file = split (m!/!, $line_in);
7401: my $file_part = pop (@paths_and_file);
7402: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7403: $path_part.='/';
7404: my $path_and_file = $path_part.$file_part;
7405: if ($path_part eq $path) {
7406: $return_files{$file_part}= 'selected';
7407: }
7408: }
1.574 banghart 7409: close (IN);
7410: return (\%return_files);
1.572 banghart 7411: }
7412:
7413: # called in portfolio select mode, to show files selected NOT in current directory
7414: sub files_not_in_path {
7415: my ($user, $path) = @_;
7416: my $filename = $user."savedfiles";
7417: my @return_files;
7418: my $path_part;
1.800 albertel 7419: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7420: while (my $line = <IN>) {
1.572 banghart 7421: #ok, I know it's clunky, but I want it to work
1.800 albertel 7422: my @paths_and_file = split(m|/|, $line);
7423: my $file_part = pop(@paths_and_file);
7424: chomp($file_part);
7425: my $path_part = join('/', @paths_and_file);
1.572 banghart 7426: $path_part .= '/';
7427: my $path_and_file = $path_part.$file_part;
7428: if ($path_part ne $path) {
1.800 albertel 7429: push(@return_files, ($path_and_file));
1.572 banghart 7430: }
7431: }
1.800 albertel 7432: close(OUT);
1.574 banghart 7433: return (@return_files);
1.572 banghart 7434: }
7435:
1.745 raeburn 7436: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7437:
1.745 raeburn 7438: sub get_portfile_permissions {
7439: my ($domain,$user) = @_;
1.613 albertel 7440: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7441: my ($tmp)=keys(%current_permissions);
7442: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7443: return \%current_permissions;
7444: }
7445:
7446: #---------------------------------------------Get portfolio file access controls
7447:
1.749 raeburn 7448: sub get_access_controls {
1.745 raeburn 7449: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7450: my %access;
7451: my $real_file = $file;
7452: $file =~ s/\.meta$//;
1.745 raeburn 7453: if (defined($file)) {
1.749 raeburn 7454: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7455: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7456: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7457: }
7458: }
1.745 raeburn 7459: } else {
1.749 raeburn 7460: foreach my $key (keys(%{$current_permissions})) {
7461: if ($key =~ /\0accesscontrol$/) {
7462: if (defined($group)) {
7463: if ($key !~ m-^\Q$group\E/-) {
7464: next;
7465: }
7466: }
7467: my ($fullpath) = split(/\0/,$key);
7468: if (ref($$current_permissions{$key}) eq 'HASH') {
7469: foreach my $control (keys(%{$$current_permissions{$key}})) {
7470: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7471: }
7472: }
7473: }
7474: }
7475: }
7476: return %access;
7477: }
7478:
7479: sub modify_access_controls {
7480: my ($file_name,$changes,$domain,$user)=@_;
7481: my ($outcome,$deloutcome);
7482: my %store_permissions;
7483: my %new_values;
7484: my %new_control;
7485: my %translation;
7486: my @deletions = ();
7487: my $now = time;
7488: if (exists($$changes{'activate'})) {
7489: if (ref($$changes{'activate'}) eq 'HASH') {
7490: my @newitems = sort(keys(%{$$changes{'activate'}}));
7491: my $numnew = scalar(@newitems);
7492: for (my $i=0; $i<$numnew; $i++) {
7493: my $newkey = $newitems[$i];
7494: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7495: if ($newkey =~ /^\d+:/) {
7496: $newkey =~ s/^(\d+)/$newid/;
7497: $translation{$1} = $newid;
7498: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7499: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7500: $translation{$1} = $newid;
7501: }
1.749 raeburn 7502: $new_values{$file_name."\0".$newkey} =
7503: $$changes{'activate'}{$newitems[$i]};
7504: $new_control{$newkey} = $now;
7505: }
7506: }
7507: }
7508: my %todelete;
7509: my %changed_items;
7510: foreach my $action ('delete','update') {
7511: if (exists($$changes{$action})) {
7512: if (ref($$changes{$action}) eq 'HASH') {
7513: foreach my $key (keys(%{$$changes{$action}})) {
7514: my ($itemnum) = ($key =~ /^([^:]+):/);
7515: if ($action eq 'delete') {
7516: $todelete{$itemnum} = 1;
7517: } else {
7518: $changed_items{$itemnum} = $key;
7519: }
7520: }
1.745 raeburn 7521: }
7522: }
1.749 raeburn 7523: }
7524: # get lock on access controls for file.
7525: my $lockhash = {
7526: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7527: ':'.$env{'user.domain'},
7528: };
7529: my $tries = 0;
7530: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7531:
7532: while (($gotlock ne 'ok') && $tries <3) {
7533: $tries ++;
7534: sleep 1;
7535: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7536: }
7537: if ($gotlock eq 'ok') {
7538: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7539: my ($tmp)=keys(%curr_permissions);
7540: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7541: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7542: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7543: if (ref($curr_controls) eq 'HASH') {
7544: foreach my $control_item (keys(%{$curr_controls})) {
7545: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7546: if (defined($todelete{$itemnum})) {
7547: push(@deletions,$file_name."\0".$control_item);
7548: } else {
7549: if (defined($changed_items{$itemnum})) {
7550: $new_control{$changed_items{$itemnum}} = $now;
7551: push(@deletions,$file_name."\0".$control_item);
7552: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7553: } else {
7554: $new_control{$control_item} = $$curr_controls{$control_item};
7555: }
7556: }
1.745 raeburn 7557: }
7558: }
7559: }
1.970 raeburn 7560: my ($group);
7561: if (&is_course($domain,$user)) {
7562: ($group,my $file) = split(/\//,$file_name,2);
7563: }
1.749 raeburn 7564: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7565: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7566: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7567: # remove lock
7568: my @del_lock = ($file_name."\0".'locked_access_records');
7569: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7570: my $sqlresult =
1.970 raeburn 7571: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7572: $group);
1.749 raeburn 7573: } else {
7574: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7575: }
1.749 raeburn 7576: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7577: }
7578:
1.827 raeburn 7579: sub make_public_indefinitely {
7580: my ($requrl) = @_;
7581: my $now = time;
7582: my $action = 'activate';
7583: my $aclnum = 0;
7584: if (&is_portfolio_url($requrl)) {
7585: my (undef,$udom,$unum,$file_name,$group) =
7586: &parse_portfolio_url($requrl);
7587: my $current_perms = &get_portfile_permissions($udom,$unum);
7588: my %access_controls = &get_access_controls($current_perms,
7589: $group,$file_name);
7590: foreach my $key (keys(%{$access_controls{$file_name}})) {
7591: my ($num,$scope,$end,$start) =
7592: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7593: if ($scope eq 'public') {
7594: if ($start <= $now && $end == 0) {
7595: $action = 'none';
7596: } else {
7597: $action = 'update';
7598: $aclnum = $num;
7599: }
7600: last;
7601: }
7602: }
7603: if ($action eq 'none') {
7604: return 'ok';
7605: } else {
7606: my %changes;
7607: my $newend = 0;
7608: my $newstart = $now;
7609: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7610: $changes{$action}{$newkey} = {
7611: type => 'public',
7612: time => {
7613: start => $newstart,
7614: end => $newend,
7615: },
7616: };
7617: my ($outcome,$deloutcome,$new_values,$translation) =
7618: &modify_access_controls($file_name,\%changes,$udom,$unum);
7619: return $outcome;
7620: }
7621: } else {
7622: return 'invalid';
7623: }
7624: }
7625:
1.745 raeburn 7626: #------------------------------------------------------Get Marked as Read Only
7627:
7628: sub get_marked_as_readonly {
7629: my ($domain,$user,$what,$group) = @_;
7630: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7631: my @readonly_files;
1.629 banghart 7632: my $cmp1=$what;
7633: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7634: while (my ($file_name,$value) = each(%{$current_permissions})) {
7635: if (defined($group)) {
7636: if ($file_name !~ m-^\Q$group\E/-) {
7637: next;
7638: }
7639: }
1.561 banghart 7640: if (ref($value) eq "ARRAY"){
7641: foreach my $stored_what (@{$value}) {
1.629 banghart 7642: my $cmp2=$stored_what;
1.759 albertel 7643: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7644: $cmp2=join('',@{$stored_what});
1.745 raeburn 7645: }
1.629 banghart 7646: if ($cmp1 eq $cmp2) {
1.561 banghart 7647: push(@readonly_files, $file_name);
1.745 raeburn 7648: last;
1.563 banghart 7649: } elsif (!defined($what)) {
7650: push(@readonly_files, $file_name);
1.745 raeburn 7651: last;
1.561 banghart 7652: }
7653: }
1.745 raeburn 7654: }
1.561 banghart 7655: }
7656: return @readonly_files;
7657: }
1.577 banghart 7658: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7659:
1.577 banghart 7660: sub get_marked_as_readonly_hash {
1.745 raeburn 7661: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7662: my %readonly_files;
1.745 raeburn 7663: while (my ($file_name,$value) = each(%{$current_permissions})) {
7664: if (defined($group)) {
7665: if ($file_name !~ m-^\Q$group\E/-) {
7666: next;
7667: }
7668: }
1.577 banghart 7669: if (ref($value) eq "ARRAY"){
7670: foreach my $stored_what (@{$value}) {
1.745 raeburn 7671: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7672: foreach my $lock_descriptor(@{$stored_what}) {
7673: if ($lock_descriptor eq 'graded') {
7674: $readonly_files{$file_name} = 'graded';
7675: } elsif ($lock_descriptor eq 'handback') {
7676: $readonly_files{$file_name} = 'handback';
7677: } else {
7678: if (!exists($readonly_files{$file_name})) {
7679: $readonly_files{$file_name} = 'locked';
7680: }
7681: }
1.745 raeburn 7682: }
1.750 banghart 7683: }
1.577 banghart 7684: }
7685: }
7686: }
7687: return %readonly_files;
7688: }
1.559 banghart 7689: # ------------------------------------------------------------ Unmark as Read Only
7690:
7691: sub unmark_as_readonly {
1.629 banghart 7692: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7693: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7694: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7695: $file_name = &declutter_portfile($file_name);
1.634 albertel 7696: my $symb_crs = $what;
7697: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7698: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7699: my ($tmp)=keys(%current_permissions);
7700: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7701: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7702: foreach my $file (@readonly_files) {
1.759 albertel 7703: my $clean_file = &declutter_portfile($file);
7704: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7705: my $current_locks = $current_permissions{$file};
1.563 banghart 7706: my @new_locks;
7707: my @del_keys;
7708: if (ref($current_locks) eq "ARRAY"){
7709: foreach my $locker (@{$current_locks}) {
1.632 albertel 7710: my $compare=$locker;
1.749 raeburn 7711: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7712: $compare=join('',@{$locker});
1.746 raeburn 7713: if ($compare ne $symb_crs) {
7714: push(@new_locks, $locker);
7715: }
1.563 banghart 7716: }
7717: }
1.650 albertel 7718: if (scalar(@new_locks) > 0) {
1.563 banghart 7719: $current_permissions{$file} = \@new_locks;
7720: } else {
7721: push(@del_keys, $file);
1.613 albertel 7722: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7723: delete($current_permissions{$file});
1.563 banghart 7724: }
7725: }
1.561 banghart 7726: }
1.613 albertel 7727: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7728: return;
7729: }
1.512 banghart 7730:
1.17 www 7731: # ------------------------------------------------------------ Directory lister
7732:
7733: sub dirlist {
1.955 raeburn 7734: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7735: $uri=~s/^\///;
7736: $uri=~s/\/$//;
1.253 stredwic 7737: my ($udom, $uname);
1.955 raeburn 7738: if ($getuserdir) {
1.253 stredwic 7739: $udom = $userdomain;
7740: $uname = $username;
1.955 raeburn 7741: } else {
7742: (undef,$udom,$uname)=split(/\//,$uri);
7743: if(defined($userdomain)) {
7744: $udom = $userdomain;
7745: }
7746: if(defined($username)) {
7747: $uname = $username;
7748: }
1.253 stredwic 7749: }
1.955 raeburn 7750: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7751:
1.955 raeburn 7752: $dirRoot = $perlvar{'lonDocRoot'};
7753: if (defined($getpropath)) {
7754: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7755: $dirRoot =~ s/\/$//;
1.955 raeburn 7756: } elsif (defined($getuserdir)) {
7757: my $subdir=$uname.'__';
7758: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7759: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7760: ."/$udom/$subdir/$uname";
7761: } elsif (defined($alternateRoot)) {
7762: $dirRoot = $alternateRoot;
1.751 banghart 7763: }
1.253 stredwic 7764:
7765: if($udom) {
7766: if($uname) {
1.955 raeburn 7767: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7768: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7769: .':'.&escape($uname).':'.&escape($udom),
7770: &homeserver($uname,$udom));
7771: if ($listing eq 'unknown_cmd') {
7772: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7773: &homeserver($uname,$udom));
7774: } else {
7775: @listing_results = map { &unescape($_); } split(/:/,$listing);
7776: }
1.605 matthew 7777: if ($listing eq 'unknown_cmd') {
1.800 albertel 7778: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7779: &homeserver($uname,$udom));
1.605 matthew 7780: @listing_results = split(/:/,$listing);
7781: } else {
7782: @listing_results = map { &unescape($_); } split(/:/,$listing);
7783: }
7784: return @listing_results;
1.955 raeburn 7785: } elsif(!$alternateRoot) {
1.800 albertel 7786: my %allusers;
1.841 albertel 7787: my %servers = &get_servers($udom,'library');
1.955 raeburn 7788: foreach my $tryserver (keys(%servers)) {
7789: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7790: &escape($udom),$tryserver);
7791: if ($listing eq 'unknown_cmd') {
7792: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7793: $udom, $tryserver);
7794: } else {
7795: @listing_results = map { &unescape($_); } split(/:/,$listing);
7796: }
1.841 albertel 7797: if ($listing eq 'unknown_cmd') {
7798: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7799: $udom, $tryserver);
7800: @listing_results = split(/:/,$listing);
7801: } else {
7802: @listing_results =
7803: map { &unescape($_); } split(/:/,$listing);
7804: }
7805: if ($listing_results[0] ne 'no_such_dir' &&
7806: $listing_results[0] ne 'empty' &&
7807: $listing_results[0] ne 'con_lost') {
7808: foreach my $line (@listing_results) {
7809: my ($entry) = split(/&/,$line,2);
7810: $allusers{$entry} = 1;
7811: }
7812: }
1.253 stredwic 7813: }
7814: my $alluserstr='';
1.800 albertel 7815: foreach my $user (sort(keys(%allusers))) {
7816: $alluserstr.=$user.'&user:';
1.253 stredwic 7817: }
7818: $alluserstr=~s/:$//;
7819: return split(/:/,$alluserstr);
7820: } else {
1.800 albertel 7821: return ('missing user name');
1.253 stredwic 7822: }
1.955 raeburn 7823: } elsif(!defined($getpropath)) {
1.841 albertel 7824: my @all_domains = sort(&all_domains());
1.955 raeburn 7825: foreach my $domain (@all_domains) {
7826: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7827: }
7828: return @all_domains;
7829: } else {
1.800 albertel 7830: return ('missing domain');
1.275 stredwic 7831: }
7832: }
7833:
7834: # --------------------------------------------- GetFileTimestamp
7835: # This function utilizes dirlist and returns the date stamp for
7836: # when it was last modified. It will also return an error of -1
7837: # if an error occurs
7838:
7839: sub GetFileTimestamp {
1.955 raeburn 7840: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7841: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7842: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7843: my ($fileStat) =
7844: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7845: undef,$getuserdir);
1.275 stredwic 7846: my @stats = split('&', $fileStat);
7847: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7848: # @stats contains first the filename, then the stat output
7849: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7850: } else {
7851: return -1;
1.253 stredwic 7852: }
1.26 www 7853: }
7854:
1.712 albertel 7855: sub stat_file {
7856: my ($uri) = @_;
1.787 albertel 7857: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7858:
1.955 raeburn 7859: my ($udom,$uname,$file);
1.712 albertel 7860: if ($uri =~ m-^/(uploaded|editupload)/-) {
7861: ($udom,$uname,$file) =
1.811 albertel 7862: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7863: $file = 'userfiles/'.$file;
7864: }
7865: if ($uri =~ m-^/res/-) {
7866: ($udom,$uname) =
1.807 albertel 7867: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7868: $file = $uri;
7869: }
7870:
7871: if (!$udom || !$uname || !$file) {
7872: # unable to handle the uri
7873: return ();
7874: }
1.956 raeburn 7875: my $getpropath;
7876: if ($file =~ /^userfiles\//) {
7877: $getpropath = 1;
7878: }
1.955 raeburn 7879: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7880: my @stats = split('&', $result);
1.721 banghart 7881:
1.712 albertel 7882: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7883: shift(@stats); #filename is first
7884: return @stats;
7885: }
7886: return ();
7887: }
7888:
1.26 www 7889: # -------------------------------------------------------- Value of a Condition
7890:
1.713 albertel 7891: # gets the value of a specific preevaluated condition
7892: # stored in the string $env{user.state.<cid>}
7893: # or looks up a condition reference in the bighash and if if hasn't
7894: # already been evaluated recurses into docondval to get the value of
7895: # the condition, then memoizing it to
7896: # $env{user.state.<cid>.<condition>}
1.40 www 7897: sub directcondval {
7898: my $number=shift;
1.620 albertel 7899: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7900: &Apache::lonuserstate::evalstate();
7901: }
1.713 albertel 7902: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7903: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7904: } elsif ($number =~ /^_/) {
7905: my $sub_condition;
7906: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7907: &GDBM_READER(),0640)) {
7908: $sub_condition=$bighash{'conditions'.$number};
7909: untie(%bighash);
7910: }
7911: my $value = &docondval($sub_condition);
1.949 raeburn 7912: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7913: return $value;
7914: }
1.620 albertel 7915: if ($env{'user.state.'.$env{'request.course.id'}}) {
7916: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7917: } else {
7918: return 2;
7919: }
7920: }
7921:
1.713 albertel 7922: # get the collection of conditions for this resource
1.26 www 7923: sub condval {
7924: my $condidx=shift;
1.54 www 7925: my $allpathcond='';
1.713 albertel 7926: foreach my $cond (split(/\|/,$condidx)) {
7927: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7928: $allpathcond.=
7929: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7930: }
1.191 harris41 7931: }
1.54 www 7932: $allpathcond=~s/\|$//;
1.713 albertel 7933: return &docondval($allpathcond);
7934: }
7935:
7936: #evaluates an expression of conditions
7937: sub docondval {
7938: my ($allpathcond) = @_;
7939: my $result=0;
7940: if ($env{'request.course.id'}
7941: && defined($allpathcond)) {
7942: my $operand='|';
7943: my @stack;
7944: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7945: if ($chunk eq '(') {
7946: push @stack,($operand,$result);
7947: } elsif ($chunk eq ')') {
7948: my $before=pop @stack;
7949: if (pop @stack eq '&') {
7950: $result=$result>$before?$before:$result;
7951: } else {
7952: $result=$result>$before?$result:$before;
7953: }
7954: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7955: $operand=$chunk;
7956: } else {
7957: my $new=directcondval($chunk);
7958: if ($operand eq '&') {
7959: $result=$result>$new?$new:$result;
7960: } else {
7961: $result=$result>$new?$result:$new;
7962: }
7963: }
7964: }
1.26 www 7965: }
7966: return $result;
1.421 albertel 7967: }
7968:
7969: # ---------------------------------------------------- Devalidate courseresdata
7970:
7971: sub devalidatecourseresdata {
7972: my ($coursenum,$coursedomain)=@_;
7973: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7974: &devalidate_cache_new('courseres',$hashid);
1.28 www 7975: }
7976:
1.763 www 7977:
1.200 www 7978: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7979: #
7980: # Parameters:
7981: # $coursenum - Number of the course.
7982: # $coursedomain - Domain at which the course was created.
7983: # Returns:
7984: # A hash of the course parameters along (I think) with timestamps
7985: # and version info.
1.877 foxr 7986:
1.624 albertel 7987: sub get_courseresdata {
7988: my ($coursenum,$coursedomain)=@_;
1.200 www 7989: my $coursehom=&homeserver($coursenum,$coursedomain);
7990: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7991: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7992: my %dumpreply;
1.417 albertel 7993: unless (defined($cached)) {
1.624 albertel 7994: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7995: $result=\%dumpreply;
1.251 albertel 7996: my ($tmp) = keys(%dumpreply);
7997: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7998: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7999: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8000: return $tmp;
1.416 albertel 8001: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8002: $result=undef;
1.599 albertel 8003: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8004: }
8005: }
1.624 albertel 8006: return $result;
8007: }
8008:
1.633 albertel 8009: sub devalidateuserresdata {
8010: my ($uname,$udom)=@_;
8011: my $hashid="$udom:$uname";
8012: &devalidate_cache_new('userres',$hashid);
8013: }
8014:
1.624 albertel 8015: sub get_userresdata {
8016: my ($uname,$udom)=@_;
8017: #most student don\'t have any data set, check if there is some data
8018: if (&EXT_cache_status($udom,$uname)) { return undef; }
8019:
8020: my $hashid="$udom:$uname";
8021: my ($result,$cached)=&is_cached_new('userres',$hashid);
8022: if (!defined($cached)) {
8023: my %resourcedata=&dump('resourcedata',$udom,$uname);
8024: $result=\%resourcedata;
8025: &do_cache_new('userres',$hashid,$result,600);
8026: }
8027: my ($tmp)=keys(%$result);
8028: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8029: return $result;
8030: }
8031: #error 2 occurs when the .db doesn't exist
8032: if ($tmp!~/error: 2 /) {
1.672 albertel 8033: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8034: " Trying to get resource data for ".
8035: $uname." at ".$udom.": ".
8036: $tmp."</font>");
8037: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8038: #&EXT_cache_set($udom,$uname);
8039: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8040: undef($tmp); # not really an error so don't send it back
1.624 albertel 8041: }
8042: return $tmp;
8043: }
1.879 foxr 8044: #----------------------------------------------- resdata - return resource data
8045: # Purpose:
8046: # Return resource data for either users or for a course.
8047: # Parameters:
8048: # $name - Course/user name.
8049: # $domain - Name of the domain the user/course is registered on.
8050: # $type - Type of thing $name is (must be 'course' or 'user'
8051: # @which - Array of names of resources desired.
8052: # Returns:
8053: # The value of the first reasource in @which that is found in the
8054: # resource hash.
8055: # Exceptional Conditions:
8056: # If the $type passed in is not valid (not the string 'course' or
8057: # 'user', an undefined reference is returned.
8058: # If none of the resources are found, an undef is returned
1.624 albertel 8059: sub resdata {
8060: my ($name,$domain,$type,@which)=@_;
8061: my $result;
8062: if ($type eq 'course') {
8063: $result=&get_courseresdata($name,$domain);
8064: } elsif ($type eq 'user') {
8065: $result=&get_userresdata($name,$domain);
8066: }
8067: if (!ref($result)) { return $result; }
1.251 albertel 8068: foreach my $item (@which) {
1.927 albertel 8069: if (defined($result->{$item->[0]})) {
8070: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8071: }
1.250 albertel 8072: }
1.291 albertel 8073: return undef;
1.200 www 8074: }
8075:
1.379 matthew 8076: #
8077: # EXT resource caching routines
8078: #
8079:
8080: sub clear_EXT_cache_status {
1.383 albertel 8081: &delenv('cache.EXT.');
1.379 matthew 8082: }
8083:
8084: sub EXT_cache_status {
8085: my ($target_domain,$target_user) = @_;
1.383 albertel 8086: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8087: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8088: # We know already the user has no data
8089: return 1;
8090: } else {
8091: return 0;
8092: }
8093: }
8094:
8095: sub EXT_cache_set {
8096: my ($target_domain,$target_user) = @_;
1.383 albertel 8097: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8098: #&appenv({$cachename => time});
1.379 matthew 8099: }
8100:
1.28 www 8101: # --------------------------------------------------------- Value of a Variable
1.58 www 8102: sub EXT {
1.715 albertel 8103:
1.395 albertel 8104: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8105: unless ($varname) { return ''; }
1.218 albertel 8106: #get real user name/domain, courseid and symb
8107: my $courseid;
1.359 albertel 8108: my $publicuser;
1.427 www 8109: if ($symbparm) {
8110: $symbparm=&get_symb_from_alias($symbparm);
8111: }
1.218 albertel 8112: if (!($uname && $udom)) {
1.790 albertel 8113: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8114: if (!$symbparm) { $symbparm=$cursymb; }
8115: } else {
1.620 albertel 8116: $courseid=$env{'request.course.id'};
1.218 albertel 8117: }
1.48 www 8118: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8119: my $rest;
1.320 albertel 8120: if (defined($therest[0])) {
1.48 www 8121: $rest=join('.',@therest);
8122: } else {
8123: $rest='';
8124: }
1.320 albertel 8125:
1.57 www 8126: my $qualifierrest=$qualifier;
8127: if ($rest) { $qualifierrest.='.'.$rest; }
8128: my $spacequalifierrest=$space;
8129: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8130: if ($realm eq 'user') {
1.48 www 8131: # --------------------------------------------------------------- user.resource
8132: if ($space eq 'resource') {
1.651 albertel 8133: if ( (defined($Apache::lonhomework::parsing_a_problem)
8134: || defined($Apache::lonhomework::parsing_a_task))
8135: &&
1.744 albertel 8136: ($symbparm eq &symbread()) ) {
8137: # if we are in the middle of processing the resource the
8138: # get the value we are planning on committing
8139: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8140: return $Apache::lonhomework::results{$qualifierrest};
8141: } else {
8142: return $Apache::lonhomework::history{$qualifierrest};
8143: }
1.335 albertel 8144: } else {
1.359 albertel 8145: my %restored;
1.620 albertel 8146: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8147: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8148: } else {
8149: %restored=&restore($symbparm,$courseid,$udom,$uname);
8150: }
1.335 albertel 8151: return $restored{$qualifierrest};
8152: }
1.48 www 8153: # ----------------------------------------------------------------- user.access
8154: } elsif ($space eq 'access') {
1.218 albertel 8155: # FIXME - not supporting calls for a specific user
1.48 www 8156: return &allowed($qualifier,$rest);
8157: # ------------------------------------------ user.preferences, user.environment
8158: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8159: if (($uname eq $env{'user.name'}) &&
8160: ($udom eq $env{'user.domain'})) {
8161: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8162: } else {
1.359 albertel 8163: my %returnhash;
8164: if (!$publicuser) {
8165: %returnhash=&userenvironment($udom,$uname,
8166: $qualifierrest);
8167: }
1.218 albertel 8168: return $returnhash{$qualifierrest};
8169: }
1.48 www 8170: # ----------------------------------------------------------------- user.course
8171: } elsif ($space eq 'course') {
1.218 albertel 8172: # FIXME - not supporting calls for a specific user
1.620 albertel 8173: return $env{join('.',('request.course',$qualifier))};
1.48 www 8174: # ------------------------------------------------------------------- user.role
8175: } elsif ($space eq 'role') {
1.218 albertel 8176: # FIXME - not supporting calls for a specific user
1.620 albertel 8177: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8178: if ($qualifier eq 'value') {
8179: return $role;
8180: } elsif ($qualifier eq 'extent') {
8181: return $where;
8182: }
8183: # ----------------------------------------------------------------- user.domain
8184: } elsif ($space eq 'domain') {
1.218 albertel 8185: return $udom;
1.48 www 8186: # ------------------------------------------------------------------- user.name
8187: } elsif ($space eq 'name') {
1.218 albertel 8188: return $uname;
1.48 www 8189: # ---------------------------------------------------- Any other user namespace
1.29 www 8190: } else {
1.359 albertel 8191: my %reply;
8192: if (!$publicuser) {
8193: %reply=&get($space,[$qualifierrest],$udom,$uname);
8194: }
8195: return $reply{$qualifierrest};
1.48 www 8196: }
1.236 www 8197: } elsif ($realm eq 'query') {
8198: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8199: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8200: [$spacequalifierrest]);
1.620 albertel 8201: return $env{'form.'.$spacequalifierrest};
1.236 www 8202: } elsif ($realm eq 'request') {
1.48 www 8203: # ------------------------------------------------------------- request.browser
8204: if ($space eq 'browser') {
1.430 www 8205: if ($qualifier eq 'textremote') {
1.676 albertel 8206: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8207: return 1;
8208: } else {
8209: return 0;
8210: }
8211: } else {
1.620 albertel 8212: return $env{'browser.'.$qualifier};
1.430 www 8213: }
1.57 www 8214: # ------------------------------------------------------------ request.filename
8215: } else {
1.620 albertel 8216: return $env{'request.'.$spacequalifierrest};
1.29 www 8217: }
1.28 www 8218: } elsif ($realm eq 'course') {
1.48 www 8219: # ---------------------------------------------------------- course.description
1.620 albertel 8220: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8221: } elsif ($realm eq 'resource') {
1.165 www 8222:
1.620 albertel 8223: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8224: if (!$symbparm) { $symbparm=&symbread(); }
8225: }
1.693 albertel 8226:
8227: if ($space eq 'title') {
8228: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8229: return &gettitle($symbparm);
8230: }
8231:
8232: if ($space eq 'map') {
8233: my ($map) = &decode_symb($symbparm);
8234: return &symbread($map);
8235: }
1.905 albertel 8236: if ($space eq 'filename') {
8237: if ($symbparm) {
8238: return &clutter((&decode_symb($symbparm))[2]);
8239: }
8240: return &hreflocation('',$env{'request.filename'});
8241: }
1.693 albertel 8242:
8243: my ($section, $group, @groups);
1.593 albertel 8244: my ($courselevelm,$courselevel);
1.539 albertel 8245: if ($symbparm && defined($courseid) &&
1.620 albertel 8246: $courseid eq $env{'request.course.id'}) {
1.165 www 8247:
1.218 albertel 8248: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8249:
1.60 www 8250: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8251: my $symbp=$symbparm;
1.735 albertel 8252: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8253:
8254: my $symbparm=$symbp.'.'.$spacequalifierrest;
8255: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8256:
1.620 albertel 8257: if (($env{'user.name'} eq $uname) &&
8258: ($env{'user.domain'} eq $udom)) {
8259: $section=$env{'request.course.sec'};
1.733 raeburn 8260: @groups = split(/:/,$env{'request.course.groups'});
8261: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8262: } else {
1.539 albertel 8263: if (! defined($usection)) {
1.551 albertel 8264: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8265: } else {
8266: $section = $usection;
8267: }
1.733 raeburn 8268: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8269: }
8270:
8271: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8272: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8273: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8274:
1.593 albertel 8275: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8276: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8277: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8278:
1.60 www 8279: # ----------------------------------------------------------- first, check user
1.624 albertel 8280:
8281: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8282: ([$courselevelr,'resource'],
8283: [$courselevelm,'map' ],
8284: [$courselevel, 'course' ]));
1.931 albertel 8285: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8286:
1.594 albertel 8287: # ------------------------------------------------ second, check some of course
1.684 raeburn 8288: my $coursereply;
1.691 raeburn 8289: if (@groups > 0) {
8290: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8291: $mapparm,$spacequalifierrest);
1.927 albertel 8292: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8293: }
1.96 www 8294:
1.684 raeburn 8295: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8296: $env{'course.'.$courseid.'.domain'},
8297: 'course',
8298: ([$seclevelr, 'resource'],
8299: [$seclevelm, 'map' ],
8300: [$seclevel, 'course' ],
8301: [$courselevelr,'resource']));
8302: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8303:
1.60 www 8304: # ------------------------------------------------------ third, check map parms
1.218 albertel 8305: my %parmhash=();
8306: my $thisparm='';
8307: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8308: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8309: &GDBM_READER(),0640)) {
1.218 albertel 8310: $thisparm=$parmhash{$symbparm};
8311: untie(%parmhash);
8312: }
1.927 albertel 8313: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8314: }
1.594 albertel 8315: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8316:
1.218 albertel 8317: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8318: my $filename;
8319: if (!$symbparm) { $symbparm=&symbread(); }
8320: if ($symbparm) {
1.409 www 8321: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8322: } else {
1.620 albertel 8323: $filename=$env{'request.filename'};
1.282 albertel 8324: }
8325: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8326: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8327: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8328: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8329:
1.927 albertel 8330: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8331: if ($symbparm && defined($courseid) &&
1.620 albertel 8332: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8333: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8334: $env{'course.'.$courseid.'.domain'},
8335: 'course',
1.927 albertel 8336: ([$courselevelm,'map' ],
8337: [$courselevel, 'course']));
8338: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8339: }
1.145 www 8340: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8341: unless ($space eq '0') {
1.336 albertel 8342: my @parts=split(/_/,$space);
8343: my $id=pop(@parts);
8344: my $part=join('_',@parts);
8345: if ($part eq '') { $part='0'; }
1.927 albertel 8346: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8347: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8348: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8349: }
1.395 albertel 8350: if ($recurse) { return undef; }
8351: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8352: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8353: # ---------------------------------------------------- Any other user namespace
8354: } elsif ($realm eq 'environment') {
8355: # ----------------------------------------------------------------- environment
1.620 albertel 8356: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8357: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8358: } else {
1.770 albertel 8359: if ($uname eq 'anonymous' && $udom eq '') {
8360: return '';
8361: }
1.219 albertel 8362: my %returnhash=&userenvironment($udom,$uname,
8363: $spacequalifierrest);
8364: return $returnhash{$spacequalifierrest};
8365: }
1.28 www 8366: } elsif ($realm eq 'system') {
1.48 www 8367: # ----------------------------------------------------------------- system.time
8368: if ($space eq 'time') {
8369: return time;
8370: }
1.696 albertel 8371: } elsif ($realm eq 'server') {
8372: # ----------------------------------------------------------------- system.time
8373: if ($space eq 'name') {
8374: return $ENV{'SERVER_NAME'};
8375: }
1.28 www 8376: }
1.48 www 8377: return '';
1.61 www 8378: }
8379:
1.927 albertel 8380: sub get_reply {
8381: my ($reply_value) = @_;
1.940 raeburn 8382: if (ref($reply_value) eq 'ARRAY') {
8383: if (wantarray) {
8384: return @$reply_value;
8385: }
8386: return $reply_value->[0];
8387: } else {
8388: return $reply_value;
1.927 albertel 8389: }
8390: }
8391:
1.691 raeburn 8392: sub check_group_parms {
8393: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8394: my @groupitems = ();
8395: my $resultitem;
1.927 albertel 8396: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8397: foreach my $group (@{$groups}) {
8398: foreach my $level (@levels) {
1.927 albertel 8399: my $item = $courseid.'.['.$group.'].'.$level->[0];
8400: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8401: }
8402: }
8403: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8404: $env{'course.'.$courseid.'.domain'},
8405: 'course',@groupitems);
8406: return $coursereply;
8407: }
8408:
8409: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8410: my ($courseid,@groups) = @_;
8411: @groups = sort(@groups);
1.691 raeburn 8412: return @groups;
8413: }
8414:
1.395 albertel 8415: sub packages_tab_default {
8416: my ($uri,$varname)=@_;
8417: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8418:
8419: my (@extension,@specifics,$do_default);
8420: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8421: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8422: if ($pack_type eq 'default') {
8423: $do_default=1;
8424: } elsif ($pack_type eq 'extension') {
8425: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8426: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8427: # only look at packages defaults for packages that this id is
1.738 albertel 8428: push(@specifics,[$package,$pack_type,$pack_part]);
8429: }
8430: }
8431: # first look for a package that matches the requested part id
8432: foreach my $package (@specifics) {
8433: my (undef,$pack_type,$pack_part)=@{$package};
8434: next if ($pack_part ne $part);
8435: if (defined($packagetab{"$pack_type&$name&default"})) {
8436: return $packagetab{"$pack_type&$name&default"};
8437: }
8438: }
8439: # look for any possible matching non extension_ package
8440: foreach my $package (@specifics) {
8441: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8442: if (defined($packagetab{"$pack_type&$name&default"})) {
8443: return $packagetab{"$pack_type&$name&default"};
8444: }
1.585 albertel 8445: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8446: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8447: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8448: }
8449: }
1.738 albertel 8450: # look for any posible extension_ match
8451: foreach my $package (@extension) {
8452: my ($package,$pack_type)=@{$package};
8453: if (defined($packagetab{"$pack_type&$name&default"})) {
8454: return $packagetab{"$pack_type&$name&default"};
8455: }
8456: if (defined($packagetab{$package."&$name&default"})) {
8457: return $packagetab{$package."&$name&default"};
8458: }
8459: }
8460: # look for a global default setting
8461: if ($do_default && defined($packagetab{"default&$name&default"})) {
8462: return $packagetab{"default&$name&default"};
8463: }
1.395 albertel 8464: return undef;
8465: }
8466:
1.334 albertel 8467: sub add_prefix_and_part {
8468: my ($prefix,$part)=@_;
8469: my $keyroot;
8470: if (defined($prefix) && $prefix !~ /^__/) {
8471: # prefix that has a part already
8472: $keyroot=$prefix;
8473: } elsif (defined($prefix)) {
8474: # prefix that is missing a part
8475: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8476: } else {
8477: # no prefix at all
8478: if (defined($part)) { $keyroot='_'.$part; }
8479: }
8480: return $keyroot;
8481: }
8482:
1.71 www 8483: # ---------------------------------------------------------------- Get metadata
8484:
1.599 albertel 8485: my %metaentry;
1.71 www 8486: sub metadata {
1.176 www 8487: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8488: $uri=&declutter($uri);
1.288 albertel 8489: # if it is a non metadata possible uri return quickly
1.529 albertel 8490: if (($uri eq '') ||
8491: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8492: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924 albertel 8493: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
8494: return undef;
8495: }
8496: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8497: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8498: return undef;
1.288 albertel 8499: }
1.73 www 8500: my $filename=$uri;
8501: $uri=~s/\.meta$//;
1.172 www 8502: #
8503: # Is the metadata already cached?
1.177 www 8504: # Look at timestamp of caching
1.172 www 8505: # Everything is cached by the main uri, libraries are never directly cached
8506: #
1.428 albertel 8507: if (!defined($liburi)) {
1.599 albertel 8508: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8509: if (defined($cached)) { return $result->{':'.$what}; }
8510: }
8511: {
1.172 www 8512: #
8513: # Is this a recursive call for a library?
8514: #
1.599 albertel 8515: # if (! exists($metacache{$uri})) {
8516: # $metacache{$uri}={};
8517: # }
1.924 albertel 8518: my $cachetime = 60*60;
1.171 www 8519: if ($liburi) {
8520: $liburi=&declutter($liburi);
8521: $filename=$liburi;
1.401 bowersj2 8522: } else {
1.599 albertel 8523: &devalidate_cache_new('meta',$uri);
8524: undef(%metaentry);
1.401 bowersj2 8525: }
1.140 www 8526: my %metathesekeys=();
1.73 www 8527: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8528: my $metastring;
1.924 albertel 8529: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8530: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8531: $metastring =
1.929 albertel 8532: &Apache::lonnet::ssi_body($which,
1.924 albertel 8533: ('grade_target' => 'meta'));
8534: $cachetime = 1; # only want this cached in the child not long term
8535: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8536: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8537: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8538: $metastring=&getfile($file);
1.489 albertel 8539: }
1.208 albertel 8540: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8541: my $token;
1.140 www 8542: undef %metathesekeys;
1.71 www 8543: while ($token=$parser->get_token) {
1.339 albertel 8544: if ($token->[0] eq 'S') {
8545: if (defined($token->[2]->{'package'})) {
1.172 www 8546: #
8547: # This is a package - get package info
8548: #
1.339 albertel 8549: my $package=$token->[2]->{'package'};
8550: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8551: if (defined($token->[2]->{'id'})) {
8552: $keyroot.='_'.$token->[2]->{'id'};
8553: }
1.599 albertel 8554: if ($metaentry{':packages'}) {
8555: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8556: } else {
1.599 albertel 8557: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8558: }
1.736 albertel 8559: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8560: my $part=$keyroot;
8561: $part=~s/^\_//;
1.736 albertel 8562: if ($pack_entry=~/^\Q$package\E\&/ ||
8563: $pack_entry=~/^\Q$package\E_0\&/) {
8564: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8565: # ignore package.tab specified default values
8566: # here &package_tab_default() will fetch those
8567: if ($subp eq 'default') { next; }
1.736 albertel 8568: my $value=$packagetab{$pack_entry};
1.432 albertel 8569: my $unikey;
8570: if ($pack =~ /_0$/) {
8571: $unikey='parameter_0_'.$name;
8572: $part=0;
8573: } else {
8574: $unikey='parameter'.$keyroot.'_'.$name;
8575: }
1.339 albertel 8576: if ($subp eq 'display') {
8577: $value.=' [Part: '.$part.']';
8578: }
1.599 albertel 8579: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8580: $metathesekeys{$unikey}=1;
1.599 albertel 8581: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8582: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8583: }
1.599 albertel 8584: if (defined($metaentry{':'.$unikey.'.default'})) {
8585: $metaentry{':'.$unikey}=
8586: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8587: }
1.339 albertel 8588: }
8589: }
8590: } else {
1.172 www 8591: #
8592: # This is not a package - some other kind of start tag
1.339 albertel 8593: #
8594: my $entry=$token->[1];
8595: my $unikey;
8596: if ($entry eq 'import') {
8597: $unikey='';
8598: } else {
8599: $unikey=$entry;
8600: }
8601: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8602:
8603: if (defined($token->[2]->{'id'})) {
8604: $unikey.='_'.$token->[2]->{'id'};
8605: }
1.175 www 8606:
1.339 albertel 8607: if ($entry eq 'import') {
1.175 www 8608: #
8609: # Importing a library here
1.339 albertel 8610: #
8611: if ($depthcount<20) {
8612: my $location=$parser->get_text('/import');
8613: my $dir=$filename;
8614: $dir=~s|[^/]*$||;
8615: $location=&filelocation($dir,$location);
1.736 albertel 8616: my $metadata =
8617: &metadata($uri,'keys', $location,$unikey,
8618: $depthcount+1);
8619: foreach my $meta (split(',',$metadata)) {
8620: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8621: $metathesekeys{$meta}=1;
1.339 albertel 8622: }
8623: }
8624: } else {
8625: if (defined($token->[2]->{'name'})) {
8626: $unikey.='_'.$token->[2]->{'name'};
8627: }
8628: $metathesekeys{$unikey}=1;
1.736 albertel 8629: foreach my $param (@{$token->[3]}) {
8630: $metaentry{':'.$unikey.'.'.$param} =
8631: $token->[2]->{$param};
1.339 albertel 8632: }
8633: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8634: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8635: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8636: # only ws inside the tag, and not in default, so use default
8637: # as value
1.599 albertel 8638: $metaentry{':'.$unikey}=$default;
1.908 albertel 8639: } elsif ( $internaltext =~ /\S/ ) {
8640: # something interesting inside the tag
8641: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8642: } else {
1.908 albertel 8643: # no interesting values, don't set a default
1.339 albertel 8644: }
1.172 www 8645: # end of not-a-package not-a-library import
1.339 albertel 8646: }
1.172 www 8647: # end of not-a-package start tag
1.339 albertel 8648: }
1.172 www 8649: # the next is the end of "start tag"
1.339 albertel 8650: }
8651: }
1.483 albertel 8652: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8653: $extension = lc($extension);
8654: if ($extension eq 'htm') { $extension='html'; }
8655:
1.737 albertel 8656: foreach my $key (keys(%packagetab)) {
1.483 albertel 8657: #no specific packages #how's our extension
8658: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8659: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8660: \%metathesekeys);
8661: }
1.883 albertel 8662:
8663: if (!exists($metaentry{':packages'})
8664: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8665: foreach my $key (keys(%packagetab)) {
1.483 albertel 8666: #no specific packages well let's get default then
8667: if ($key!~/^default&/) { next; }
1.488 albertel 8668: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8669: \%metathesekeys);
8670: }
8671: }
1.338 www 8672: # are there custom rights to evaluate
1.599 albertel 8673: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8674:
1.338 www 8675: #
8676: # Importing a rights file here
1.339 albertel 8677: #
8678: unless ($depthcount) {
1.599 albertel 8679: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8680: my $dir=$filename;
8681: $dir=~s|[^/]*$||;
8682: $location=&filelocation($dir,$location);
1.736 albertel 8683: my $rights_metadata =
8684: &metadata($uri,'keys',$location,'_rights',
8685: $depthcount+1);
8686: foreach my $rights (split(',',$rights_metadata)) {
8687: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8688: $metathesekeys{$rights}=1;
1.339 albertel 8689: }
8690: }
8691: }
1.737 albertel 8692: # uniqifiy package listing
8693: my %seen;
8694: my @uniq_packages =
8695: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8696: $metaentry{':packages'} = join(',',@uniq_packages);
8697:
8698: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8699: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8700: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8701: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8702: # this is the end of "was not already recently cached
1.71 www 8703: }
1.599 albertel 8704: return $metaentry{':'.$what};
1.261 albertel 8705: }
8706:
1.488 albertel 8707: sub metadata_create_package_def {
1.483 albertel 8708: my ($uri,$key,$package,$metathesekeys)=@_;
8709: my ($pack,$name,$subp)=split(/\&/,$key);
8710: if ($subp eq 'default') { next; }
8711:
1.599 albertel 8712: if (defined($metaentry{':packages'})) {
8713: $metaentry{':packages'}.=','.$package;
1.483 albertel 8714: } else {
1.599 albertel 8715: $metaentry{':packages'}=$package;
1.483 albertel 8716: }
8717: my $value=$packagetab{$key};
8718: my $unikey;
8719: $unikey='parameter_0_'.$name;
1.599 albertel 8720: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8721: $$metathesekeys{$unikey}=1;
1.599 albertel 8722: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8723: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8724: }
1.599 albertel 8725: if (defined($metaentry{':'.$unikey.'.default'})) {
8726: $metaentry{':'.$unikey}=
8727: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8728: }
8729: }
8730:
1.261 albertel 8731: sub metadata_generate_part0 {
8732: my ($metadata,$metacache,$uri) = @_;
8733: my %allnames;
1.737 albertel 8734: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8735: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8736: my $part=$$metacache{':'.$metakey.'.part'};
8737: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8738: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8739: $allnames{$name}=$part;
8740: }
8741: }
8742: }
8743: foreach my $name (keys(%allnames)) {
8744: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8745: my $key=":parameter_0_$name";
1.261 albertel 8746: $$metacache{"$key.part"}='0';
8747: $$metacache{"$key.name"}=$name;
1.428 albertel 8748: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8749: $allnames{$name}.'_'.$name.
8750: '.type'};
1.428 albertel 8751: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8752: '.display'};
1.644 www 8753: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8754: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8755: $$metacache{"$key.display"}=$olddis;
8756: }
1.71 www 8757: }
8758:
1.764 albertel 8759: # ------------------------------------------------------ Devalidate title cache
8760:
8761: sub devalidate_title_cache {
8762: my ($url)=@_;
8763: if (!$env{'request.course.id'}) { return; }
8764: my $symb=&symbread($url);
8765: if (!$symb) { return; }
8766: my $key=$env{'request.course.id'}."\0".$symb;
8767: &devalidate_cache_new('title',$key);
8768: }
8769:
1.1014 droeschl 8770: # ------------------------------------------------- Get the title of a course
8771:
8772: sub current_course_title {
8773: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8774: }
1.301 www 8775: # ------------------------------------------------- Get the title of a resource
8776:
8777: sub gettitle {
8778: my $urlsymb=shift;
8779: my $symb=&symbread($urlsymb);
1.534 albertel 8780: if ($symb) {
1.620 albertel 8781: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8782: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8783: if (defined($cached)) {
8784: return $result;
8785: }
1.534 albertel 8786: my ($map,$resid,$url)=&decode_symb($symb);
8787: my $title='';
1.907 albertel 8788: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8789: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8790: } else {
8791: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8792: &GDBM_READER(),0640)) {
8793: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8794: $title=$bighash{'title_'.$mapid.'.'.$resid};
8795: untie(%bighash);
8796: }
1.534 albertel 8797: }
8798: $title=~s/\&colon\;/\:/gs;
8799: if ($title) {
1.599 albertel 8800: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8801: }
8802: $urlsymb=$url;
8803: }
8804: my $title=&metadata($urlsymb,'title');
8805: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8806: return $title;
1.301 www 8807: }
1.613 albertel 8808:
1.614 albertel 8809: sub get_slot {
8810: my ($which,$cnum,$cdom)=@_;
8811: if (!$cnum || !$cdom) {
1.790 albertel 8812: (undef,my $courseid)=&whichuser();
1.620 albertel 8813: $cdom=$env{'course.'.$courseid.'.domain'};
8814: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8815: }
1.703 albertel 8816: my $key=join("\0",'slots',$cdom,$cnum,$which);
8817: my %slotinfo;
8818: if (exists($remembered{$key})) {
8819: $slotinfo{$which} = $remembered{$key};
8820: } else {
8821: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8822: &Apache::lonhomework::showhash(%slotinfo);
8823: my ($tmp)=keys(%slotinfo);
8824: if ($tmp=~/^error:/) { return (); }
8825: $remembered{$key} = $slotinfo{$which};
8826: }
1.616 albertel 8827: if (ref($slotinfo{$which}) eq 'HASH') {
8828: return %{$slotinfo{$which}};
8829: }
8830: return $slotinfo{$which};
1.614 albertel 8831: }
1.31 www 8832: # ------------------------------------------------- Update symbolic store links
8833:
8834: sub symblist {
8835: my ($mapname,%newhash)=@_;
1.438 www 8836: $mapname=&deversion(&declutter($mapname));
1.31 www 8837: my %hash;
1.620 albertel 8838: if (($env{'request.course.fn'}) && (%newhash)) {
8839: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8840: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8841: foreach my $url (keys(%newhash)) {
1.711 albertel 8842: next if ($url eq 'last_known'
8843: && $env{'form.no_update_last_known'});
8844: $hash{declutter($url)}=&encode_symb($mapname,
8845: $newhash{$url}->[1],
8846: $newhash{$url}->[0]);
1.191 harris41 8847: }
1.31 www 8848: if (untie(%hash)) {
8849: return 'ok';
8850: }
8851: }
8852: }
8853: return 'error';
1.212 www 8854: }
8855:
8856: # --------------------------------------------------------------- Verify a symb
8857:
8858: sub symbverify {
1.510 www 8859: my ($symb,$thisurl)=@_;
8860: my $thisfn=$thisurl;
1.439 www 8861: $thisfn=&declutter($thisfn);
1.215 www 8862: # direct jump to resource in page or to a sequence - will construct own symbs
8863: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8864: # check URL part
1.409 www 8865: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8866:
1.431 www 8867: unless ($url eq $thisfn) { return 0; }
1.213 www 8868:
1.216 www 8869: $symb=&symbclean($symb);
1.510 www 8870: $thisurl=&deversion($thisurl);
1.439 www 8871: $thisfn=&deversion($thisfn);
1.213 www 8872:
8873: my %bighash;
8874: my $okay=0;
1.431 www 8875:
1.620 albertel 8876: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8877: &GDBM_READER(),0640)) {
1.1032 raeburn 8878: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8879: $thisurl =~ s/\?.+$//;
8880: }
1.510 www 8881: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8882: unless ($ids) {
1.510 www 8883: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8884: }
8885: if ($ids) {
8886: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8887: foreach my $id (split(/\,/,$ids)) {
8888: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8889: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8890: $symb =~ s/\?.+$//;
8891: }
1.216 www 8892: if (
8893: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8894: eq $symb) {
1.620 albertel 8895: if (($env{'request.role.adv'}) ||
1.800 albertel 8896: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8897: $okay=1;
8898: }
8899: }
1.216 www 8900: }
8901: }
1.213 www 8902: untie(%bighash);
8903: }
8904: return $okay;
1.31 www 8905: }
8906:
1.210 www 8907: # --------------------------------------------------------------- Clean-up symb
8908:
8909: sub symbclean {
8910: my $symb=shift;
1.568 albertel 8911: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8912: # remove version from map
8913: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8914:
1.210 www 8915: # remove version from URL
8916: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8917:
1.507 www 8918: # remove wrapper
8919:
1.510 www 8920: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8921: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8922: return $symb;
1.409 www 8923: }
8924:
8925: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8926:
8927: sub encode_symb {
8928: my ($map,$resid,$url)=@_;
8929: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8930: }
1.409 www 8931:
8932: sub decode_symb {
1.568 albertel 8933: my $symb=shift;
8934: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8935: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8936: return (&fixversion($map),$resid,&fixversion($url));
8937: }
8938:
8939: sub fixversion {
8940: my $fn=shift;
1.609 banghart 8941: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8942: my %bighash;
8943: my $uri=&clutter($fn);
1.620 albertel 8944: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8945: # is this cached?
1.599 albertel 8946: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8947: if (defined($cached)) { return $result; }
8948: # unfortunately not cached, or expired
1.620 albertel 8949: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8950: &GDBM_READER(),0640)) {
8951: if ($bighash{'version_'.$uri}) {
8952: my $version=$bighash{'version_'.$uri};
1.444 www 8953: unless (($version eq 'mostrecent') ||
8954: ($version==&getversion($uri))) {
1.440 www 8955: $uri=~s/\.(\w+)$/\.$version\.$1/;
8956: }
8957: }
8958: untie %bighash;
1.413 www 8959: }
1.599 albertel 8960: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8961: }
8962:
8963: sub deversion {
8964: my $url=shift;
8965: $url=~s/\.\d+\.(\w+)$/\.$1/;
8966: return $url;
1.210 www 8967: }
8968:
1.31 www 8969: # ------------------------------------------------------ Return symb list entry
8970:
8971: sub symbread {
1.249 www 8972: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 8973: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 8974: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 8975: # no filename provided? try from environment
1.44 www 8976: unless ($thisfn) {
1.620 albertel 8977: if ($env{'request.symb'}) {
8978: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 8979: }
1.620 albertel 8980: $thisfn=$env{'request.filename'};
1.44 www 8981: }
1.569 albertel 8982: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 8983: # is that filename actually a symb? Verify, clean, and return
8984: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 8985: if (&symbverify($thisfn,$1)) {
1.620 albertel 8986: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 8987: }
1.242 www 8988: }
1.44 www 8989: $thisfn=declutter($thisfn);
1.31 www 8990: my %hash;
1.37 www 8991: my %bighash;
8992: my $syval='';
1.620 albertel 8993: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 8994: my $targetfn = $thisfn;
1.609 banghart 8995: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 8996: $targetfn = 'adm/wrapper/'.$thisfn;
8997: }
1.687 albertel 8998: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8999: $targetfn=$1;
9000: }
1.620 albertel 9001: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9002: &GDBM_READER(),0640)) {
1.481 raeburn 9003: $syval=$hash{$targetfn};
1.37 www 9004: untie(%hash);
9005: }
9006: # ---------------------------------------------------------- There was an entry
9007: if ($syval) {
1.601 albertel 9008: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9009: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9010: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9011: #return $env{$cache_str}='';
1.601 albertel 9012: #}
9013: #$syval.=$1;
9014: #}
1.37 www 9015: } else {
9016: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9017: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9018: &GDBM_READER(),0640)) {
1.37 www 9019: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9020: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9021: unless ($ids) {
9022: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9023: }
9024: unless ($ids) {
9025: # alias?
9026: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9027: }
1.37 www 9028: if ($ids) {
9029: # ------------------------------------------------------------------- Has ID(s)
9030: my @possibilities=split(/\,/,$ids);
1.39 www 9031: if ($#possibilities==0) {
9032: # ----------------------------------------------- There is only one possibility
1.37 www 9033: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9034: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9035: $resid,$thisfn);
1.249 www 9036: } elsif (!$donotrecurse) {
1.39 www 9037: # ------------------------------------------ There is more than one possibility
9038: my $realpossible=0;
1.800 albertel 9039: foreach my $id (@possibilities) {
9040: my $file=$bighash{'src_'.$id};
1.39 www 9041: if (&allowed('bre',$file)) {
1.800 albertel 9042: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9043: if ($bighash{'map_type_'.$mapid} ne 'page') {
9044: $realpossible++;
1.626 albertel 9045: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9046: $resid,$thisfn);
1.39 www 9047: }
9048: }
1.191 harris41 9049: }
1.39 www 9050: if ($realpossible!=1) { $syval=''; }
1.249 www 9051: } else {
9052: $syval='';
1.37 www 9053: }
9054: }
9055: untie(%bighash)
1.481 raeburn 9056: }
1.31 www 9057: }
1.62 www 9058: if ($syval) {
1.620 albertel 9059: return $env{$cache_str}=$syval;
1.62 www 9060: }
1.31 www 9061: }
1.949 raeburn 9062: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9063: return $env{$cache_str}='';
1.31 www 9064: }
9065:
9066: # ---------------------------------------------------------- Return random seed
9067:
1.32 www 9068: sub numval {
9069: my $txt=shift;
9070: $txt=~tr/A-J/0-9/;
9071: $txt=~tr/a-j/0-9/;
9072: $txt=~tr/K-T/0-9/;
9073: $txt=~tr/k-t/0-9/;
9074: $txt=~tr/U-Z/0-5/;
9075: $txt=~tr/u-z/0-5/;
9076: $txt=~s/\D//g;
1.564 albertel 9077: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9078: return int($txt);
1.368 albertel 9079: }
9080:
1.484 albertel 9081: sub numval2 {
9082: my $txt=shift;
9083: $txt=~tr/A-J/0-9/;
9084: $txt=~tr/a-j/0-9/;
9085: $txt=~tr/K-T/0-9/;
9086: $txt=~tr/k-t/0-9/;
9087: $txt=~tr/U-Z/0-5/;
9088: $txt=~tr/u-z/0-5/;
9089: $txt=~s/\D//g;
9090: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9091: my $total;
9092: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9093: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9094: return int($total);
9095: }
9096:
1.575 albertel 9097: sub numval3 {
9098: use integer;
9099: my $txt=shift;
9100: $txt=~tr/A-J/0-9/;
9101: $txt=~tr/a-j/0-9/;
9102: $txt=~tr/K-T/0-9/;
9103: $txt=~tr/k-t/0-9/;
9104: $txt=~tr/U-Z/0-5/;
9105: $txt=~tr/u-z/0-5/;
9106: $txt=~s/\D//g;
9107: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9108: my $total;
9109: foreach my $val (@txts) { $total+=$val; }
9110: if ($_64bit) { $total=(($total<<32)>>32); }
9111: return $total;
9112: }
9113:
1.675 albertel 9114: sub digest {
9115: my ($data)=@_;
9116: my $digest=&Digest::MD5::md5($data);
9117: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9118: my ($e,$f);
9119: {
9120: use integer;
9121: $e=($a+$b);
9122: $f=($c+$d);
9123: if ($_64bit) {
9124: $e=(($e<<32)>>32);
9125: $f=(($f<<32)>>32);
9126: }
9127: }
9128: if (wantarray) {
9129: return ($e,$f);
9130: } else {
9131: my $g;
9132: {
9133: use integer;
9134: $g=($e+$f);
9135: if ($_64bit) {
9136: $g=(($g<<32)>>32);
9137: }
9138: }
9139: return $g;
9140: }
9141: }
9142:
1.368 albertel 9143: sub latest_rnd_algorithm_id {
1.675 albertel 9144: return '64bit5';
1.366 albertel 9145: }
1.32 www 9146:
1.503 albertel 9147: sub get_rand_alg {
9148: my ($courseid)=@_;
1.790 albertel 9149: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9150: if ($courseid) {
1.620 albertel 9151: return $env{"course.$courseid.rndseed"};
1.503 albertel 9152: }
9153: return &latest_rnd_algorithm_id();
9154: }
9155:
1.562 albertel 9156: sub validCODE {
9157: my ($CODE)=@_;
9158: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9159: return 0;
9160: }
9161:
1.491 albertel 9162: sub getCODE {
1.620 albertel 9163: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9164: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9165: defined($Apache::lonhomework::parsing_a_task) ) &&
9166: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9167: return $Apache::lonhomework::history{'resource.CODE'};
9168: }
9169: return undef;
9170: }
9171:
1.31 www 9172: sub rndseed {
1.155 albertel 9173: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9174: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9175: if (!defined($symb)) {
1.366 albertel 9176: unless ($symb=$wsymb) { return time; }
9177: }
9178: if (!$courseid) { $courseid=$wcourseid; }
9179: if (!$domain) { $domain=$wdomain; }
9180: if (!$username) { $username=$wusername }
1.503 albertel 9181: my $which=&get_rand_alg();
1.803 albertel 9182:
1.491 albertel 9183: if (defined(&getCODE())) {
1.675 albertel 9184: if ($which eq '64bit5') {
9185: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9186: } elsif ($which eq '64bit4') {
1.575 albertel 9187: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9188: } else {
9189: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9190: }
1.675 albertel 9191: } elsif ($which eq '64bit5') {
9192: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9193: } elsif ($which eq '64bit4') {
9194: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9195: } elsif ($which eq '64bit3') {
9196: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9197: } elsif ($which eq '64bit2') {
9198: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9199: } elsif ($which eq '64bit') {
9200: return &rndseed_64bit($symb,$courseid,$domain,$username);
9201: }
9202: return &rndseed_32bit($symb,$courseid,$domain,$username);
9203: }
9204:
9205: sub rndseed_32bit {
9206: my ($symb,$courseid,$domain,$username)=@_;
9207: {
9208: use integer;
9209: my $symbchck=unpack("%32C*",$symb) << 27;
9210: my $symbseed=numval($symb) << 22;
9211: my $namechck=unpack("%32C*",$username) << 17;
9212: my $nameseed=numval($username) << 12;
9213: my $domainseed=unpack("%32C*",$domain) << 7;
9214: my $courseseed=unpack("%32C*",$courseid);
9215: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9216: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9217: #&logthis("rndseed :$num:$symb");
1.564 albertel 9218: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9219: return $num;
9220: }
9221: }
9222:
9223: sub rndseed_64bit {
9224: my ($symb,$courseid,$domain,$username)=@_;
9225: {
9226: use integer;
9227: my $symbchck=unpack("%32S*",$symb) << 21;
9228: my $symbseed=numval($symb) << 10;
9229: my $namechck=unpack("%32S*",$username);
9230:
9231: my $nameseed=numval($username) << 21;
9232: my $domainseed=unpack("%32S*",$domain) << 10;
9233: my $courseseed=unpack("%32S*",$courseid);
9234:
9235: my $num1=$symbchck+$symbseed+$namechck;
9236: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9237: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9238: #&logthis("rndseed :$num:$symb");
1.564 albertel 9239: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9240: return "$num1,$num2";
1.155 albertel 9241: }
1.366 albertel 9242: }
9243:
1.443 albertel 9244: sub rndseed_64bit2 {
9245: my ($symb,$courseid,$domain,$username)=@_;
9246: {
9247: use integer;
9248: # strings need to be an even # of cahracters long, it it is odd the
9249: # last characters gets thrown away
9250: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9251: my $symbseed=numval($symb) << 10;
9252: my $namechck=unpack("%32S*",$username.' ');
9253:
9254: my $nameseed=numval($username) << 21;
1.501 albertel 9255: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9256: my $courseseed=unpack("%32S*",$courseid.' ');
9257:
9258: my $num1=$symbchck+$symbseed+$namechck;
9259: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9260: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9261: #&logthis("rndseed :$num:$symb");
1.803 albertel 9262: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9263: return "$num1,$num2";
9264: }
9265: }
9266:
9267: sub rndseed_64bit3 {
9268: my ($symb,$courseid,$domain,$username)=@_;
9269: {
9270: use integer;
9271: # strings need to be an even # of cahracters long, it it is odd the
9272: # last characters gets thrown away
9273: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9274: my $symbseed=numval2($symb) << 10;
9275: my $namechck=unpack("%32S*",$username.' ');
9276:
9277: my $nameseed=numval2($username) << 21;
1.443 albertel 9278: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9279: my $courseseed=unpack("%32S*",$courseid.' ');
9280:
9281: my $num1=$symbchck+$symbseed+$namechck;
9282: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9283: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9284: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9285: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9286:
1.503 albertel 9287: return "$num1:$num2";
1.443 albertel 9288: }
9289: }
9290:
1.575 albertel 9291: sub rndseed_64bit4 {
9292: my ($symb,$courseid,$domain,$username)=@_;
9293: {
9294: use integer;
9295: # strings need to be an even # of cahracters long, it it is odd the
9296: # last characters gets thrown away
9297: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9298: my $symbseed=numval3($symb) << 10;
9299: my $namechck=unpack("%32S*",$username.' ');
9300:
9301: my $nameseed=numval3($username) << 21;
9302: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9303: my $courseseed=unpack("%32S*",$courseid.' ');
9304:
9305: my $num1=$symbchck+$symbseed+$namechck;
9306: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9307: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9308: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9309: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9310:
9311: return "$num1:$num2";
9312: }
9313: }
9314:
1.675 albertel 9315: sub rndseed_64bit5 {
9316: my ($symb,$courseid,$domain,$username)=@_;
9317: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9318: return "$num1:$num2";
9319: }
9320:
1.366 albertel 9321: sub rndseed_CODE_64bit {
9322: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9323: {
1.366 albertel 9324: use integer;
1.443 albertel 9325: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9326: my $symbseed=numval2($symb);
1.491 albertel 9327: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9328: my $CODEseed=numval(&getCODE());
1.443 albertel 9329: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9330: my $num1=$symbseed+$CODEchck;
9331: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9332: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9333: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9334: if ($_64bit) { $num1=(($num1<<32)>>32); }
9335: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9336: return "$num1:$num2";
1.366 albertel 9337: }
9338: }
9339:
1.575 albertel 9340: sub rndseed_CODE_64bit4 {
9341: my ($symb,$courseid,$domain,$username)=@_;
9342: {
9343: use integer;
9344: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9345: my $symbseed=numval3($symb);
9346: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9347: my $CODEseed=numval3(&getCODE());
9348: my $courseseed=unpack("%32S*",$courseid.' ');
9349: my $num1=$symbseed+$CODEchck;
9350: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9351: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9352: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9353: if ($_64bit) { $num1=(($num1<<32)>>32); }
9354: if ($_64bit) { $num2=(($num2<<32)>>32); }
9355: return "$num1:$num2";
9356: }
9357: }
9358:
1.675 albertel 9359: sub rndseed_CODE_64bit5 {
9360: my ($symb,$courseid,$domain,$username)=@_;
9361: my $code = &getCODE();
9362: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9363: return "$num1:$num2";
9364: }
9365:
1.366 albertel 9366: sub setup_random_from_rndseed {
9367: my ($rndseed)=@_;
1.503 albertel 9368: if ($rndseed =~/([,:])/) {
9369: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9370: &Math::Random::random_set_seed(abs($num1),abs($num2));
9371: } else {
9372: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9373: }
1.36 albertel 9374: }
9375:
1.474 albertel 9376: sub latest_receipt_algorithm_id {
1.835 albertel 9377: return 'receipt3';
1.474 albertel 9378: }
9379:
1.480 www 9380: sub recunique {
9381: my $fucourseid=shift;
9382: my $unique;
1.835 albertel 9383: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9384: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9385: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9386: } else {
9387: $unique=$perlvar{'lonReceipt'};
9388: }
9389: return unpack("%32C*",$unique);
9390: }
9391:
9392: sub recprefix {
9393: my $fucourseid=shift;
9394: my $prefix;
1.835 albertel 9395: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9396: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9397: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9398: } else {
9399: $prefix=$perlvar{'lonHostID'};
9400: }
9401: return unpack("%32C*",$prefix);
9402: }
9403:
1.76 www 9404: sub ireceipt {
1.474 albertel 9405: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9406:
9407: my $return =&recprefix($fucourseid).'-';
9408:
9409: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9410: $env{'request.state'} eq 'construct') {
9411: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9412: return $return;
9413: }
9414:
1.76 www 9415: my $cuname=unpack("%32C*",$funame);
9416: my $cudom=unpack("%32C*",$fudom);
9417: my $cucourseid=unpack("%32C*",$fucourseid);
9418: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9419: my $cunique=&recunique($fucourseid);
1.474 albertel 9420: my $cpart=unpack("%32S*",$part);
1.835 albertel 9421: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9422:
1.790 albertel 9423: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9424:
9425: $return.= ($cunique%$cuname+
9426: $cunique%$cudom+
9427: $cusymb%$cuname+
9428: $cusymb%$cudom+
9429: $cucourseid%$cuname+
9430: $cucourseid%$cudom+
9431: $cpart%$cuname+
9432: $cpart%$cudom);
9433: } else {
9434: $return.= ($cunique%$cuname+
9435: $cunique%$cudom+
9436: $cusymb%$cuname+
9437: $cusymb%$cudom+
9438: $cucourseid%$cuname+
9439: $cucourseid%$cudom);
9440: }
9441: return $return;
1.76 www 9442: }
9443:
9444: sub receipt {
1.474 albertel 9445: my ($part)=@_;
1.790 albertel 9446: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9447: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9448: }
1.260 ng 9449:
1.790 albertel 9450: sub whichuser {
9451: my ($passedsymb)=@_;
9452: my ($symb,$courseid,$domain,$name,$publicuser);
9453: if (defined($env{'form.grade_symb'})) {
9454: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9455: my $allowed=&allowed('vgr',$tmp_courseid);
9456: if (!$allowed &&
9457: exists($env{'request.course.sec'}) &&
9458: $env{'request.course.sec'} !~ /^\s*$/) {
9459: $allowed=&allowed('vgr',$tmp_courseid.
9460: '/'.$env{'request.course.sec'});
9461: }
9462: if ($allowed) {
9463: ($symb)=&get_env_multiple('form.grade_symb');
9464: $courseid=$tmp_courseid;
9465: ($domain)=&get_env_multiple('form.grade_domain');
9466: ($name)=&get_env_multiple('form.grade_username');
9467: return ($symb,$courseid,$domain,$name,$publicuser);
9468: }
9469: }
9470: if (!$passedsymb) {
9471: $symb=&symbread();
9472: } else {
9473: $symb=$passedsymb;
9474: }
9475: $courseid=$env{'request.course.id'};
9476: $domain=$env{'user.domain'};
9477: $name=$env{'user.name'};
9478: if ($name eq 'public' && $domain eq 'public') {
9479: if (!defined($env{'form.username'})) {
9480: $env{'form.username'}.=time.rand(10000000);
9481: }
9482: $name.=$env{'form.username'};
9483: }
9484: return ($symb,$courseid,$domain,$name,$publicuser);
9485:
9486: }
9487:
1.36 albertel 9488: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9489: # returns either the contents of the file or
9490: # -1 if the file doesn't exist
1.481 raeburn 9491: #
9492: # if the target is a file that was uploaded via DOCS,
9493: # a check will be made to see if a current copy exists on the local server,
9494: # if it does this will be served, otherwise a copy will be retrieved from
9495: # the home server for the course and stored in /home/httpd/html/userfiles on
9496: # the local server.
1.472 albertel 9497:
1.36 albertel 9498: sub getfile {
1.538 albertel 9499: my ($file) = @_;
1.609 banghart 9500: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9501: &repcopy($file);
9502: return &readfile($file);
9503: }
9504:
9505: sub repcopy_userfile {
9506: my ($file)=@_;
1.609 banghart 9507: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9508: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9509: my ($cdom,$cnum,$filename) =
1.811 albertel 9510: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9511: my $uri="/uploaded/$cdom/$cnum/$filename";
9512: if (-e "$file") {
1.828 www 9513: # we already have a local copy, check it out
1.538 albertel 9514: my @fileinfo = stat($file);
1.828 www 9515: my $rtncode;
9516: my $info;
1.538 albertel 9517: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9518: if ($lwpresp ne 'ok') {
1.828 www 9519: # there is no such file anymore, even though we had a local copy
1.482 albertel 9520: if ($rtncode eq '404') {
1.538 albertel 9521: unlink($file);
1.482 albertel 9522: }
9523: return -1;
9524: }
9525: if ($info < $fileinfo[9]) {
1.828 www 9526: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9527: return 'ok';
1.828 www 9528: } else {
9529: # the file is outdated, get rid of it
9530: unlink($file);
1.482 albertel 9531: }
1.828 www 9532: }
9533: # one way or the other, at this point, we don't have the file
9534: # construct the correct path for the file
9535: my @parts = ($cdom,$cnum);
9536: if ($filename =~ m|^(.+)/[^/]+$|) {
9537: push @parts, split(/\//,$1);
9538: }
9539: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9540: foreach my $part (@parts) {
9541: $path .= '/'.$part;
9542: if (!-e $path) {
9543: mkdir($path,0770);
1.482 albertel 9544: }
9545: }
1.828 www 9546: # now the path exists for sure
9547: # get a user agent
9548: my $ua=new LWP::UserAgent;
9549: my $transferfile=$file.'.in.transfer';
9550: # FIXME: this should flock
9551: if (-e $transferfile) { return 'ok'; }
9552: my $request;
9553: $uri=~s/^\///;
1.980 raeburn 9554: my $homeserver = &homeserver($cnum,$cdom);
9555: my $protocol = $protocol{$homeserver};
9556: $protocol = 'http' if ($protocol ne 'https');
9557: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9558: my $response=$ua->request($request,$transferfile);
9559: # did it work?
9560: if ($response->is_error()) {
9561: unlink($transferfile);
9562: &logthis("Userfile repcopy failed for $uri");
9563: return -1;
9564: }
9565: # worked, rename the transfer file
9566: rename($transferfile,$file);
1.607 raeburn 9567: return 'ok';
1.481 raeburn 9568: }
9569:
1.517 albertel 9570: sub tokenwrapper {
9571: my $uri=shift;
1.980 raeburn 9572: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9573: $uri=~s|^/||;
1.620 albertel 9574: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9575: my $token=$1;
1.552 albertel 9576: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9577: if ($udom && $uname && $file) {
9578: $file=~s|(\?\.*)*$||;
1.949 raeburn 9579: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9580: my $homeserver = &homeserver($uname,$udom);
9581: my $protocol = $protocol{$homeserver};
9582: $protocol = 'http' if ($protocol ne 'https');
9583: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9584: (($uri=~/\?/)?'&':'?').'token='.$token.
9585: '&tokenissued='.$perlvar{'lonHostID'};
9586: } else {
9587: return '/adm/notfound.html';
9588: }
9589: }
9590:
1.828 www 9591: # call with reqtype HEAD: get last modification time
9592: # call with reqtype GET: get the file contents
9593: # Do not call this with reqtype GET for large files! It loads everything into memory
9594: #
1.481 raeburn 9595: sub getuploaded {
9596: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9597: $uri=~s/^\///;
1.980 raeburn 9598: my $homeserver = &homeserver($cnum,$cdom);
9599: my $protocol = $protocol{$homeserver};
9600: $protocol = 'http' if ($protocol ne 'https');
9601: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9602: my $ua=new LWP::UserAgent;
9603: my $request=new HTTP::Request($reqtype,$uri);
9604: my $response=$ua->request($request);
9605: $$rtncode = $response->code;
1.482 albertel 9606: if (! $response->is_success()) {
9607: return 'failed';
9608: }
9609: if ($reqtype eq 'HEAD') {
1.486 www 9610: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9611: } elsif ($reqtype eq 'GET') {
9612: $$info = $response->content;
1.472 albertel 9613: }
1.482 albertel 9614: return 'ok';
1.36 albertel 9615: }
9616:
1.481 raeburn 9617: sub readfile {
9618: my $file = shift;
9619: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9620: my $fh;
9621: open($fh,"<$file");
9622: my $a='';
1.800 albertel 9623: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9624: return $a;
9625: }
9626:
1.36 albertel 9627: sub filelocation {
1.590 banghart 9628: my ($dir,$file) = @_;
9629: my $location;
9630: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9631:
9632: if ($file =~ m-^/adm/-) {
9633: $file=~s-^/adm/wrapper/-/-;
9634: $file=~s-^/adm/coursedocs/showdoc/-/-;
9635: }
1.882 albertel 9636:
1.590 banghart 9637: if ($file=~m:^/~:) { # is a contruction space reference
9638: $location = $file;
9639: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9640: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9641: # is a correct contruction space reference
9642: $location = $file;
1.956 raeburn 9643: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9644: $location = $file;
1.609 banghart 9645: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9646: my ($udom,$uname,$filename)=
1.811 albertel 9647: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9648: my $home=&homeserver($uname,$udom);
9649: my $is_me=0;
9650: my @ids=¤t_machine_ids();
9651: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9652: if ($is_me) {
1.955 raeburn 9653: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9654: } else {
9655: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9656: $udom.'/'.$uname.'/'.$filename;
9657: }
1.882 albertel 9658: } elsif ($file =~ m-^/adm/-) {
9659: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9660: } else {
9661: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9662: $file=~s:^/res/:/:;
9663: if ( !( $file =~ m:^/:) ) {
9664: $location = $dir. '/'.$file;
9665: } else {
9666: $location = '/home/httpd/html/res'.$file;
9667: }
1.59 albertel 9668: }
1.590 banghart 9669: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9670: while ($location=~m{/\.\./}) {
9671: if ($location =~ m{/[^/]+/\.\./}) {
9672: $location=~ s{/[^/]+/\.\./}{/}g;
9673: } else {
9674: $location=~ s{/\.\./}{/}g;
9675: }
9676: } #remove dir/..
1.590 banghart 9677: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9678: return $location;
1.46 www 9679: }
1.36 albertel 9680:
1.46 www 9681: sub hreflocation {
9682: my ($dir,$file)=@_;
1.980 raeburn 9683: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9684: $file=filelocation($dir,$file);
1.700 albertel 9685: } elsif ($file=~m-^/adm/-) {
9686: $file=~s-^/adm/wrapper/-/-;
9687: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9688: }
9689: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9690: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9691: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9692: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9693: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9694: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9695: -/uploaded/$1/$2/-x;
1.46 www 9696: }
1.913 albertel 9697: if ($file=~ m{^/userfiles/}) {
9698: $file =~ s{^/userfiles/}{/uploaded/};
9699: }
1.462 albertel 9700: return $file;
1.465 albertel 9701: }
9702:
9703: sub current_machine_domains {
1.853 albertel 9704: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9705: }
9706:
9707: sub machine_domains {
9708: my ($hostname) = @_;
1.465 albertel 9709: my @domains;
1.838 albertel 9710: my %hostname = &all_hostnames();
1.465 albertel 9711: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9712: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9713: if ($hostname eq $name) {
1.844 albertel 9714: push(@domains,&host_domain($id));
1.465 albertel 9715: }
9716: }
9717: return @domains;
9718: }
9719:
9720: sub current_machine_ids {
1.853 albertel 9721: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9722: }
9723:
9724: sub machine_ids {
9725: my ($hostname) = @_;
9726: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9727: my @ids;
1.888 albertel 9728: my %name_to_host = &all_names();
1.889 albertel 9729: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9730: return @{ $name_to_host{$hostname} };
9731: }
9732: return;
1.31 www 9733: }
9734:
1.824 raeburn 9735: sub additional_machine_domains {
9736: my @domains;
9737: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9738: while( my $line = <$fh>) {
9739: $line =~ s/\s//g;
9740: push(@domains,$line);
9741: }
9742: return @domains;
9743: }
9744:
9745: sub default_login_domain {
9746: my $domain = $perlvar{'lonDefDomain'};
9747: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9748: foreach my $posdom (¤t_machine_domains(),
9749: &additional_machine_domains()) {
9750: if (lc($posdom) eq lc($testdomain)) {
9751: $domain=$posdom;
9752: last;
9753: }
9754: }
9755: return $domain;
9756: }
9757:
1.31 www 9758: # ------------------------------------------------------------- Declutters URLs
9759:
9760: sub declutter {
9761: my $thisfn=shift;
1.569 albertel 9762: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9763: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9764: $thisfn=~s/^\///;
1.697 albertel 9765: $thisfn=~s|^adm/wrapper/||;
9766: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9767: $thisfn=~s/^res\///;
1.1032 raeburn 9768: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9769: $thisfn=~s/\?.+$//;
9770: }
1.268 www 9771: return $thisfn;
9772: }
9773:
9774: # ------------------------------------------------------------- Clutter up URLs
9775:
9776: sub clutter {
9777: my $thisfn='/'.&declutter(shift);
1.887 albertel 9778: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9779: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9780: $thisfn='/res'.$thisfn;
9781: }
1.1031 raeburn 9782: if ($thisfn !~m|^/adm|) {
9783: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9784: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9785: } else {
9786: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9787: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9788: if ($embstyle eq 'ssi'
9789: || ($embstyle eq 'hdn')
9790: || ($embstyle eq 'rat')
9791: || ($embstyle eq 'prv')
9792: || ($embstyle eq 'ign')) {
9793: #do nothing with these
9794: } elsif (($embstyle eq 'img')
1.695 albertel 9795: || ($embstyle eq 'emb')
9796: || ($embstyle eq 'wrp')) {
9797: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9798: } elsif ($embstyle eq 'unk'
9799: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9800: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9801: } else {
1.718 www 9802: # &logthis("Got a blank emb style");
1.695 albertel 9803: }
1.694 albertel 9804: }
9805: }
1.31 www 9806: return $thisfn;
1.12 www 9807: }
9808:
1.787 albertel 9809: sub clutter_with_no_wrapper {
9810: my $uri = &clutter(shift);
9811: if ($uri =~ m-^/adm/-) {
9812: $uri =~ s-^/adm/wrapper/-/-;
9813: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9814: }
9815: return $uri;
9816: }
9817:
1.557 albertel 9818: sub freeze_escape {
9819: my ($value)=@_;
9820: if (ref($value)) {
9821: $value=&nfreeze($value);
9822: return '__FROZEN__'.&escape($value);
9823: }
9824: return &escape($value);
9825: }
9826:
1.11 www 9827:
1.557 albertel 9828: sub thaw_unescape {
9829: my ($value)=@_;
9830: if ($value =~ /^__FROZEN__/) {
9831: substr($value,0,10,undef);
9832: $value=&unescape($value);
9833: return &thaw($value);
9834: }
9835: return &unescape($value);
9836: }
9837:
1.436 albertel 9838: sub correct_line_ends {
9839: my ($result)=@_;
9840: $$result =~s/\r\n/\n/mg;
9841: $$result =~s/\r/\n/mg;
1.415 albertel 9842: }
1.1 albertel 9843: # ================================================================ Main Program
9844:
1.184 www 9845: sub goodbye {
1.204 albertel 9846: &logthis("Starting Shut down");
1.443 albertel 9847: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9848: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9849: #converted
1.599 albertel 9850: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9851: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9852: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9853: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9854: #1.1 only
1.870 albertel 9855: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9856: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9857: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9858: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9859: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9860: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9861: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9862: &flushcourselogs();
9863: &logthis("Shutting down");
9864: }
9865:
1.852 albertel 9866: sub get_dns {
1.869 albertel 9867: my ($url,$func,$ignore_cache) = @_;
9868: if (!$ignore_cache) {
9869: my ($content,$cached)=
9870: &Apache::lonnet::is_cached_new('dns',$url);
9871: if ($cached) {
9872: &$func($content);
9873: return;
9874: }
9875: }
9876:
9877: my %alldns;
1.852 albertel 9878: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9879: foreach my $dns (<$config>) {
9880: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9881: my $line = $1;
9882: my ($host,$protocol) = split(/:/,$line);
9883: if ($protocol ne 'https') {
9884: $protocol = 'http';
9885: }
9886: $alldns{$host} = $protocol;
1.869 albertel 9887: }
9888: while (%alldns) {
9889: my ($dns) = keys(%alldns);
1.852 albertel 9890: my $ua=new LWP::UserAgent;
1.979 raeburn 9891: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9892: my $response=$ua->request($request);
1.979 raeburn 9893: delete($alldns{$dns});
1.852 albertel 9894: next if ($response->is_error());
9895: my @content = split("\n",$response->content);
1.869 albertel 9896: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9897: &$func(\@content);
1.869 albertel 9898: return;
1.852 albertel 9899: }
9900: close($config);
1.871 albertel 9901: my $which = (split('/',$url))[3];
9902: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9903: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9904: my @content = <$config>;
9905: &$func(\@content);
9906: return;
1.852 albertel 9907: }
1.327 albertel 9908: # ------------------------------------------------------------ Read domain file
9909: {
1.852 albertel 9910: my $loaded;
1.846 albertel 9911: my %domain;
9912:
1.852 albertel 9913: sub parse_domain_tab {
9914: my ($lines) = @_;
9915: foreach my $line (@$lines) {
9916: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9917:
1.846 albertel 9918: chomp($line);
1.852 albertel 9919: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9920: my %this_domain;
9921: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9922: 'lang_def', 'city', 'longi', 'lati',
9923: 'primary') {
9924: $this_domain{$field} = shift(@elements);
9925: }
9926: $domain{$name} = \%this_domain;
1.852 albertel 9927: }
9928: }
1.864 albertel 9929:
9930: sub reset_domain_info {
9931: undef($loaded);
9932: undef(%domain);
9933: }
9934:
1.852 albertel 9935: sub load_domain_tab {
1.869 albertel 9936: my ($ignore_cache) = @_;
9937: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9938: my $fh;
9939: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9940: my @lines = <$fh>;
9941: &parse_domain_tab(\@lines);
1.448 albertel 9942: }
1.852 albertel 9943: close($fh);
9944: $loaded = 1;
1.327 albertel 9945: }
1.846 albertel 9946:
9947: sub domain {
1.852 albertel 9948: &load_domain_tab() if (!$loaded);
9949:
1.846 albertel 9950: my ($name,$what) = @_;
9951: return if ( !exists($domain{$name}) );
9952:
9953: if (!$what) {
9954: return $domain{$name}{'description'};
9955: }
9956: return $domain{$name}{$what};
9957: }
1.974 raeburn 9958:
9959: sub domain_info {
9960: &load_domain_tab() if (!$loaded);
9961: return %domain;
9962: }
9963:
1.327 albertel 9964: }
9965:
9966:
1.1 albertel 9967: # ------------------------------------------------------------- Read hosts file
9968: {
1.838 albertel 9969: my %hostname;
1.844 albertel 9970: my %hostdom;
1.845 albertel 9971: my %libserv;
1.852 albertel 9972: my $loaded;
1.888 albertel 9973: my %name_to_host;
1.1056.4.6 raeburn 9974: my %internetdom;
1.852 albertel 9975:
9976: sub parse_hosts_tab {
9977: my ($file) = @_;
9978: foreach my $configline (@$file) {
9979: next if ($configline =~ /^(\#|\s*$ )/x);
9980: next if ($configline =~ /^\^/);
9981: chomp($configline);
1.1056.4.6 raeburn 9982: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 9983: $name=~s/\s//g;
9984: if ($id && $domain && $role && $name) {
9985: $hostname{$id}=$name;
1.888 albertel 9986: push(@{$name_to_host{$name}}, $id);
1.852 albertel 9987: $hostdom{$id}=$domain;
9988: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 9989: if (defined($protocol)) {
9990: if ($protocol eq 'https') {
9991: $protocol{$id} = $protocol;
9992: } else {
9993: $protocol{$id} = 'http';
9994: }
1.968 raeburn 9995: } else {
1.969 raeburn 9996: $protocol{$id} = 'http';
1.968 raeburn 9997: }
1.1056.4.6 raeburn 9998: if (defined($intdom)) {
9999: $internetdom{$id} = $intdom;
10000: }
1.852 albertel 10001: }
10002: }
10003: }
1.864 albertel 10004:
10005: sub reset_hosts_info {
1.897 albertel 10006: &purge_remembered();
1.864 albertel 10007: &reset_domain_info();
10008: &reset_hosts_ip_info();
1.892 albertel 10009: undef(%name_to_host);
1.864 albertel 10010: undef(%hostname);
10011: undef(%hostdom);
10012: undef(%libserv);
10013: undef($loaded);
10014: }
1.1 albertel 10015:
1.852 albertel 10016: sub load_hosts_tab {
1.869 albertel 10017: my ($ignore_cache) = @_;
10018: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10019: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10020: my @config = <$config>;
10021: &parse_hosts_tab(\@config);
10022: close($config);
10023: $loaded=1;
1.1 albertel 10024: }
1.852 albertel 10025:
1.838 albertel 10026: sub hostname {
1.852 albertel 10027: &load_hosts_tab() if (!$loaded);
10028:
1.838 albertel 10029: my ($lonid) = @_;
10030: return $hostname{$lonid};
10031: }
1.845 albertel 10032:
1.838 albertel 10033: sub all_hostnames {
1.852 albertel 10034: &load_hosts_tab() if (!$loaded);
10035:
1.838 albertel 10036: return %hostname;
10037: }
1.845 albertel 10038:
1.888 albertel 10039: sub all_names {
10040: &load_hosts_tab() if (!$loaded);
10041:
10042: return %name_to_host;
10043: }
10044:
1.974 raeburn 10045: sub all_host_domain {
10046: &load_hosts_tab() if (!$loaded);
10047: return %hostdom;
10048: }
10049:
1.845 albertel 10050: sub is_library {
1.852 albertel 10051: &load_hosts_tab() if (!$loaded);
10052:
1.845 albertel 10053: return exists($libserv{$_[0]});
10054: }
10055:
10056: sub all_library {
1.852 albertel 10057: &load_hosts_tab() if (!$loaded);
10058:
1.845 albertel 10059: return %libserv;
10060: }
10061:
1.1056.4.2 raeburn 10062: sub unique_library {
10063: #2x reverse removes all hostnames that appear more than once
10064: my %unique = reverse &all_library();
10065: return reverse %unique;
10066: }
10067:
1.841 albertel 10068: sub get_servers {
1.852 albertel 10069: &load_hosts_tab() if (!$loaded);
10070:
1.841 albertel 10071: my ($domain,$type) = @_;
10072: my %possible_hosts = ($type eq 'library') ? %libserv
10073: : %hostname;
10074: my %result;
1.842 albertel 10075: if (ref($domain) eq 'ARRAY') {
10076: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10077: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10078: $result{$host} = $hostname;
10079: }
10080: }
10081: } else {
10082: while ( my ($host,$hostname) = each(%possible_hosts)) {
10083: if ($hostdom{$host} eq $domain) {
10084: $result{$host} = $hostname;
10085: }
1.841 albertel 10086: }
10087: }
10088: return %result;
10089: }
1.845 albertel 10090:
1.1056.4.2 raeburn 10091: sub get_unique_servers {
10092: my %unique = reverse &get_servers(@_);
10093: return reverse %unique;
10094: }
10095:
1.844 albertel 10096: sub host_domain {
1.852 albertel 10097: &load_hosts_tab() if (!$loaded);
10098:
1.844 albertel 10099: my ($lonid) = @_;
10100: return $hostdom{$lonid};
10101: }
10102:
1.841 albertel 10103: sub all_domains {
1.852 albertel 10104: &load_hosts_tab() if (!$loaded);
10105:
1.841 albertel 10106: my %seen;
10107: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10108: return @uniq;
10109: }
1.1056.4.3 raeburn 10110:
10111: sub internet_dom {
10112: &load_hosts_tab() if (!$loaded);
10113:
10114: my ($lonid) = @_;
10115: return $internetdom{$lonid};
10116: }
1.1 albertel 10117: }
10118:
1.847 albertel 10119: {
10120: my %iphost;
1.856 albertel 10121: my %name_to_ip;
10122: my %lonid_to_ip;
1.869 albertel 10123:
1.847 albertel 10124: sub get_hosts_from_ip {
10125: my ($ip) = @_;
10126: my %iphosts = &get_iphost();
10127: if (ref($iphosts{$ip})) {
10128: return @{$iphosts{$ip}};
10129: }
10130: return;
1.839 albertel 10131: }
1.864 albertel 10132:
10133: sub reset_hosts_ip_info {
10134: undef(%iphost);
10135: undef(%name_to_ip);
10136: undef(%lonid_to_ip);
10137: }
1.856 albertel 10138:
10139: sub get_host_ip {
10140: my ($lonid) = @_;
10141: if (exists($lonid_to_ip{$lonid})) {
10142: return $lonid_to_ip{$lonid};
10143: }
10144: my $name=&hostname($lonid);
10145: my $ip = gethostbyname($name);
10146: return if (!$ip || length($ip) ne 4);
10147: $ip=inet_ntoa($ip);
10148: $name_to_ip{$name} = $ip;
10149: $lonid_to_ip{$lonid} = $ip;
10150: return $ip;
10151: }
1.847 albertel 10152:
10153: sub get_iphost {
1.869 albertel 10154: my ($ignore_cache) = @_;
1.894 albertel 10155:
1.869 albertel 10156: if (!$ignore_cache) {
10157: if (%iphost) {
10158: return %iphost;
10159: }
10160: my ($ip_info,$cached)=
10161: &Apache::lonnet::is_cached_new('iphost','iphost');
10162: if ($cached) {
10163: %iphost = %{$ip_info->[0]};
10164: %name_to_ip = %{$ip_info->[1]};
10165: %lonid_to_ip = %{$ip_info->[2]};
10166: return %iphost;
10167: }
10168: }
1.894 albertel 10169:
10170: # get yesterday's info for fallback
10171: my %old_name_to_ip;
10172: my ($ip_info,$cached)=
10173: &Apache::lonnet::is_cached_new('iphost','iphost');
10174: if ($cached) {
10175: %old_name_to_ip = %{$ip_info->[1]};
10176: }
10177:
1.888 albertel 10178: my %name_to_host = &all_names();
10179: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10180: my $ip;
10181: if (!exists($name_to_ip{$name})) {
10182: $ip = gethostbyname($name);
10183: if (!$ip || length($ip) ne 4) {
1.894 albertel 10184: if (defined($old_name_to_ip{$name})) {
10185: $ip = $old_name_to_ip{$name};
10186: &logthis("Can't find $name defaulting to old $ip");
10187: } else {
10188: &logthis("Name $name no IP found");
10189: next;
10190: }
10191: } else {
10192: $ip=inet_ntoa($ip);
1.847 albertel 10193: }
10194: $name_to_ip{$name} = $ip;
10195: } else {
10196: $ip = $name_to_ip{$name};
1.653 albertel 10197: }
1.888 albertel 10198: foreach my $id (@{ $name_to_host{$name} }) {
10199: $lonid_to_ip{$id} = $ip;
10200: }
10201: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10202: }
1.869 albertel 10203: &Apache::lonnet::do_cache_new('iphost','iphost',
10204: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10205: 48*60*60);
1.869 albertel 10206:
1.847 albertel 10207: return %iphost;
1.598 albertel 10208: }
10209:
1.992 raeburn 10210: #
10211: # Given a DNS returns the loncapa host name for that DNS
10212: #
10213: sub host_from_dns {
10214: my ($dns) = @_;
10215: my @hosts;
10216: my $ip;
10217:
1.993 raeburn 10218: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10219: $ip = $name_to_ip{$dns};
10220: }
10221: if (!$ip) {
10222: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10223: if (length($ip) == 4) {
10224: $ip = &IO::Socket::inet_ntoa($ip);
10225: }
10226: }
10227: if ($ip) {
10228: @hosts = get_hosts_from_ip($ip);
10229: return $hosts[0];
10230: }
10231: return undef;
1.986 foxr 10232: }
1.992 raeburn 10233:
1.1056.4.3 raeburn 10234: sub get_internet_names {
10235: my ($lonid) = @_;
10236: return if ($lonid eq '');
10237: my ($idnref,$cached)=
10238: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10239: if ($cached) {
10240: return $idnref;
10241: }
10242: my $ip = &get_host_ip($lonid);
10243: my @hosts = &get_hosts_from_ip($ip);
10244: my %iphost = &get_iphost();
10245: my (@idns,%seen);
10246: foreach my $id (@hosts) {
10247: my $dom = &host_domain($id);
10248: my $prim_id = &domain($dom,'primary');
10249: my $prim_ip = &get_host_ip($prim_id);
10250: next if ($seen{$prim_ip});
10251: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10252: foreach my $id (@{$iphost{$prim_ip}}) {
10253: my $intdom = &internet_dom($id);
10254: unless (grep(/^\Q$intdom\E$/,@idns)) {
10255: push(@idns,$intdom);
10256: }
10257: }
10258: }
10259: $seen{$prim_ip} = 1;
10260: }
10261: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10262: }
10263:
10264: }
10265:
10266: sub all_loncaparevs {
10267: 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);
1.986 foxr 10268: }
10269:
1.862 albertel 10270: BEGIN {
10271:
10272: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10273: unless ($readit) {
10274: {
10275: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10276: %perlvar = (%perlvar,%{$configvars});
10277: }
10278:
10279:
1.1 albertel 10280: # ------------------------------------------------------ Read spare server file
10281: {
1.448 albertel 10282: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10283:
10284: while (my $configline=<$config>) {
10285: chomp($configline);
1.284 matthew 10286: if ($configline) {
1.784 albertel 10287: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10288: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10289: push(@{ $spareid{$type} }, $host);
1.1 albertel 10290: }
10291: }
1.448 albertel 10292: close($config);
1.1 albertel 10293: }
1.11 www 10294: # ------------------------------------------------------------ Read permissions
10295: {
1.448 albertel 10296: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10297:
10298: while (my $configline=<$config>) {
1.448 albertel 10299: chomp($configline);
10300: if ($configline) {
10301: my ($role,$perm)=split(/ /,$configline);
10302: if ($perm ne '') { $pr{$role}=$perm; }
10303: }
1.11 www 10304: }
1.448 albertel 10305: close($config);
1.11 www 10306: }
10307:
10308: # -------------------------------------------- Read plain texts for permissions
10309: {
1.448 albertel 10310: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10311:
10312: while (my $configline=<$config>) {
1.448 albertel 10313: chomp($configline);
10314: if ($configline) {
1.742 raeburn 10315: my ($short,@plain)=split(/:/,$configline);
10316: %{$prp{$short}} = ();
10317: if (@plain > 0) {
10318: $prp{$short}{'std'} = $plain[0];
10319: for (my $i=1; $i<@plain; $i++) {
10320: $prp{$short}{'alt'.$i} = $plain[$i];
10321: }
10322: }
1.448 albertel 10323: }
1.135 www 10324: }
1.448 albertel 10325: close($config);
1.135 www 10326: }
10327:
10328: # ---------------------------------------------------------- Read package table
10329: {
1.448 albertel 10330: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10331:
10332: while (my $configline=<$config>) {
1.483 albertel 10333: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10334: chomp($configline);
10335: my ($short,$plain)=split(/:/,$configline);
10336: my ($pack,$name)=split(/\&/,$short);
10337: if ($plain ne '') {
10338: $packagetab{$pack.'&'.$name.'&name'}=$name;
10339: $packagetab{$short}=$plain;
10340: }
1.11 www 10341: }
1.448 albertel 10342: close($config);
1.329 matthew 10343: }
10344:
1.1056.4.3 raeburn 10345: # ---------------------------------------------------------- Read loncaparev table
10346: {
10347: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10348: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10349: while (my $configline=<$config>) {
10350: chomp($configline);
10351: my ($hostid,$loncaparev)=split(/:/,$configline);
10352: $loncaparevs{$hostid}=$loncaparev;
10353: }
10354: close($config);
10355: }
10356: }
10357: }
10358:
10359: # ---------------------------------------------------------- Read serverhostID table
10360: {
10361: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10362: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10363: while (my $configline=<$config>) {
10364: chomp($configline);
10365: my ($name,$id)=split(/:/,$configline);
10366: $serverhomeIDs{$name}=$id;
10367: }
10368: close($config);
10369: }
10370: }
10371: }
10372:
1.1056.4.5 raeburn 10373: {
10374: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10375: if (-e $file) {
10376: my $parser = HTML::LCParser->new($file);
10377: while (my $token = $parser->get_token()) {
10378: if ($token->[0] eq 'S') {
10379: my $item = $token->[1];
10380: my $name = $token->[2]{'name'};
10381: my $value = $token->[2]{'value'};
10382: if ($item ne '' && $name ne '' && $value ne '') {
10383: my $release = $parser->get_text();
10384: $release =~ s/(^\s*|\s*$ )//gx;
10385: $needsrelease{$item.':'.$name.':'.$value} = $release;
10386: }
10387: }
10388: }
10389: }
10390: }
10391:
1.329 matthew 10392: # ------------- set up temporary directory
10393: {
10394: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10395:
1.11 www 10396: }
10397:
1.794 albertel 10398: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10399: 'compress_threshold'=> 20_000,
10400: });
1.185 www 10401:
1.281 www 10402: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10403: $dumpcount=0;
1.958 www 10404: $locknum=0;
1.22 www 10405:
1.163 harris41 10406: &logtouch();
1.672 albertel 10407: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10408: $readit=1;
1.564 albertel 10409: {
10410: use integer;
10411: my $test=(2**32)+1;
1.568 albertel 10412: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10413: &logthis(" Detected 64bit platform ($_64bit)");
10414: }
1.195 www 10415: }
1.1 albertel 10416: }
1.179 www 10417:
1.1 albertel 10418: 1;
1.191 harris41 10419: __END__
10420:
1.243 albertel 10421: =pod
10422:
1.191 harris41 10423: =head1 NAME
10424:
1.243 albertel 10425: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10426:
10427: =head1 SYNOPSIS
10428:
1.243 albertel 10429: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10430:
10431: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10432:
1.243 albertel 10433: Common parameters:
10434:
10435: =over 4
10436:
10437: =item *
10438:
10439: $uname : an internal username (if $cname expecting a course Id specifically)
10440:
10441: =item *
10442:
10443: $udom : a domain (if $cdom expecting a course's domain specifically)
10444:
10445: =item *
10446:
10447: $symb : a resource instance identifier
10448:
10449: =item *
10450:
10451: $namespace : the name of a .db file that contains the data needed or
10452: being set.
10453:
10454: =back
10455:
1.394 bowersj2 10456: =head1 OVERVIEW
1.191 harris41 10457:
1.394 bowersj2 10458: lonnet provides subroutines which interact with the
10459: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10460: about classes, users, and resources.
1.243 albertel 10461:
10462: For many of these objects you can also use this to store data about
10463: them or modify them in various ways.
1.191 harris41 10464:
1.394 bowersj2 10465: =head2 Symbs
1.191 harris41 10466:
1.394 bowersj2 10467: To identify a specific instance of a resource, LON-CAPA uses symbols
10468: or "symbs"X<symb>. These identifiers are built from the URL of the
10469: map, the resource number of the resource in the map, and the URL of
10470: the resource itself. The latter is somewhat redundant, but might help
10471: if maps change.
10472:
10473: An example is
10474:
10475: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10476:
10477: The respective map entry is
10478:
10479: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10480: title="Problem 2">
10481: </resource>
10482:
10483: Symbs are used by the random number generator, as well as to store and
10484: restore data specific to a certain instance of for example a problem.
10485:
10486: =head2 Storing And Retrieving Data
10487:
10488: X<store()>X<cstore()>X<restore()>Three of the most important functions
10489: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10490: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10491: is is the non-critical message twin of cstore. These functions are for
10492: handlers to store a perl hash to a user's permanent data space in an
10493: easy manner, and to retrieve it again on another call. It is expected
10494: that a handler would use this once at the beginning to retrieve data,
10495: and then again once at the end to send only the new data back.
10496:
10497: The data is stored in the user's data directory on the user's
10498: homeserver under the ID of the course.
10499:
10500: The hash that is returned by restore will have all of the previous
10501: value for all of the elements of the hash.
10502:
10503: Example:
10504:
10505: #creating a hash
10506: my %hash;
10507: $hash{'foo'}='bar';
10508:
10509: #storing it
10510: &Apache::lonnet::cstore(\%hash);
10511:
10512: #changing a value
10513: $hash{'foo'}='notbar';
10514:
10515: #adding a new value
10516: $hash{'bar'}='foo';
10517: &Apache::lonnet::cstore(\%hash);
10518:
10519: #retrieving the hash
10520: my %history=&Apache::lonnet::restore();
10521:
10522: #print the hash
10523: foreach my $key (sort(keys(%history))) {
10524: print("\%history{$key} = $history{$key}");
10525: }
10526:
10527: Will print out:
1.191 harris41 10528:
1.394 bowersj2 10529: %history{1:foo} = bar
10530: %history{1:keys} = foo:timestamp
10531: %history{1:timestamp} = 990455579
10532: %history{2:bar} = foo
10533: %history{2:foo} = notbar
10534: %history{2:keys} = foo:bar:timestamp
10535: %history{2:timestamp} = 990455580
10536: %history{bar} = foo
10537: %history{foo} = notbar
10538: %history{timestamp} = 990455580
10539: %history{version} = 2
10540:
10541: Note that the special hash entries C<keys>, C<version> and
10542: C<timestamp> were added to the hash. C<version> will be equal to the
10543: total number of versions of the data that have been stored. The
10544: C<timestamp> attribute will be the UNIX time the hash was
10545: stored. C<keys> is available in every historical section to list which
10546: keys were added or changed at a specific historical revision of a
10547: hash.
10548:
10549: B<Warning>: do not store the hash that restore returns directly. This
10550: will cause a mess since it will restore the historical keys as if the
10551: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10552:
1.394 bowersj2 10553: Calling convention:
1.191 harris41 10554:
1.394 bowersj2 10555: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10556: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10557:
1.394 bowersj2 10558: For more detailed information, see lonnet specific documentation.
1.191 harris41 10559:
1.394 bowersj2 10560: =head1 RETURN MESSAGES
1.191 harris41 10561:
1.394 bowersj2 10562: =over 4
1.191 harris41 10563:
1.394 bowersj2 10564: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10565:
1.394 bowersj2 10566: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10567: when the connection is brought back up
1.191 harris41 10568:
1.394 bowersj2 10569: =item * B<con_failed>: unable to contact remote host and unable to save message
10570: for later delivery
1.191 harris41 10571:
1.967 bisitz 10572: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10573:
1.394 bowersj2 10574: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10575: that was requested
1.191 harris41 10576:
1.243 albertel 10577: =back
1.191 harris41 10578:
1.243 albertel 10579: =head1 PUBLIC SUBROUTINES
1.191 harris41 10580:
1.243 albertel 10581: =head2 Session Environment Functions
1.191 harris41 10582:
1.243 albertel 10583: =over 4
1.191 harris41 10584:
1.394 bowersj2 10585: =item *
10586: X<appenv()>
1.949 raeburn 10587: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10588: the user envirnoment file, and will be restored for each access this
1.620 albertel 10589: user makes during this session, also modifies the %env for the current
1.949 raeburn 10590: process. Optional rolesarrayref - if defined contains a reference to an array
10591: of roles which are exempt from the restriction on modifying user.role entries
10592: in the user's environment.db and in %env.
1.191 harris41 10593:
10594: =item *
1.394 bowersj2 10595: X<delenv()>
1.987 raeburn 10596: B<delenv($delthis,$regexp)>: removes all items from the session
10597: environment file that begin with $delthis. If the
10598: optional second arg - $regexp - is true, $delthis is treated as a
10599: regular expression, otherwise \Q$delthis\E is used.
10600: The values are also deleted from the current processes %env.
1.191 harris41 10601:
1.795 albertel 10602: =item * get_env_multiple($name)
10603:
10604: gets $name from the %env hash, it seemlessly handles the cases where multiple
10605: values may be defined and end up as an array ref.
10606:
10607: returns an array of values
10608:
1.243 albertel 10609: =back
10610:
10611: =head2 User Information
1.191 harris41 10612:
1.243 albertel 10613: =over 4
1.191 harris41 10614:
10615: =item *
1.394 bowersj2 10616: X<queryauthenticate()>
10617: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10618: authentication scheme
10619:
10620: =item *
1.394 bowersj2 10621: X<authenticate()>
1.1056.4.3 raeburn 10622: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10623: authenticate user from domain's lib servers (first use the current
10624: one). C<$upass> should be the users password.
1.1056.4.3 raeburn 10625: $checkdefauth is optional (value is 1 if a check should be made to
10626: authenticate user using default authentication method, and allow
10627: account creation if username does not have account in the domain).
10628: $clientcancheckhost is optional (value is 1 if checking whether the
10629: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10630:
10631: =item *
1.394 bowersj2 10632: X<homeserver()>
10633: B<homeserver($uname,$udom)>: find the server which has
10634: the user's directory and files (there must be only one), this caches
10635: the answer, and also caches if there is a borken connection.
1.191 harris41 10636:
10637: =item *
1.394 bowersj2 10638: X<idget()>
10639: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10640: (IDs are a unique resource in a domain, there must be only 1 ID per
10641: username, and only 1 username per ID in a specific domain) (returns
10642: hash: id=>name,id=>name)
1.191 harris41 10643:
10644: =item *
1.394 bowersj2 10645: X<idrget()>
10646: B<idrget($udom,@unames)>: find the IDs behind a list of
10647: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10648:
10649: =item *
1.394 bowersj2 10650: X<idput()>
10651: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10652:
10653: =item *
1.394 bowersj2 10654: X<rolesinit()>
10655: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10656:
10657: =item *
1.551 albertel 10658: X<getsection()>
10659: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10660: course $cname, return section name/number or '' for "not in course"
10661: and '-1' for "no section"
10662:
10663: =item *
1.394 bowersj2 10664: X<userenvironment()>
10665: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10666: passed in @what from the requested user's environment, returns a hash
10667:
1.858 raeburn 10668: =item *
10669: X<userlog_query()>
1.859 albertel 10670: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10671: activity.log file. %filters defines filters applied when parsing the
10672: log file. These can be start or end timestamps, or the type of action
10673: - log to look for Login or Logout events, check for Checkin or
10674: Checkout, role for role selection. The response is in the form
10675: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10676: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10677:
1.243 albertel 10678: =back
10679:
10680: =head2 User Roles
10681:
10682: =over 4
10683:
10684: =item *
10685:
1.810 raeburn 10686: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10687: F: full access
10688: U,I,K: authentication modes (cxx only)
10689: '': forbidden
10690: 1: user needs to choose course
10691: 2: browse allowed
1.766 albertel 10692: A: passphrase authentication needed
1.243 albertel 10693:
10694: =item *
10695:
10696: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10697: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10698: and course level
10699:
10700: =item *
10701:
1.988 raeburn 10702: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10703: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10704: $type is Course (default) or Community.
1.988 raeburn 10705: If $forcedefault evaluates to true, text returned will be default
10706: text for $type. Otherwise, if this is a course, the text returned
10707: will be a custom name for the role (if defined in the course's
10708: environment). If no custom name is defined the default is returned.
10709:
1.832 raeburn 10710: =item *
10711:
1.935 raeburn 10712: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10713: All arguments are optional. Returns a hash of a roles, either for
10714: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10715: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10716: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10717: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10718: For each key, value is set to colon-separated start and end times for
10719: the role. If no username and domain are specified, will default to
1.934 raeburn 10720: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10721: of role statuses (active, future or previous), roles
10722: (e.g., cc,in, st etc.) and domains of the roles which can be used
10723: to restrict the list of roles reported. If no array ref is
10724: provided for types, will default to return only active roles.
1.834 albertel 10725:
1.243 albertel 10726: =back
10727:
10728: =head2 User Modification
10729:
10730: =over 4
10731:
10732: =item *
10733:
1.957 raeburn 10734: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10735: user for the level given by URL. Optional start and end dates (leave empty
10736: string or zero for "no date")
1.191 harris41 10737:
10738: =item *
10739:
1.243 albertel 10740: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10741: change a users, password, possible return values are: ok,
10742: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10743: refused
1.191 harris41 10744:
10745: =item *
10746:
1.243 albertel 10747: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10748:
10749: =item *
10750:
1.1056.4.1 raeburn 10751: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10752: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10753:
10754: will update user information (firstname,middlename,lastname,generation,
10755: permanentemail), and if forceid is true, student/employee ID also.
10756: A user's institutional affiliation(s) can also be updated.
10757: User information fields will not be overwritten with empty entries
10758: unless the field is included in the $candelete array reference.
10759: This array is included when a single user is modified via "Manage Users",
10760: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10761:
10762: =item *
10763:
1.286 matthew 10764: modifystudent
10765:
1.957 raeburn 10766: modify a student's enrollment and identification information.
1.286 matthew 10767: The course id is resolved based on the current users environment.
10768: This means the envoking user must be a course coordinator or otherwise
10769: associated with a course.
10770:
1.297 matthew 10771: This call is essentially a wrapper for lonnet::modifyuser and
10772: lonnet::modify_student_enrollment
1.286 matthew 10773:
10774: Inputs:
10775:
10776: =over 4
10777:
1.957 raeburn 10778: =item B<$udom> Student's loncapa domain
1.286 matthew 10779:
1.957 raeburn 10780: =item B<$uname> Student's loncapa login name
1.286 matthew 10781:
1.964 bisitz 10782: =item B<$uid> Student/Employee ID
1.286 matthew 10783:
1.957 raeburn 10784: =item B<$umode> Student's authentication mode
1.286 matthew 10785:
1.957 raeburn 10786: =item B<$upass> Student's password
1.286 matthew 10787:
1.957 raeburn 10788: =item B<$first> Student's first name
1.286 matthew 10789:
1.957 raeburn 10790: =item B<$middle> Student's middle name
1.286 matthew 10791:
1.957 raeburn 10792: =item B<$last> Student's last name
1.286 matthew 10793:
1.957 raeburn 10794: =item B<$gene> Student's generation
1.286 matthew 10795:
1.957 raeburn 10796: =item B<$usec> Student's section in course
1.286 matthew 10797:
10798: =item B<$end> Unix time of the roles expiration
10799:
10800: =item B<$start> Unix time of the roles start date
10801:
10802: =item B<$forceid> If defined, allow $uid to be changed
10803:
10804: =item B<$desiredhome> server to use as home server for student
10805:
1.957 raeburn 10806: =item B<$email> Student's permanent e-mail address
10807:
10808: =item B<$type> Type of enrollment (auto or manual)
10809:
1.963 raeburn 10810: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10811:
10812: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10813:
1.963 raeburn 10814: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10815:
1.963 raeburn 10816: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10817:
1.963 raeburn 10818: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10819:
1.286 matthew 10820: =back
1.297 matthew 10821:
10822: =item *
10823:
10824: modify_student_enrollment
10825:
10826: Change a students enrollment status in a class. The environment variable
10827: 'role.request.course' must be defined for this function to proceed.
10828:
10829: Inputs:
10830:
10831: =over 4
10832:
10833: =item $udom, students domain
10834:
10835: =item $uname, students name
10836:
10837: =item $uid, students user id
10838:
10839: =item $first, students first name
10840:
10841: =item $middle
10842:
10843: =item $last
10844:
10845: =item $gene
10846:
10847: =item $usec
10848:
10849: =item $end
10850:
10851: =item $start
10852:
1.957 raeburn 10853: =item $type
10854:
10855: =item $locktype
10856:
10857: =item $cid
10858:
10859: =item $selfenroll
10860:
10861: =item $context
10862:
1.297 matthew 10863: =back
10864:
1.191 harris41 10865:
10866: =item *
10867:
1.243 albertel 10868: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10869: custom role; give a custom role to a user for the level given by URL. Specify
10870: name and domain of role author, and role name
1.191 harris41 10871:
10872: =item *
10873:
1.243 albertel 10874: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10875:
10876: =item *
10877:
1.243 albertel 10878: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10879:
10880: =back
10881:
10882: =head2 Course Infomation
10883:
10884: =over 4
1.191 harris41 10885:
10886: =item *
10887:
1.631 albertel 10888: coursedescription($courseid) : returns a hash of information about the
10889: specified course id, including all environment settings for the
10890: course, the description of the course will be in the hash under the
10891: key 'description'
1.191 harris41 10892:
10893: =item *
10894:
1.624 albertel 10895: resdata($name,$domain,$type,@which) : request for current parameter
10896: setting for a specific $type, where $type is either 'course' or 'user',
10897: @what should be a list of parameters to ask about. This routine caches
10898: answers for 5 minutes.
1.243 albertel 10899:
1.877 foxr 10900: =item *
10901:
10902: get_courseresdata($courseid, $domain) : dump the entire course resource
10903: data base, returning a hash that is keyed by the resource name and has
10904: values that are the resource value. I believe that the timestamps and
10905: versions are also returned.
10906:
10907:
1.243 albertel 10908: =back
10909:
10910: =head2 Course Modification
10911:
10912: =over 4
1.191 harris41 10913:
10914: =item *
10915:
1.243 albertel 10916: writecoursepref($courseid,%prefs) : write preferences (environment
10917: database) for a course
1.191 harris41 10918:
10919: =item *
10920:
1.1011 raeburn 10921: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10922:
10923: =item *
10924:
1.1038 raeburn 10925: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10926:
10927: =back
10928:
10929: =head2 Resource Subroutines
10930:
10931: =over 4
1.191 harris41 10932:
10933: =item *
10934:
1.243 albertel 10935: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10936:
10937: =item *
10938:
1.243 albertel 10939: repcopy($filename) : subscribes to the requested file, and attempts to
10940: replicate from the owning library server, Might return
1.607 raeburn 10941: 'unavailable', 'not_found', 'forbidden', 'ok', or
10942: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10943: resource. Expects the local filesystem pathname
10944: (/home/httpd/html/res/....)
10945:
10946: =back
10947:
10948: =head2 Resource Information
10949:
10950: =over 4
1.191 harris41 10951:
10952: =item *
10953:
1.243 albertel 10954: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10955: a vairety of different possible values, $varname should be a request
10956: string, and the other parameters can be used to specify who and what
10957: one is asking about.
10958:
10959: Possible values for $varname are environment.lastname (or other item
10960: from the envirnment hash), user.name (or someother aspect about the
10961: user), resource.0.maxtries (or some other part and parameter of a
10962: resource)
1.204 albertel 10963:
10964: =item *
10965:
1.243 albertel 10966: directcondval($number) : get current value of a condition; reads from a state
10967: string
1.204 albertel 10968:
10969: =item *
10970:
1.243 albertel 10971: condval($condidx) : value of condition index based on state
1.204 albertel 10972:
10973: =item *
10974:
1.243 albertel 10975: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10976: resource's metadata, $what should be either a specific key, or either
10977: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10978: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10979:
10980: this function automatically caches all requests
1.191 harris41 10981:
10982: =item *
10983:
1.243 albertel 10984: metadata_query($query,$custom,$customshow) : make a metadata query against the
10985: network of library servers; returns file handle of where SQL and regex results
10986: will be stored for query
1.191 harris41 10987:
10988: =item *
10989:
1.243 albertel 10990: symbread($filename) : return symbolic list entry (filename argument optional);
10991: returns the data handle
1.191 harris41 10992:
10993: =item *
10994:
1.243 albertel 10995: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 10996: a possible symb for the URL in $thisfn, and if is an encryypted
10997: resource that the user accessed using /enc/ returns a 1 on success, 0
10998: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 10999: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11000:
1.191 harris41 11001:
11002: =item *
11003:
1.243 albertel 11004: symbclean($symb) : removes versions numbers from a symb, returns the
11005: cleaned symb
1.191 harris41 11006:
11007: =item *
11008:
1.243 albertel 11009: is_on_map($uri) : checks if the $uri is somewhere on the current
11010: course map, user must be in a course for it to work.
1.191 harris41 11011:
11012: =item *
11013:
1.243 albertel 11014: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11015:
11016: =item *
11017:
1.243 albertel 11018: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11019: a random seed, all arguments are optional, if they aren't sent it uses the
11020: environment to derive them. Note: if symb isn't sent and it can't get one
11021: from &symbread it will use the current time as its return value
1.191 harris41 11022:
11023: =item *
11024:
1.243 albertel 11025: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11026: unfakeable, receipt
1.191 harris41 11027:
11028: =item *
11029:
1.620 albertel 11030: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11031:
11032: =item *
11033:
1.243 albertel 11034: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11035:
11036: =item *
11037:
1.243 albertel 11038: 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 11039:
11040: =item *
11041:
1.243 albertel 11042: 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 11043:
11044: =item *
11045:
1.243 albertel 11046: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11047:
11048: =item *
11049:
1.243 albertel 11050: devalidate($symb) : devalidate temporary spreadsheet calculations,
11051: forcing spreadsheet to reevaluate the resource scores next time.
11052:
11053: =back
11054:
11055: =head2 Storing/Retreiving Data
11056:
11057: =over 4
1.191 harris41 11058:
11059: =item *
11060:
1.243 albertel 11061: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11062: for this url; hashref needs to be given and should be a \%hashname; the
11063: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11064: be derived from the env
1.191 harris41 11065:
11066: =item *
11067:
1.243 albertel 11068: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11069: uses critical subroutine
1.191 harris41 11070:
11071: =item *
11072:
1.243 albertel 11073: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11074: all args are optional
1.191 harris41 11075:
11076: =item *
11077:
1.717 albertel 11078: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11079: dumps the complete (or key matching regexp) namespace into a hash
11080: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11081: normally &store()ed into
11082:
11083: $range should be either an integer '100' (give me the first 100
11084: matching records)
11085: or be two integers sperated by a - with no spaces
11086: '30-50' (give me the 30th through the 50th matching
11087: records)
11088:
11089:
11090: =item *
11091:
11092: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11093: replaces a &store() version of data with a replacement set of data
11094: for a particular resource in a namespace passed in the $storehash hash
11095: reference
11096:
11097: =item *
11098:
1.243 albertel 11099: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11100: works very similar to store/cstore, but all data is stored in a
11101: temporary location and can be reset using tmpreset, $storehash should
11102: be a hash reference, returns nothing on success
1.191 harris41 11103:
11104: =item *
11105:
1.243 albertel 11106: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11107: similar to restore, but all data is stored in a temporary location and
11108: can be reset using tmpreset. Returns a hash of values on success,
11109: error string otherwise.
1.191 harris41 11110:
11111: =item *
11112:
1.243 albertel 11113: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11114: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11115:
11116: =item *
11117:
1.243 albertel 11118: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11119: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11120:
11121: =item *
11122:
1.243 albertel 11123: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11124: namesp ($udom and $uname are optional)
1.191 harris41 11125:
11126: =item *
11127:
1.702 albertel 11128: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11129: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11130: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11131:
1.702 albertel 11132: $range should be either an integer '100' (give me the first 100
11133: matching records)
11134: or be two integers sperated by a - with no spaces
11135: '30-50' (give me the 30th through the 50th matching
11136: records)
1.449 matthew 11137: =item *
11138:
11139: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11140: $store can be a scalar, an array reference, or if the amount to be
11141: incremented is > 1, a hash reference.
11142:
11143: ($udom and $uname are optional)
1.191 harris41 11144:
11145: =item *
11146:
1.243 albertel 11147: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11148: ($udom and $uname are optional)
1.191 harris41 11149:
11150: =item *
11151:
1.243 albertel 11152: cput($namespace,$storehash,$udom,$uname) : critical put
11153: ($udom and $uname are optional)
1.191 harris41 11154:
11155: =item *
11156:
1.748 albertel 11157: newput($namespace,$storehash,$udom,$uname) :
11158:
11159: Attempts to store the items in the $storehash, but only if they don't
11160: currently exist, if this succeeds you can be certain that you have
11161: successfully created a new key value pair in the $namespace db.
11162:
11163:
11164: Args:
11165: $namespace: name of database to store values to
11166: $storehash: hashref to store to the db
11167: $udom: (optional) domain of user containing the db
11168: $uname: (optional) name of user caontaining the db
11169:
11170: Returns:
11171: 'ok' -> succeeded in storing all keys of $storehash
11172: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11173: least <key> already existed in the db (other
11174: requested keys may also already exist)
1.967 bisitz 11175: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11176: 'con_lost' -> unable to contact request server
11177: 'refused' -> action was not allowed by remote machine
11178:
11179:
11180: =item *
11181:
1.243 albertel 11182: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11183: reference filled in from namesp (encrypts the return communication)
11184: ($udom and $uname are optional)
1.191 harris41 11185:
11186: =item *
11187:
1.243 albertel 11188: log($udom,$name,$home,$message) : write to permanent log for user; use
11189: critical subroutine
11190:
1.806 raeburn 11191: =item *
11192:
1.860 raeburn 11193: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11194: array reference filled in from namespace found in domain level on either
11195: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11196:
11197: =item *
11198:
1.860 raeburn 11199: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11200: domain level either on specified domain server ($uhome) or primary domain
11201: server ($udom and $uhome are optional)
1.806 raeburn 11202:
1.943 raeburn 11203: =item *
11204:
11205: get_domain_defaults($target_domain) : returns hash with defaults for
11206: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11207: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11208: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11209: Values are retrieved from cache (if current), or from domain's configuration.db
11210: (if available), or lastly from values in lonTabs/dns_domain,tab,
11211: or lonTabs/domain.tab.
11212:
11213: %domdefaults = &get_auth_defaults($target_domain);
11214:
1.243 albertel 11215: =back
11216:
11217: =head2 Network Status Functions
11218:
11219: =over 4
1.191 harris41 11220:
11221: =item *
11222:
11223: dirlist($uri) : return directory list based on URI
11224:
11225: =item *
11226:
1.243 albertel 11227: spareserver() : find server with least workload from spare.tab
11228:
1.986 foxr 11229:
11230: =item *
11231:
11232: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11233: if there is no corresponding loncapa host.
11234:
1.243 albertel 11235: =back
11236:
1.986 foxr 11237:
1.243 albertel 11238: =head2 Apache Request
11239:
11240: =over 4
1.191 harris41 11241:
11242: =item *
11243:
1.243 albertel 11244: ssi($url,%hash) : server side include, does a complete request cycle on url to
11245: localhost, posts hash
11246:
11247: =back
11248:
11249: =head2 Data to String to Data
11250:
11251: =over 4
1.191 harris41 11252:
11253: =item *
11254:
1.243 albertel 11255: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11256: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11257:
11258: =item *
11259:
1.243 albertel 11260: hashref2str($hashref) : convert a hashref into a string complete with
11261: escaping and '=' and '&' separators, supports elements that are
11262: arrayrefs and hashrefs
1.191 harris41 11263:
11264: =item *
11265:
1.243 albertel 11266: arrayref2str($arrayref) : convert an arrayref into a string complete
11267: with escaping and '&' separators, supports elements that are arrayrefs
11268: and hashrefs
1.191 harris41 11269:
11270: =item *
11271:
1.243 albertel 11272: str2hash($string) : convert string to hash using unescaping and
11273: splitting on '=' and '&', supports elements that are arrayrefs and
11274: hashrefs
1.191 harris41 11275:
11276: =item *
11277:
1.243 albertel 11278: str2array($string) : convert string to hash using unescaping and
11279: splitting on '&', supports elements that are arrayrefs and hashrefs
11280:
11281: =back
11282:
11283: =head2 Logging Routines
11284:
11285: =over 4
11286:
11287: These routines allow one to make log messages in the lonnet.log and
11288: lonnet.perm logfiles.
1.191 harris41 11289:
11290: =item *
11291:
1.243 albertel 11292: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11293:
11294: =item *
11295:
1.243 albertel 11296: logthis() : append message to the normal lonnet.log file, it gets
11297: preiodically rolled over and deleted.
1.191 harris41 11298:
11299: =item *
11300:
1.243 albertel 11301: logperm() : append a permanent message to lonnet.perm.log, this log
11302: file never gets deleted by any automated portion of the system, only
11303: messages of critical importance should go in here.
11304:
11305: =back
11306:
11307: =head2 General File Helper Routines
11308:
11309: =over 4
1.191 harris41 11310:
11311: =item *
11312:
1.481 raeburn 11313: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11314: (a) files in /uploaded
11315: (i) If a local copy of the file exists -
11316: compares modification date of local copy with last-modified date for
11317: definitive version stored on home server for course. If local copy is
11318: stale, requests a new version from the home server and stores it.
11319: If the original has been removed from the home server, then local copy
11320: is unlinked.
11321: (ii) If local copy does not exist -
11322: requests the file from the home server and stores it.
11323:
11324: If $caller is 'uploadrep':
11325: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11326: for request for files originally uploaded via DOCS.
11327: - returns 'ok' if fresh local copy now available, -1 otherwise.
11328:
11329: Otherwise:
11330: This indicates a call from the content generation phase of the request.
11331: - returns the entire contents of the file or -1.
11332:
11333: (b) files in /res
11334: - returns the entire contents of a file or -1;
11335: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11336:
1.712 albertel 11337:
11338: =item *
11339:
11340: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11341: reference
11342:
11343: returns either a stat() list of data about the file or an empty list
11344: if the file doesn't exist or couldn't find out about it (connection
11345: problems or user unknown)
11346:
1.191 harris41 11347: =item *
11348:
1.243 albertel 11349: filelocation($dir,$file) : returns file system location of a file
11350: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11351: directory that relative $file lookups are to looked in ($dir of /a/dir
11352: and a file of ../bob will become /a/bob)
1.191 harris41 11353:
11354: =item *
11355:
11356: hreflocation($dir,$file) : returns file system location or a URL; same as
11357: filelocation except for hrefs
11358:
11359: =item *
11360:
11361: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11362:
1.243 albertel 11363: =back
11364:
1.608 albertel 11365: =head2 Usererfile file routines (/uploaded*)
11366:
11367: =over 4
11368:
11369: =item *
11370:
11371: userfileupload(): main rotine for putting a file in a user or course's
11372: filespace, arguments are,
11373:
1.620 albertel 11374: formname - required - this is the name of the element in $env where the
1.608 albertel 11375: filename, and the contents of the file to create/modifed exist
1.620 albertel 11376: the filename is in $env{'form.'.$formname.'.filename'} and the
11377: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 11378: coursedoc - if true, store the file in the course of the active role
11379: of the current user
11380: subdir - required - subdirectory to put the file in under ../userfiles/
11381: if undefined, it will be placed in "unknown"
11382:
11383: (This routine calls clean_filename() to remove any dangerous
11384: characters from the filename, and then calls finuserfileupload() to
11385: complete the transaction)
11386:
11387: returns either the url of the uploaded file (/uploaded/....) if successful
11388: and /adm/notfound.html if unsuccessful
11389:
11390: =item *
11391:
11392: clean_filename(): routine for cleaing a filename up for storage in
11393: userfile space, argument is:
11394:
11395: filename - proposed filename
11396:
11397: returns: the new clean filename
11398:
11399: =item *
11400:
11401: finishuserfileupload(): routine that creaes and sends the file to
11402: userspace, probably shouldn't be called directly
11403:
11404: docuname: username or courseid of destination for the file
11405: docudom: domain of user/course of destination for the file
11406: formname: same as for userfileupload()
11407: fname: filename (inculding subdirectories) for the file
11408:
11409: returns either the url of the uploaded file (/uploaded/....) if successful
11410: and /adm/notfound.html if unsuccessful
11411:
11412: =item *
11413:
11414: renameuserfile(): renames an existing userfile to a new name
11415:
11416: Args:
11417: docuname: username or courseid of destination for the file
11418: docudom: domain of user/course of destination for the file
11419: old: current file name (including any subdirs under userfiles)
11420: new: desired file name (including any subdirs under userfiles)
11421:
11422: =item *
11423:
11424: mkdiruserfile(): creates a directory is a userfiles dir
11425:
11426: Args:
11427: docuname: username or courseid of destination for the file
11428: docudom: domain of user/course of destination for the file
11429: dir: dir to create (including any subdirs under userfiles)
11430:
11431: =item *
11432:
11433: removeuserfile(): removes a file that exists in userfiles
11434:
11435: Args:
11436: docuname: username or courseid of destination for the file
11437: docudom: domain of user/course of destination for the file
11438: fname: filname to delete (including any subdirs under userfiles)
11439:
11440: =item *
11441:
11442: removeuploadedurl(): convience function for removeuserfile()
11443:
11444: Args:
11445: url: a full /uploaded/... url to delete
11446:
1.747 albertel 11447: =item *
11448:
11449: get_portfile_permissions():
11450: Args:
11451: domain: domain of user or course contain the portfolio files
11452: user: name of user or num of course contain the portfolio files
11453: Returns:
11454: hashref of a dump of the proper file_permissions.db
11455:
11456:
11457: =item *
11458:
11459: get_access_controls():
11460:
11461: Args:
11462: current_permissions: the hash ref returned from get_portfile_permissions()
11463: group: (optional) the group you want the files associated with
11464: file: (optional) the file you want access info on
11465:
11466: Returns:
1.749 raeburn 11467: a hash (keys are file names) of hashes containing
11468: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11469: values are XML containing access control settings (see below)
1.747 albertel 11470:
11471: Internal notes:
11472:
1.749 raeburn 11473: access controls are stored in file_permissions.db as key=value pairs.
11474: key -> path to file/file_name\0uniqueID:scope_end_start
11475: where scope -> public,guest,course,group,domains or users.
11476: end -> UNIX time for end of access (0 -> no end date)
11477: start -> UNIX time for start of access
11478:
11479: value -> XML description of access control
11480: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11481: <start></start>
11482: <end></end>
11483:
11484: <password></password> for scope type = guest
11485:
11486: <domain></domain> for scope type = course or group
11487: <number></number>
11488: <roles id="">
11489: <role></role>
11490: <access></access>
11491: <section></section>
11492: <group></group>
11493: </roles>
11494:
11495: <dom></dom> for scope type = domains
11496:
11497: <users> for scope type = users
11498: <user>
11499: <uname></uname>
11500: <udom></udom>
11501: </user>
11502: </users>
11503: </scope>
11504:
11505: Access data is also aggregated for each file in an additional key=value pair:
11506: key -> path to file/file_name\0accesscontrol
11507: value -> reference to hash
11508: hash contains key = value pairs
11509: where key = uniqueID:scope_end_start
11510: value = UNIX time record was last updated
11511:
11512: Used to improve speed of look-ups of access controls for each file.
11513:
11514: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11515:
11516: modify_access_controls():
11517:
11518: Modifies access controls for a portfolio file
11519: Args
11520: 1. file name
11521: 2. reference to hash of required changes,
11522: 3. domain
11523: 4. username
11524: where domain,username are the domain of the portfolio owner
11525: (either a user or a course)
11526:
11527: Returns:
11528: 1. result of additions or updates ('ok' or 'error', with error message).
11529: 2. result of deletions ('ok' or 'error', with error message).
11530: 3. reference to hash of any new or updated access controls.
11531: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11532: key = integer (inbound ID)
11533: value = uniqueID
1.747 albertel 11534:
1.608 albertel 11535: =back
11536:
1.243 albertel 11537: =head2 HTTP Helper Routines
11538:
11539: =over 4
11540:
1.191 harris41 11541: =item *
11542:
11543: escape() : unpack non-word characters into CGI-compatible hex codes
11544:
11545: =item *
11546:
11547: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11548:
1.243 albertel 11549: =back
11550:
11551: =head1 PRIVATE SUBROUTINES
11552:
11553: =head2 Underlying communication routines (Shouldn't call)
11554:
11555: =over 4
11556:
11557: =item *
11558:
11559: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11560:
11561: =item *
11562:
11563: reply() : uses subreply to send a message to remote machine, logs all failures
11564:
11565: =item *
11566:
11567: critical() : passes a critical message to another server; if cannot
11568: get through then place message in connection buffer directory and
11569: returns con_delayed, if incapable of saving message, returns
11570: con_failed
11571:
11572: =item *
11573:
11574: reconlonc() : tries to reconnect lonc client processes.
11575:
11576: =back
11577:
11578: =head2 Resource Access Logging
11579:
11580: =over 4
11581:
11582: =item *
11583:
11584: flushcourselogs() : flush (save) buffer logs and access logs
11585:
11586: =item *
11587:
11588: courselog($what) : save message for course in hash
11589:
11590: =item *
11591:
11592: courseacclog($what) : save message for course using &courselog(). Perform
11593: special processing for specific resource types (problems, exams, quizzes, etc).
11594:
1.191 harris41 11595: =item *
11596:
11597: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11598: as a PerlChildExitHandler
1.243 albertel 11599:
11600: =back
11601:
11602: =head2 Other
11603:
11604: =over 4
11605:
11606: =item *
11607:
11608: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11609:
11610: =back
11611:
11612: =cut
1.877 foxr 11613:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>