Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1101
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1101 ! raeburn 4: # $Id: lonnet.pm,v 1.1100 2011/01/18 20:19:29 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1079 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.1024 raeburn 95: use File::MMagic;
1.807 albertel 96: use LONCAPA qw(:DEFAULT :match);
1.740 www 97: use LONCAPA::Configuration;
1.1090 raeburn 98: use File::Copy;
1.676 albertel 99:
1.195 www 100: my $readit;
1.550 foxr 101: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 102:
1.619 albertel 103: require Exporter;
104:
105: our @ISA = qw (Exporter);
106: our @EXPORT = qw(%env);
107:
1.449 matthew 108:
1.1 albertel 109: # --------------------------------------------------------------------- Logging
1.729 www 110: {
111: my $logid;
112: sub instructor_log {
1.957 raeburn 113: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
114: if (($cnum eq '') || ($cdom eq '')) {
115: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
116: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
117: }
1.729 www 118: $logid++;
1.957 raeburn 119: my $now = time();
120: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 121: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 122: { $id => {
123: 'exe_uname' => $env{'user.name'},
124: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 125: 'exe_time' => $now,
1.730 www 126: 'exe_ip' => $ENV{'REMOTE_ADDR'},
127: 'delflag' => $delflag,
128: 'logentry' => $storehash,
129: 'uname' => $uname,
130: 'udom' => $udom,
131: }
1.957 raeburn 132: },$cdom,$cnum);
1.729 www 133: }
134: }
1.1 albertel 135:
1.163 harris41 136: sub logtouch {
137: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 138: unless (-e "$execdir/logs/lonnet.log") {
139: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 140: close $fh;
141: }
142: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
143: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
144: }
145:
1.1 albertel 146: sub logthis {
147: my $message=shift;
148: my $execdir=$perlvar{'lonDaemons'};
149: my $now=time;
150: my $local=localtime($now);
1.448 albertel 151: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 152: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
153: print $fh $logstring;
1.448 albertel 154: close($fh);
155: }
1.1 albertel 156: return 1;
157: }
158:
159: sub logperm {
160: my $message=shift;
161: my $execdir=$perlvar{'lonDaemons'};
162: my $now=time;
163: my $local=localtime($now);
1.448 albertel 164: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
165: print $fh "$now:$message:$local\n";
166: close($fh);
167: }
1.1 albertel 168: return 1;
169: }
170:
1.850 albertel 171: sub create_connection {
1.853 albertel 172: my ($hostname,$lonid) = @_;
1.851 albertel 173: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 174: Type => SOCK_STREAM,
175: Timeout => 10);
176: return 0 if (!$client);
1.890 albertel 177: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 178: my $result = <$client>;
179: chomp($result);
180: return 1 if ($result eq 'done');
181: return 0;
182: }
183:
1.983 raeburn 184: sub get_server_timezone {
185: my ($cnum,$cdom) = @_;
186: my $home=&homeserver($cnum,$cdom);
187: if ($home ne 'no_host') {
188: my $cachetime = 24*3600;
189: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
190: if (defined($cached)) {
191: return $timezone;
192: } else {
193: my $timezone = &reply('servertimezone',$home);
194: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
195: }
196: }
197: }
1.850 albertel 198:
1.993 raeburn 199: sub get_server_loncaparev {
1.1073 raeburn 200: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 201: if (defined($lonhost)) {
202: if (!defined(&hostname($lonhost))) {
203: undef($lonhost);
204: }
205: }
206: if (!defined($lonhost)) {
207: if (defined(&domain($dom,'primary'))) {
208: $lonhost=&domain($dom,'primary');
209: if ($lonhost eq 'no_host') {
210: undef($lonhost);
211: }
212: }
213: }
214: if (defined($lonhost)) {
1.1073 raeburn 215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
218: if (defined($cached)) {
219: return $loncaparev;
220: }
221: }
222: my ($answer,$loncaparev);
223: my @ids=¤t_machine_ids();
224: if (grep(/^\Q$lonhost\E$/,@ids)) {
225: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 226: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 227: $loncaparev = $1;
228: }
229: } else {
230: $answer = &reply('serverloncaparev',$lonhost);
231: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
232: if ($caller eq 'loncron') {
233: my $ua=new LWP::UserAgent;
1.1082 raeburn 234: $ua->timeout(4);
1.1073 raeburn 235: my $protocol = $protocol{$lonhost};
236: $protocol = 'http' if ($protocol ne 'https');
237: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
238: my $request=new HTTP::Request('GET',$url);
239: my $response=$ua->request($request);
240: unless ($response->is_error()) {
241: my $content = $response->content;
1.1081 raeburn 242: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 243: $loncaparev = $1;
244: }
245: }
246: } else {
247: $loncaparev = $loncaparevs{$lonhost};
248: }
1.1081 raeburn 249: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 250: $loncaparev = $1;
251: }
1.993 raeburn 252: }
1.1073 raeburn 253: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 254: }
255: }
256:
1.1074 raeburn 257: sub get_server_homeID {
258: my ($hostname,$ignore_cache,$caller) = @_;
259: unless ($ignore_cache) {
260: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
261: if (defined($cached)) {
262: return $serverhomeID;
263: }
264: }
265: my $cachetime = 12*3600;
266: my $serverhomeID;
267: if ($caller eq 'loncron') {
268: my @machine_ids = &machine_ids($hostname);
269: foreach my $id (@machine_ids) {
270: my $response = &reply('serverhomeID',$id);
271: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
272: $serverhomeID = $response;
273: last;
274: }
275: }
276: if ($serverhomeID eq '') {
277: $serverhomeID = $machine_ids[-1];
278: }
279: } else {
280: $serverhomeID = $serverhomeIDs{$hostname};
281: }
282: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
283: }
284:
1.1 albertel 285: # -------------------------------------------------- Non-critical communication
286: sub subreply {
287: my ($cmd,$server)=@_;
1.838 albertel 288: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 289: #
290: # With loncnew process trimming, there's a timing hole between lonc server
291: # process exit and the master server picking up the listen on the AF_UNIX
292: # socket. In that time interval, a lock file will exist:
293:
294: my $lockfile=$peerfile.".lock";
295: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
296: sleep(1);
297: }
298: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 299: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 300: #
1.550 foxr 301: # We'll give the connection a few tries before abandoning it. If
302: # connection is not possible, we'll con_lost back to the client.
303: #
304: my $client;
305: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
306: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
307: Type => SOCK_STREAM,
308: Timeout => 10);
1.869 albertel 309: if ($client) {
1.550 foxr 310: last; # Connected!
1.850 albertel 311: } else {
1.853 albertel 312: &create_connection(&hostname($server),$server);
1.550 foxr 313: }
1.850 albertel 314: sleep(1); # Try again later if failed connection.
1.550 foxr 315: }
316: my $answer;
317: if ($client) {
1.704 albertel 318: print $client "sethost:$server:$cmd\n";
1.550 foxr 319: $answer=<$client>;
320: if (!$answer) { $answer="con_lost"; }
321: chomp($answer);
322: } else {
323: $answer = 'con_lost'; # Failed connection.
324: }
1.1 albertel 325: return $answer;
326: }
327:
328: sub reply {
329: my ($cmd,$server)=@_;
1.838 albertel 330: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 331: my $answer=subreply($cmd,$server);
1.65 www 332: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 333: &logthis("<font color=\"blue\">WARNING:".
1.12 www 334: " $cmd to $server returned $answer</font>");
335: }
1.1 albertel 336: return $answer;
337: }
338:
339: # ----------------------------------------------------------- Send USR1 to lonc
340:
341: sub reconlonc {
1.891 albertel 342: my ($lonid) = @_;
343: my $hostname = &hostname($lonid);
344: if ($lonid) {
345: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
346: if ($hostname && -e $peerfile) {
347: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
348: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
349: Type => SOCK_STREAM,
350: Timeout => 10);
351: if ($client) {
352: print $client ("reset_retries\n");
353: my $answer=<$client>;
354: #reset just this one.
355: }
356: }
357: return;
358: }
359:
1.836 www 360: &logthis("Trying to reconnect lonc");
1.1 albertel 361: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 362: if (open(my $fh,"<$loncfile")) {
1.1 albertel 363: my $loncpid=<$fh>;
364: chomp($loncpid);
365: if (kill 0 => $loncpid) {
366: &logthis("lonc at pid $loncpid responding, sending USR1");
367: kill USR1 => $loncpid;
368: sleep 1;
1.836 www 369: } else {
1.12 www 370: &logthis(
1.672 albertel 371: "<font color=\"blue\">WARNING:".
1.12 www 372: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 373: }
374: } else {
1.836 www 375: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 376: }
377: }
378:
379: # ------------------------------------------------------ Critical communication
1.12 www 380:
1.1 albertel 381: sub critical {
382: my ($cmd,$server)=@_;
1.838 albertel 383: unless (&hostname($server)) {
1.672 albertel 384: &logthis("<font color=\"blue\">WARNING:".
1.89 www 385: " Critical message to unknown server ($server)</font>");
386: return 'no_such_host';
387: }
1.1 albertel 388: my $answer=reply($cmd,$server);
389: if ($answer eq 'con_lost') {
390: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 391: my $answer=reply($cmd,$server);
1.1 albertel 392: if ($answer eq 'con_lost') {
393: my $now=time;
394: my $middlename=$cmd;
1.5 www 395: $middlename=substr($middlename,0,16);
1.1 albertel 396: $middlename=~s/\W//g;
397: my $dfilename=
1.305 www 398: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
399: $dumpcount++;
1.1 albertel 400: {
1.448 albertel 401: my $dfh;
402: if (open($dfh,">$dfilename")) {
403: print $dfh "$cmd\n";
404: close($dfh);
405: }
1.1 albertel 406: }
407: sleep 2;
408: my $wcmd='';
409: {
1.448 albertel 410: my $dfh;
411: if (open($dfh,"<$dfilename")) {
412: $wcmd=<$dfh>;
413: close($dfh);
414: }
1.1 albertel 415: }
416: chomp($wcmd);
1.7 www 417: if ($wcmd eq $cmd) {
1.672 albertel 418: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 419: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 420: &logperm("D:$server:$cmd");
421: return 'con_delayed';
422: } else {
1.672 albertel 423: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 424: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 425: &logperm("F:$server:$cmd");
426: return 'con_failed';
427: }
428: }
429: }
430: return $answer;
1.405 albertel 431: }
432:
1.755 albertel 433: # ------------------------------------------- check if return value is an error
434:
435: sub error {
436: my ($result) = @_;
1.756 albertel 437: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 438: if ($2 == 2) { return undef; }
439: return $1;
440: }
441: return undef;
442: }
443:
1.783 albertel 444: sub convert_and_load_session_env {
445: my ($lonidsdir,$handle)=@_;
446: my @profile;
447: {
1.917 albertel 448: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
449: if (!$opened) {
1.915 albertel 450: return 0;
451: }
1.783 albertel 452: flock($idf,LOCK_SH);
453: @profile=<$idf>;
454: close($idf);
455: }
456: my %temp_env;
457: foreach my $line (@profile) {
1.786 albertel 458: if ($line !~ m/=/) {
459: return 0;
460: }
1.783 albertel 461: chomp($line);
462: my ($envname,$envvalue)=split(/=/,$line,2);
463: $temp_env{&unescape($envname)} = &unescape($envvalue);
464: }
465: unlink("$lonidsdir/$handle.id");
466: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
467: 0640)) {
468: %disk_env = %temp_env;
469: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
470: untie(%disk_env);
471: }
1.786 albertel 472: return 1;
1.783 albertel 473: }
474:
1.374 www 475: # ------------------------------------------- Transfer profile into environment
1.780 albertel 476: my $env_loaded;
477: sub transfer_profile_to_env {
1.788 albertel 478: my ($lonidsdir,$handle,$force_transfer) = @_;
479: if (!$force_transfer && $env_loaded) { return; }
1.374 www 480:
1.720 albertel 481: if (!defined($lonidsdir)) {
482: $lonidsdir = $perlvar{'lonIDsDir'};
483: }
484: if (!defined($handle)) {
485: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
486: }
487:
1.786 albertel 488: my $convert;
489: {
1.917 albertel 490: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
491: if (!$opened) {
1.915 albertel 492: return;
493: }
1.786 albertel 494: flock($idf,LOCK_SH);
495: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
496: &GDBM_READER(),0640)) {
497: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
498: untie(%disk_env);
499: } else {
500: $convert = 1;
501: }
502: }
503: if ($convert) {
504: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
505: &logthis("Failed to load session, or convert session.");
506: }
1.374 www 507: }
1.783 albertel 508:
1.786 albertel 509: my %remove;
1.783 albertel 510: while ( my $envname = each(%env) ) {
1.433 matthew 511: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
512: if ($time < time-300) {
1.783 albertel 513: $remove{$key}++;
1.433 matthew 514: }
515: }
516: }
1.783 albertel 517:
1.619 albertel 518: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 519: $env_loaded=1;
1.783 albertel 520: foreach my $expired_key (keys(%remove)) {
1.433 matthew 521: &delenv($expired_key);
1.374 www 522: }
1.1 albertel 523: }
524:
1.916 albertel 525: # ---------------------------------------------------- Check for valid session
526: sub check_for_valid_session {
527: my ($r) = @_;
528: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
529: my $lonid=$cookies{'lonID'};
530: return undef if (!$lonid);
531:
532: my $handle=&LONCAPA::clean_handle($lonid->value);
533: my $lonidsdir=$r->dir_config('lonIDsDir');
534: return undef if (!-e "$lonidsdir/$handle.id");
535:
1.917 albertel 536: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
537: return undef if (!$opened);
1.916 albertel 538:
539: flock($idf,LOCK_SH);
540: my %disk_env;
541: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
542: &GDBM_READER(),0640)) {
543: return undef;
544: }
545:
546: if (!defined($disk_env{'user.name'})
547: || !defined($disk_env{'user.domain'})) {
548: return undef;
549: }
550: return $handle;
551: }
552:
1.830 albertel 553: sub timed_flock {
554: my ($file,$lock_type) = @_;
555: my $failed=0;
556: eval {
557: local $SIG{__DIE__}='DEFAULT';
558: local $SIG{ALRM}=sub {
559: $failed=1;
560: die("failed lock");
561: };
562: alarm(13);
563: flock($file,$lock_type);
564: alarm(0);
565: };
566: if ($failed) {
567: return undef;
568: } else {
569: return 1;
570: }
571: }
572:
1.5 www 573: # ---------------------------------------------------------- Append Environment
574:
575: sub appenv {
1.949 raeburn 576: my ($newenv,$roles) = @_;
577: if (ref($newenv) eq 'HASH') {
578: foreach my $key (keys(%{$newenv})) {
579: my $refused = 0;
580: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
581: $refused = 1;
582: if (ref($roles) eq 'ARRAY') {
583: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
584: if (grep(/^\Q$role\E$/,@{$roles})) {
585: $refused = 0;
586: }
587: }
588: }
589: if ($refused) {
590: &logthis("<font color=\"blue\">WARNING: ".
591: "Attempt to modify environment ".$key." to ".$newenv->{$key}
592: .'</font>');
593: delete($newenv->{$key});
594: } else {
595: $env{$key}=$newenv->{$key};
596: }
597: }
598: my $opened = open(my $env_file,'+<',$env{'user.environment'});
599: if ($opened
600: && &timed_flock($env_file,LOCK_EX)
601: &&
602: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
603: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
604: while (my ($key,$value) = each(%{$newenv})) {
605: $disk_env{$key} = $value;
606: }
607: untie(%disk_env);
1.35 www 608: }
1.191 harris41 609: }
1.56 www 610: return 'ok';
611: }
612: # ----------------------------------------------------- Delete from Environment
613:
614: sub delenv {
1.987 raeburn 615: my ($delthis,$regexp) = @_;
1.56 www 616: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 617: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 618: "Attempt to delete from environment ".$delthis);
619: return 'error';
620: }
1.917 albertel 621: my $opened = open(my $env_file,'+<',$env{'user.environment'});
622: if ($opened
1.915 albertel 623: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 624: &&
625: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
626: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 627: foreach my $key (keys(%disk_env)) {
1.987 raeburn 628: if ($regexp) {
629: if ($key=~/^$delthis/) {
630: delete($env{$key});
631: delete($disk_env{$key});
632: }
633: } else {
634: if ($key=~/^\Q$delthis\E/) {
635: delete($env{$key});
636: delete($disk_env{$key});
637: }
638: }
1.448 albertel 639: }
1.783 albertel 640: untie(%disk_env);
1.5 www 641: }
642: return 'ok';
1.369 albertel 643: }
644:
1.790 albertel 645: sub get_env_multiple {
646: my ($name) = @_;
647: my @values;
648: if (defined($env{$name})) {
649: # exists is it an array
650: if (ref($env{$name})) {
651: @values=@{ $env{$name} };
652: } else {
653: $values[0]=$env{$name};
654: }
655: }
656: return(@values);
657: }
658:
1.958 www 659: # ------------------------------------------------------------------- Locking
660:
661: sub set_lock {
662: my ($text)=@_;
663: $locknum++;
664: my $id=$$.'-'.$locknum;
665: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
666: 'session.lock.'.$id => $text});
667: return $id;
668: }
669:
670: sub get_locks {
671: my $num=0;
672: my %texts=();
673: foreach my $lock (split(/\,/,$env{'session.locks'})) {
674: if ($lock=~/\w/) {
675: $num++;
676: $texts{$lock}=$env{'session.lock.'.$lock};
677: }
678: }
679: return ($num,%texts);
680: }
681:
682: sub remove_lock {
683: my ($id)=@_;
684: my $newlocks='';
685: foreach my $lock (split(/\,/,$env{'session.locks'})) {
686: if (($lock=~/\w/) && ($lock ne $id)) {
687: $newlocks.=','.$lock;
688: }
689: }
690: &appenv({'session.locks' => $newlocks});
691: &delenv('session.lock.'.$id);
692: }
693:
694: sub remove_all_locks {
695: my $activelocks=$env{'session.locks'};
696: foreach my $lock (split(/\,/,$env{'session.locks'})) {
697: if ($lock=~/\w/) {
698: &remove_lock($lock);
699: }
700: }
701: }
702:
703:
1.369 albertel 704: # ------------------------------------------ Find out current server userload
705: sub userload {
706: my $numusers=0;
707: {
708: opendir(LONIDS,$perlvar{'lonIDsDir'});
709: my $filename;
710: my $curtime=time;
711: while ($filename=readdir(LONIDS)) {
1.925 albertel 712: next if ($filename eq '.' || $filename eq '..');
713: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 714: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 715: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 716: }
717: closedir(LONIDS);
718: }
719: my $userloadpercent=0;
720: my $maxuserload=$perlvar{'lonUserLoadLim'};
721: if ($maxuserload) {
1.371 albertel 722: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 723: }
1.372 albertel 724: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 725: return $userloadpercent;
1.283 www 726: }
727:
1.1 albertel 728: # ------------------------------ Find server with least workload from spare.tab
1.11 www 729:
1.1 albertel 730: sub spareserver {
1.1083 raeburn 731: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 732: my $spare_server;
1.370 albertel 733: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 734: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
735: : $userloadpercent;
1.1083 raeburn 736: my ($uint_dom,$remotesessions);
737: if (($udom ne '') && (&domain($udom) ne '')) {
738: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
739: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
740: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
741: $remotesessions = $udomdefaults{'remotesessions'};
742: }
1.784 albertel 743: foreach my $try_server (@{ $spareid{'primary'} }) {
1.1083 raeburn 744: if ($uint_dom) {
745: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
746: $try_server));
747: }
1.784 albertel 748: ($spare_server, $lowest_load) =
749: &compare_server_load($try_server, $spare_server, $lowest_load);
750: }
751:
752: my $found_server = ($spare_server ne '' && $lowest_load < 100);
753:
754: if (!$found_server) {
755: foreach my $try_server (@{ $spareid{'default'} }) {
1.1083 raeburn 756: if ($uint_dom) {
757: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
758: $try_server));
759: }
1.784 albertel 760: ($spare_server, $lowest_load) =
761: &compare_server_load($try_server, $spare_server, $lowest_load);
762: }
763: }
764:
765: if (!$want_server_name) {
1.968 raeburn 766: my $protocol = 'http';
767: if ($protocol{$spare_server} eq 'https') {
768: $protocol = $protocol{$spare_server};
769: }
1.1001 raeburn 770: if (defined($spare_server)) {
771: my $hostname = &hostname($spare_server);
1.1083 raeburn 772: if (defined($hostname)) {
1.1001 raeburn 773: $spare_server = $protocol.'://'.$hostname;
774: }
775: }
1.784 albertel 776: }
777: return $spare_server;
778: }
779:
780: sub compare_server_load {
781: my ($try_server, $spare_server, $lowest_load) = @_;
782:
783: my $loadans = &reply('load', $try_server);
784: my $userloadans = &reply('userload',$try_server);
785:
786: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1072 www 787: return; #didn't get a number from the server
1.784 albertel 788: }
789:
790: my $load;
791: if ($loadans =~ /\d/) {
792: if ($userloadans =~ /\d/) {
793: #both are numbers, pick the bigger one
794: $load = ($loadans > $userloadans) ? $loadans
795: : $userloadans;
1.411 albertel 796: } else {
1.784 albertel 797: $load = $loadans;
1.411 albertel 798: }
1.784 albertel 799: } else {
800: $load = $userloadans;
801: }
802:
803: if (($load =~ /\d/) && ($load < $lowest_load)) {
804: $spare_server = $try_server;
805: $lowest_load = $load;
1.370 albertel 806: }
1.784 albertel 807: return ($spare_server,$lowest_load);
1.202 matthew 808: }
1.914 albertel 809:
810: # --------------------------- ask offload servers if user already has a session
811: sub find_existing_session {
812: my ($udom,$uname) = @_;
813: foreach my $try_server (@{ $spareid{'primary'} },
814: @{ $spareid{'default'} }) {
815: return $try_server if (&has_user_session($try_server, $udom, $uname));
816: }
817: return;
818: }
819:
820: # -------------------------------- ask if server already has a session for user
821: sub has_user_session {
822: my ($lonid,$udom,$uname) = @_;
823: my $result = &reply(join(':','userhassession',
824: map {&escape($_)} ($udom,$uname)),$lonid);
825: return 1 if ($result eq 'ok');
826:
827: return 0;
828: }
829:
1.1076 raeburn 830: # --------- determine least loaded server in a user's domain which allows login
831:
832: sub choose_server {
833: my ($udom) = @_;
834: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 835: my %servers = &get_servers($udom);
1.1076 raeburn 836: my $lowest_load = 30000;
837: my ($login_host,$hostname);
838: foreach my $lonhost (keys(%servers)) {
839: my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
840: if ($loginvia eq '') {
841: ($login_host, $lowest_load) =
842: &compare_server_load($lonhost, $login_host, $lowest_load);
843: }
844: }
845: if ($login_host ne '') {
846: $hostname = $servers{$login_host};
847: }
848: return ($login_host,$hostname);
849: }
850:
1.202 matthew 851: # --------------------------------------------- Try to change a user's password
852:
853: sub changepass {
1.799 raeburn 854: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 855: $currentpass = &escape($currentpass);
856: $newpass = &escape($newpass);
1.1030 raeburn 857: my $lonhost = $perlvar{'lonHostID'};
858: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 859: $server);
860: if (! $answer) {
861: &logthis("No reply on password change request to $server ".
862: "by $uname in domain $udom.");
863: } elsif ($answer =~ "^ok") {
864: &logthis("$uname in $udom successfully changed their password ".
865: "on $server.");
866: } elsif ($answer =~ "^pwchange_failure") {
867: &logthis("$uname in $udom was unable to change their password ".
868: "on $server. The action was blocked by either lcpasswd ".
869: "or pwchange");
870: } elsif ($answer =~ "^non_authorized") {
871: &logthis("$uname in $udom did not get their password correct when ".
872: "attempting to change it on $server.");
873: } elsif ($answer =~ "^auth_mode_error") {
874: &logthis("$uname in $udom attempted to change their password despite ".
875: "not being locally or internally authenticated on $server.");
876: } elsif ($answer =~ "^unknown_user") {
877: &logthis("$uname in $udom attempted to change their password ".
878: "on $server but were unable to because $server is not ".
879: "their home server.");
880: } elsif ($answer =~ "^refused") {
881: &logthis("$server refused to change $uname in $udom password because ".
882: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 883: } elsif ($answer =~ "invalid_client") {
884: &logthis("$server refused to change $uname in $udom password because ".
885: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 886: }
887: return $answer;
1.1 albertel 888: }
889:
1.169 harris41 890: # ----------------------- Try to determine user's current authentication scheme
891:
892: sub queryauthenticate {
893: my ($uname,$udom)=@_;
1.456 albertel 894: my $uhome=&homeserver($uname,$udom);
895: if (!$uhome) {
896: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
897: return 'no_host';
898: }
899: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
900: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
901: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 902: }
1.456 albertel 903: return $answer;
1.169 harris41 904: }
905:
1.1 albertel 906: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 907:
1.1 albertel 908: sub authenticate {
1.1073 raeburn 909: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 910: $upass=&escape($upass);
911: $uname= &LONCAPA::clean_username($uname);
1.836 www 912: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 913: my $newhome;
1.836 www 914: if ((!$uhome) || ($uhome eq 'no_host')) {
915: # Maybe the machine was offline and only re-appeared again recently?
916: &reconlonc();
917: # One more
1.952 raeburn 918: $uhome=&homeserver($uname,$udom,1);
919: if (($uhome eq 'no_host') && $checkdefauth) {
920: if (defined(&domain($udom,'primary'))) {
921: $newhome=&domain($udom,'primary');
922: }
923: if ($newhome ne '') {
924: $uhome = $newhome;
925: }
926: }
1.836 www 927: if ((!$uhome) || ($uhome eq 'no_host')) {
928: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 929: return 'no_host';
930: }
1.1 albertel 931: }
1.1073 raeburn 932: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 933: if ($answer eq 'authorized') {
1.952 raeburn 934: if ($newhome) {
935: &logthis("User $uname at $udom authorized by $uhome, but needs account");
936: return 'no_account_on_host';
937: } else {
938: &logthis("User $uname at $udom authorized by $uhome");
939: return $uhome;
940: }
1.471 albertel 941: }
942: if ($answer eq 'non_authorized') {
943: &logthis("User $uname at $udom rejected by $uhome");
944: return 'no_host';
1.9 www 945: }
1.471 albertel 946: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 947: return 'no_host';
948: }
949:
1.1073 raeburn 950: sub can_host_session {
1.1074 raeburn 951: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 952: my $canhost = 1;
1.1074 raeburn 953: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 954: if (ref($remotesessions) eq 'HASH') {
955: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 956: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 957: $canhost = 0;
958: } else {
959: $canhost = 1;
960: }
961: }
962: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 963: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 964: $canhost = 1;
965: } else {
966: $canhost = 0;
967: }
968: }
969: if ($canhost) {
970: if ($remotesessions->{'version'} ne '') {
971: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
972: if ($reqmajor ne '' && $reqminor ne '') {
973: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
974: my $major = $1;
975: my $minor = $2;
976: if (($major < $reqmajor ) ||
977: (($major == $reqmajor) && ($minor < $reqminor))) {
978: $canhost = 0;
979: }
980: } else {
981: $canhost = 0;
982: }
983: }
984: }
985: }
986: }
987: if ($canhost) {
988: if (ref($hostedsessions) eq 'HASH') {
989: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
990: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
991: $canhost = 0;
992: } else {
993: $canhost = 1;
994: }
995: }
996: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
997: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
998: $canhost = 1;
999: } else {
1000: $canhost = 0;
1001: }
1002: }
1003: }
1004: }
1005: return $canhost;
1006: }
1007:
1.1083 raeburn 1008: sub spare_can_host {
1009: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1010: my $canhost=1;
1011: my @intdoms;
1012: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1013: if (ref($internet_names) eq 'ARRAY') {
1014: @intdoms = @{$internet_names};
1015: }
1016: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1017: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1018: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1019: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1020: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1021: $canhost = &can_host_session($udom,$try_server,$remoterev,
1022: $remotesessions,
1023: $defdomdefaults{'hostedsessions'});
1024: }
1025: return $canhost;
1026: }
1027:
1.1 albertel 1028: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1029:
1.599 albertel 1030: my %homecache;
1.1 albertel 1031: sub homeserver {
1.230 stredwic 1032: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1033: my $index="$uname:$udom";
1.426 albertel 1034:
1.599 albertel 1035: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1036:
1037: my %servers = &get_servers($udom,'library');
1038: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1039: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1040: exists($badServerCache{$tryserver}));
1.841 albertel 1041:
1042: my $answer=reply("home:$udom:$uname",$tryserver);
1043: if ($answer eq 'found') {
1044: delete($badServerCache{$tryserver});
1045: return $homecache{$index}=$tryserver;
1046: } elsif ($answer eq 'no_host') {
1047: $badServerCache{$tryserver}=1;
1048: }
1.1 albertel 1049: }
1050: return 'no_host';
1.70 www 1051: }
1052:
1053: # ------------------------------------- Find the usernames behind a list of IDs
1054:
1055: sub idget {
1056: my ($udom,@ids)=@_;
1057: my %returnhash=();
1058:
1.841 albertel 1059: my %servers = &get_servers($udom,'library');
1060: foreach my $tryserver (keys(%servers)) {
1061: my $idlist=join('&',@ids);
1062: $idlist=~tr/A-Z/a-z/;
1063: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1064: my @answer=();
1065: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1066: @answer=split(/\&/,$reply);
1067: } ;
1068: my $i;
1069: for ($i=0;$i<=$#ids;$i++) {
1070: if ($answer[$i]) {
1071: $returnhash{$ids[$i]}=$answer[$i];
1072: }
1073: }
1074: }
1.70 www 1075: return %returnhash;
1076: }
1077:
1078: # ------------------------------------- Find the IDs behind a list of usernames
1079:
1080: sub idrget {
1081: my ($udom,@unames)=@_;
1082: my %returnhash=();
1.800 albertel 1083: foreach my $uname (@unames) {
1084: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1085: }
1.70 www 1086: return %returnhash;
1087: }
1088:
1089: # ------------------------------- Store away a list of names and associated IDs
1090:
1091: sub idput {
1092: my ($udom,%ids)=@_;
1093: my %servers=();
1.800 albertel 1094: foreach my $uname (keys(%ids)) {
1095: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1096: my $uhom=&homeserver($uname,$udom);
1.70 www 1097: if ($uhom ne 'no_host') {
1.800 albertel 1098: my $id=&escape($ids{$uname});
1.70 www 1099: $id=~tr/A-Z/a-z/;
1.800 albertel 1100: my $esc_unam=&escape($uname);
1.70 www 1101: if ($servers{$uhom}) {
1.800 albertel 1102: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1103: } else {
1.800 albertel 1104: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1105: }
1106: }
1.191 harris41 1107: }
1.800 albertel 1108: foreach my $server (keys(%servers)) {
1109: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1110: }
1.344 www 1111: }
1112:
1.1023 raeburn 1113: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1114: sub dump_dom {
1.1023 raeburn 1115: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1116: if (!$udom) {
1117: $udom=$env{'user.domain'};
1118: }
1119: my %returnhash;
1.1023 raeburn 1120: if ($udom) {
1121: my $uname = &get_domainconfiguser($udom);
1122: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1123: }
1124: return %returnhash;
1125: }
1126:
1.1023 raeburn 1127: # ------------------------------------------ get items from domain db files
1.806 raeburn 1128:
1129: sub get_dom {
1.860 raeburn 1130: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1131: my $items='';
1132: foreach my $item (@$storearr) {
1133: $items.=&escape($item).'&';
1134: }
1135: $items=~s/\&$//;
1.860 raeburn 1136: if (!$udom) {
1137: $udom=$env{'user.domain'};
1138: if (defined(&domain($udom,'primary'))) {
1139: $uhome=&domain($udom,'primary');
1140: } else {
1.874 albertel 1141: undef($uhome);
1.860 raeburn 1142: }
1143: } else {
1144: if (!$uhome) {
1145: if (defined(&domain($udom,'primary'))) {
1146: $uhome=&domain($udom,'primary');
1147: }
1148: }
1149: }
1150: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1151: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1152: my %returnhash;
1.875 albertel 1153: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1154: return %returnhash;
1155: }
1.806 raeburn 1156: my @pairs=split(/\&/,$rep);
1157: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1158: return @pairs;
1159: }
1160: my $i=0;
1161: foreach my $item (@$storearr) {
1162: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1163: $i++;
1164: }
1165: return %returnhash;
1166: } else {
1.880 banghart 1167: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1168: }
1169: }
1170:
1171: # -------------------------------------------- put items in domain db files
1172:
1173: sub put_dom {
1.860 raeburn 1174: my ($namespace,$storehash,$udom,$uhome)=@_;
1175: if (!$udom) {
1176: $udom=$env{'user.domain'};
1177: if (defined(&domain($udom,'primary'))) {
1178: $uhome=&domain($udom,'primary');
1179: } else {
1.874 albertel 1180: undef($uhome);
1.860 raeburn 1181: }
1182: } else {
1183: if (!$uhome) {
1184: if (defined(&domain($udom,'primary'))) {
1185: $uhome=&domain($udom,'primary');
1186: }
1187: }
1188: }
1189: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1190: my $items='';
1191: foreach my $item (keys(%$storehash)) {
1192: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1193: }
1194: $items=~s/\&$//;
1195: return &reply("putdom:$udom:$namespace:$items",$uhome);
1196: } else {
1.860 raeburn 1197: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1198: }
1199: }
1200:
1.1023 raeburn 1201: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1202: sub newput_dom {
1.1023 raeburn 1203: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1204: my $result;
1205: if (!$udom) {
1206: $udom=$env{'user.domain'};
1207: }
1.1023 raeburn 1208: if ($udom) {
1209: my $uname = &get_domainconfiguser($udom);
1210: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1211: }
1212: return $result;
1213: }
1214:
1.1023 raeburn 1215: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1216: sub del_dom {
1.1023 raeburn 1217: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1218: if (ref($storearr) eq 'ARRAY') {
1219: if (!$udom) {
1220: $udom=$env{'user.domain'};
1221: }
1.1023 raeburn 1222: if ($udom) {
1223: my $uname = &get_domainconfiguser($udom);
1224: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1225: }
1226: }
1227: }
1228:
1.1023 raeburn 1229: # ----------------------------------construct domainconfig user for a domain
1230: sub get_domainconfiguser {
1231: my ($udom) = @_;
1232: return $udom.'-domainconfig';
1233: }
1234:
1.837 raeburn 1235: sub retrieve_inst_usertypes {
1236: my ($udom) = @_;
1237: my (%returnhash,@order);
1.989 raeburn 1238: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1239: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1240: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1241: %returnhash = %{$domdefs{'inststatustypes'}};
1242: @order = @{$domdefs{'inststatusorder'}};
1243: } else {
1244: if (defined(&domain($udom,'primary'))) {
1245: my $uhome=&domain($udom,'primary');
1246: my $rep=&reply("inst_usertypes:$udom",$uhome);
1247: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1248: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1249: return (\%returnhash,\@order);
1250: }
1251: my ($hashitems,$orderitems) = split(/:/,$rep);
1252: my @pairs=split(/\&/,$hashitems);
1253: foreach my $item (@pairs) {
1254: my ($key,$value)=split(/=/,$item,2);
1255: $key = &unescape($key);
1256: next if ($key =~ /^error: 2 /);
1257: $returnhash{$key}=&thaw_unescape($value);
1258: }
1259: my @esc_order = split(/\&/,$orderitems);
1260: foreach my $item (@esc_order) {
1261: push(@order,&unescape($item));
1262: }
1263: } else {
1264: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1265: }
1266: }
1267: return (\%returnhash,\@order);
1268: }
1269:
1.868 raeburn 1270: sub is_domainimage {
1271: my ($url) = @_;
1272: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1273: if (&domain($1) ne '') {
1274: return '1';
1275: }
1276: }
1277: return;
1278: }
1279:
1.899 raeburn 1280: sub inst_directory_query {
1281: my ($srch) = @_;
1282: my $udom = $srch->{'srchdomain'};
1283: my %results;
1284: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1285: my $outcome;
1.899 raeburn 1286: if ($homeserver ne '') {
1.904 albertel 1287: my $queryid=&reply("querysend:instdirsearch:".
1288: &escape($srch->{'srchby'}).':'.
1289: &escape($srch->{'srchterm'}).':'.
1290: &escape($srch->{'srchtype'}),$homeserver);
1291: my $host=&hostname($homeserver);
1292: if ($queryid !~/^\Q$host\E\_/) {
1293: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1294: return;
1295: }
1296: my $response = &get_query_reply($queryid);
1297: my $maxtries = 5;
1298: my $tries = 1;
1299: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1300: $response = &get_query_reply($queryid);
1301: $tries ++;
1302: }
1303:
1304: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1305: if ($response eq 'unavailable') {
1306: $outcome = $response;
1307: } else {
1308: $outcome = 'ok';
1309: my @matches = split(/\n/,$response);
1310: foreach my $match (@matches) {
1311: my ($key,$value) = split(/=/,$match);
1312: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1313: }
1.899 raeburn 1314: }
1315: }
1316: }
1.909 raeburn 1317: return ($outcome,%results);
1.899 raeburn 1318: }
1319:
1320: sub usersearch {
1321: my ($srch) = @_;
1322: my $dom = $srch->{'srchdomain'};
1323: my %results;
1324: my %libserv = &all_library();
1325: my $query = 'usersearch';
1326: foreach my $tryserver (keys(%libserv)) {
1327: if (&host_domain($tryserver) eq $dom) {
1328: my $host=&hostname($tryserver);
1329: my $queryid=
1.911 raeburn 1330: &reply("querysend:".&escape($query).':'.
1331: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1332: &escape($srch->{'srchtype'}).':'.
1333: &escape($srch->{'srchterm'}),$tryserver);
1334: if ($queryid !~/^\Q$host\E\_/) {
1335: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1336: next;
1.899 raeburn 1337: }
1338: my $reply = &get_query_reply($queryid);
1339: my $maxtries = 1;
1340: my $tries = 1;
1341: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1342: $reply = &get_query_reply($queryid);
1343: $tries ++;
1344: }
1345: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1346: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1347: } else {
1.911 raeburn 1348: my @matches;
1349: if ($reply =~ /\n/) {
1350: @matches = split(/\n/,$reply);
1351: } else {
1352: @matches = split(/\&/,$reply);
1353: }
1.899 raeburn 1354: foreach my $match (@matches) {
1355: my ($uname,$udom,%userhash);
1.911 raeburn 1356: foreach my $entry (split(/:/,$match)) {
1357: my ($key,$value) =
1358: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1359: $userhash{$key} = $value;
1360: if ($key eq 'username') {
1361: $uname = $value;
1362: } elsif ($key eq 'domain') {
1363: $udom = $value;
1.911 raeburn 1364: }
1.899 raeburn 1365: }
1366: $results{$uname.':'.$udom} = \%userhash;
1367: }
1368: }
1369: }
1370: }
1371: return %results;
1372: }
1373:
1.912 raeburn 1374: sub get_instuser {
1375: my ($udom,$uname,$id) = @_;
1376: my $homeserver = &domain($udom,'primary');
1377: my ($outcome,%results);
1378: if ($homeserver ne '') {
1379: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1380: &escape($id).':'.&escape($udom),$homeserver);
1381: my $host=&hostname($homeserver);
1382: if ($queryid !~/^\Q$host\E\_/) {
1383: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1384: return;
1385: }
1386: my $response = &get_query_reply($queryid);
1387: my $maxtries = 5;
1388: my $tries = 1;
1389: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1390: $response = &get_query_reply($queryid);
1391: $tries ++;
1392: }
1393: if (!&error($response) && $response ne 'refused') {
1394: if ($response eq 'unavailable') {
1395: $outcome = $response;
1396: } else {
1397: $outcome = 'ok';
1398: my @matches = split(/\n/,$response);
1399: foreach my $match (@matches) {
1400: my ($key,$value) = split(/=/,$match);
1401: $results{&unescape($key)} = &thaw_unescape($value);
1402: }
1403: }
1404: }
1405: }
1406: my %userinfo;
1407: if (ref($results{$uname}) eq 'HASH') {
1408: %userinfo = %{$results{$uname}};
1409: }
1410: return ($outcome,%userinfo);
1411: }
1412:
1413: sub inst_rulecheck {
1.923 raeburn 1414: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1415: my %returnhash;
1416: if ($udom ne '') {
1417: if (ref($rules) eq 'ARRAY') {
1418: @{$rules} = map {&escape($_);} (@{$rules});
1419: my $rulestr = join(':',@{$rules});
1420: my $homeserver=&domain($udom,'primary');
1421: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1422: my $response;
1423: if ($item eq 'username') {
1424: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1425: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1426: $homeserver));
1.923 raeburn 1427: } elsif ($item eq 'id') {
1428: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1429: ':'.&escape($id).':'.$rulestr,
1430: $homeserver));
1.945 raeburn 1431: } elsif ($item eq 'selfcreate') {
1432: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1433: &escape($udom).':'.&escape($uname).
1434: ':'.$rulestr,$homeserver));
1.923 raeburn 1435: }
1.912 raeburn 1436: if ($response ne 'refused') {
1437: my @pairs=split(/\&/,$response);
1438: foreach my $item (@pairs) {
1439: my ($key,$value)=split(/=/,$item,2);
1440: $key = &unescape($key);
1441: next if ($key =~ /^error: 2 /);
1442: $returnhash{$key}=&thaw_unescape($value);
1443: }
1444: }
1445: }
1446: }
1447: }
1448: return %returnhash;
1449: }
1450:
1451: sub inst_userrules {
1.923 raeburn 1452: my ($udom,$check) = @_;
1.912 raeburn 1453: my (%ruleshash,@ruleorder);
1454: if ($udom ne '') {
1455: my $homeserver=&domain($udom,'primary');
1456: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1457: my $response;
1458: if ($check eq 'id') {
1459: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1460: $homeserver);
1.943 raeburn 1461: } elsif ($check eq 'email') {
1462: $response=&reply('instemailrules:'.&escape($udom),
1463: $homeserver);
1.923 raeburn 1464: } else {
1465: $response=&reply('instuserrules:'.&escape($udom),
1466: $homeserver);
1467: }
1.912 raeburn 1468: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1469: ($response ne 'unknown_cmd') &&
1.912 raeburn 1470: ($response ne 'no_such_host')) {
1471: my ($hashitems,$orderitems) = split(/:/,$response);
1472: my @pairs=split(/\&/,$hashitems);
1473: foreach my $item (@pairs) {
1474: my ($key,$value)=split(/=/,$item,2);
1475: $key = &unescape($key);
1476: next if ($key =~ /^error: 2 /);
1477: $ruleshash{$key}=&thaw_unescape($value);
1478: }
1479: my @esc_order = split(/\&/,$orderitems);
1480: foreach my $item (@esc_order) {
1481: push(@ruleorder,&unescape($item));
1482: }
1483: }
1484: }
1485: }
1486: return (\%ruleshash,\@ruleorder);
1487: }
1488:
1.976 raeburn 1489: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1490:
1491: sub get_domain_defaults {
1492: my ($domain) = @_;
1493: my $cachetime = 60*60*24;
1494: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1495: if (defined($cached)) {
1496: if (ref($result) eq 'HASH') {
1497: return %{$result};
1498: }
1499: }
1500: my %domdefaults;
1501: my %domconfig =
1.989 raeburn 1502: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1503: 'requestcourses','inststatus',
1.1073 raeburn 1504: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1505: if (ref($domconfig{'defaults'}) eq 'HASH') {
1506: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1507: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1508: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1509: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1510: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1511: } else {
1512: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1513: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1514: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1515: }
1.976 raeburn 1516: if (ref($domconfig{'quotas'}) eq 'HASH') {
1517: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1518: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1519: } else {
1520: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1521: }
1522: my @usertools = ('aboutme','blog','portfolio');
1523: foreach my $item (@usertools) {
1524: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1525: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1526: }
1527: }
1528: }
1.985 raeburn 1529: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1530: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1531: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1532: }
1533: }
1.989 raeburn 1534: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1535: foreach my $item ('inststatustypes','inststatusorder') {
1536: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1537: }
1538: }
1.1047 raeburn 1539: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1540: foreach my $item ('canuse_pdfforms') {
1541: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1542: }
1543: }
1.1073 raeburn 1544: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1545: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1546: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1547: }
1548: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1549: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1550: }
1551: }
1.943 raeburn 1552: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1553: $cachetime);
1554: return %domdefaults;
1555: }
1556:
1.344 www 1557: # --------------------------------------------------- Assign a key to a student
1558:
1559: sub assign_access_key {
1.364 www 1560: #
1561: # a valid key looks like uname:udom#comments
1562: # comments are being appended
1563: #
1.498 www 1564: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1565: $kdom=
1.620 albertel 1566: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1567: $knum=
1.620 albertel 1568: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1569: $cdom=
1.620 albertel 1570: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1571: $cnum=
1.620 albertel 1572: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1573: $udom=$env{'user.name'} unless (defined($udom));
1574: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1575: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1576: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1577: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1578: # assigned to this person
1579: # - this should not happen,
1.345 www 1580: # unless something went wrong
1581: # the first time around
1582: # ready to assign
1.364 www 1583: $logentry=$1.'; '.$logentry;
1.496 www 1584: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1585: $kdom,$knum) eq 'ok') {
1.345 www 1586: # key now belongs to user
1.346 www 1587: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1588: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1589: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1590: return 'ok';
1591: } else {
1592: return
1593: 'error: Count not permanently assign key, will need to be re-entered later.';
1594: }
1595: } else {
1596: return 'error: Could not assign key, try again later.';
1597: }
1.364 www 1598: } elsif (!$existing{$ckey}) {
1.345 www 1599: # the key does not exist
1600: return 'error: The key does not exist';
1601: } else {
1602: # the key is somebody else's
1603: return 'error: The key is already in use';
1604: }
1.344 www 1605: }
1606:
1.364 www 1607: # ------------------------------------------ put an additional comment on a key
1608:
1609: sub comment_access_key {
1610: #
1611: # a valid key looks like uname:udom#comments
1612: # comments are being appended
1613: #
1614: my ($ckey,$cdom,$cnum,$logentry)=@_;
1615: $cdom=
1.620 albertel 1616: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1617: $cnum=
1.620 albertel 1618: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1619: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1620: if ($existing{$ckey}) {
1621: $existing{$ckey}.='; '.$logentry;
1622: # ready to assign
1.367 www 1623: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1624: $cdom,$cnum) eq 'ok') {
1625: return 'ok';
1626: } else {
1627: return 'error: Count not store comment.';
1628: }
1629: } else {
1630: # the key does not exist
1631: return 'error: The key does not exist';
1632: }
1633: }
1634:
1.344 www 1635: # ------------------------------------------------------ Generate a set of keys
1636:
1637: sub generate_access_keys {
1.364 www 1638: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1639: $cdom=
1.620 albertel 1640: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1641: $cnum=
1.620 albertel 1642: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1643: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1644: unless (($cdom) && ($cnum)) { return 0; }
1645: if ($number>10000) { return 0; }
1646: sleep(2); # make sure don't get same seed twice
1647: srand(time()^($$+($$<<15))); # from "Programming Perl"
1648: my $total=0;
1649: for (my $i=1;$i<=$number;$i++) {
1650: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1651: sprintf("%lx",int(100000*rand)).'-'.
1652: sprintf("%lx",int(100000*rand));
1653: $newkey=~s/1/g/g; # folks mix up 1 and l
1654: $newkey=~s/0/h/g; # and also 0 and O
1655: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1656: if ($existing{$newkey}) {
1657: $i--;
1658: } else {
1.364 www 1659: if (&put('accesskeys',
1660: { $newkey => '# generated '.localtime().
1.620 albertel 1661: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1662: '; '.$logentry },
1663: $cdom,$cnum) eq 'ok') {
1.344 www 1664: $total++;
1665: }
1666: }
1667: }
1.620 albertel 1668: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1669: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1670: return $total;
1671: }
1672:
1673: # ------------------------------------------------------- Validate an accesskey
1674:
1675: sub validate_access_key {
1676: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1677: $cdom=
1.620 albertel 1678: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1679: $cnum=
1.620 albertel 1680: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1681: $udom=$env{'user.domain'} unless (defined($udom));
1682: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1683: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1684: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1685: }
1686:
1687: # ------------------------------------- Find the section of student in a course
1.652 albertel 1688: sub devalidate_getsection_cache {
1689: my ($udom,$unam,$courseid)=@_;
1690: my $hashid="$udom:$unam:$courseid";
1691: &devalidate_cache_new('getsection',$hashid);
1692: }
1.298 matthew 1693:
1.815 albertel 1694: sub courseid_to_courseurl {
1695: my ($courseid) = @_;
1696: #already url style courseid
1697: return $courseid if ($courseid =~ m{^/});
1698:
1699: if (exists($env{'course.'.$courseid.'.num'})) {
1700: my $cnum = $env{'course.'.$courseid.'.num'};
1701: my $cdom = $env{'course.'.$courseid.'.domain'};
1702: return "/$cdom/$cnum";
1703: }
1704:
1705: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1706: if (exists($courseinfo{'num'})) {
1707: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1708: }
1709:
1710: return undef;
1711: }
1712:
1.298 matthew 1713: sub getsection {
1714: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1715: my $cachetime=1800;
1.551 albertel 1716:
1717: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1718: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1719: if (defined($cached)) { return $result; }
1720:
1.298 matthew 1721: my %Pending;
1722: my %Expired;
1723: #
1724: # Each role can either have not started yet (pending), be active,
1725: # or have expired.
1726: #
1727: # If there is an active role, we are done.
1728: #
1729: # If there is more than one role which has not started yet,
1730: # choose the one which will start sooner
1731: # If there is one role which has not started yet, return it.
1732: #
1733: # If there is more than one expired role, choose the one which ended last.
1734: # If there is a role which has expired, return it.
1735: #
1.815 albertel 1736: $courseid = &courseid_to_courseurl($courseid);
1.1086 raeburn 1737: my $extra = &freeze_escape({'skipcheck' => 1});
1738: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 1739: foreach my $key (keys(%roleshash)) {
1.479 albertel 1740: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1741: my $section=$1;
1742: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1743: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1744: my $now=time;
1.548 albertel 1745: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1746: $Expired{$end}=$section;
1747: next;
1748: }
1.548 albertel 1749: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1750: $Pending{$start}=$section;
1751: next;
1752: }
1.599 albertel 1753: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1754: }
1755: #
1756: # Presumedly there will be few matching roles from the above
1757: # loop and the sorting time will be negligible.
1758: if (scalar(keys(%Pending))) {
1759: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1760: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1761: }
1762: if (scalar(keys(%Expired))) {
1763: my @sorted = sort {$a <=> $b} keys(%Expired);
1764: my $time = pop(@sorted);
1.599 albertel 1765: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1766: }
1.599 albertel 1767: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1768: }
1.70 www 1769:
1.599 albertel 1770: sub save_cache {
1771: &purge_remembered();
1.722 albertel 1772: #&Apache::loncommon::validate_page();
1.620 albertel 1773: undef(%env);
1.780 albertel 1774: undef($env_loaded);
1.599 albertel 1775: }
1.452 albertel 1776:
1.599 albertel 1777: my $to_remember=-1;
1778: my %remembered;
1779: my %accessed;
1780: my $kicks=0;
1781: my $hits=0;
1.849 albertel 1782: sub make_key {
1783: my ($name,$id) = @_;
1.872 albertel 1784: if (length($id) > 65
1785: && length(&escape($id)) > 200) {
1786: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1787: }
1.849 albertel 1788: return &escape($name.':'.$id);
1789: }
1790:
1.599 albertel 1791: sub devalidate_cache_new {
1792: my ($name,$id,$debug) = @_;
1793: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1794: $id=&make_key($name,$id);
1.599 albertel 1795: $memcache->delete($id);
1796: delete($remembered{$id});
1797: delete($accessed{$id});
1798: }
1799:
1800: sub is_cached_new {
1801: my ($name,$id,$debug) = @_;
1.849 albertel 1802: $id=&make_key($name,$id);
1.599 albertel 1803: if (exists($remembered{$id})) {
1804: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1805: $accessed{$id}=[&gettimeofday()];
1806: $hits++;
1807: return ($remembered{$id},1);
1808: }
1809: my $value = $memcache->get($id);
1810: if (!(defined($value))) {
1811: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1812: return (undef,undef);
1.416 albertel 1813: }
1.599 albertel 1814: if ($value eq '__undef__') {
1815: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1816: $value=undef;
1817: }
1818: &make_room($id,$value,$debug);
1819: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1820: return ($value,1);
1821: }
1822:
1823: sub do_cache_new {
1824: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1825: $id=&make_key($name,$id);
1.599 albertel 1826: my $setvalue=$value;
1827: if (!defined($setvalue)) {
1828: $setvalue='__undef__';
1829: }
1.623 albertel 1830: if (!defined($time) ) {
1831: $time=600;
1832: }
1.599 albertel 1833: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1834: my $result = $memcache->set($id,$setvalue,$time);
1835: if (! $result) {
1.872 albertel 1836: &logthis("caching of id -> $id failed");
1.910 albertel 1837: $memcache->disconnect_all();
1.872 albertel 1838: }
1.600 albertel 1839: # need to make a copy of $value
1.919 albertel 1840: &make_room($id,$value,$debug);
1.599 albertel 1841: return $value;
1842: }
1843:
1844: sub make_room {
1845: my ($id,$value,$debug)=@_;
1.919 albertel 1846:
1847: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1848: : $value;
1.599 albertel 1849: if ($to_remember<0) { return; }
1850: $accessed{$id}=[&gettimeofday()];
1851: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1852: my $to_kick;
1853: my $max_time=0;
1854: foreach my $other (keys(%accessed)) {
1855: if (&tv_interval($accessed{$other}) > $max_time) {
1856: $to_kick=$other;
1857: $max_time=&tv_interval($accessed{$other});
1858: }
1859: }
1860: delete($remembered{$to_kick});
1861: delete($accessed{$to_kick});
1862: $kicks++;
1863: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1864: return;
1865: }
1866:
1.599 albertel 1867: sub purge_remembered {
1.604 albertel 1868: #&logthis("Tossing ".scalar(keys(%remembered)));
1869: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1870: undef(%remembered);
1871: undef(%accessed);
1.428 albertel 1872: }
1.70 www 1873: # ------------------------------------- Read an entry from a user's environment
1874:
1875: sub userenvironment {
1876: my ($udom,$unam,@what)=@_;
1.976 raeburn 1877: my $items;
1878: foreach my $item (@what) {
1879: $items.=&escape($item).'&';
1880: }
1881: $items=~s/\&$//;
1.70 www 1882: my %returnhash=();
1.1009 raeburn 1883: my $uhome = &homeserver($unam,$udom);
1884: unless ($uhome eq 'no_host') {
1885: my @answer=split(/\&/,
1886: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1887: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1888: return %returnhash;
1889: }
1.1009 raeburn 1890: my $i;
1891: for ($i=0;$i<=$#what;$i++) {
1892: $returnhash{$what[$i]}=&unescape($answer[$i]);
1893: }
1.70 www 1894: }
1895: return %returnhash;
1.1 albertel 1896: }
1897:
1.617 albertel 1898: # ---------------------------------------------------------- Get a studentphoto
1899: sub studentphoto {
1900: my ($udom,$unam,$ext) = @_;
1901: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1902: if (defined($env{'request.course.id'})) {
1.708 raeburn 1903: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1904: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1905: return(&retrievestudentphoto($udom,$unam,$ext));
1906: } else {
1907: my ($result,$perm_reqd)=
1.707 albertel 1908: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1909: if ($result eq 'ok') {
1910: if (!($perm_reqd eq 'yes')) {
1911: return(&retrievestudentphoto($udom,$unam,$ext));
1912: }
1913: }
1914: }
1915: }
1916: } else {
1917: my ($result,$perm_reqd) =
1.707 albertel 1918: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1919: if ($result eq 'ok') {
1920: if (!($perm_reqd eq 'yes')) {
1921: return(&retrievestudentphoto($udom,$unam,$ext));
1922: }
1923: }
1924: }
1925: return '/adm/lonKaputt/lonlogo_broken.gif';
1926: }
1927:
1928: sub retrievestudentphoto {
1929: my ($udom,$unam,$ext,$type) = @_;
1930: my $home=&Apache::lonnet::homeserver($unam,$udom);
1931: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1932: if ($ret eq 'ok') {
1933: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1934: if ($type eq 'thumbnail') {
1935: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1936: }
1937: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1938: return $tokenurl;
1939: } else {
1940: if ($type eq 'thumbnail') {
1941: return '/adm/lonKaputt/genericstudent_tn.gif';
1942: } else {
1943: return '/adm/lonKaputt/lonlogo_broken.gif';
1944: }
1.617 albertel 1945: }
1946: }
1947:
1.263 www 1948: # -------------------------------------------------------------------- New chat
1949:
1950: sub chatsend {
1.724 raeburn 1951: my ($newentry,$anon,$group)=@_;
1.620 albertel 1952: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1953: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1954: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1955: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1956: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1957: &escape($newentry)).':'.$group,$chome);
1.292 www 1958: }
1959:
1960: # ------------------------------------------ Find current version of a resource
1961:
1962: sub getversion {
1963: my $fname=&clutter(shift);
1964: unless ($fname=~/^\/res\//) { return -1; }
1965: return ¤tversion(&filelocation('',$fname));
1966: }
1967:
1968: sub currentversion {
1969: my $fname=shift;
1.599 albertel 1970: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1971: if (defined($cached)) { return $result; }
1.292 www 1972: my $author=$fname;
1973: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1974: my ($udom,$uname)=split(/\//,$author);
1975: my $home=homeserver($uname,$udom);
1976: if ($home eq 'no_host') {
1977: return -1;
1978: }
1979: my $answer=reply("currentversion:$fname",$home);
1980: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1981: return -1;
1982: }
1.599 albertel 1983: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1984: }
1985:
1.1 albertel 1986: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1987:
1.1 albertel 1988: sub subscribe {
1989: my $fname=shift;
1.761 raeburn 1990: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1991: $fname=~s/[\n\r]//g;
1.1 albertel 1992: my $author=$fname;
1993: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1994: my ($udom,$uname)=split(/\//,$author);
1995: my $home=homeserver($uname,$udom);
1.335 albertel 1996: if ($home eq 'no_host') {
1997: return 'not_found';
1.1 albertel 1998: }
1999: my $answer=reply("sub:$fname",$home);
1.64 www 2000: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2001: $answer.=' by '.$home;
2002: }
1.1 albertel 2003: return $answer;
2004: }
2005:
1.8 www 2006: # -------------------------------------------------------------- Replicate file
2007:
2008: sub repcopy {
2009: my $filename=shift;
1.23 www 2010: $filename=~s/\/+/\//g;
1.607 raeburn 2011: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2012: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2013: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2014: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2015: return &repcopy_userfile($filename);
2016: }
1.532 albertel 2017: $filename=~s/[\n\r]//g;
1.8 www 2018: my $transname="$filename.in.transfer";
1.828 www 2019: # FIXME: this should flock
1.607 raeburn 2020: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2021: my $remoteurl=subscribe($filename);
1.64 www 2022: if ($remoteurl =~ /^con_lost by/) {
2023: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2024: return 'unavailable';
1.8 www 2025: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2026: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2027: return 'not_found';
1.64 www 2028: } elsif ($remoteurl =~ /^rejected by/) {
2029: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2030: return 'forbidden';
1.20 www 2031: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2032: return 'ok';
1.8 www 2033: } else {
1.290 www 2034: my $author=$filename;
2035: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2036: my ($udom,$uname)=split(/\//,$author);
2037: my $home=homeserver($uname,$udom);
2038: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2039: my @parts=split(/\//,$filename);
2040: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2041: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2042: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2043: return 'bad_request';
1.8 www 2044: }
2045: my $count;
2046: for ($count=5;$count<$#parts;$count++) {
2047: $path.="/$parts[$count]";
2048: if ((-e $path)!=1) {
2049: mkdir($path,0777);
2050: }
2051: }
2052: my $ua=new LWP::UserAgent;
2053: my $request=new HTTP::Request('GET',"$remoteurl");
2054: my $response=$ua->request($request,$transname);
2055: if ($response->is_error()) {
2056: unlink($transname);
2057: my $message=$response->status_line;
1.672 albertel 2058: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2059: ." LWP get: $message: $filename</font>");
1.607 raeburn 2060: return 'unavailable';
1.8 www 2061: } else {
1.16 www 2062: if ($remoteurl!~/\.meta$/) {
2063: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2064: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2065: if ($mresponse->is_error()) {
2066: unlink($filename.'.meta');
2067: &logthis(
1.672 albertel 2068: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2069: }
2070: }
1.8 www 2071: rename($transname,$filename);
1.607 raeburn 2072: return 'ok';
1.8 www 2073: }
1.290 www 2074: }
1.8 www 2075: }
1.330 www 2076: }
2077:
2078: # ------------------------------------------------ Get server side include body
2079: sub ssi_body {
1.381 albertel 2080: my ($filelink,%form)=@_;
1.606 matthew 2081: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2082: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2083: }
1.953 www 2084: my $output='';
2085: my $response;
1.980 raeburn 2086: if ($filelink=~/^https?\:/) {
1.954 raeburn 2087: ($output,$response)=&externalssi($filelink);
1.953 www 2088: } else {
1.1004 droeschl 2089: $filelink .= $filelink=~/\?/ ? '&' : '?';
2090: $filelink .= 'inhibitmenu=yes';
1.953 www 2091: ($output,$response)=&ssi($filelink,%form);
2092: }
1.778 albertel 2093: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2094: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2095: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2096: if (wantarray) {
2097: return ($output, $response);
2098: } else {
2099: return $output;
2100: }
1.8 www 2101: }
2102:
1.15 www 2103: # --------------------------------------------------------- Server Side Include
2104:
1.782 albertel 2105: sub absolute_url {
2106: my ($host_name) = @_;
2107: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2108: if ($host_name eq '') {
2109: $host_name = $ENV{'SERVER_NAME'};
2110: }
2111: return $protocol.$host_name;
2112: }
2113:
1.942 foxr 2114: #
2115: # Server side include.
2116: # Parameters:
2117: # fn Possibly encrypted resource name/id.
2118: # form Hash that describes how the rendering should be done
2119: # and other things.
1.944 foxr 2120: # Returns:
1.950 raeburn 2121: # Scalar context: The content of the response.
2122: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2123: #
1.15 www 2124: sub ssi {
2125:
1.944 foxr 2126: my ($fn,%form)=@_;
1.15 www 2127: my $ua=new LWP::UserAgent;
1.23 www 2128: my $request;
1.711 albertel 2129:
2130: $form{'no_update_last_known'}=1;
1.895 albertel 2131: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2132: if (%form) {
1.782 albertel 2133: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2134: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2135: } else {
1.782 albertel 2136: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2137: }
2138:
1.15 www 2139: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2140: my $response=$ua->request($request);
2141:
1.944 foxr 2142: if (wantarray) {
2143: return ($response->content, $response);
2144: } else {
2145: return $response->content;
1.942 foxr 2146: }
1.324 www 2147: }
2148:
2149: sub externalssi {
2150: my ($url)=@_;
2151: my $ua=new LWP::UserAgent;
2152: my $request=new HTTP::Request('GET',$url);
2153: my $response=$ua->request($request);
1.954 raeburn 2154: if (wantarray) {
2155: return ($response->content, $response);
2156: } else {
2157: return $response->content;
2158: }
1.15 www 2159: }
1.254 www 2160:
1.492 albertel 2161: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2162:
2163: sub allowuploaded {
2164: my ($srcurl,$url)=@_;
2165: $url=&clutter(&declutter($url));
2166: my $dir=$url;
2167: $dir=~s/\/[^\/]+$//;
2168: my %httpref=();
2169: my $httpurl=&hreflocation('',$url);
2170: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2171: &Apache::lonnet::appenv(\%httpref);
1.254 www 2172: }
1.477 raeburn 2173:
1.478 albertel 2174: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2175: # input: action, courseID, current domain, intended
1.637 raeburn 2176: # path to file, source of file, instruction to parse file for objects,
2177: # ref to hash for embedded objects,
2178: # ref to hash for codebase of java objects.
1.1095 raeburn 2179: # reference to scalar to accommodate mime type determined
2180: # from File::MMagic if $parser = parse.
1.637 raeburn 2181: #
1.485 raeburn 2182: # output: url to file (if action was uploaddoc),
2183: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2184: #
1.478 albertel 2185: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2186: # course.
1.477 raeburn 2187: #
1.478 albertel 2188: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2189: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2190: # course's home server.
1.477 raeburn 2191: #
1.478 albertel 2192: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2193: # be copied from $source (current location) to
2194: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2195: # and will then be copied to
2196: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2197: # course's home server.
1.485 raeburn 2198: #
1.481 raeburn 2199: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2200: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2201: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2202: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2203: # in course's home server.
1.637 raeburn 2204: #
1.477 raeburn 2205:
2206: sub process_coursefile {
1.1095 raeburn 2207: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2208: $mimetype)=@_;
1.477 raeburn 2209: my $fetchresult;
1.638 albertel 2210: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2211: if ($action eq 'propagate') {
1.638 albertel 2212: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2213: $home);
1.481 raeburn 2214: } else {
1.477 raeburn 2215: my $fpath = '';
2216: my $fname = $file;
1.478 albertel 2217: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2218: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2219: my $filepath = &build_filepath($fpath);
1.481 raeburn 2220: if ($action eq 'copy') {
2221: if ($source eq '') {
2222: $fetchresult = 'no source file';
2223: return $fetchresult;
2224: } else {
2225: my $destination = $filepath.'/'.$fname;
2226: rename($source,$destination);
2227: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2228: $home);
1.481 raeburn 2229: }
2230: } elsif ($action eq 'uploaddoc') {
2231: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2232: print $fh $env{'form.'.$source};
1.481 raeburn 2233: close($fh);
1.637 raeburn 2234: if ($parser eq 'parse') {
1.1024 raeburn 2235: my $mm = new File::MMagic;
1.1095 raeburn 2236: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2237: if ($type eq 'text/html') {
1.1024 raeburn 2238: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2239: unless ($parse_result eq 'ok') {
2240: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2241: }
1.637 raeburn 2242: }
1.1095 raeburn 2243: if (ref($mimetype)) {
2244: $$mimetype = $type;
2245: }
1.637 raeburn 2246: }
1.477 raeburn 2247: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2248: $home);
1.481 raeburn 2249: if ($fetchresult eq 'ok') {
2250: return '/uploaded/'.$fpath.'/'.$fname;
2251: } else {
2252: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2253: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2254: return '/adm/notfound.html';
2255: }
1.477 raeburn 2256: }
2257: }
1.485 raeburn 2258: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2259: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2260: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2261: }
2262: return $fetchresult;
2263: }
2264:
1.637 raeburn 2265: sub build_filepath {
2266: my ($fpath) = @_;
2267: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2268: unless ($fpath eq '') {
2269: my @parts=split('/',$fpath);
2270: foreach my $part (@parts) {
2271: $filepath.= '/'.$part;
2272: if ((-e $filepath)!=1) {
2273: mkdir($filepath,0777);
2274: }
2275: }
2276: }
2277: return $filepath;
2278: }
2279:
2280: sub store_edited_file {
1.638 albertel 2281: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2282: my $file = $primary_url;
2283: $file =~ s#^/uploaded/$docudom/$docuname/##;
2284: my $fpath = '';
2285: my $fname = $file;
2286: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2287: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2288: my $filepath = &build_filepath($fpath);
2289: open(my $fh,'>'.$filepath.'/'.$fname);
2290: print $fh $content;
2291: close($fh);
1.638 albertel 2292: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2293: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2294: $home);
1.637 raeburn 2295: if ($$fetchresult eq 'ok') {
2296: return '/uploaded/'.$fpath.'/'.$fname;
2297: } else {
1.638 albertel 2298: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2299: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2300: return '/adm/notfound.html';
2301: }
2302: }
2303:
1.531 albertel 2304: sub clean_filename {
1.831 albertel 2305: my ($fname,$args)=@_;
1.315 www 2306: # Replace Windows backslashes by forward slashes
1.257 www 2307: $fname=~s/\\/\//g;
1.831 albertel 2308: if (!$args->{'keep_path'}) {
2309: # Get rid of everything but the actual filename
2310: $fname=~s/^.*\/([^\/]+)$/$1/;
2311: }
1.315 www 2312: # Replace spaces by underscores
2313: $fname=~s/\s+/\_/g;
2314: # Replace all other weird characters by nothing
1.831 albertel 2315: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2316: # Replace all .\d. sequences with _\d. so they no longer look like version
2317: # numbers
2318: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2319: return $fname;
2320: }
1.1051 raeburn 2321: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2322: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2323: # image with the same aspect ratio as the original, but with dimensions which do
2324: # not exceed $resizewidth and $resizeheight.
2325:
1.984 neumanie 2326: sub resizeImage {
1.1051 raeburn 2327: my ($img_path,$resizewidth,$resizeheight) = @_;
2328: my $ima = Image::Magick->new;
2329: my $resized;
2330: if (-e $img_path) {
2331: $ima->Read($img_path);
2332: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2333: my $width = $ima->Get('width');
2334: my $height = $ima->Get('height');
2335: if ($width > $resizewidth) {
2336: my $factor = $width/$resizewidth;
2337: my $newheight = $height/$factor;
2338: $ima->Scale(width=>$resizewidth,height=>$newheight);
2339: $resized = 1;
2340: }
2341: }
2342: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2343: my $width = $ima->Get('width');
2344: my $height = $ima->Get('height');
2345: if ($height > $resizeheight) {
2346: my $factor = $height/$resizeheight;
2347: my $newwidth = $width/$factor;
2348: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2349: $resized = 1;
2350: }
2351: }
2352: if ($resized) {
2353: $ima->Write($img_path);
2354: }
2355: }
2356: return;
1.977 amueller 2357: }
2358:
1.608 albertel 2359: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2360: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2361: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2362: # $context - possible values: coursedoc, existingfile, overwrite,
2363: # canceloverwrite, or ''.
2364: # if 'coursedoc': upload to the current course
2365: # if 'existingfile': write file to tmp/overwrites directory
2366: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2367: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2368: # $subdir - directory in userfile to store the file into
1.858 raeburn 2369: # $parser - instruction to parse file for objects ($parser = parse)
2370: # $allfiles - reference to hash for embedded objects
2371: # $codebase - reference to hash for codebase of java objects
2372: # $desuname - username for permanent storage of uploaded file
2373: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2374: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2375: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2376: # $resizewidth - width (pixels) to which to resize uploaded image
2377: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2378: # $mimetype - reference to scalar to accommodate mime type determined
2379: # from File::MMagic if $parser = parse.
1.858 raeburn 2380: #
1.686 albertel 2381: # output: url of file in userspace, or error: <message>
2382: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2383:
1.531 albertel 2384: sub userfileupload {
1.1090 raeburn 2385: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2386: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2387: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2388: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2389: $fname=&clean_filename($fname);
1.1090 raeburn 2390: # See if there is anything left
1.257 www 2391: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2392: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2393: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2394: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2395: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2396: my $now = time;
1.1090 raeburn 2397: my $filepath;
1.1095 raeburn 2398: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2399: $filepath = 'tmp/helprequests/'.$now;
2400: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2401: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2402: '_'.$env{'user.domain'}.'/pending';
2403: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2404: my ($docuname,$docudom);
2405: if ($destudom) {
2406: $docudom = $destudom;
2407: } else {
2408: $docudom = $env{'user.domain'};
2409: }
2410: if ($destuname) {
2411: $docuname = $destuname;
2412: } else {
2413: $docuname = $env{'user.name'};
2414: }
2415: if (exists($env{'form.group'})) {
2416: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2417: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2418: }
2419: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2420: if ($context eq 'canceloverwrite') {
2421: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2422: if (-e $tempfile) {
2423: my @info = stat($tempfile);
2424: if ($info[9] eq $env{'form.timestamp'}) {
2425: unlink($tempfile);
2426: }
2427: }
2428: return;
1.523 raeburn 2429: }
2430: }
1.1090 raeburn 2431: # Create the directory if not present
1.741 raeburn 2432: my @parts=split(/\//,$filepath);
2433: my $fullpath = $perlvar{'lonDaemons'};
2434: for (my $i=0;$i<@parts;$i++) {
2435: $fullpath .= '/'.$parts[$i];
2436: if ((-e $fullpath)!=1) {
2437: mkdir($fullpath,0777);
2438: }
2439: }
2440: open(my $fh,'>'.$fullpath.'/'.$fname);
2441: print $fh $env{'form.'.$formname};
2442: close($fh);
1.1090 raeburn 2443: if ($context eq 'existingfile') {
2444: my @info = stat($fullpath.'/'.$fname);
2445: return ($fullpath.'/'.$fname,$info[9]);
2446: } else {
2447: return $fullpath.'/'.$fname;
2448: }
1.523 raeburn 2449: }
1.995 raeburn 2450: if ($subdir eq 'scantron') {
2451: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2452: } else {
1.995 raeburn 2453: $fname="$subdir/$fname";
2454: }
1.1090 raeburn 2455: if ($context eq 'coursedoc') {
1.638 albertel 2456: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2457: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2458: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2459: return &finishuserfileupload($docuname,$docudom,
2460: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2461: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2462: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2463: } else {
1.620 albertel 2464: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2465: return &process_coursefile('uploaddoc',$docuname,$docudom,
2466: $fname,$formname,$parser,
1.1095 raeburn 2467: $allfiles,$codebase,$mimetype);
1.481 raeburn 2468: }
1.719 banghart 2469: } elsif (defined($destuname)) {
2470: my $docuname=$destuname;
2471: my $docudom=$destudom;
1.860 raeburn 2472: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2473: $parser,$allfiles,$codebase,
1.1051 raeburn 2474: $thumbwidth,$thumbheight,
1.1095 raeburn 2475: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2476: } else {
1.638 albertel 2477: my $docuname=$env{'user.name'};
2478: my $docudom=$env{'user.domain'};
1.714 raeburn 2479: if (exists($env{'form.group'})) {
2480: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2481: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2482: }
1.860 raeburn 2483: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2484: $parser,$allfiles,$codebase,
1.1051 raeburn 2485: $thumbwidth,$thumbheight,
1.1095 raeburn 2486: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2487: }
1.271 www 2488: }
2489:
2490: sub finishuserfileupload {
1.860 raeburn 2491: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2492: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2493: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2494: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2495:
1.860 raeburn 2496: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2497: $file=$fname;
2498: if ($fname=~m|/|) {
2499: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2500: $path.=$fnamepath.'/';
2501: }
1.259 www 2502: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2503: my $count;
2504: for ($count=4;$count<=$#parts;$count++) {
2505: $filepath.="/$parts[$count]";
2506: if ((-e $filepath)!=1) {
2507: mkdir($filepath,0777);
2508: }
2509: }
1.984 neumanie 2510:
1.258 www 2511: # Save the file
2512: {
1.701 albertel 2513: if (!open(FH,'>'.$filepath.'/'.$file)) {
2514: &logthis('Failed to create '.$filepath.'/'.$file);
2515: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2516: return '/adm/notfound.html';
2517: }
1.1090 raeburn 2518: if ($context eq 'overwrite') {
2519: my $source = $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2520: my $target = $filepath.'/'.$file;
2521: if (-e $source) {
2522: my @info = stat($source);
2523: if ($info[9] eq $env{'form.timestamp'}) {
2524: unless (&File::Copy::move($source,$target)) {
2525: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2526: return "Moving from $source failed";
2527: }
2528: } else {
2529: return "Temporary file: $source had unexpected date/time for last modification";
2530: }
2531: } else {
2532: return "Temporary file: $source missing";
2533: }
2534: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2535: &logthis('Failed to write to '.$filepath.'/'.$file);
2536: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2537: return '/adm/notfound.html';
2538: }
1.570 albertel 2539: close(FH);
1.1051 raeburn 2540: if ($resizewidth && $resizeheight) {
2541: my $mm = new File::MMagic;
2542: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2543: if ($mime_type =~ m{^image/}) {
2544: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2545: }
1.977 amueller 2546: }
1.258 www 2547: }
1.637 raeburn 2548: if ($parser eq 'parse') {
1.1024 raeburn 2549: my $mm = new File::MMagic;
1.1095 raeburn 2550: my $type = $mm->checktype_filename($filepath.'/'.$file);
2551: if ($type eq 'text/html') {
1.1024 raeburn 2552: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2553: $allfiles,$codebase);
2554: unless ($parse_result eq 'ok') {
2555: &logthis('Failed to parse '.$filepath.$file.
2556: ' for embedded media: '.$parse_result);
2557: }
1.637 raeburn 2558: }
1.1095 raeburn 2559: if (ref($mimetype)) {
2560: $$mimetype = $type;
2561: }
1.637 raeburn 2562: }
1.860 raeburn 2563: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2564: my $input = $filepath.'/'.$file;
2565: my $output = $filepath.'/'.'tn-'.$file;
2566: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2567: system("convert -sample $thumbsize $input $output");
2568: if (-e $filepath.'/'.'tn-'.$file) {
2569: $fetchthumb = 1;
2570: }
2571: }
1.858 raeburn 2572:
1.259 www 2573: # Notify homeserver to grep it
2574: #
1.984 neumanie 2575: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2576: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2577: if ($fetchresult eq 'ok') {
1.860 raeburn 2578: if ($fetchthumb) {
2579: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2580: if ($thumbresult ne 'ok') {
2581: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2582: $docuhome.': '.$thumbresult);
2583: }
2584: }
1.259 www 2585: #
1.258 www 2586: # Return the URL to it
1.494 albertel 2587: return '/uploaded/'.$path.$file;
1.263 www 2588: } else {
1.494 albertel 2589: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2590: ': '.$fetchresult);
1.263 www 2591: return '/adm/notfound.html';
1.858 raeburn 2592: }
1.493 albertel 2593: }
2594:
1.637 raeburn 2595: sub extract_embedded_items {
1.961 raeburn 2596: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2597: my @state = ();
2598: my %javafiles = (
2599: codebase => '',
2600: code => '',
2601: archive => ''
2602: );
2603: my %mediafiles = (
2604: src => '',
2605: movie => '',
2606: );
1.648 raeburn 2607: my $p;
2608: if ($content) {
2609: $p = HTML::LCParser->new($content);
2610: } else {
1.961 raeburn 2611: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2612: }
1.641 albertel 2613: while (my $t=$p->get_token()) {
1.640 albertel 2614: if ($t->[0] eq 'S') {
2615: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2616: push(@state, $tagname);
1.648 raeburn 2617: if (lc($tagname) eq 'allow') {
2618: &add_filetype($allfiles,$attr->{'src'},'src');
2619: }
1.640 albertel 2620: if (lc($tagname) eq 'img') {
2621: &add_filetype($allfiles,$attr->{'src'},'src');
2622: }
1.886 albertel 2623: if (lc($tagname) eq 'a') {
2624: &add_filetype($allfiles,$attr->{'href'},'href');
2625: }
1.645 raeburn 2626: if (lc($tagname) eq 'script') {
2627: if ($attr->{'archive'} =~ /\.jar$/i) {
2628: &add_filetype($allfiles,$attr->{'archive'},'archive');
2629: } else {
2630: &add_filetype($allfiles,$attr->{'src'},'src');
2631: }
2632: }
2633: if (lc($tagname) eq 'link') {
2634: if (lc($attr->{'rel'}) eq 'stylesheet') {
2635: &add_filetype($allfiles,$attr->{'href'},'href');
2636: }
2637: }
1.640 albertel 2638: if (lc($tagname) eq 'object' ||
2639: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2640: foreach my $item (keys(%javafiles)) {
2641: $javafiles{$item} = '';
2642: }
2643: }
2644: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2645: my $name = lc($attr->{'name'});
2646: foreach my $item (keys(%javafiles)) {
2647: if ($name eq $item) {
2648: $javafiles{$item} = $attr->{'value'};
2649: last;
2650: }
2651: }
2652: foreach my $item (keys(%mediafiles)) {
2653: if ($name eq $item) {
2654: &add_filetype($allfiles, $attr->{'value'}, 'value');
2655: last;
2656: }
2657: }
2658: }
2659: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2660: foreach my $item (keys(%javafiles)) {
2661: if ($attr->{$item}) {
2662: $javafiles{$item} = $attr->{$item};
2663: last;
2664: }
2665: }
2666: foreach my $item (keys(%mediafiles)) {
2667: if ($attr->{$item}) {
2668: &add_filetype($allfiles,$attr->{$item},$item);
2669: last;
2670: }
2671: }
2672: }
2673: } elsif ($t->[0] eq 'E') {
2674: my ($tagname) = ($t->[1]);
2675: if ($javafiles{'codebase'} ne '') {
2676: $javafiles{'codebase'} .= '/';
2677: }
2678: if (lc($tagname) eq 'applet' ||
2679: lc($tagname) eq 'object' ||
2680: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2681: ) {
2682: foreach my $item (keys(%javafiles)) {
2683: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2684: my $file=$javafiles{'codebase'}.$javafiles{$item};
2685: &add_filetype($allfiles,$file,$item);
2686: }
2687: }
2688: }
2689: pop @state;
2690: }
2691: }
1.637 raeburn 2692: return 'ok';
2693: }
2694:
1.639 albertel 2695: sub add_filetype {
2696: my ($allfiles,$file,$type)=@_;
2697: if (exists($allfiles->{$file})) {
2698: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2699: push(@{$allfiles->{$file}}, &escape($type));
2700: }
2701: } else {
2702: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2703: }
2704: }
2705:
1.493 albertel 2706: sub removeuploadedurl {
1.984 neumanie 2707: my ($url)=@_;
2708: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2709: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2710: }
2711:
2712: sub removeuserfile {
2713: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2714: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2715: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2716: if ($result eq 'ok') {
1.798 raeburn 2717: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2718: my $metafile = $fname.'.meta';
2719: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2720: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2721: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2722: my $sqlresult =
1.823 albertel 2723: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2724: 'portfolio_metadata',$group,
2725: 'delete');
1.798 raeburn 2726: }
2727: }
2728: return $result;
1.257 www 2729: }
1.15 www 2730:
1.530 albertel 2731: sub mkdiruserfile {
2732: my ($docuname,$docudom,$dir)=@_;
2733: my $home=&homeserver($docuname,$docudom);
2734: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2735: }
2736:
1.531 albertel 2737: sub renameuserfile {
2738: my ($docuname,$docudom,$old,$new)=@_;
2739: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2740: my $result = &reply("renameuserfile:$docudom:$docuname:".
2741: &escape("$old").':'.&escape("$new"),$home);
2742: if ($result eq 'ok') {
2743: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2744: my $oldmeta = $old.'.meta';
2745: my $newmeta = $new.'.meta';
2746: my $metaresult =
2747: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2748: my $url = "/uploaded/$docudom/$docuname/$old";
2749: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2750: my $sqlresult =
1.823 albertel 2751: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2752: 'portfolio_metadata',$group,
2753: 'delete');
1.798 raeburn 2754: }
2755: }
2756: return $result;
1.531 albertel 2757: }
2758:
1.14 www 2759: # ------------------------------------------------------------------------- Log
2760:
2761: sub log {
2762: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2763: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2764: }
2765:
2766: # ------------------------------------------------------------------ Course Log
1.352 www 2767: #
2768: # This routine flushes several buffers of non-mission-critical nature
2769: #
1.157 www 2770:
2771: sub flushcourselogs {
1.352 www 2772: &logthis('Flushing log buffers');
2773: #
2774: # course logs
2775: # This is a log of all transactions in a course, which can be used
2776: # for data mining purposes
2777: #
2778: # It also collects the courseid database, which lists last transaction
2779: # times and course titles for all courseids
2780: #
2781: my %courseidbuffer=();
1.921 raeburn 2782: foreach my $crsid (keys(%courselogs)) {
1.352 www 2783: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2784: &escape($courselogs{$crsid}),
2785: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2786: delete $courselogs{$crsid};
2787: } else {
2788: &logthis('Failed to flush log buffer for '.$crsid);
2789: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2790: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2791: " exceeded maximum size, deleting.</font>");
2792: delete $courselogs{$crsid};
2793: }
1.352 www 2794: }
1.920 raeburn 2795: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2796: 'description' => $coursedescrbuf{$crsid},
2797: 'inst_code' => $courseinstcodebuf{$crsid},
2798: 'type' => $coursetypebuf{$crsid},
2799: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2800: };
1.191 harris41 2801: }
1.352 www 2802: #
2803: # Write course id database (reverse lookup) to homeserver of courses
2804: # Is used in pickcourse
2805: #
1.840 albertel 2806: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2807: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2808: $courseidbuffer{$crs_home},
2809: $crs_home,'timeonly');
1.352 www 2810: }
2811: #
2812: # File accesses
2813: # Writes to the dynamic metadata of resources to get hit counts, etc.
2814: #
1.449 matthew 2815: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2816: if ($entry =~ /___count$/) {
2817: my ($dom,$name);
1.807 albertel 2818: ($dom,$name,undef)=
1.811 albertel 2819: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2820: if (! defined($dom) || $dom eq '' ||
2821: ! defined($name) || $name eq '') {
1.620 albertel 2822: my $cid = $env{'request.course.id'};
2823: $dom = $env{'request.'.$cid.'.domain'};
2824: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2825: }
1.450 matthew 2826: my $value = $accesshash{$entry};
2827: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2828: my %temphash=($url => $value);
1.449 matthew 2829: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2830: if ($result eq 'ok') {
2831: delete $accesshash{$entry};
2832: } elsif ($result eq 'unknown_cmd') {
2833: # Target server has old code running on it.
1.450 matthew 2834: my %temphash=($entry => $value);
1.449 matthew 2835: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2836: delete $accesshash{$entry};
2837: }
2838: }
2839: } else {
1.811 albertel 2840: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2841: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2842: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2843: delete $accesshash{$entry};
2844: }
1.185 www 2845: }
1.191 harris41 2846: }
1.352 www 2847: #
2848: # Roles
2849: # Reverse lookup of user roles for course faculty/staff and co-authorship
2850: #
1.800 albertel 2851: foreach my $entry (keys(%userrolehash)) {
1.351 www 2852: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2853: split(/\:/,$entry);
2854: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2855: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2856: $rudom,$runame) eq 'ok') {
2857: delete $userrolehash{$entry};
2858: }
2859: }
1.662 raeburn 2860: #
2861: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2862: #
2863: my %domrolebuffer = ();
1.1000 raeburn 2864: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2865: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2866: if ($domrolebuffer{$rudom}) {
2867: $domrolebuffer{$rudom}.='&'.&escape($entry).
2868: '='.&escape($domainrolehash{$entry});
2869: } else {
2870: $domrolebuffer{$rudom}.=&escape($entry).
2871: '='.&escape($domainrolehash{$entry});
2872: }
2873: delete $domainrolehash{$entry};
2874: }
2875: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2876: my %servers = &get_servers($dom,'library');
2877: foreach my $tryserver (keys(%servers)) {
2878: unless (&reply('domroleput:'.$dom.':'.
2879: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2880: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2881: }
1.662 raeburn 2882: }
2883: }
1.186 www 2884: $dumpcount++;
1.157 www 2885: }
2886:
2887: sub courselog {
2888: my $what=shift;
1.158 www 2889: $what=time.':'.$what;
1.620 albertel 2890: unless ($env{'request.course.id'}) { return ''; }
2891: $coursedombuf{$env{'request.course.id'}}=
2892: $env{'course.'.$env{'request.course.id'}.'.domain'};
2893: $coursenumbuf{$env{'request.course.id'}}=
2894: $env{'course.'.$env{'request.course.id'}.'.num'};
2895: $coursehombuf{$env{'request.course.id'}}=
2896: $env{'course.'.$env{'request.course.id'}.'.home'};
2897: $coursedescrbuf{$env{'request.course.id'}}=
2898: $env{'course.'.$env{'request.course.id'}.'.description'};
2899: $courseinstcodebuf{$env{'request.course.id'}}=
2900: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2901: $courseownerbuf{$env{'request.course.id'}}=
2902: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2903: $coursetypebuf{$env{'request.course.id'}}=
2904: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2905: if (defined $courselogs{$env{'request.course.id'}}) {
2906: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2907: } else {
1.620 albertel 2908: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2909: }
1.620 albertel 2910: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2911: &flushcourselogs();
2912: }
1.158 www 2913: }
2914:
2915: sub courseacclog {
2916: my $fnsymb=shift;
1.620 albertel 2917: unless ($env{'request.course.id'}) { return ''; }
2918: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2919: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2920: $what.=':POST';
1.583 matthew 2921: # FIXME: Probably ought to escape things....
1.800 albertel 2922: foreach my $key (keys(%env)) {
2923: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2924: my $formitem = $1;
2925: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2926: $what.=':'.$formitem.'='.$env{$key};
2927: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2928: $what.=':'.$formitem.'='.$env{$key};
2929: }
1.158 www 2930: }
1.191 harris41 2931: }
1.583 matthew 2932: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2933: # FIXME: We should not be depending on a form parameter that someone
2934: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2935: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2936: $what.= ':POST';
2937: # FIXME: Probably ought to escape things....
2938: foreach my $element ('courseexp','crsfulltext','crsrelated',
2939: 'crsdiscuss') {
1.620 albertel 2940: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2941: }
2942: }
1.158 www 2943: }
2944: &courselog($what);
1.149 www 2945: }
2946:
1.185 www 2947: sub countacc {
2948: my $url=&declutter(shift);
1.458 matthew 2949: return if (! defined($url) || $url eq '');
1.620 albertel 2950: unless ($env{'request.course.id'}) { return ''; }
2951: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2952: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2953: $accesshash{$key}++;
1.185 www 2954: }
1.349 www 2955:
1.361 www 2956: sub linklog {
2957: my ($from,$to)=@_;
2958: $from=&declutter($from);
2959: $to=&declutter($to);
2960: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2961: $accesshash{$to.'___'.$from.'___goto'}=1;
2962: }
2963:
1.349 www 2964: sub userrolelog {
2965: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2966: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2967: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2968: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2969: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2970: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2971: $userrolehash
2972: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2973: =$tend.':'.$tstart;
1.662 raeburn 2974: }
1.898 albertel 2975: if (($env{'request.role'} =~ /dc\./) &&
2976: (($trole=~/^au/) || ($trole=~/^in/) ||
2977: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2978: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2979: ($trole=~/^co/))) {
1.898 albertel 2980: $userrolehash
2981: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2982: =$tend.':'.$tstart;
2983: }
1.662 raeburn 2984: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2985: ($trole=~/^li/) || ($trole=~/^li/) ||
2986: ($trole=~/^au/) || ($trole=~/^dg/) ||
2987: ($trole=~/^sc/)) {
2988: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2989: $domainrolehash
2990: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2991: = $tend.':'.$tstart;
2992: }
1.351 www 2993: }
2994:
1.957 raeburn 2995: sub courserolelog {
2996: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2997: if (($trole eq 'cc') || ($trole eq 'in') ||
2998: ($trole eq 'ep') || ($trole eq 'ad') ||
2999: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3000: ($trole=~/^cr/) || ($trole eq 'gr') ||
3001: ($trole eq 'co')) {
1.957 raeburn 3002: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3003: my $cdom = $1;
3004: my $cnum = $2;
3005: my $sec = $3;
3006: my $namespace = 'rolelog';
3007: my %storehash = (
3008: role => $trole,
3009: start => $tstart,
3010: end => $tend,
3011: selfenroll => $selfenroll,
3012: context => $context,
3013: );
3014: if ($trole eq 'gr') {
3015: $namespace = 'groupslog';
3016: $storehash{'group'} = $sec;
3017: } else {
3018: $storehash{'section'} = $sec;
3019: }
3020: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3021: if (($trole ne 'st') || ($sec ne '')) {
3022: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3023: }
1.957 raeburn 3024: }
3025: }
3026: return;
3027: }
3028:
1.351 www 3029: sub get_course_adv_roles {
1.948 raeburn 3030: my ($cid,$codes) = @_;
1.620 albertel 3031: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3032: my %coursehash=&coursedescription($cid);
1.988 raeburn 3033: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3034: my %nothide=();
1.800 albertel 3035: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3036: if ($user !~ /:/) {
3037: $nothide{join(':',split(/[\@]/,$user))}=1;
3038: } else {
3039: $nothide{$user}=1;
3040: }
1.470 www 3041: }
1.351 www 3042: my %returnhash=();
3043: my %dumphash=
3044: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3045: my $now=time;
1.997 raeburn 3046: my %privileged;
1.1000 raeburn 3047: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3048: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3049: if (($tstart) && ($tstart<0)) { next; }
3050: if (($tend) && ($tend<$now)) { next; }
3051: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3052: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3053: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3054: unless (ref($privileged{$domain}) eq 'HASH') {
3055: my %dompersonnel =
1.998 raeburn 3056: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3057: $privileged{$domain} = {};
3058: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3059: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3060: foreach my $user (keys(%{$dompersonnel{$server}})) {
3061: my ($trole,$uname,$udom) = split(/:/,$user);
3062: $privileged{$udom}{$uname} = 1;
3063: }
3064: }
3065: }
3066: }
3067: if ((exists($privileged{$domain}{$username})) &&
3068: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3069: if ($role eq 'cr') { next; }
1.948 raeburn 3070: if ($codes) {
3071: if ($section) { $role .= ':'.$section; }
3072: if ($returnhash{$role}) {
3073: $returnhash{$role}.=','.$username.':'.$domain;
3074: } else {
3075: $returnhash{$role}=$username.':'.$domain;
3076: }
1.351 www 3077: } else {
1.988 raeburn 3078: my $key=&plaintext($role,$crstype);
1.973 bisitz 3079: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3080: if ($returnhash{$key}) {
3081: $returnhash{$key}.=','.$username.':'.$domain;
3082: } else {
3083: $returnhash{$key}=$username.':'.$domain;
3084: }
1.351 www 3085: }
1.948 raeburn 3086: }
1.400 www 3087: return %returnhash;
3088: }
3089:
3090: sub get_my_roles {
1.937 raeburn 3091: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3092: unless (defined($uname)) { $uname=$env{'user.name'}; }
3093: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3094: my (%dumphash,%nothide);
1.1086 raeburn 3095: if ($context eq 'userroles') {
3096: my $extra = &freeze_escape({'skipcheck' => 1});
3097: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3098: } else {
3099: %dumphash=
1.400 www 3100: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3101: if ($hidepriv) {
3102: my %coursehash=&coursedescription($udom.'_'.$uname);
3103: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3104: if ($user !~ /:/) {
3105: $nothide{join(':',split(/[\@]/,$user))} = 1;
3106: } else {
3107: $nothide{$user} = 1;
3108: }
3109: }
3110: }
1.858 raeburn 3111: }
1.400 www 3112: my %returnhash=();
3113: my $now=time;
1.999 raeburn 3114: my %privileged;
1.800 albertel 3115: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3116: my ($role,$tend,$tstart);
3117: if ($context eq 'userroles') {
3118: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3119: } else {
3120: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3121: }
1.400 www 3122: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3123: my $status = 'active';
1.939 raeburn 3124: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3125: $status = 'previous';
3126: }
3127: if (($tstart) && ($now<$tstart)) {
3128: $status = 'future';
3129: }
3130: if (ref($types) eq 'ARRAY') {
3131: if (!grep(/^\Q$status\E$/,@{$types})) {
3132: next;
3133: }
3134: } else {
3135: if ($status ne 'active') {
3136: next;
3137: }
3138: }
1.867 raeburn 3139: my ($rolecode,$username,$domain,$section,$area);
3140: if ($context eq 'userroles') {
3141: ($area,$rolecode) = split(/_/,$entry);
3142: (undef,$domain,$username,$section) = split(/\//,$area);
3143: } else {
3144: ($role,$username,$domain,$section) = split(/\:/,$entry);
3145: }
1.832 raeburn 3146: if (ref($roledoms) eq 'ARRAY') {
3147: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3148: next;
3149: }
3150: }
3151: if (ref($roles) eq 'ARRAY') {
3152: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3153: if ($role =~ /^cr\//) {
3154: if (!grep(/^cr$/,@{$roles})) {
3155: next;
3156: }
3157: } else {
3158: next;
3159: }
1.832 raeburn 3160: }
1.867 raeburn 3161: }
1.937 raeburn 3162: if ($hidepriv) {
1.999 raeburn 3163: if ($context eq 'userroles') {
3164: if ((&privileged($username,$domain)) &&
3165: (!$nothide{$username.':'.$domain})) {
3166: next;
3167: }
3168: } else {
3169: unless (ref($privileged{$domain}) eq 'HASH') {
3170: my %dompersonnel =
3171: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3172: $privileged{$domain} = {};
3173: if (keys(%dompersonnel)) {
3174: foreach my $server (keys(%dompersonnel)) {
3175: if (ref($dompersonnel{$server}) eq 'HASH') {
3176: foreach my $user (keys(%{$dompersonnel{$server}})) {
3177: my ($trole,$uname,$udom) = split(/:/,$user);
3178: $privileged{$udom}{$uname} = $trole;
3179: }
3180: }
3181: }
3182: }
3183: }
3184: if (exists($privileged{$domain}{$username})) {
3185: if (!$nothide{$username.':'.$domain}) {
3186: next;
3187: }
3188: }
1.937 raeburn 3189: }
3190: }
1.933 raeburn 3191: if ($withsec) {
3192: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3193: $tstart.':'.$tend;
3194: } else {
3195: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3196: }
1.832 raeburn 3197: }
1.373 www 3198: return %returnhash;
1.399 www 3199: }
3200:
3201: # ----------------------------------------------------- Frontpage Announcements
3202: #
3203: #
3204:
3205: sub postannounce {
3206: my ($server,$text)=@_;
1.844 albertel 3207: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3208: unless ($text=~/\w/) { $text=''; }
3209: return &reply('setannounce:'.&escape($text),$server);
3210: }
3211:
3212: sub getannounce {
1.448 albertel 3213:
3214: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3215: my $announcement='';
1.800 albertel 3216: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3217: close($fh);
1.399 www 3218: if ($announcement=~/\w/) {
3219: return
3220: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3221: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3222: } else {
3223: return '';
3224: }
3225: } else {
3226: return '';
3227: }
1.351 www 3228: }
1.353 www 3229:
3230: # ---------------------------------------------------------- Course ID routines
3231: # Deal with domain's nohist_courseid.db files
3232: #
3233:
3234: sub courseidput {
1.921 raeburn 3235: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3236: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3237: my $outcome;
3238: if ($caller eq 'timeonly') {
3239: my $cids = '';
3240: foreach my $item (keys(%$storehash)) {
3241: $cids.=&escape($item).'&';
3242: }
3243: $cids=~s/\&$//;
3244: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3245: $coursehome);
3246: } else {
3247: my $items = '';
3248: foreach my $item (keys(%$storehash)) {
3249: $items.= &escape($item).'='.
3250: &freeze_escape($$storehash{$item}).'&';
3251: }
3252: $items=~s/\&$//;
3253: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3254: $coursehome);
1.918 raeburn 3255: }
3256: if ($outcome eq 'unknown_cmd') {
3257: my $what;
3258: foreach my $cid (keys(%$storehash)) {
3259: $what .= &escape($cid).'=';
1.921 raeburn 3260: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3261: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3262: }
3263: $what =~ s/\:$/&/;
3264: }
3265: $what =~ s/\&$//;
3266: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3267: } else {
3268: return $outcome;
3269: }
1.353 www 3270: }
3271:
3272: sub courseiddump {
1.921 raeburn 3273: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3274: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3275: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3276: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3277: my $as_hash = 1;
3278: my %returnhash;
3279: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3280: my %libserv = &all_library();
3281: foreach my $tryserver (keys(%libserv)) {
3282: if ( ( $hostidflag == 1
3283: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3284: || (!defined($hostidflag)) ) {
3285:
1.918 raeburn 3286: if (($domfilter eq '') ||
3287: (&host_domain($tryserver) eq $domfilter)) {
3288: my $rep =
3289: &reply('courseiddump:'.&host_domain($tryserver).':'.
3290: $sincefilter.':'.&escape($descfilter).':'.
3291: &escape($instcodefilter).':'.&escape($ownerfilter).
3292: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3293: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3294: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3295: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3296: &escape($cc_clone).':'.$cloneonly.':'.
3297: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3298: &escape($creationcontext).':'.$domcloner,
3299: $tryserver);
1.918 raeburn 3300: my @pairs=split(/\&/,$rep);
3301: foreach my $item (@pairs) {
3302: my ($key,$value)=split(/\=/,$item,2);
3303: $key = &unescape($key);
3304: next if ($key =~ /^error: 2 /);
3305: my $result = &thaw_unescape($value);
3306: if (ref($result) eq 'HASH') {
3307: $returnhash{$key}=$result;
3308: } else {
1.921 raeburn 3309: my @responses = split(/:/,$value);
3310: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3311: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3312: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3313: }
1.1008 raeburn 3314: }
1.353 www 3315: }
3316: }
3317: }
3318: }
3319: return %returnhash;
3320: }
3321:
1.1055 raeburn 3322: sub courselastaccess {
3323: my ($cdom,$cnum,$hostidref) = @_;
3324: my %returnhash;
3325: if ($cdom && $cnum) {
3326: my $chome = &homeserver($cnum,$cdom);
3327: if ($chome ne 'no_host') {
3328: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3329: &extract_lastaccess(\%returnhash,$rep);
3330: }
3331: } else {
3332: if (!$cdom) { $cdom=''; }
3333: my %libserv = &all_library();
3334: foreach my $tryserver (keys(%libserv)) {
3335: if (ref($hostidref) eq 'ARRAY') {
3336: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3337: }
3338: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3339: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3340: &extract_lastaccess(\%returnhash,$rep);
3341: }
3342: }
3343: }
3344: return %returnhash;
3345: }
3346:
3347: sub extract_lastaccess {
3348: my ($returnhash,$rep) = @_;
3349: if (ref($returnhash) eq 'HASH') {
3350: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3351: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3352: $rep eq '') {
3353: my @pairs=split(/\&/,$rep);
3354: foreach my $item (@pairs) {
3355: my ($key,$value)=split(/\=/,$item,2);
3356: $key = &unescape($key);
3357: next if ($key =~ /^error: 2 /);
3358: $returnhash->{$key} = &thaw_unescape($value);
3359: }
3360: }
3361: }
3362: return;
3363: }
3364:
1.658 raeburn 3365: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3366:
3367: sub dcmailput {
1.685 raeburn 3368: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3369: my $status = &Apache::lonnet::critical(
1.740 www 3370: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3371: &escape($message),$server);
1.662 raeburn 3372: return $status;
3373: }
3374:
1.658 raeburn 3375: sub dcmaildump {
3376: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3377: my %returnhash=();
1.846 albertel 3378:
3379: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3380: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3381: &escape($enddate).':';
3382: my @esc_senders=map { &escape($_)} @$senders;
3383: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3384: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3385: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3386: if (($key) && ($value)) {
3387: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3388: }
3389: }
3390: }
3391: return %returnhash;
3392: }
1.662 raeburn 3393: # ---------------------------------------------------------- Domain roles
3394:
3395: sub get_domain_roles {
3396: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3397: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3398: $startdate = '.';
3399: }
1.1018 raeburn 3400: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3401: $enddate = '.';
3402: }
1.922 raeburn 3403: my $rolelist;
3404: if (ref($roles) eq 'ARRAY') {
3405: $rolelist = join(':',@{$roles});
3406: }
1.662 raeburn 3407: my %personnel = ();
1.841 albertel 3408:
3409: my %servers = &get_servers($dom,'library');
3410: foreach my $tryserver (keys(%servers)) {
3411: %{$personnel{$tryserver}}=();
3412: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3413: &escape($startdate).':'.
3414: &escape($enddate).':'.
3415: &escape($rolelist), $tryserver))) {
3416: my ($key,$value) = split(/\=/,$line,2);
3417: if (($key) && ($value)) {
3418: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3419: }
3420: }
1.662 raeburn 3421: }
3422: return %personnel;
3423: }
1.658 raeburn 3424:
1.1057 www 3425: # ----------------------------------------------------------- Interval timing
1.149 www 3426:
1.504 albertel 3427: sub get_first_access {
3428: my ($type,$argsymb)=@_;
1.790 albertel 3429: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3430: if ($argsymb) { $symb=$argsymb; }
3431: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3432: if ($type eq 'course') {
3433: $res='course';
3434: } elsif ($type eq 'map') {
1.588 albertel 3435: $res=&symbread($map);
3436: } else {
3437: $res=$symb;
3438: }
3439: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3440: return $times{"$courseid\0$res"};
1.504 albertel 3441: }
3442:
3443: sub set_first_access {
3444: my ($type)=@_;
1.790 albertel 3445: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3446: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3447: if ($type eq 'course') {
3448: $res='course';
3449: } elsif ($type eq 'map') {
1.588 albertel 3450: $res=&symbread($map);
3451: } else {
3452: $res=$symb;
3453: }
3454: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3455: if (!$firstaccess) {
1.588 albertel 3456: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3457: }
3458: return 'already_set';
1.504 albertel 3459: }
3460:
1.110 www 3461: # --------------------------------------------- Set Expire Date for Spreadsheet
3462:
3463: sub expirespread {
3464: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3465: my $cid=$env{'request.course.id'};
1.110 www 3466: if ($cid) {
3467: my $now=time;
3468: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3469: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3470: $env{'course.'.$cid.'.num'}.
1.110 www 3471: ':nohist_expirationdates:'.
3472: &escape($key).'='.$now,
1.620 albertel 3473: $env{'course.'.$cid.'.home'})
1.110 www 3474: }
3475: return 'ok';
1.14 www 3476: }
3477:
1.109 www 3478: # ----------------------------------------------------- Devalidate Spreadsheets
3479:
3480: sub devalidate {
1.325 www 3481: my ($symb,$uname,$udom)=@_;
1.620 albertel 3482: my $cid=$env{'request.course.id'};
1.109 www 3483: if ($cid) {
1.391 matthew 3484: # delete the stored spreadsheets for
3485: # - the student level sheet of this user in course's homespace
3486: # - the assessment level sheet for this resource
3487: # for this user in user's homespace
1.553 albertel 3488: # - current conditional state info
1.325 www 3489: my $key=$uname.':'.$udom.':';
1.109 www 3490: my $status=
1.299 matthew 3491: &del('nohist_calculatedsheets',
1.391 matthew 3492: [$key.'studentcalc:'],
1.620 albertel 3493: $env{'course.'.$cid.'.domain'},
3494: $env{'course.'.$cid.'.num'})
1.133 albertel 3495: .' '.
3496: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3497: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3498: unless ($status eq 'ok ok') {
3499: &logthis('Could not devalidate spreadsheet '.
1.325 www 3500: $uname.' at '.$udom.' for '.
1.109 www 3501: $symb.': '.$status);
1.133 albertel 3502: }
1.553 albertel 3503: &delenv('user.state.'.$cid);
1.109 www 3504: }
3505: }
3506:
1.265 albertel 3507: sub get_scalar {
3508: my ($string,$end) = @_;
3509: my $value;
3510: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3511: $value = $1;
3512: } elsif ($$string =~ s/^([^&]*?)&//) {
3513: $value = $1;
3514: }
3515: return &unescape($value);
3516: }
3517:
3518: sub array2str {
3519: my (@array) = @_;
3520: my $result=&arrayref2str(\@array);
3521: $result=~s/^__ARRAY_REF__//;
3522: $result=~s/__END_ARRAY_REF__$//;
3523: return $result;
3524: }
3525:
1.204 albertel 3526: sub arrayref2str {
3527: my ($arrayref) = @_;
1.265 albertel 3528: my $result='__ARRAY_REF__';
1.204 albertel 3529: foreach my $elem (@$arrayref) {
1.265 albertel 3530: if(ref($elem) eq 'ARRAY') {
3531: $result.=&arrayref2str($elem).'&';
3532: } elsif(ref($elem) eq 'HASH') {
3533: $result.=&hashref2str($elem).'&';
3534: } elsif(ref($elem)) {
3535: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3536: } else {
3537: $result.=&escape($elem).'&';
3538: }
3539: }
3540: $result=~s/\&$//;
1.265 albertel 3541: $result .= '__END_ARRAY_REF__';
1.204 albertel 3542: return $result;
3543: }
3544:
1.168 albertel 3545: sub hash2str {
1.204 albertel 3546: my (%hash) = @_;
3547: my $result=&hashref2str(\%hash);
1.265 albertel 3548: $result=~s/^__HASH_REF__//;
3549: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3550: return $result;
3551: }
3552:
3553: sub hashref2str {
3554: my ($hashref)=@_;
1.265 albertel 3555: my $result='__HASH_REF__';
1.800 albertel 3556: foreach my $key (sort(keys(%$hashref))) {
3557: if (ref($key) eq 'ARRAY') {
3558: $result.=&arrayref2str($key).'=';
3559: } elsif (ref($key) eq 'HASH') {
3560: $result.=&hashref2str($key).'=';
3561: } elsif (ref($key)) {
1.265 albertel 3562: $result.='=';
1.800 albertel 3563: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3564: } else {
1.800 albertel 3565: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3566: }
3567:
1.800 albertel 3568: if(ref($hashref->{$key}) eq 'ARRAY') {
3569: $result.=&arrayref2str($hashref->{$key}).'&';
3570: } elsif(ref($hashref->{$key}) eq 'HASH') {
3571: $result.=&hashref2str($hashref->{$key}).'&';
3572: } elsif(ref($hashref->{$key})) {
1.265 albertel 3573: $result.='&';
1.800 albertel 3574: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3575: } else {
1.800 albertel 3576: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3577: }
3578: }
1.168 albertel 3579: $result=~s/\&$//;
1.265 albertel 3580: $result .= '__END_HASH_REF__';
1.168 albertel 3581: return $result;
3582: }
3583:
3584: sub str2hash {
1.265 albertel 3585: my ($string)=@_;
3586: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3587: return %$hash;
3588: }
3589:
3590: sub str2hashref {
1.168 albertel 3591: my ($string) = @_;
1.265 albertel 3592:
3593: my %hash;
3594:
3595: if($string !~ /^__HASH_REF__/) {
3596: if (! ($string eq '' || !defined($string))) {
3597: $hash{'error'}='Not hash reference';
3598: }
3599: return (\%hash, $string);
3600: }
3601:
3602: $string =~ s/^__HASH_REF__//;
3603:
3604: while($string !~ /^__END_HASH_REF__/) {
3605: #key
3606: my $key='';
3607: if($string =~ /^__HASH_REF__/) {
3608: ($key, $string)=&str2hashref($string);
3609: if(defined($key->{'error'})) {
3610: $hash{'error'}='Bad data';
3611: return (\%hash, $string);
3612: }
3613: } elsif($string =~ /^__ARRAY_REF__/) {
3614: ($key, $string)=&str2arrayref($string);
3615: if($key->[0] eq 'Array reference error') {
3616: $hash{'error'}='Bad data';
3617: return (\%hash, $string);
3618: }
3619: } else {
3620: $string =~ s/^(.*?)=//;
1.267 albertel 3621: $key=&unescape($1);
1.265 albertel 3622: }
3623: $string =~ s/^=//;
3624:
3625: #value
3626: my $value='';
3627: if($string =~ /^__HASH_REF__/) {
3628: ($value, $string)=&str2hashref($string);
3629: if(defined($value->{'error'})) {
3630: $hash{'error'}='Bad data';
3631: return (\%hash, $string);
3632: }
3633: } elsif($string =~ /^__ARRAY_REF__/) {
3634: ($value, $string)=&str2arrayref($string);
3635: if($value->[0] eq 'Array reference error') {
3636: $hash{'error'}='Bad data';
3637: return (\%hash, $string);
3638: }
3639: } else {
3640: $value=&get_scalar(\$string,'__END_HASH_REF__');
3641: }
3642: $string =~ s/^&//;
3643:
3644: $hash{$key}=$value;
1.204 albertel 3645: }
1.265 albertel 3646:
3647: $string =~ s/^__END_HASH_REF__//;
3648:
3649: return (\%hash, $string);
1.204 albertel 3650: }
3651:
3652: sub str2array {
1.265 albertel 3653: my ($string)=@_;
3654: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3655: return @$array;
3656: }
3657:
3658: sub str2arrayref {
1.204 albertel 3659: my ($string) = @_;
1.265 albertel 3660: my @array;
3661:
3662: if($string !~ /^__ARRAY_REF__/) {
3663: if (! ($string eq '' || !defined($string))) {
3664: $array[0]='Array reference error';
3665: }
3666: return (\@array, $string);
3667: }
3668:
3669: $string =~ s/^__ARRAY_REF__//;
3670:
3671: while($string !~ /^__END_ARRAY_REF__/) {
3672: my $value='';
3673: if($string =~ /^__HASH_REF__/) {
3674: ($value, $string)=&str2hashref($string);
3675: if(defined($value->{'error'})) {
3676: $array[0] ='Array reference error';
3677: return (\@array, $string);
3678: }
3679: } elsif($string =~ /^__ARRAY_REF__/) {
3680: ($value, $string)=&str2arrayref($string);
3681: if($value->[0] eq 'Array reference error') {
3682: $array[0] ='Array reference error';
3683: return (\@array, $string);
3684: }
3685: } else {
3686: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3687: }
3688: $string =~ s/^&//;
3689:
3690: push(@array, $value);
1.191 harris41 3691: }
1.265 albertel 3692:
3693: $string =~ s/^__END_ARRAY_REF__//;
3694:
3695: return (\@array, $string);
1.168 albertel 3696: }
3697:
1.167 albertel 3698: # -------------------------------------------------------------------Temp Store
3699:
1.168 albertel 3700: sub tmpreset {
3701: my ($symb,$namespace,$domain,$stuname) = @_;
3702: if (!$symb) {
3703: $symb=&symbread();
1.620 albertel 3704: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3705: }
3706: $symb=escape($symb);
3707:
1.620 albertel 3708: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3709: $namespace=~s/\//\_/g;
3710: $namespace=~s/\W//g;
3711:
1.620 albertel 3712: if (!$domain) { $domain=$env{'user.domain'}; }
3713: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3714: if ($domain eq 'public' && $stuname eq 'public') {
3715: $stuname=$ENV{'REMOTE_ADDR'};
3716: }
1.168 albertel 3717: my $path=$perlvar{'lonDaemons'}.'/tmp';
3718: my %hash;
3719: if (tie(%hash,'GDBM_File',
3720: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3721: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3722: foreach my $key (keys(%hash)) {
1.180 albertel 3723: if ($key=~ /:$symb/) {
1.168 albertel 3724: delete($hash{$key});
3725: }
3726: }
3727: }
3728: }
3729:
1.167 albertel 3730: sub tmpstore {
1.168 albertel 3731: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3732:
3733: if (!$symb) {
3734: $symb=&symbread();
1.620 albertel 3735: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3736: }
3737: $symb=escape($symb);
3738:
3739: if (!$namespace) {
3740: # I don't think we would ever want to store this for a course.
3741: # it seems this will only be used if we don't have a course.
1.620 albertel 3742: #$namespace=$env{'request.course.id'};
1.168 albertel 3743: #if (!$namespace) {
1.620 albertel 3744: $namespace=$env{'request.state'};
1.168 albertel 3745: #}
3746: }
3747: $namespace=~s/\//\_/g;
3748: $namespace=~s/\W//g;
1.620 albertel 3749: if (!$domain) { $domain=$env{'user.domain'}; }
3750: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3751: if ($domain eq 'public' && $stuname eq 'public') {
3752: $stuname=$ENV{'REMOTE_ADDR'};
3753: }
1.168 albertel 3754: my $now=time;
3755: my %hash;
3756: my $path=$perlvar{'lonDaemons'}.'/tmp';
3757: if (tie(%hash,'GDBM_File',
3758: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3759: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3760: $hash{"version:$symb"}++;
3761: my $version=$hash{"version:$symb"};
3762: my $allkeys='';
3763: foreach my $key (keys(%$storehash)) {
3764: $allkeys.=$key.':';
1.591 albertel 3765: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3766: }
3767: $hash{"$version:$symb:timestamp"}=$now;
3768: $allkeys.='timestamp';
3769: $hash{"$version:keys:$symb"}=$allkeys;
3770: if (untie(%hash)) {
3771: return 'ok';
3772: } else {
3773: return "error:$!";
3774: }
3775: } else {
3776: return "error:$!";
3777: }
3778: }
1.167 albertel 3779:
1.168 albertel 3780: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3781:
1.168 albertel 3782: sub tmprestore {
3783: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3784:
1.168 albertel 3785: if (!$symb) {
3786: $symb=&symbread();
1.620 albertel 3787: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3788: }
3789: $symb=escape($symb);
3790:
1.620 albertel 3791: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3792:
1.620 albertel 3793: if (!$domain) { $domain=$env{'user.domain'}; }
3794: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3795: if ($domain eq 'public' && $stuname eq 'public') {
3796: $stuname=$ENV{'REMOTE_ADDR'};
3797: }
1.168 albertel 3798: my %returnhash;
3799: $namespace=~s/\//\_/g;
3800: $namespace=~s/\W//g;
3801: my %hash;
3802: my $path=$perlvar{'lonDaemons'}.'/tmp';
3803: if (tie(%hash,'GDBM_File',
3804: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3805: &GDBM_READER(),0640)) {
1.168 albertel 3806: my $version=$hash{"version:$symb"};
3807: $returnhash{'version'}=$version;
3808: my $scope;
3809: for ($scope=1;$scope<=$version;$scope++) {
3810: my $vkeys=$hash{"$scope:keys:$symb"};
3811: my @keys=split(/:/,$vkeys);
3812: my $key;
3813: $returnhash{"$scope:keys"}=$vkeys;
3814: foreach $key (@keys) {
1.591 albertel 3815: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3816: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3817: }
3818: }
1.168 albertel 3819: if (!(untie(%hash))) {
3820: return "error:$!";
3821: }
3822: } else {
3823: return "error:$!";
3824: }
3825: return %returnhash;
1.167 albertel 3826: }
3827:
1.9 www 3828: # ----------------------------------------------------------------------- Store
3829:
3830: sub store {
1.124 www 3831: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3832: my $home='';
3833:
1.168 albertel 3834: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3835:
1.213 www 3836: $symb=&symbclean($symb);
1.122 albertel 3837: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3838:
1.620 albertel 3839: if (!$domain) { $domain=$env{'user.domain'}; }
3840: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3841:
3842: &devalidate($symb,$stuname,$domain);
1.109 www 3843:
3844: $symb=escape($symb);
1.187 www 3845: if (!$namespace) {
1.620 albertel 3846: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3847: return '';
3848: }
3849: }
1.620 albertel 3850: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3851:
3852: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3853: $$storehash{'host'}=$perlvar{'lonHostID'};
3854:
1.12 www 3855: my $namevalue='';
1.800 albertel 3856: foreach my $key (keys(%$storehash)) {
3857: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3858: }
1.12 www 3859: $namevalue=~s/\&$//;
1.187 www 3860: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3861: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3862: }
3863:
1.47 www 3864: # -------------------------------------------------------------- Critical Store
3865:
3866: sub cstore {
1.124 www 3867: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3868: my $home='';
3869:
1.168 albertel 3870: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3871:
1.213 www 3872: $symb=&symbclean($symb);
1.122 albertel 3873: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3874:
1.620 albertel 3875: if (!$domain) { $domain=$env{'user.domain'}; }
3876: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3877:
3878: &devalidate($symb,$stuname,$domain);
1.109 www 3879:
3880: $symb=escape($symb);
1.187 www 3881: if (!$namespace) {
1.620 albertel 3882: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3883: return '';
3884: }
3885: }
1.620 albertel 3886: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3887:
3888: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3889: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3890:
1.47 www 3891: my $namevalue='';
1.800 albertel 3892: foreach my $key (keys(%$storehash)) {
3893: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3894: }
1.47 www 3895: $namevalue=~s/\&$//;
1.187 www 3896: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3897: return critical
3898: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3899: }
3900:
1.9 www 3901: # --------------------------------------------------------------------- Restore
3902:
3903: sub restore {
1.124 www 3904: my ($symb,$namespace,$domain,$stuname) = @_;
3905: my $home='';
3906:
1.168 albertel 3907: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3908:
1.122 albertel 3909: if (!$symb) {
3910: unless ($symb=escape(&symbread())) { return ''; }
3911: } else {
1.213 www 3912: $symb=&escape(&symbclean($symb));
1.122 albertel 3913: }
1.188 www 3914: if (!$namespace) {
1.620 albertel 3915: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3916: return '';
3917: }
3918: }
1.620 albertel 3919: if (!$domain) { $domain=$env{'user.domain'}; }
3920: if (!$stuname) { $stuname=$env{'user.name'}; }
3921: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3922: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3923:
1.12 www 3924: my %returnhash=();
1.800 albertel 3925: foreach my $line (split(/\&/,$answer)) {
3926: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3927: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3928: }
1.75 www 3929: my $version;
3930: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3931: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3932: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3933: }
1.75 www 3934: }
1.13 www 3935: return %returnhash;
1.34 www 3936: }
3937:
3938: # ---------------------------------------------------------- Course Description
3939:
3940: sub coursedescription {
1.731 albertel 3941: my ($courseid,$args)=@_;
1.34 www 3942: $courseid=~s/^\///;
1.49 www 3943: $courseid=~s/\_/\//g;
1.34 www 3944: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3945: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3946: my $normalid=$cdomain.'_'.$cnum;
3947: # need to always cache even if we get errors otherwise we keep
3948: # trying and trying and trying to get the course description.
3949: my %envhash=();
3950: my %returnhash=();
1.731 albertel 3951:
3952: my $expiretime=600;
3953: if ($env{'request.course.id'} eq $normalid) {
3954: $expiretime=120;
3955: }
3956:
3957: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3958: if (!$args->{'freshen_cache'}
3959: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3960: foreach my $key (keys(%env)) {
3961: next if ($key !~ /^\Q$prefix\E(.*)/);
3962: my ($setting) = $1;
3963: $returnhash{$setting} = $env{$key};
3964: }
3965: return %returnhash;
3966: }
3967:
3968: # get the data agin
3969: if (!$args->{'one_time'}) {
3970: $envhash{'course.'.$normalid.'.last_cache'}=time;
3971: }
1.811 albertel 3972:
1.34 www 3973: if ($chome ne 'no_host') {
1.302 albertel 3974: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3975: if (!exists($returnhash{'con_lost'})) {
3976: $returnhash{'home'}= $chome;
3977: $returnhash{'domain'} = $cdomain;
3978: $returnhash{'num'} = $cnum;
1.741 raeburn 3979: if (!defined($returnhash{'type'})) {
3980: $returnhash{'type'} = 'Course';
3981: }
1.130 albertel 3982: while (my ($name,$value) = each %returnhash) {
1.53 www 3983: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3984: }
1.270 www 3985: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3986: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3987: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3988: $envhash{'course.'.$normalid.'.home'}=$chome;
3989: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3990: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3991: }
3992: }
1.731 albertel 3993: if (!$args->{'one_time'}) {
1.949 raeburn 3994: &appenv(\%envhash);
1.731 albertel 3995: }
1.302 albertel 3996: return %returnhash;
1.461 www 3997: }
3998:
1.1080 raeburn 3999: sub update_released_required {
4000: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4001: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4002: $cid = $env{'request.course.id'};
4003: $cdom = $env{'course.'.$cid.'.domain'};
4004: $cnum = $env{'course.'.$cid.'.num'};
4005: $chome = $env{'course.'.$cid.'.home'};
4006: }
4007: if ($needsrelease) {
4008: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4009: my $needsupdate;
4010: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4011: $needsupdate = 1;
4012: } else {
4013: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4014: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4015: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4016: $needsupdate = 1;
4017: }
4018: }
4019: if ($needsupdate) {
4020: my %needshash = (
4021: 'internal.releaserequired' => $needsrelease,
4022: );
4023: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4024: if ($putresult eq 'ok') {
4025: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4026: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4027: if (ref($crsinfo{$cid}) eq 'HASH') {
4028: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4029: &courseidput($cdom,\%crsinfo,$chome,'notime');
4030: }
4031: }
4032: }
4033: }
4034: return;
4035: }
4036:
1.461 www 4037: # -------------------------------------------------See if a user is privileged
4038:
4039: sub privileged {
4040: my ($username,$domain)=@_;
4041: my $rolesdump=&reply("dump:$domain:$username:roles",
4042: &homeserver($username,$domain));
1.1033 raeburn 4043: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4044: ($rolesdump =~ /^error:/)) {
4045: return 0;
4046: }
1.461 www 4047: my $now=time;
4048: if ($rolesdump ne '') {
1.800 albertel 4049: foreach my $entry (split(/&/,$rolesdump)) {
4050: if ($entry!~/^rolesdef_/) {
4051: my ($area,$role)=split(/=/,$entry);
1.461 www 4052: $area=~s/\_\w\w$//;
4053: my ($trole,$tend,$tstart)=split(/_/,$role);
4054: if (($trole eq 'dc') || ($trole eq 'su')) {
4055: my $active=1;
4056: if ($tend) {
4057: if ($tend<$now) { $active=0; }
4058: }
4059: if ($tstart) {
4060: if ($tstart>$now) { $active=0; }
4061: }
4062: if ($active) { return 1; }
4063: }
4064: }
4065: }
4066: }
4067: return 0;
1.9 www 4068: }
1.1 albertel 4069:
1.103 harris41 4070: # -------------------------------------------------------- Get user privileges
1.11 www 4071:
4072: sub rolesinit {
4073: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4074: my $now=time;
4075: my %userroles = ('user.login.time' => $now);
1.1086 raeburn 4076: my $extra = &freeze_escape({'skipcheck' => 1});
1.1078 raeburn 4077: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4078: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1078 raeburn 4079: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4080: return \%userroles;
4081: }
1.11 www 4082: my %allroles=();
1.678 raeburn 4083: my %allgroups=();
4084: my $group_privs;
1.11 www 4085:
4086: if ($rolesdump ne '') {
1.800 albertel 4087: foreach my $entry (split(/&/,$rolesdump)) {
4088: if ($entry!~/^rolesdef_/) {
4089: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4090: $area=~s/\_\w\w$//;
1.678 raeburn 4091: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4092: if ($role=~/^cr/) {
1.807 albertel 4093: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4094: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4095: ($tend,$tstart)=split('_',$trest);
4096: } else {
4097: $trole=$role;
4098: }
1.678 raeburn 4099: } elsif ($role =~ m|^gr/|) {
4100: ($trole,$tend,$tstart) = split(/_/,$role);
4101: ($trole,$group_privs) = split(/\//,$trole);
4102: $group_privs = &unescape($group_privs);
1.587 albertel 4103: } else {
4104: ($trole,$tend,$tstart)=split(/_/,$role);
4105: }
1.743 albertel 4106: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4107: $username);
4108: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4109: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4110: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4111: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4112: my $spec=$trole.'.'.$area;
4113: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4114: if ($trole =~ /^cr\//) {
1.567 raeburn 4115: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4116: } elsif ($trole eq 'gr') {
4117: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4118: } else {
1.567 raeburn 4119: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4120: }
1.12 www 4121: }
1.662 raeburn 4122: }
1.191 harris41 4123: }
1.743 albertel 4124: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4125: $userroles{'user.adv'} = $adv;
4126: $userroles{'user.author'} = $author;
1.620 albertel 4127: $env{'user.adv'}=$adv;
1.11 www 4128: }
1.743 albertel 4129: return \%userroles;
1.11 www 4130: }
4131:
1.567 raeburn 4132: sub set_arearole {
4133: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4134: # log the associated role with the area
4135: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4136: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4137: }
4138:
4139: sub custom_roleprivs {
4140: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4141: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4142: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4143: if (&hostname($homsvr) ne '') {
1.567 raeburn 4144: my ($rdummy,$roledef)=
4145: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4146: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4147: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4148: if (defined($syspriv)) {
1.1043 raeburn 4149: if ($trest =~ /^$match_community$/) {
4150: $syspriv =~ s/bre\&S//;
4151: }
1.567 raeburn 4152: $$allroles{'cm./'}.=':'.$syspriv;
4153: $$allroles{$spec.'./'}.=':'.$syspriv;
4154: }
4155: if ($tdomain ne '') {
4156: if (defined($dompriv)) {
4157: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4158: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4159: }
4160: if (($trest ne '') && (defined($coursepriv))) {
4161: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4162: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4163: }
4164: }
4165: }
4166: }
4167: }
4168:
1.678 raeburn 4169: sub group_roleprivs {
4170: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4171: my $access = 1;
4172: my $now = time;
4173: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4174: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4175: if ($access) {
1.811 albertel 4176: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4177: $$allgroups{$course}{$group} .=':'.$group_privs;
4178: }
4179: }
1.567 raeburn 4180:
4181: sub standard_roleprivs {
4182: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4183: if (defined($pr{$trole.':s'})) {
4184: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4185: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4186: }
4187: if ($tdomain ne '') {
4188: if (defined($pr{$trole.':d'})) {
4189: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4190: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4191: }
4192: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4193: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4194: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4195: }
4196: }
4197: }
4198:
4199: sub set_userprivs {
1.1064 raeburn 4200: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4201: my $author=0;
4202: my $adv=0;
1.678 raeburn 4203: my %grouproles = ();
4204: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4205: my @groupkeys;
1.1000 raeburn 4206: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4207: push(@groupkeys,$role);
4208: }
4209: if (ref($groups_roles) eq 'HASH') {
4210: foreach my $key (keys(%{$groups_roles})) {
4211: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4212: push(@groupkeys,$key);
4213: }
4214: }
4215: }
4216: if (@groupkeys > 0) {
4217: foreach my $role (@groupkeys) {
4218: my ($trole,$area,$sec,$extendedarea);
4219: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4220: $trole = $1;
4221: $area = $2;
4222: $sec = $3;
4223: $extendedarea = $area.$sec;
4224: if (exists($$allgroups{$area})) {
4225: foreach my $group (keys(%{$$allgroups{$area}})) {
4226: my $spec = $trole.'.'.$extendedarea;
4227: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4228: $$allgroups{$area}{$group};
1.1064 raeburn 4229: }
1.678 raeburn 4230: }
4231: }
4232: }
4233: }
4234: }
1.800 albertel 4235: foreach my $group (keys(%grouproles)) {
4236: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4237: }
1.800 albertel 4238: foreach my $role (keys(%{$allroles})) {
4239: my %thesepriv;
1.941 raeburn 4240: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4241: foreach my $item (split(/:/,$$allroles{$role})) {
4242: if ($item ne '') {
4243: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4244: if ($restrictions eq '') {
4245: $thesepriv{$privilege}='F';
4246: } elsif ($thesepriv{$privilege} ne 'F') {
4247: $thesepriv{$privilege}.=$restrictions;
4248: }
4249: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4250: }
4251: }
4252: my $thesestr='';
1.800 albertel 4253: foreach my $priv (keys(%thesepriv)) {
4254: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4255: }
4256: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4257: }
4258: return ($author,$adv);
4259: }
4260:
1.994 raeburn 4261: sub role_status {
1.1002 raeburn 4262: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4263: my @pwhere = ();
4264: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4265: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4266: unless (!defined($$role) || $$role eq '') {
4267: $$where=join('.',@pwhere);
4268: $$trolecode=$$role.'.'.$$where;
4269: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4270: $$tstatus='is';
4271: if ($$tstart && $$tstart>$then) {
4272: $$tstatus='future';
1.1034 raeburn 4273: if ($$tstart<$now) {
4274: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4275: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4276: my (%allroles,%allgroups,$group_privs,
4277: %groups_roles,@rolecodes);
1.1002 raeburn 4278: my %userroles = (
4279: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4280: );
1.1064 raeburn 4281: @rolecodes = ('cm');
1.1002 raeburn 4282: my $spec=$$role.'.'.$$where;
4283: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4284: if ($$role =~ /^cr\//) {
4285: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4286: push(@rolecodes,'cr');
1.1002 raeburn 4287: } elsif ($$role eq 'gr') {
1.1064 raeburn 4288: push(@rolecodes,$$role);
1.1002 raeburn 4289: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4290: $env{'user.name'});
1.1064 raeburn 4291: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4292: (undef,my $group_privs) = split(/\//,$trole);
4293: $group_privs = &unescape($group_privs);
4294: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4295: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4296: if (keys(%course_roles) > 0) {
4297: my ($tnum) = ($trest =~ /^($match_courseid)/);
4298: if ($tdomain ne '' && $tnum ne '') {
4299: foreach my $key (keys(%course_roles)) {
4300: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4301: my $crsrole = $1;
4302: my $crssec = $2;
4303: if ($crsrole =~ /^cr/) {
4304: unless (grep(/^cr$/,@rolecodes)) {
4305: push(@rolecodes,'cr');
4306: }
4307: } else {
4308: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4309: push(@rolecodes,$crsrole);
4310: }
4311: }
4312: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4313: if ($crssec ne '') {
4314: $rolekey .= '/'.$crssec;
4315: }
4316: $rolekey .= './';
4317: $groups_roles{$rolekey} = \@rolecodes;
4318: }
4319: }
4320: }
4321: }
1.1002 raeburn 4322: } else {
1.1064 raeburn 4323: push(@rolecodes,$$role);
1.1002 raeburn 4324: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4325: }
1.1064 raeburn 4326: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4327: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4328: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4329: }
4330: }
1.1034 raeburn 4331: $$tstatus = 'is';
1.1002 raeburn 4332: }
1.994 raeburn 4333: }
4334: if ($$tend) {
4335: if ($$tend<$then) {
4336: $$tstatus='expired';
4337: } elsif ($$tend<$now) {
4338: $$tstatus='will_not';
4339: }
4340: }
4341: }
4342: }
4343: }
4344:
4345: sub check_adhoc_privs {
1.1088 raeburn 4346: my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4347: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4348: if ($env{$cckey}) {
4349: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4350: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4351: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 4352: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4353: }
4354: } else {
1.1088 raeburn 4355: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4356: }
4357: }
4358:
4359: sub set_adhoc_privileges {
4360: # role can be cc or ca
1.1088 raeburn 4361: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4362: my $area = '/'.$dcdom.'/'.$pickedcourse;
4363: my $spec = $role.'.'.$area;
4364: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4365: $env{'user.name'});
4366: my %ccrole = ();
4367: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4368: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4369: &appenv(\%userroles,[$role,'cm']);
4370: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 4371: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4372: &appenv( {'request.role' => $spec,
4373: 'request.role.domain' => $dcdom,
4374: 'request.course.sec' => ''
4375: }
4376: );
4377: my $tadv=0;
4378: if (&allowed('adv') eq 'F') { $tadv=1; }
4379: &appenv({'request.role.adv' => $tadv});
4380: }
1.994 raeburn 4381: }
4382:
1.12 www 4383: # --------------------------------------------------------------- get interface
4384:
4385: sub get {
1.131 albertel 4386: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4387: my $items='';
1.800 albertel 4388: foreach my $item (@$storearr) {
4389: $items.=&escape($item).'&';
1.191 harris41 4390: }
1.12 www 4391: $items=~s/\&$//;
1.620 albertel 4392: if (!$udomain) { $udomain=$env{'user.domain'}; }
4393: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4394: my $uhome=&homeserver($uname,$udomain);
4395:
1.133 albertel 4396: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4397: my @pairs=split(/\&/,$rep);
1.273 albertel 4398: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4399: return @pairs;
4400: }
1.15 www 4401: my %returnhash=();
1.42 www 4402: my $i=0;
1.800 albertel 4403: foreach my $item (@$storearr) {
4404: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4405: $i++;
1.191 harris41 4406: }
1.15 www 4407: return %returnhash;
1.27 www 4408: }
4409:
4410: # --------------------------------------------------------------- del interface
4411:
4412: sub del {
1.133 albertel 4413: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4414: my $items='';
1.800 albertel 4415: foreach my $item (@$storearr) {
4416: $items.=&escape($item).'&';
1.191 harris41 4417: }
1.984 neumanie 4418:
1.27 www 4419: $items=~s/\&$//;
1.620 albertel 4420: if (!$udomain) { $udomain=$env{'user.domain'}; }
4421: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4422: my $uhome=&homeserver($uname,$udomain);
4423: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4424: }
4425:
4426: # -------------------------------------------------------------- dump interface
4427:
4428: sub dump {
1.1086 raeburn 4429: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4430: if (!$udomain) { $udomain=$env{'user.domain'}; }
4431: if (!$uname) { $uname=$env{'user.name'}; }
4432: my $uhome=&homeserver($uname,$udomain);
4433: if ($regexp) {
4434: $regexp=&escape($regexp);
4435: } else {
4436: $regexp='.';
4437: }
1.1086 raeburn 4438: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4439: my @pairs=split(/\&/,$rep);
4440: my %returnhash=();
1.1098 foxr 4441: if (!($rep =~ /^error/ )) {
4442: foreach my $item (@pairs) {
4443: my ($key,$value)=split(/=/,$item,2);
4444: $key = &unescape($key);
4445: next if ($key =~ /^error: 2 /);
4446: $returnhash{$key}=&thaw_unescape($value);
4447: }
1.755 albertel 4448: }
4449: return %returnhash;
1.407 www 4450: }
4451:
1.1098 foxr 4452:
1.717 albertel 4453: # --------------------------------------------------------- dumpstore interface
4454:
4455: sub dumpstore {
4456: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4457: if (!$udomain) { $udomain=$env{'user.domain'}; }
4458: if (!$uname) { $uname=$env{'user.name'}; }
4459: my $uhome=&homeserver($uname,$udomain);
4460: if ($regexp) {
4461: $regexp=&escape($regexp);
4462: } else {
4463: $regexp='.';
4464: }
4465: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4466: my @pairs=split(/\&/,$rep);
4467: my %returnhash=();
4468: foreach my $item (@pairs) {
4469: my ($key,$value)=split(/=/,$item,2);
4470: next if ($key =~ /^error: 2 /);
4471: $returnhash{$key}=&thaw_unescape($value);
4472: }
4473: return %returnhash;
1.717 albertel 4474: }
4475:
1.407 www 4476: # -------------------------------------------------------------- keys interface
4477:
4478: sub getkeys {
4479: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4480: if (!$udomain) { $udomain=$env{'user.domain'}; }
4481: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4482: my $uhome=&homeserver($uname,$udomain);
4483: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4484: my @keyarray=();
1.800 albertel 4485: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4486: next if ($key =~ /^error: 2 /);
1.800 albertel 4487: push(@keyarray,&unescape($key));
1.407 www 4488: }
4489: return @keyarray;
1.318 matthew 4490: }
4491:
1.319 matthew 4492: # --------------------------------------------------------------- currentdump
4493: sub currentdump {
1.328 matthew 4494: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4495: $courseid = $env{'request.course.id'} if (! defined($courseid));
4496: $sdom = $env{'user.domain'} if (! defined($sdom));
4497: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4498: my $uhome = &homeserver($sname,$sdom);
4499: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4500: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4501: #
1.318 matthew 4502: my %returnhash=();
1.319 matthew 4503: #
4504: if ($rep eq "unknown_cmd") {
4505: # an old lond will not know currentdump
4506: # Do a dump and make it look like a currentdump
1.822 albertel 4507: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4508: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4509: my %hash = @tmp;
4510: @tmp=();
1.424 matthew 4511: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4512: } else {
4513: my @pairs=split(/\&/,$rep);
1.800 albertel 4514: foreach my $pair (@pairs) {
4515: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4516: my ($symb,$param) = split(/:/,$key);
4517: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4518: &thaw_unescape($value);
1.319 matthew 4519: }
1.191 harris41 4520: }
1.12 www 4521: return %returnhash;
1.424 matthew 4522: }
4523:
4524: sub convert_dump_to_currentdump{
4525: my %hash = %{shift()};
4526: my %returnhash;
4527: # Code ripped from lond, essentially. The only difference
4528: # here is the unescaping done by lonnet::dump(). Conceivably
4529: # we might run in to problems with parameter names =~ /^v\./
4530: while (my ($key,$value) = each(%hash)) {
4531: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4532: $symb = &unescape($symb);
4533: $param = &unescape($param);
1.424 matthew 4534: next if ($v eq 'version' || $symb eq 'keys');
4535: next if (exists($returnhash{$symb}) &&
4536: exists($returnhash{$symb}->{$param}) &&
4537: $returnhash{$symb}->{'v.'.$param} > $v);
4538: $returnhash{$symb}->{$param}=$value;
4539: $returnhash{$symb}->{'v.'.$param}=$v;
4540: }
4541: #
4542: # Remove all of the keys in the hashes which keep track of
4543: # the version of the parameter.
4544: while (my ($symb,$param_hash) = each(%returnhash)) {
4545: # use a foreach because we are going to delete from the hash.
4546: foreach my $key (keys(%$param_hash)) {
4547: delete($param_hash->{$key}) if ($key =~ /^v\./);
4548: }
4549: }
4550: return \%returnhash;
1.12 www 4551: }
4552:
1.627 albertel 4553: # ------------------------------------------------------ critical inc interface
4554:
4555: sub cinc {
4556: return &inc(@_,'critical');
4557: }
4558:
1.449 matthew 4559: # --------------------------------------------------------------- inc interface
4560:
4561: sub inc {
1.627 albertel 4562: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4563: if (!$udomain) { $udomain=$env{'user.domain'}; }
4564: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4565: my $uhome=&homeserver($uname,$udomain);
4566: my $items='';
4567: if (! ref($store)) {
4568: # got a single value, so use that instead
4569: $items = &escape($store).'=&';
4570: } elsif (ref($store) eq 'SCALAR') {
4571: $items = &escape($$store).'=&';
4572: } elsif (ref($store) eq 'ARRAY') {
4573: $items = join('=&',map {&escape($_);} @{$store});
4574: } elsif (ref($store) eq 'HASH') {
4575: while (my($key,$value) = each(%{$store})) {
4576: $items.= &escape($key).'='.&escape($value).'&';
4577: }
4578: }
4579: $items=~s/\&$//;
1.627 albertel 4580: if ($critical) {
4581: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4582: } else {
4583: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4584: }
1.449 matthew 4585: }
4586:
1.12 www 4587: # --------------------------------------------------------------- put interface
4588:
4589: sub put {
1.134 albertel 4590: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4591: if (!$udomain) { $udomain=$env{'user.domain'}; }
4592: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4593: my $uhome=&homeserver($uname,$udomain);
1.12 www 4594: my $items='';
1.800 albertel 4595: foreach my $item (keys(%$storehash)) {
4596: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4597: }
1.12 www 4598: $items=~s/\&$//;
1.134 albertel 4599: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4600: }
4601:
1.631 albertel 4602: # ------------------------------------------------------------ newput interface
4603:
4604: sub newput {
4605: my ($namespace,$storehash,$udomain,$uname)=@_;
4606: if (!$udomain) { $udomain=$env{'user.domain'}; }
4607: if (!$uname) { $uname=$env{'user.name'}; }
4608: my $uhome=&homeserver($uname,$udomain);
4609: my $items='';
4610: foreach my $key (keys(%$storehash)) {
4611: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4612: }
4613: $items=~s/\&$//;
4614: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4615: }
4616:
4617: # --------------------------------------------------------- putstore interface
4618:
1.524 raeburn 4619: sub putstore {
1.715 albertel 4620: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4621: if (!$udomain) { $udomain=$env{'user.domain'}; }
4622: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4623: my $uhome=&homeserver($uname,$udomain);
4624: my $items='';
1.715 albertel 4625: foreach my $key (keys(%$storehash)) {
4626: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4627: }
1.715 albertel 4628: $items=~s/\&$//;
1.716 albertel 4629: my $esc_symb=&escape($symb);
4630: my $esc_v=&escape($version);
1.715 albertel 4631: my $reply =
1.716 albertel 4632: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4633: $uhome);
4634: if ($reply eq 'unknown_cmd') {
1.716 albertel 4635: # gfall back to way things use to be done
1.715 albertel 4636: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4637: $uname);
1.524 raeburn 4638: }
1.715 albertel 4639: return $reply;
4640: }
4641:
4642: sub old_putstore {
1.716 albertel 4643: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4644: if (!$udomain) { $udomain=$env{'user.domain'}; }
4645: if (!$uname) { $uname=$env{'user.name'}; }
4646: my $uhome=&homeserver($uname,$udomain);
4647: my %newstorehash;
1.800 albertel 4648: foreach my $item (keys(%$storehash)) {
4649: my $key = $version.':'.&escape($symb).':'.$item;
4650: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4651: }
4652: my $items='';
4653: my %allitems = ();
1.800 albertel 4654: foreach my $item (keys(%newstorehash)) {
4655: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4656: my $key = $1.':keys:'.$2;
4657: $allitems{$key} .= $3.':';
4658: }
1.800 albertel 4659: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4660: }
1.800 albertel 4661: foreach my $item (keys(%allitems)) {
4662: $allitems{$item} =~ s/\:$//;
4663: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4664: }
4665: $items=~s/\&$//;
4666: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4667: }
4668:
1.47 www 4669: # ------------------------------------------------------ critical put interface
4670:
4671: sub cput {
1.134 albertel 4672: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4673: if (!$udomain) { $udomain=$env{'user.domain'}; }
4674: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4675: my $uhome=&homeserver($uname,$udomain);
1.47 www 4676: my $items='';
1.800 albertel 4677: foreach my $item (keys(%$storehash)) {
4678: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4679: }
1.47 www 4680: $items=~s/\&$//;
1.134 albertel 4681: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4682: }
4683:
4684: # -------------------------------------------------------------- eget interface
4685:
4686: sub eget {
1.133 albertel 4687: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4688: my $items='';
1.800 albertel 4689: foreach my $item (@$storearr) {
4690: $items.=&escape($item).'&';
1.191 harris41 4691: }
1.12 www 4692: $items=~s/\&$//;
1.620 albertel 4693: if (!$udomain) { $udomain=$env{'user.domain'}; }
4694: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4695: my $uhome=&homeserver($uname,$udomain);
4696: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4697: my @pairs=split(/\&/,$rep);
4698: my %returnhash=();
1.42 www 4699: my $i=0;
1.800 albertel 4700: foreach my $item (@$storearr) {
4701: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4702: $i++;
1.191 harris41 4703: }
1.12 www 4704: return %returnhash;
4705: }
4706:
1.667 albertel 4707: # ------------------------------------------------------------ tmpput interface
4708: sub tmpput {
1.802 raeburn 4709: my ($storehash,$server,$context)=@_;
1.667 albertel 4710: my $items='';
1.800 albertel 4711: foreach my $item (keys(%$storehash)) {
4712: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4713: }
4714: $items=~s/\&$//;
1.802 raeburn 4715: if (defined($context)) {
4716: $items .= ':'.&escape($context);
4717: }
1.667 albertel 4718: return &reply("tmpput:$items",$server);
4719: }
4720:
4721: # ------------------------------------------------------------ tmpget interface
4722: sub tmpget {
1.688 albertel 4723: my ($token,$server)=@_;
4724: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4725: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4726: my %returnhash;
4727: foreach my $item (split(/\&/,$rep)) {
4728: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4729: next if ($key =~ /^error: 2 /);
1.667 albertel 4730: $returnhash{&unescape($key)}=&thaw_unescape($value);
4731: }
4732: return %returnhash;
4733: }
4734:
1.688 albertel 4735: # ------------------------------------------------------------ tmpget interface
4736: sub tmpdel {
4737: my ($token,$server)=@_;
4738: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4739: return &reply("tmpdel:$token",$server);
4740: }
4741:
1.765 albertel 4742: # -------------------------------------------------- portfolio access checking
4743:
4744: sub portfolio_access {
1.766 albertel 4745: my ($requrl) = @_;
1.765 albertel 4746: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4747: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4748: if ($result) {
4749: my %setters;
4750: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4751: my ($startblock,$endblock) =
4752: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4753: if ($startblock && $endblock) {
4754: return 'B';
4755: }
4756: } else {
4757: my ($startblock,$endblock) =
4758: &Apache::loncommon::blockcheck(\%setters,'port');
4759: if ($startblock && $endblock) {
4760: return 'B';
4761: }
4762: }
4763: }
1.765 albertel 4764: if ($result eq 'ok') {
1.766 albertel 4765: return 'F';
1.765 albertel 4766: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4767: return 'A';
1.765 albertel 4768: }
1.766 albertel 4769: return '';
1.765 albertel 4770: }
4771:
4772: sub get_portfolio_access {
1.767 albertel 4773: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4774:
4775: if (!ref($access_hash)) {
4776: my $current_perms = &get_portfile_permissions($udom,$unum);
4777: my %access_controls = &get_access_controls($current_perms,$group,
4778: $file_name);
4779: $access_hash = $access_controls{$file_name};
4780: }
4781:
1.765 albertel 4782: my ($public,$guest,@domains,@users,@courses,@groups);
4783: my $now = time;
4784: if (ref($access_hash) eq 'HASH') {
4785: foreach my $key (keys(%{$access_hash})) {
4786: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4787: if ($start > $now) {
4788: next;
4789: }
4790: if ($end && $end<$now) {
4791: next;
4792: }
4793: if ($scope eq 'public') {
4794: $public = $key;
4795: last;
4796: } elsif ($scope eq 'guest') {
4797: $guest = $key;
4798: } elsif ($scope eq 'domains') {
4799: push(@domains,$key);
4800: } elsif ($scope eq 'users') {
4801: push(@users,$key);
4802: } elsif ($scope eq 'course') {
4803: push(@courses,$key);
4804: } elsif ($scope eq 'group') {
4805: push(@groups,$key);
4806: }
4807: }
4808: if ($public) {
4809: return 'ok';
4810: }
4811: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4812: if ($guest) {
4813: return $guest;
4814: }
4815: } else {
4816: if (@domains > 0) {
4817: foreach my $domkey (@domains) {
4818: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4819: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4820: return 'ok';
4821: }
4822: }
4823: }
4824: }
4825: if (@users > 0) {
4826: foreach my $userkey (@users) {
1.865 raeburn 4827: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4828: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4829: if (ref($item) eq 'HASH') {
4830: if (($item->{'uname'} eq $env{'user.name'}) &&
4831: ($item->{'udom'} eq $env{'user.domain'})) {
4832: return 'ok';
4833: }
4834: }
4835: }
4836: }
1.765 albertel 4837: }
4838: }
4839: my %roleshash;
4840: my @courses_and_groups = @courses;
4841: push(@courses_and_groups,@groups);
4842: if (@courses_and_groups > 0) {
4843: my (%allgroups,%allroles);
4844: my ($start,$end,$role,$sec,$group);
4845: foreach my $envkey (%env) {
1.1060 raeburn 4846: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4847: my $cid = $2.'_'.$3;
4848: if ($1 eq 'gr') {
4849: $group = $4;
4850: $allgroups{$cid}{$group} = $env{$envkey};
4851: } else {
4852: if ($4 eq '') {
4853: $sec = 'none';
4854: } else {
4855: $sec = $4;
4856: }
4857: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4858: }
1.811 albertel 4859: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4860: my $cid = $2.'_'.$3;
4861: if ($4 eq '') {
4862: $sec = 'none';
4863: } else {
4864: $sec = $4;
4865: }
4866: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4867: }
4868: }
4869: if (keys(%allroles) == 0) {
4870: return;
4871: }
4872: foreach my $key (@courses_and_groups) {
4873: my %content = %{$$access_hash{$key}};
4874: my $cnum = $content{'number'};
4875: my $cdom = $content{'domain'};
4876: my $cid = $cdom.'_'.$cnum;
4877: if (!exists($allroles{$cid})) {
4878: next;
4879: }
4880: foreach my $role_id (keys(%{$content{'roles'}})) {
4881: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4882: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4883: my @status = @{$content{'roles'}{$role_id}{'access'}};
4884: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4885: foreach my $role (keys(%{$allroles{$cid}})) {
4886: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4887: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4888: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4889: if (grep/^all$/,@sections) {
4890: return 'ok';
4891: } else {
4892: if (grep/^$sec$/,@sections) {
4893: return 'ok';
4894: }
4895: }
4896: }
4897: }
4898: if (keys(%{$allgroups{$cid}}) == 0) {
4899: if (grep/^none$/,@groups) {
4900: return 'ok';
4901: }
4902: } else {
4903: if (grep/^all$/,@groups) {
4904: return 'ok';
4905: }
4906: foreach my $group (keys(%{$allgroups{$cid}})) {
4907: if (grep/^$group$/,@groups) {
4908: return 'ok';
4909: }
4910: }
4911: }
4912: }
4913: }
4914: }
4915: }
4916: }
4917: if ($guest) {
4918: return $guest;
4919: }
4920: }
4921: }
4922: return;
4923: }
4924:
4925: sub course_group_datechecker {
4926: my ($dates,$now,$status) = @_;
4927: my ($start,$end) = split(/\./,$dates);
4928: if (!$start && !$end) {
4929: return 'ok';
4930: }
4931: if (grep/^active$/,@{$status}) {
4932: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4933: return 'ok';
4934: }
4935: }
4936: if (grep/^previous$/,@{$status}) {
4937: if ($end > $now ) {
4938: return 'ok';
4939: }
4940: }
4941: if (grep/^future$/,@{$status}) {
4942: if ($start > $now) {
4943: return 'ok';
4944: }
4945: }
4946: return;
4947: }
4948:
4949: sub parse_portfolio_url {
4950: my ($url) = @_;
4951:
4952: my ($type,$udom,$unum,$group,$file_name);
4953:
1.823 albertel 4954: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4955: $type = 1;
4956: $udom = $1;
4957: $unum = $2;
4958: $file_name = $3;
1.823 albertel 4959: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4960: $type = 2;
4961: $udom = $1;
4962: $unum = $2;
4963: $group = $3;
4964: $file_name = $3.'/'.$4;
4965: }
4966: if (wantarray) {
4967: return ($type,$udom,$unum,$file_name,$group);
4968: }
4969: return $type;
4970: }
4971:
4972: sub is_portfolio_url {
4973: my ($url) = @_;
4974: return scalar(&parse_portfolio_url($url));
4975: }
4976:
1.798 raeburn 4977: sub is_portfolio_file {
4978: my ($file) = @_;
1.820 raeburn 4979: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4980: return 1;
4981: }
4982: return;
4983: }
4984:
1.976 raeburn 4985: sub usertools_access {
1.1084 raeburn 4986: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 4987: my ($access,%tools);
4988: if ($context eq '') {
4989: $context = 'tools';
4990: }
4991: if ($context eq 'requestcourses') {
4992: %tools = (
4993: official => 1,
4994: unofficial => 1,
1.1006 raeburn 4995: community => 1,
1.985 raeburn 4996: );
4997: } else {
4998: %tools = (
4999: aboutme => 1,
5000: blog => 1,
5001: portfolio => 1,
5002: );
5003: }
1.976 raeburn 5004: return if (!defined($tools{$tool}));
5005:
5006: if ((!defined($udom)) || (!defined($uname))) {
5007: $udom = $env{'user.domain'};
5008: $uname = $env{'user.name'};
5009: }
5010:
1.978 raeburn 5011: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5012: if ($action ne 'reload') {
1.985 raeburn 5013: if ($context eq 'requestcourses') {
5014: return $env{'environment.canrequest.'.$tool};
5015: } else {
5016: return $env{'environment.availabletools.'.$tool};
5017: }
5018: }
1.976 raeburn 5019: }
5020:
5021: my ($toolstatus,$inststatus);
5022:
1.985 raeburn 5023: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5024: ($action ne 'reload')) {
5025: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5026: $inststatus = $env{'environment.inststatus'};
5027: } else {
1.1084 raeburn 5028: if (ref($userenvref) eq 'HASH') {
5029: $toolstatus = $userenvref->{$context.'.'.$tool};
5030: $inststatus = $userenvref->{'inststatus'};
5031: } else {
5032: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5033: $toolstatus = $userenv{$context.'.'.$tool};
5034: $inststatus = $userenv{'inststatus'};
5035: }
1.976 raeburn 5036: }
5037:
5038: if ($toolstatus ne '') {
5039: if ($toolstatus) {
5040: $access = 1;
5041: } else {
5042: $access = 0;
5043: }
5044: return $access;
5045: }
5046:
1.1084 raeburn 5047: my ($is_adv,%domdef);
5048: if (ref($is_advref) eq 'HASH') {
5049: $is_adv = $is_advref->{'is_adv'};
5050: } else {
5051: $is_adv = &is_advanced_user($udom,$uname);
5052: }
5053: if (ref($domdefref) eq 'HASH') {
5054: %domdef = %{$domdefref};
5055: } else {
5056: %domdef = &get_domain_defaults($udom);
5057: }
1.976 raeburn 5058: if (ref($domdef{$tool}) eq 'HASH') {
5059: if ($is_adv) {
5060: if ($domdef{$tool}{'_LC_adv'} ne '') {
5061: if ($domdef{$tool}{'_LC_adv'}) {
5062: $access = 1;
5063: } else {
5064: $access = 0;
5065: }
5066: return $access;
5067: }
5068: }
5069: if ($inststatus ne '') {
5070: my ($hasaccess,$hasnoaccess);
5071: foreach my $affiliation (split(/:/,$inststatus)) {
5072: if ($domdef{$tool}{$affiliation} ne '') {
5073: if ($domdef{$tool}{$affiliation}) {
5074: $hasaccess = 1;
5075: } else {
5076: $hasnoaccess = 1;
5077: }
5078: }
5079: }
5080: if ($hasaccess || $hasnoaccess) {
5081: if ($hasaccess) {
5082: $access = 1;
5083: } elsif ($hasnoaccess) {
5084: $access = 0;
5085: }
5086: return $access;
5087: }
5088: } else {
5089: if ($domdef{$tool}{'default'} ne '') {
5090: if ($domdef{$tool}{'default'}) {
5091: $access = 1;
5092: } elsif ($domdef{$tool}{'default'} == 0) {
5093: $access = 0;
5094: }
5095: return $access;
5096: }
5097: }
5098: } else {
1.985 raeburn 5099: if ($context eq 'tools') {
5100: $access = 1;
5101: } else {
5102: $access = 0;
5103: }
1.976 raeburn 5104: return $access;
5105: }
5106: }
5107:
1.1050 raeburn 5108: sub is_course_owner {
5109: my ($cdom,$cnum,$udom,$uname) = @_;
5110: if (($udom eq '') || ($uname eq '')) {
5111: $udom = $env{'user.domain'};
5112: $uname = $env{'user.name'};
5113: }
5114: unless (($udom eq '') || ($uname eq '')) {
5115: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5116: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5117: return 1;
5118: } else {
5119: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5120: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5121: return 1;
5122: }
5123: }
5124: }
5125: }
5126: return;
5127: }
5128:
1.976 raeburn 5129: sub is_advanced_user {
5130: my ($udom,$uname) = @_;
1.1085 raeburn 5131: if ($udom ne '' && $uname ne '') {
5132: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5133: return $env{'user.adv'};
5134: }
5135: }
1.976 raeburn 5136: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5137: my %allroles;
5138: my $is_adv;
5139: foreach my $role (keys(%roleshash)) {
5140: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5141: my $area = '/'.$tdomain.'/'.$trest;
5142: if ($sec ne '') {
5143: $area .= '/'.$sec;
5144: }
5145: if (($area ne '') && ($trole ne '')) {
5146: my $spec=$trole.'.'.$area;
5147: if ($trole =~ /^cr\//) {
5148: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5149: } elsif ($trole ne 'gr') {
5150: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5151: }
5152: }
5153: }
5154: foreach my $role (keys(%allroles)) {
5155: last if ($is_adv);
5156: foreach my $item (split(/:/,$allroles{$role})) {
5157: if ($item ne '') {
5158: my ($privilege,$restrictions)=split(/&/,$item);
5159: if ($privilege eq 'adv') {
5160: $is_adv = 1;
5161: last;
5162: }
5163: }
5164: }
5165: }
5166: return $is_adv;
5167: }
1.798 raeburn 5168:
1.1035 raeburn 5169: sub check_can_request {
1.1036 raeburn 5170: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5171: my $canreq = 0;
5172: my ($types,$typename) = &Apache::loncommon::course_types();
5173: my @options = ('approval','validate','autolimit');
5174: my $optregex = join('|',@options);
5175: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5176: foreach my $type (@{$types}) {
5177: if (&usertools_access($env{'user.name'},
5178: $env{'user.domain'},
5179: $type,undef,'requestcourses')) {
5180: $canreq ++;
1.1036 raeburn 5181: if (ref($request_domains) eq 'HASH') {
5182: push(@{$request_domains->{$type}},$env{'user.domain'});
5183: }
1.1035 raeburn 5184: if ($dom eq $env{'user.domain'}) {
5185: $can_request->{$type} = 1;
5186: }
5187: }
5188: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5189: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5190: if (@curr > 0) {
1.1036 raeburn 5191: foreach my $item (@curr) {
5192: if (ref($request_domains) eq 'HASH') {
5193: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5194: if ($otherdom ne '') {
5195: if (ref($request_domains->{$type}) eq 'ARRAY') {
5196: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5197: push(@{$request_domains->{$type}},$otherdom);
5198: }
5199: } else {
5200: push(@{$request_domains->{$type}},$otherdom);
5201: }
5202: }
5203: }
5204: }
5205: unless($dom eq $env{'user.domain'}) {
5206: $canreq ++;
1.1035 raeburn 5207: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5208: $can_request->{$type} = 1;
5209: }
5210: }
5211: }
5212: }
5213: }
5214: }
5215: return $canreq;
5216: }
5217:
1.341 www 5218: # ---------------------------------------------- Custom access rule evaluation
5219:
5220: sub customaccess {
5221: my ($priv,$uri)=@_;
1.807 albertel 5222: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5223: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5224: $udom = &LONCAPA::clean_domain($udom);
5225: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5226: my $access=0;
1.800 albertel 5227: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5228: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5229: if ($type eq 'user') {
5230: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5231: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5232: if ($tdom) {
5233: if ($tdom ne $env{'user.domain'}) { next; }
5234: }
1.896 albertel 5235: if ($tuname) {
5236: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5237: }
5238: $access=($effect eq 'allow');
5239: last;
5240: }
5241: } else {
5242: if ($role) {
5243: if ($role ne $urole) { next; }
5244: }
5245: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5246: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5247: if ($tdom) {
5248: if ($tdom ne $udom) { next; }
5249: }
5250: if ($tcrs) {
5251: if ($tcrs ne $ucrs) { next; }
5252: }
5253: if ($tsec) {
5254: if ($tsec ne $usec) { next; }
5255: }
5256: $access=($effect eq 'allow');
5257: last;
5258: }
5259: if ($realm eq '' && $role eq '') {
5260: $access=($effect eq 'allow');
5261: }
1.402 bowersj2 5262: }
1.341 www 5263: }
5264: return $access;
5265: }
5266:
1.103 harris41 5267: # ------------------------------------------------- Check for a user privilege
1.12 www 5268:
5269: sub allowed {
1.810 raeburn 5270: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5271: my $ver_orguri=$uri;
1.439 www 5272: $uri=&deversion($uri);
1.152 www 5273: my $orguri=$uri;
1.52 www 5274: $uri=&declutter($uri);
1.809 raeburn 5275:
1.810 raeburn 5276: if ($priv eq 'evb') {
5277: # Evade communication block restrictions for specified role in a course
5278: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5279: return $1;
5280: } else {
5281: return;
5282: }
5283: }
5284:
1.620 albertel 5285: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5286: # Free bre access to adm and meta resources
1.775 albertel 5287: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5288: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5289: && ($priv eq 'bre')) {
1.14 www 5290: return 'F';
1.159 www 5291: }
5292:
1.545 banghart 5293: # Free bre access to user's own portfolio contents
1.714 raeburn 5294: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5295: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5296: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5297: my %setters;
5298: my ($startblock,$endblock) =
5299: &Apache::loncommon::blockcheck(\%setters,'port');
5300: if ($startblock && $endblock) {
5301: return 'B';
5302: } else {
5303: return 'F';
5304: }
1.545 banghart 5305: }
5306:
1.762 raeburn 5307: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5308: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5309: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5310: if (exists($env{'request.course.id'})) {
5311: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5312: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5313: if (($domain eq $cdom) && ($name eq $cnum)) {
5314: my $courseprivid=$env{'request.course.id'};
5315: $courseprivid=~s/\_/\//;
5316: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5317: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5318: return $1;
1.762 raeburn 5319: } else {
5320: if ($env{'request.course.sec'}) {
5321: $courseprivid.='/'.$env{'request.course.sec'};
5322: }
5323: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5324: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5325: return $2;
5326: }
1.714 raeburn 5327: }
5328: }
5329: }
5330: }
5331:
1.159 www 5332: # Free bre to public access
5333:
5334: if ($priv eq 'bre') {
1.238 www 5335: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5336: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5337: return 'F';
5338: }
1.238 www 5339: if ($copyright eq 'priv') {
5340: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5341: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5342: return '';
5343: }
5344: }
5345: if ($copyright eq 'domain') {
5346: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5347: unless (($env{'user.domain'} eq $1) ||
5348: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5349: return '';
5350: }
1.262 matthew 5351: }
1.620 albertel 5352: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5353: # Library role, so allow browsing of resources in this domain.
5354: return 'F';
1.238 www 5355: }
1.341 www 5356: if ($copyright eq 'custom') {
5357: unless (&customaccess($priv,$uri)) { return ''; }
5358: }
1.14 www 5359: }
1.264 matthew 5360: # Domain coordinator is trying to create a course
1.620 albertel 5361: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5362: # uri is the requested domain in this case.
5363: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5364: # a role of dc for the domain in question.
1.620 albertel 5365: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5366: }
1.29 www 5367:
1.52 www 5368: my $thisallowed='';
5369: my $statecond=0;
5370: my $courseprivid='';
5371:
1.1039 raeburn 5372: my $ownaccess;
1.1043 raeburn 5373: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5374: if (($priv eq 'bro') && ($env{'user.author'})) {
5375: if ($uri eq '') {
5376: $ownaccess = 1;
5377: } else {
5378: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5379: my $udom = $env{'user.domain'};
5380: my $uname = $env{'user.name'};
5381: if ($uri =~ m{^\Q$udom\E/?$}) {
5382: $ownaccess = 1;
1.1040 raeburn 5383: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5384: unless ($uri =~ m{\.\./}) {
5385: $ownaccess = 1;
5386: }
5387: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5388: my $now = time;
5389: if ($uri =~ m{^([^/]+)/?$}) {
5390: my $adom = $1;
5391: foreach my $key (keys(%env)) {
1.1042 raeburn 5392: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5393: my ($start,$end) = split('.',$env{$key});
5394: if (($now >= $start) && (!$end || $end < $now)) {
5395: $ownaccess = 1;
5396: last;
5397: }
5398: }
5399: }
5400: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5401: my $adom = $1;
5402: my $aname = $2;
1.1042 raeburn 5403: foreach my $role ('ca','aa') {
5404: if ($env{"user.role.$role./$adom/$aname"}) {
5405: my ($start,$end) =
5406: split('.',$env{"user.role.$role./$adom/$aname"});
5407: if (($now >= $start) && (!$end || $end < $now)) {
5408: $ownaccess = 1;
5409: last;
5410: }
1.1039 raeburn 5411: }
5412: }
5413: }
5414: }
5415: }
5416: }
5417: }
5418:
1.52 www 5419: # Course
5420:
1.620 albertel 5421: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5422: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5423: $thisallowed.=$1;
5424: }
1.52 www 5425: }
1.29 www 5426:
1.52 www 5427: # Domain
5428:
1.620 albertel 5429: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5430: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5431: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5432: $thisallowed.=$1;
5433: }
1.12 www 5434: }
1.52 www 5435:
5436: # Course: uri itself is a course
1.66 www 5437: my $courseuri=$uri;
5438: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5439: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5440:
1.620 albertel 5441: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5442: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5443: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5444: $thisallowed.=$1;
5445: }
1.12 www 5446: }
1.29 www 5447:
1.665 albertel 5448: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5449: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5450: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5451: $thisallowed='';
1.671 raeburn 5452: my ($match)=&is_on_map($uri);
5453: if ($match) {
5454: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5455: =~/\Q$priv\E\&([^\:]*)/) {
5456: $thisallowed.=$1;
5457: }
5458: } else {
1.705 albertel 5459: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5460: if ($refuri) {
5461: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5462: $thisallowed='F';
1.671 raeburn 5463: } else {
5464: $refuri=&declutter($refuri);
5465: my ($match) = &is_on_map($refuri);
5466: if ($match) {
5467: $thisallowed='F';
5468: }
1.669 raeburn 5469: }
1.671 raeburn 5470: }
5471: }
1.314 www 5472: }
1.492 albertel 5473:
1.766 albertel 5474: if ($priv eq 'bre'
5475: && $thisallowed ne 'F'
5476: && $thisallowed ne '2'
5477: && &is_portfolio_url($uri)) {
5478: $thisallowed = &portfolio_access($uri);
5479: }
5480:
1.52 www 5481: # Full access at system, domain or course-wide level? Exit.
1.29 www 5482: if ($thisallowed=~/F/) {
5483: return 'F';
5484: }
5485:
1.52 www 5486: # If this is generating or modifying users, exit with special codes
1.29 www 5487:
1.643 www 5488: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5489: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5490: my ($audom,$auname)=split('/',$uri);
1.643 www 5491: # no author name given, so this just checks on the general right to make a co-author in this domain
5492: unless ($auname) { return $thisallowed; }
5493: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5494: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5495: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5496: ($audom ne $env{'request.role.domain'}))) { return ''; }
5497: }
1.52 www 5498: return $thisallowed;
5499: }
5500: #
1.103 harris41 5501: # Gathered so far: system, domain and course wide privileges
1.52 www 5502: #
5503: # Course: See if uri or referer is an individual resource that is part of
5504: # the course
5505:
1.620 albertel 5506: if ($env{'request.course.id'}) {
1.232 www 5507:
1.620 albertel 5508: $courseprivid=$env{'request.course.id'};
5509: if ($env{'request.course.sec'}) {
5510: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5511: }
5512: $courseprivid=~s/\_/\//;
5513: my $checkreferer=1;
1.232 www 5514: my ($match,$cond)=&is_on_map($uri);
5515: if ($match) {
5516: $statecond=$cond;
1.620 albertel 5517: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5518: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5519: $thisallowed.=$1;
5520: $checkreferer=0;
5521: }
1.29 www 5522: }
1.83 www 5523:
1.148 www 5524: if ($checkreferer) {
1.620 albertel 5525: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5526: unless ($refuri) {
1.800 albertel 5527: foreach my $key (keys(%env)) {
5528: if ($key=~/^httpref\..*\*/) {
5529: my $pattern=$key;
1.156 www 5530: $pattern=~s/^httpref\.\/res\///;
1.148 www 5531: $pattern=~s/\*/\[\^\/\]\+/g;
5532: $pattern=~s/\//\\\//g;
1.152 www 5533: if ($orguri=~/$pattern/) {
1.800 albertel 5534: $refuri=$env{$key};
1.148 www 5535: }
5536: }
1.191 harris41 5537: }
1.148 www 5538: }
1.232 www 5539:
1.148 www 5540: if ($refuri) {
1.152 www 5541: $refuri=&declutter($refuri);
1.232 www 5542: my ($match,$cond)=&is_on_map($refuri);
5543: if ($match) {
5544: my $refstatecond=$cond;
1.620 albertel 5545: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5546: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5547: $thisallowed.=$1;
1.53 www 5548: $uri=$refuri;
5549: $statecond=$refstatecond;
1.52 www 5550: }
5551: }
1.148 www 5552: }
1.29 www 5553: }
1.52 www 5554: }
1.29 www 5555:
1.52 www 5556: #
1.103 harris41 5557: # Gathered now: all privileges that could apply, and condition number
1.52 www 5558: #
5559: #
5560: # Full or no access?
5561: #
1.29 www 5562:
1.52 www 5563: if ($thisallowed=~/F/) {
5564: return 'F';
5565: }
1.29 www 5566:
1.52 www 5567: unless ($thisallowed) {
5568: return '';
5569: }
1.29 www 5570:
1.52 www 5571: # Restrictions exist, deal with them
5572: #
5573: # C:according to course preferences
5574: # R:according to resource settings
5575: # L:unless locked
5576: # X:according to user session state
5577: #
5578:
5579: # Possibly locked functionality, check all courses
1.54 www 5580: # Locks might take effect only after 10 minutes cache expiration for other
5581: # courses, and 2 minutes for current course
1.52 www 5582:
5583: my $envkey;
5584: if ($thisallowed=~/L/) {
1.1000 raeburn 5585: foreach $envkey (keys(%env)) {
1.54 www 5586: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5587: my $courseid=$2;
5588: my $roleid=$1.'.'.$2;
1.92 www 5589: $courseid=~s/^\///;
1.54 www 5590: my $expiretime=600;
1.620 albertel 5591: if ($env{'request.role'} eq $roleid) {
1.54 www 5592: $expiretime=120;
5593: }
5594: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5595: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5596: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5597: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5598: }
1.620 albertel 5599: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5600: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5601: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5602: &log($env{'user.domain'},$env{'user.name'},
5603: $env{'user.home'},
1.57 www 5604: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5605: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5606: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5607: return '';
5608: }
5609: }
1.620 albertel 5610: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5611: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5612: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5613: &log($env{'user.domain'},$env{'user.name'},
5614: $env{'user.home'},
1.57 www 5615: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5616: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5617: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5618: return '';
5619: }
5620: }
5621: }
1.29 www 5622: }
1.52 www 5623: }
5624:
5625: #
5626: # Rest of the restrictions depend on selected course
5627: #
5628:
1.620 albertel 5629: unless ($env{'request.course.id'}) {
1.766 albertel 5630: if ($thisallowed eq 'A') {
5631: return 'A';
1.814 raeburn 5632: } elsif ($thisallowed eq 'B') {
5633: return 'B';
1.766 albertel 5634: } else {
5635: return '1';
5636: }
1.52 www 5637: }
1.29 www 5638:
1.52 www 5639: #
5640: # Now user is definitely in a course
5641: #
1.53 www 5642:
5643:
5644: # Course preferences
5645:
5646: if ($thisallowed=~/C/) {
1.620 albertel 5647: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5648: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5649: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5650: =~/\Q$rolecode\E/) {
1.689 albertel 5651: if ($priv ne 'pch') {
5652: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5653: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5654: $env{'request.course.id'});
5655: }
1.237 www 5656: return '';
5657: }
5658:
1.620 albertel 5659: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5660: =~/\Q$unamedom\E/) {
1.689 albertel 5661: if ($priv ne 'pch') {
5662: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5663: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5664: $env{'request.course.id'});
5665: }
1.54 www 5666: return '';
5667: }
1.53 www 5668: }
5669:
5670: # Resource preferences
5671:
5672: if ($thisallowed=~/R/) {
1.620 albertel 5673: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5674: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5675: if ($priv ne 'pch') {
5676: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5677: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5678: }
5679: return '';
1.54 www 5680: }
1.53 www 5681: }
1.30 www 5682:
1.246 www 5683: # Restricted by state or randomout?
1.30 www 5684:
1.52 www 5685: if ($thisallowed=~/X/) {
1.620 albertel 5686: if ($env{'acc.randomout'}) {
1.579 albertel 5687: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5688: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5689: return '';
5690: }
1.247 www 5691: }
5692: if (&condval($statecond)) {
1.52 www 5693: return '2';
5694: } else {
5695: return '';
5696: }
5697: }
1.30 www 5698:
1.766 albertel 5699: if ($thisallowed eq 'A') {
5700: return 'A';
1.814 raeburn 5701: } elsif ($thisallowed eq 'B') {
5702: return 'B';
1.766 albertel 5703: }
1.52 www 5704: return 'F';
1.232 www 5705: }
5706:
1.710 albertel 5707: sub split_uri_for_cond {
5708: my $uri=&deversion(&declutter(shift));
5709: my @uriparts=split(/\//,$uri);
5710: my $filename=pop(@uriparts);
5711: my $pathname=join('/',@uriparts);
5712: return ($pathname,$filename);
5713: }
1.232 www 5714: # --------------------------------------------------- Is a resource on the map?
5715:
5716: sub is_on_map {
1.710 albertel 5717: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5718: #Trying to find the conditional for the file
1.620 albertel 5719: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5720: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5721: if ($match) {
1.289 bowersj2 5722: return (1,$1);
5723: } else {
1.434 www 5724: return (0,0);
1.289 bowersj2 5725: }
1.12 www 5726: }
5727:
1.427 www 5728: # --------------------------------------------------------- Get symb from alias
5729:
5730: sub get_symb_from_alias {
5731: my $symb=shift;
5732: my ($map,$resid,$url)=&decode_symb($symb);
5733: # Already is a symb
5734: if ($url) { return $symb; }
5735: # Must be an alias
5736: my $aliassymb='';
5737: my %bighash;
1.620 albertel 5738: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5739: &GDBM_READER(),0640)) {
5740: my $rid=$bighash{'mapalias_'.$symb};
5741: if ($rid) {
5742: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5743: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5744: $resid,$bighash{'src_'.$rid});
1.427 www 5745: }
5746: untie %bighash;
5747: }
5748: return $aliassymb;
5749: }
5750:
1.12 www 5751: # ----------------------------------------------------------------- Define Role
5752:
5753: sub definerole {
5754: if (allowed('mcr','/')) {
5755: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5756: foreach my $role (split(':',$sysrole)) {
5757: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5758: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5759: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5760: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5761: return "refused:s:$crole&$cqual";
5762: }
5763: }
1.191 harris41 5764: }
1.800 albertel 5765: foreach my $role (split(':',$domrole)) {
5766: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5767: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5768: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5769: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5770: return "refused:d:$crole&$cqual";
5771: }
5772: }
1.191 harris41 5773: }
1.800 albertel 5774: foreach my $role (split(':',$courole)) {
5775: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5776: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5777: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5778: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5779: return "refused:c:$crole&$cqual";
5780: }
5781: }
1.191 harris41 5782: }
1.620 albertel 5783: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5784: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5785: "rolesdef_$rolename=".
5786: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5787: return reply($command,$env{'user.home'});
1.12 www 5788: } else {
5789: return 'refused';
5790: }
1.105 harris41 5791: }
5792:
5793: # ---------------- Make a metadata query against the network of library servers
5794:
5795: sub metadata_query {
1.244 matthew 5796: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5797: my %rhash;
1.845 albertel 5798: my %libserv = &all_library();
1.244 matthew 5799: my @server_list = (defined($server_array) ? @$server_array
5800: : keys(%libserv) );
5801: for my $server (@server_list) {
1.118 harris41 5802: unless ($custom or $customshow) {
5803: my $reply=&reply("querysend:".&escape($query),$server);
5804: $rhash{$server}=$reply;
5805: }
5806: else {
5807: my $reply=&reply("querysend:".&escape($query).':'.
5808: &escape($custom).':'.&escape($customshow),
5809: $server);
5810: $rhash{$server}=$reply;
5811: }
1.112 harris41 5812: }
1.118 harris41 5813: return \%rhash;
1.240 www 5814: }
5815:
5816: # ----------------------------------------- Send log queries and wait for reply
5817:
5818: sub log_query {
5819: my ($uname,$udom,$query,%filters)=@_;
5820: my $uhome=&homeserver($uname,$udom);
5821: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5822: my $uhost=&hostname($uhome);
1.800 albertel 5823: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5824: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5825: $uhome);
1.479 albertel 5826: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5827: return get_query_reply($queryid);
5828: }
5829:
1.818 raeburn 5830: # -------------------------- Update MySQL table for portfolio file
5831:
5832: sub update_portfolio_table {
1.821 raeburn 5833: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5834: if ($group ne '') {
5835: $file_name =~s /^\Q$group\E//;
5836: }
1.818 raeburn 5837: my $homeserver = &homeserver($uname,$udom);
5838: my $queryid=
1.821 raeburn 5839: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5840: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5841: my $reply = &get_query_reply($queryid);
5842: return $reply;
5843: }
5844:
1.899 raeburn 5845: # -------------------------- Update MySQL allusers table
5846:
5847: sub update_allusers_table {
5848: my ($uname,$udom,$names) = @_;
5849: my $homeserver = &homeserver($uname,$udom);
5850: my $queryid=
5851: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5852: 'lastname='.&escape($names->{'lastname'}).'%%'.
5853: 'firstname='.&escape($names->{'firstname'}).'%%'.
5854: 'middlename='.&escape($names->{'middlename'}).'%%'.
5855: 'generation='.&escape($names->{'generation'}).'%%'.
5856: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5857: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 5858: return;
1.899 raeburn 5859: }
5860:
1.508 raeburn 5861: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5862:
5863: sub fetch_enrollment_query {
1.511 raeburn 5864: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5865: my $homeserver;
1.547 raeburn 5866: my $maxtries = 1;
1.508 raeburn 5867: if ($context eq 'automated') {
5868: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5869: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5870: } else {
5871: $homeserver = &homeserver($cnum,$dom);
5872: }
1.838 albertel 5873: my $host=&hostname($homeserver);
1.506 raeburn 5874: my $cmd = '';
1.1000 raeburn 5875: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5876: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5877: }
5878: $cmd =~ s/%%$//;
5879: $cmd = &escape($cmd);
5880: my $query = 'fetchenrollment';
1.620 albertel 5881: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5882: unless ($queryid=~/^\Q$host\E\_/) {
5883: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5884: return 'error: '.$queryid;
5885: }
1.506 raeburn 5886: my $reply = &get_query_reply($queryid);
1.547 raeburn 5887: my $tries = 1;
5888: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5889: $reply = &get_query_reply($queryid);
5890: $tries ++;
5891: }
1.526 raeburn 5892: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5893: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5894: } else {
1.901 albertel 5895: my @responses = split(/:/,$reply);
1.515 raeburn 5896: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5897: foreach my $line (@responses) {
5898: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5899: $$replyref{$key} = $value;
5900: }
5901: } else {
1.506 raeburn 5902: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5903: foreach my $line (@responses) {
5904: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5905: $$replyref{$key} = $value;
5906: if ($value > 0) {
1.800 albertel 5907: foreach my $item (@{$$affiliatesref{$key}}) {
5908: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5909: my $destname = $pathname.'/'.$filename;
5910: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5911: if ($xml_classlist =~ /^error/) {
5912: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5913: } else {
1.506 raeburn 5914: if ( open(FILE,">$destname") ) {
5915: print FILE &unescape($xml_classlist);
5916: close(FILE);
1.526 raeburn 5917: } else {
5918: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5919: }
5920: }
5921: }
5922: }
5923: }
5924: }
5925: return 'ok';
5926: }
5927: return 'error';
5928: }
5929:
1.242 www 5930: sub get_query_reply {
5931: my $queryid=shift;
1.240 www 5932: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5933: my $reply='';
5934: for (1..100) {
5935: sleep 2;
5936: if (-e $replyfile.'.end') {
1.448 albertel 5937: if (open(my $fh,$replyfile)) {
1.904 albertel 5938: $reply = join('',<$fh>);
5939: close($fh);
1.240 www 5940: } else { return 'error: reply_file_error'; }
1.242 www 5941: return &unescape($reply);
5942: }
1.240 www 5943: }
1.242 www 5944: return 'timeout:'.$queryid;
1.240 www 5945: }
5946:
5947: sub courselog_query {
1.241 www 5948: #
5949: # possible filters:
5950: # url: url or symb
5951: # username
5952: # domain
5953: # action: view, submit, grade
5954: # start: timestamp
5955: # end: timestamp
5956: #
1.240 www 5957: my (%filters)=@_;
1.620 albertel 5958: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5959: if ($filters{'url'}) {
5960: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5961: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5962: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5963: }
1.620 albertel 5964: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5965: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5966: return &log_query($cname,$cdom,'courselog',%filters);
5967: }
5968:
5969: sub userlog_query {
1.858 raeburn 5970: #
5971: # possible filters:
5972: # action: log check role
5973: # start: timestamp
5974: # end: timestamp
5975: #
1.240 www 5976: my ($uname,$udom,%filters)=@_;
5977: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5978: }
5979:
1.506 raeburn 5980: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5981:
5982: sub auto_run {
1.508 raeburn 5983: my ($cnum,$cdom) = @_;
1.876 raeburn 5984: my $response = 0;
5985: my $settings;
5986: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5987: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5988: $settings = $domconfig{'autoenroll'};
5989: if ($settings->{'run'} eq '1') {
5990: $response = 1;
5991: }
5992: } else {
1.934 raeburn 5993: my $homeserver;
5994: if (&is_course($cdom,$cnum)) {
5995: $homeserver = &homeserver($cnum,$cdom);
5996: } else {
5997: $homeserver = &domain($cdom,'primary');
5998: }
5999: if ($homeserver ne 'no_host') {
6000: $response = &reply('autorun:'.$cdom,$homeserver);
6001: }
1.876 raeburn 6002: }
1.506 raeburn 6003: return $response;
6004: }
1.776 albertel 6005:
1.506 raeburn 6006: sub auto_get_sections {
1.508 raeburn 6007: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6008: my $homeserver;
6009: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6010: $homeserver = &homeserver($cnum,$cdom);
6011: }
6012: if (!defined($homeserver)) {
6013: if ($cdom =~ /^$match_domain$/) {
6014: $homeserver = &domain($cdom,'primary');
6015: }
6016: }
6017: my @secs;
6018: if (defined($homeserver)) {
6019: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6020: unless ($response eq 'refused') {
6021: @secs = split(/:/,$response);
6022: }
1.506 raeburn 6023: }
6024: return @secs;
6025: }
1.776 albertel 6026:
1.506 raeburn 6027: sub auto_new_course {
1.1099 raeburn 6028: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6029: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6030: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6031: return $response;
6032: }
1.776 albertel 6033:
1.506 raeburn 6034: sub auto_validate_courseID {
1.508 raeburn 6035: my ($cnum,$cdom,$inst_course_id) = @_;
6036: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6037: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6038: return $response;
6039: }
1.776 albertel 6040:
1.1007 raeburn 6041: sub auto_validate_instcode {
1.1020 raeburn 6042: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6043: my ($homeserver,$response);
6044: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6045: $homeserver = &homeserver($cnum,$cdom);
6046: }
6047: if (!defined($homeserver)) {
6048: if ($cdom =~ /^$match_domain$/) {
6049: $homeserver = &domain($cdom,'primary');
6050: }
6051: }
1.1065 raeburn 6052: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6053: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6054: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6055: return ($outcome,$description);
1.1007 raeburn 6056: }
6057:
1.506 raeburn 6058: sub auto_create_password {
1.873 raeburn 6059: my ($cnum,$cdom,$authparam,$udom) = @_;
6060: my ($homeserver,$response);
1.506 raeburn 6061: my $create_passwd = 0;
6062: my $authchk = '';
1.873 raeburn 6063: if ($udom =~ /^$match_domain$/) {
6064: $homeserver = &domain($udom,'primary');
6065: }
6066: if ($homeserver eq '') {
6067: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6068: $homeserver = &homeserver($cnum,$cdom);
6069: }
6070: }
6071: if ($homeserver eq '') {
6072: $authchk = 'nodomain';
1.506 raeburn 6073: } else {
1.873 raeburn 6074: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6075: if ($response eq 'refused') {
6076: $authchk = 'refused';
6077: } else {
1.901 albertel 6078: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6079: }
1.506 raeburn 6080: }
6081: return ($authparam,$create_passwd,$authchk);
6082: }
6083:
1.706 raeburn 6084: sub auto_photo_permission {
6085: my ($cnum,$cdom,$students) = @_;
6086: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6087: my ($outcome,$perm_reqd,$conditions) =
6088: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6089: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6090: return (undef,undef);
6091: }
1.706 raeburn 6092: return ($outcome,$perm_reqd,$conditions);
6093: }
6094:
6095: sub auto_checkphotos {
6096: my ($uname,$udom,$pid) = @_;
6097: my $homeserver = &homeserver($uname,$udom);
6098: my ($result,$resulttype);
6099: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6100: &escape($uname).':'.&escape($pid),
6101: $homeserver));
1.709 albertel 6102: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6103: return (undef,undef);
6104: }
1.706 raeburn 6105: if ($outcome) {
6106: ($result,$resulttype) = split(/:/,$outcome);
6107: }
6108: return ($result,$resulttype);
6109: }
6110:
6111: sub auto_photochoice {
6112: my ($cnum,$cdom) = @_;
6113: my $homeserver = &homeserver($cnum,$cdom);
6114: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6115: &escape($cdom),
6116: $homeserver)));
1.709 albertel 6117: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6118: return (undef,undef);
6119: }
1.706 raeburn 6120: return ($update,$comment);
6121: }
6122:
6123: sub auto_photoupdate {
6124: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6125: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6126: my $host=&hostname($homeserver);
1.706 raeburn 6127: my $cmd = '';
6128: my $maxtries = 1;
1.800 albertel 6129: foreach my $affiliate (keys(%{$affiliatesref})) {
6130: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6131: }
6132: $cmd =~ s/%%$//;
6133: $cmd = &escape($cmd);
6134: my $query = 'institutionalphotos';
6135: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6136: unless ($queryid=~/^\Q$host\E\_/) {
6137: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6138: return 'error: '.$queryid;
6139: }
6140: my $reply = &get_query_reply($queryid);
6141: my $tries = 1;
6142: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6143: $reply = &get_query_reply($queryid);
6144: $tries ++;
6145: }
6146: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6147: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6148: } else {
6149: my @responses = split(/:/,$reply);
6150: my $outcome = shift(@responses);
6151: foreach my $item (@responses) {
6152: my ($key,$value) = split(/=/,$item);
6153: $$photo{$key} = $value;
6154: }
6155: return $outcome;
6156: }
6157: return 'error';
6158: }
6159:
1.521 raeburn 6160: sub auto_instcode_format {
1.793 albertel 6161: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6162: $cat_order) = @_;
1.521 raeburn 6163: my $courses = '';
1.772 raeburn 6164: my @homeservers;
1.521 raeburn 6165: if ($caller eq 'global') {
1.841 albertel 6166: my %servers = &get_servers($codedom,'library');
6167: foreach my $tryserver (keys(%servers)) {
6168: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6169: push(@homeservers,$tryserver);
6170: }
1.584 raeburn 6171: }
1.1022 raeburn 6172: } elsif ($caller eq 'requests') {
6173: if ($codedom =~ /^$match_domain$/) {
6174: my $chome = &domain($codedom,'primary');
6175: unless ($chome eq 'no_host') {
6176: push(@homeservers,$chome);
6177: }
6178: }
1.521 raeburn 6179: } else {
1.772 raeburn 6180: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6181: }
1.793 albertel 6182: foreach my $code (keys(%{$instcodes})) {
6183: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6184: }
6185: chop($courses);
1.772 raeburn 6186: my $ok_response = 0;
6187: my $response;
6188: while (@homeservers > 0 && $ok_response == 0) {
6189: my $server = shift(@homeservers);
6190: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6191: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6192: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6193: split(/:/,$response);
1.772 raeburn 6194: %{$codes} = (%{$codes},&str2hash($codes_str));
6195: push(@{$codetitles},&str2array($codetitles_str));
6196: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6197: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6198: $ok_response = 1;
6199: }
6200: }
6201: if ($ok_response) {
1.521 raeburn 6202: return 'ok';
1.772 raeburn 6203: } else {
6204: return $response;
1.521 raeburn 6205: }
6206: }
6207:
1.792 raeburn 6208: sub auto_instcode_defaults {
6209: my ($domain,$returnhash,$code_order) = @_;
6210: my @homeservers;
1.841 albertel 6211:
6212: my %servers = &get_servers($domain,'library');
6213: foreach my $tryserver (keys(%servers)) {
6214: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6215: push(@homeservers,$tryserver);
6216: }
1.792 raeburn 6217: }
1.841 albertel 6218:
1.792 raeburn 6219: my $response;
1.841 albertel 6220: foreach my $server (@homeservers) {
1.792 raeburn 6221: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6222: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6223:
6224: foreach my $pair (split(/\&/,$response)) {
6225: my ($name,$value)=split(/\=/,$pair);
6226: if ($name eq 'code_order') {
6227: @{$code_order} = split(/\&/,&unescape($value));
6228: } else {
6229: $returnhash->{&unescape($name)}=&unescape($value);
6230: }
6231: }
6232: return 'ok';
1.792 raeburn 6233: }
1.841 albertel 6234:
6235: return $response;
1.1003 raeburn 6236: }
6237:
6238: sub auto_possible_instcodes {
1.1007 raeburn 6239: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6240: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6241: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6242: return;
6243: }
1.1003 raeburn 6244: my (@homeservers,$uhome);
6245: if (defined(&domain($domain,'primary'))) {
6246: $uhome=&domain($domain,'primary');
6247: push(@homeservers,&domain($domain,'primary'));
6248: } else {
6249: my %servers = &get_servers($domain,'library');
6250: foreach my $tryserver (keys(%servers)) {
6251: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6252: push(@homeservers,$tryserver);
6253: }
6254: }
6255: }
6256: my $response;
6257: foreach my $server (@homeservers) {
6258: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6259: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6260: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6261: split(':',$response);
6262: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6263: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6264: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6265: my ($name,$value)=split('=',$item);
6266: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6267: }
6268: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6269: my ($name,$value)=split('=',$item);
6270: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6271: }
6272: return 'ok';
6273: }
6274: return $response;
6275: }
1.792 raeburn 6276:
1.1010 raeburn 6277: sub auto_courserequest_checks {
6278: my ($dom) = @_;
1.1020 raeburn 6279: my ($homeserver,%validations);
6280: if ($dom =~ /^$match_domain$/) {
6281: $homeserver = &domain($dom,'primary');
6282: }
6283: unless ($homeserver eq 'no_host') {
6284: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6285: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6286: my @items = split(/&/,$response);
6287: foreach my $item (@items) {
6288: my ($key,$value) = split('=',$item);
6289: $validations{&unescape($key)} = &thaw_unescape($value);
6290: }
6291: }
6292: }
1.1010 raeburn 6293: return %validations;
6294: }
6295:
1.1020 raeburn 6296: sub auto_courserequest_validation {
6297: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6298: my ($homeserver,$response);
6299: if ($dom =~ /^$match_domain$/) {
6300: $homeserver = &domain($dom,'primary');
6301: }
6302: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6303:
1.1020 raeburn 6304: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6305: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6306: ':'.&escape($instcode).':'.&escape($instseclist),
6307: $homeserver));
6308: }
6309: return $response;
6310: }
6311:
1.777 albertel 6312: sub auto_validate_class_sec {
1.918 raeburn 6313: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6314: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6315: my $ownerlist;
6316: if (ref($owners) eq 'ARRAY') {
6317: $ownerlist = join(',',@{$owners});
6318: } else {
6319: $ownerlist = $owners;
6320: }
1.773 raeburn 6321: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6322: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6323: return $response;
6324: }
6325:
1.679 raeburn 6326: # ------------------------------------------------------- Course Group routines
6327:
6328: sub get_coursegroups {
1.809 raeburn 6329: my ($cdom,$cnum,$group,$namespace) = @_;
6330: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6331: }
6332:
1.679 raeburn 6333: sub modify_coursegroup {
6334: my ($cdom,$cnum,$groupsettings) = @_;
6335: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6336: }
6337:
1.809 raeburn 6338: sub toggle_coursegroup_status {
6339: my ($cdom,$cnum,$group,$action) = @_;
6340: my ($from_namespace,$to_namespace);
6341: if ($action eq 'delete') {
6342: $from_namespace = 'coursegroups';
6343: $to_namespace = 'deleted_groups';
6344: } else {
6345: $from_namespace = 'deleted_groups';
6346: $to_namespace = 'coursegroups';
6347: }
6348: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6349: if (my $tmp = &error(%curr_group)) {
6350: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6351: return ('read error',$tmp);
6352: } else {
6353: my %savedsettings = %curr_group;
1.809 raeburn 6354: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6355: my $deloutcome;
6356: if ($result eq 'ok') {
1.809 raeburn 6357: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6358: } else {
6359: return ('write error',$result);
6360: }
6361: if ($deloutcome eq 'ok') {
6362: return 'ok';
6363: } else {
6364: return ('delete error',$deloutcome);
6365: }
6366: }
6367: }
6368:
1.679 raeburn 6369: sub modify_group_roles {
1.957 raeburn 6370: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6371: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6372: my $role = 'gr/'.&escape($userprivs);
6373: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6374: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6375: if ($result eq 'ok') {
6376: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6377: }
1.679 raeburn 6378: return $result;
6379: }
6380:
6381: sub modify_coursegroup_membership {
6382: my ($cdom,$cnum,$membership) = @_;
6383: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6384: return $result;
6385: }
6386:
1.682 raeburn 6387: sub get_active_groups {
6388: my ($udom,$uname,$cdom,$cnum) = @_;
6389: my $now = time;
6390: my %groups = ();
6391: foreach my $key (keys(%env)) {
1.811 albertel 6392: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6393: my ($start,$end) = split(/\./,$env{$key});
6394: if (($end!=0) && ($end<$now)) { next; }
6395: if (($start!=0) && ($start>$now)) { next; }
6396: if ($1 eq $cdom && $2 eq $cnum) {
6397: $groups{$3} = $env{$key} ;
6398: }
6399: }
6400: }
6401: return %groups;
6402: }
6403:
1.683 raeburn 6404: sub get_group_membership {
6405: my ($cdom,$cnum,$group) = @_;
6406: return(&dump('groupmembership',$cdom,$cnum,$group));
6407: }
6408:
6409: sub get_users_groups {
6410: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6411: my @usersgroups;
1.683 raeburn 6412: my $cachetime=1800;
6413:
6414: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6415: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6416: if (defined($cached)) {
1.734 albertel 6417: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6418: } else {
6419: $grouplist = '';
1.816 raeburn 6420: my $courseurl = &courseid_to_courseurl($courseid);
1.1086 raeburn 6421: my $extra = &freeze_escape({'skipcheck' => 1});
6422: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6423: my $access_end = $env{'course.'.$courseid.
6424: '.default_enrollment_end_date'};
6425: my $now = time;
6426: foreach my $key (keys(%roleshash)) {
6427: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6428: my $group = $1;
6429: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6430: my $start = $2;
6431: my $end = $1;
6432: if ($start == -1) { next; } # deleted from group
6433: if (($start!=0) && ($start>$now)) { next; }
6434: if (($end!=0) && ($end<$now)) {
6435: if ($access_end && $access_end < $now) {
6436: if ($access_end - $end < 86400) {
6437: push(@usersgroups,$group);
1.733 raeburn 6438: }
6439: }
1.817 raeburn 6440: next;
1.733 raeburn 6441: }
1.817 raeburn 6442: push(@usersgroups,$group);
1.683 raeburn 6443: }
6444: }
6445: }
1.817 raeburn 6446: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6447: $grouplist = join(':',@usersgroups);
6448: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6449: }
1.733 raeburn 6450: return @usersgroups;
1.683 raeburn 6451: }
6452:
6453: sub devalidate_getgroups_cache {
6454: my ($udom,$uname,$cdom,$cnum)=@_;
6455: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6456:
1.683 raeburn 6457: my $hashid="$udom:$uname:$courseid";
6458: &devalidate_cache_new('getgroups',$hashid);
6459: }
6460:
1.12 www 6461: # ------------------------------------------------------------------ Plain Text
6462:
6463: sub plaintext {
1.988 raeburn 6464: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6465: if ($short =~ m{^cr/}) {
1.758 albertel 6466: return (split('/',$short))[-1];
6467: }
1.742 raeburn 6468: if (!defined($cid)) {
6469: $cid = $env{'request.course.id'};
6470: }
6471: my %rolenames = (
1.1008 raeburn 6472: Course => 'std',
6473: Community => 'alt1',
1.742 raeburn 6474: );
1.1037 raeburn 6475: if ($cid ne '') {
6476: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6477: unless ($forcedefault) {
6478: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6479: &Apache::lonlocal::mt_escape(\$roletext);
6480: return &Apache::lonlocal::mt($roletext);
6481: }
6482: }
6483: }
6484: if ((defined($type)) && (defined($rolenames{$type})) &&
6485: (defined($rolenames{$type})) &&
6486: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6487: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6488: } elsif ($cid ne '') {
6489: my $crstype = $env{'course.'.$cid.'.type'};
6490: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6491: (defined($prp{$short}{$rolenames{$crstype}}))) {
6492: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6493: }
1.742 raeburn 6494: }
1.1037 raeburn 6495: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6496: }
6497:
6498: # ----------------------------------------------------------------- Assign Role
6499:
6500: sub assignrole {
1.957 raeburn 6501: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6502: $context)=@_;
1.21 www 6503: my $mrole;
6504: if ($role =~ /^cr\//) {
1.393 www 6505: my $cwosec=$url;
1.811 albertel 6506: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6507: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6508: my $refused = 1;
6509: if ($context eq 'requestcourses') {
6510: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6511: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6512: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6513: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6514: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6515: if ($crsenv{'internal.courseowner'} eq
6516: $env{'user.name'}.':'.$env{'user.domain'}) {
6517: $refused = '';
6518: }
6519: }
6520: }
6521: }
6522: }
6523: if ($refused) {
6524: &logthis('Refused custom assignrole: '.
6525: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6526: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6527: return 'refused';
6528: }
1.104 www 6529: }
1.21 www 6530: $mrole='cr';
1.678 raeburn 6531: } elsif ($role =~ /^gr\//) {
6532: my $cwogrp=$url;
1.811 albertel 6533: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6534: unless (&allowed('mdg',$cwogrp)) {
6535: &logthis('Refused group assignrole: '.
6536: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6537: $env{'user.name'}.' at '.$env{'user.domain'});
6538: return 'refused';
6539: }
6540: $mrole='gr';
1.21 www 6541: } else {
1.82 www 6542: my $cwosec=$url;
1.811 albertel 6543: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6544: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6545: my $refused;
6546: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6547: if (!(&allowed('c'.$role,$url))) {
6548: $refused = 1;
6549: }
6550: } else {
6551: $refused = 1;
6552: }
1.947 raeburn 6553: if ($refused) {
1.1045 raeburn 6554: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6555: if (!$selfenroll && $context eq 'course') {
6556: my %crsenv;
6557: if ($role eq 'cc' || $role eq 'co') {
6558: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6559: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6560: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6561: if ($crsenv{'internal.courseowner'} eq
6562: $env{'user.name'}.':'.$env{'user.domain'}) {
6563: $refused = '';
6564: }
6565: }
6566: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6567: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6568: if ($crsenv{'internal.courseowner'} eq
6569: $env{'user.name'}.':'.$env{'user.domain'}) {
6570: $refused = '';
6571: }
6572: }
6573: }
6574: }
6575: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6576: $refused = '';
1.1017 raeburn 6577: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6578: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6579: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6580: my $wrongcc;
6581: if ($cnum =~ /^$match_community$/) {
6582: $wrongcc = 1 if ($role eq 'cc');
6583: } else {
6584: $wrongcc = 1 if ($role eq 'co');
6585: }
6586: unless ($wrongcc) {
6587: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6588: if ($crsenv{'internal.courseowner'} eq
6589: $env{'user.name'}.':'.$env{'user.domain'}) {
6590: $refused = '';
6591: }
1.1017 raeburn 6592: }
6593: }
6594: }
6595: if ($refused) {
1.947 raeburn 6596: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6597: ' '.$role.' '.$end.' '.$start.' by '.
6598: $env{'user.name'}.' at '.$env{'user.domain'});
6599: return 'refused';
6600: }
1.932 raeburn 6601: }
1.104 www 6602: }
1.21 www 6603: $mrole=$role;
6604: }
1.620 albertel 6605: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6606: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6607: if ($end) { $command.='_'.$end; }
1.21 www 6608: if ($start) {
6609: if ($end) {
1.81 www 6610: $command.='_'.$start;
1.21 www 6611: } else {
1.81 www 6612: $command.='_0_'.$start;
1.21 www 6613: }
6614: }
1.739 raeburn 6615: my $origstart = $start;
6616: my $origend = $end;
1.957 raeburn 6617: my $delflag;
1.357 www 6618: # actually delete
6619: if ($deleteflag) {
1.373 www 6620: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6621: # modify command to delete the role
1.620 albertel 6622: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6623: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6624: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6625: # set start and finish to negative values for userrolelog
6626: $start=-1;
6627: $end=-1;
1.957 raeburn 6628: $delflag = 1;
1.357 www 6629: }
6630: }
6631: # send command
1.349 www 6632: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6633: # log new user role if status is ok
1.349 www 6634: if ($answer eq 'ok') {
1.663 raeburn 6635: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6636: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6637: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6638: unless ($role =~ /^gr/) {
6639: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6640: $origstart,$selfenroll,$context);
1.739 raeburn 6641: }
1.1053 raeburn 6642: if ($role eq 'cc') {
6643: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6644: }
1.349 www 6645: }
6646: return $answer;
1.169 harris41 6647: }
6648:
1.1053 raeburn 6649: sub autoupdate_coowners {
6650: my ($url,$end,$start,$uname,$udom) = @_;
6651: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6652: if (($cdom ne '') && ($cnum ne '')) {
6653: my $now = time;
6654: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6655: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6656: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6657: my $instcode = $coursehash{'internal.coursecode'};
6658: if ($instcode ne '') {
1.1056 raeburn 6659: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6660: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6661: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6662: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6663: if ($result eq 'valid') {
6664: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6665: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6666: push(@newcoowners,$coowner);
6667: }
6668: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6669: push(@newcoowners,$uname.':'.$udom);
6670: }
6671: @newcoowners = sort(@newcoowners);
6672: } else {
6673: push(@newcoowners,$uname.':'.$udom);
6674: }
6675: } else {
6676: if ($coursehash{'internal.co-owners'}) {
6677: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6678: unless ($coowner eq $uname.':'.$udom) {
6679: push(@newcoowners,$coowner);
6680: }
6681: }
6682: unless (@newcoowners > 0) {
6683: $delcoowners = 1;
6684: $coowners = '';
6685: }
6686: }
6687: }
6688: if (@newcoowners || $delcoowners) {
6689: &store_coowners($cdom,$cnum,$coursehash{'home'},
6690: $delcoowners,@newcoowners);
6691: }
6692: }
6693: }
6694: }
6695: }
6696: }
6697: }
6698:
6699: sub store_coowners {
6700: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6701: my $cid = $cdom.'_'.$cnum;
6702: my ($coowners,$delresult,$putresult);
6703: if (@newcoowners) {
6704: $coowners = join(',',@newcoowners);
6705: my %coownershash = (
6706: 'internal.co-owners' => $coowners,
6707: );
6708: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6709: if ($putresult eq 'ok') {
6710: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6711: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6712: }
6713: }
6714: }
6715: if ($delcoowners) {
6716: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6717: if ($delresult eq 'ok') {
6718: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6719: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6720: }
6721: }
6722: }
6723: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6724: my %crsinfo =
6725: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6726: if (ref($crsinfo{$cid}) eq 'HASH') {
6727: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6728: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6729: }
6730: }
6731: }
6732:
1.169 harris41 6733: # -------------------------------------------------- Modify user authentication
1.197 www 6734: # Overrides without validation
6735:
1.169 harris41 6736: sub modifyuserauth {
6737: my ($udom,$uname,$umode,$upass)=@_;
6738: my $uhome=&homeserver($uname,$udom);
1.197 www 6739: unless (&allowed('mau',$udom)) { return 'refused'; }
6740: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6741: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6742: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6743: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6744: &escape($upass),$uhome);
1.620 albertel 6745: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6746: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6747: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6748: &log($udom,,$uname,$uhome,
1.620 albertel 6749: 'Authentication changed by '.$env{'user.domain'}.', '.
6750: $env{'user.name'}.', '.$umode.
1.197 www 6751: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6752: unless ($reply eq 'ok') {
1.197 www 6753: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6754: return 'error: '.$reply;
6755: }
1.170 harris41 6756: return 'ok';
1.80 www 6757: }
6758:
1.81 www 6759: # --------------------------------------------------------------- Modify a user
1.80 www 6760:
1.81 www 6761: sub modifyuser {
1.206 matthew 6762: my ($udom, $uname, $uid,
6763: $umode, $upass, $first,
6764: $middle, $last, $gene,
1.1058 raeburn 6765: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6766: $udom= &LONCAPA::clean_domain($udom);
6767: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 6768: my $showcandelete = 'none';
6769: if (ref($candelete) eq 'ARRAY') {
6770: if (@{$candelete} > 0) {
6771: $showcandelete = join(', ',@{$candelete});
6772: }
6773: }
1.81 www 6774: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6775: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 6776: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6777: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6778: ' desiredhome not specified').
1.620 albertel 6779: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6780: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6781: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 6782: my $newuser;
6783: if ($uhome eq 'no_host') {
6784: $newuser = 1;
6785: }
1.80 www 6786: # ----------------------------------------------------------------- Create User
1.406 albertel 6787: if (($uhome eq 'no_host') &&
6788: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6789: my $unhome='';
1.844 albertel 6790: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6791: $unhome = $desiredhome;
1.620 albertel 6792: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6793: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6794: } else { # load balancing routine for determining $unhome
1.81 www 6795: my $loadm=10000000;
1.841 albertel 6796: my %servers = &get_servers($udom,'library');
6797: foreach my $tryserver (keys(%servers)) {
6798: my $answer=reply('load',$tryserver);
6799: if (($answer=~/\d+/) && ($answer<$loadm)) {
6800: $loadm=$answer;
6801: $unhome=$tryserver;
6802: }
1.80 www 6803: }
6804: }
6805: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6806: return 'error: unable to find a home server for '.$uname.
6807: ' in domain '.$udom;
1.80 www 6808: }
6809: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6810: &escape($upass),$unhome);
6811: unless ($reply eq 'ok') {
6812: return 'error: '.$reply;
6813: }
1.230 stredwic 6814: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6815: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6816: return 'error: unable verify users home machine.';
1.80 www 6817: }
1.209 matthew 6818: } # End of creation of new user
1.80 www 6819: # ---------------------------------------------------------------------- Add ID
6820: if ($uid) {
6821: $uid=~tr/A-Z/a-z/;
6822: my %uidhash=&idrget($udom,$uname);
1.196 www 6823: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6824: && (!$forceid)) {
1.80 www 6825: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6826: return 'error: user id "'.$uid.'" does not match '.
6827: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6828: }
6829: } else {
6830: &idput($udom,($uname => $uid));
6831: }
6832: }
6833: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6834: my @tmp=&get('environment',
1.899 raeburn 6835: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6836: 'permanentemail','inststatus'],
1.134 albertel 6837: $udom,$uname);
1.1075 raeburn 6838: my (%names,%oldnames);
1.313 matthew 6839: if ($tmp[0] =~ m/^error:.*/) {
6840: %names=();
6841: } else {
6842: %names = @tmp;
1.1075 raeburn 6843: %oldnames = %names;
1.313 matthew 6844: }
1.388 www 6845: #
1.1058 raeburn 6846: # If name, email and/or uid are blank (e.g., because an uploaded file
6847: # of users did not contain them), do not overwrite existing values
6848: # unless field is in $candelete array ref.
6849: #
6850:
6851: my @fields = ('firstname','middlename','lastname','generation',
6852: 'permanentemail','id');
6853: my %newvalues;
6854: if (ref($candelete) eq 'ARRAY') {
6855: foreach my $field (@fields) {
6856: if (grep(/^\Q$field\E$/,@{$candelete})) {
6857: if ($field eq 'firstname') {
6858: $names{$field} = $first;
6859: } elsif ($field eq 'middlename') {
6860: $names{$field} = $middle;
6861: } elsif ($field eq 'lastname') {
6862: $names{$field} = $last;
6863: } elsif ($field eq 'generation') {
6864: $names{$field} = $gene;
6865: } elsif ($field eq 'permanentemail') {
6866: $names{$field} = $email;
6867: } elsif ($field eq 'id') {
6868: $names{$field} = $uid;
6869: }
6870: }
6871: }
6872: }
1.388 www 6873: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6874: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6875: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6876: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6877: if ($email) {
6878: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6879: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6880: }
1.899 raeburn 6881: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6882: if (defined($inststatus)) {
6883: $names{'inststatus'} = '';
6884: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6885: if (ref($usertypes) eq 'HASH') {
6886: my @okstatuses;
6887: foreach my $item (split(/:/,$inststatus)) {
6888: if (defined($usertypes->{$item})) {
6889: push(@okstatuses,$item);
6890: }
6891: }
6892: if (@okstatuses) {
6893: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6894: }
6895: }
6896: }
1.1075 raeburn 6897: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 6898: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 6899: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 6900: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6901: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6902: } else {
6903: $logmsg .= ' during self creation';
6904: }
1.1075 raeburn 6905: my $changed;
6906: if ($newuser) {
6907: $changed = 1;
6908: } else {
6909: foreach my $field (@fields) {
6910: if ($names{$field} ne $oldnames{$field}) {
6911: $changed = 1;
6912: last;
6913: }
6914: }
6915: }
6916: unless ($changed) {
6917: $logmsg = 'No changes in user information needed for: '.$logmsg;
6918: &logthis($logmsg);
6919: return 'ok';
6920: }
6921: my $reply = &put('environment', \%names, $udom,$uname);
6922: if ($reply ne 'ok') {
6923: return 'error: '.$reply;
6924: }
1.1087 raeburn 6925: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
6926: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
6927: }
1.1075 raeburn 6928: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
6929: &devalidate_cache_new('namescache',$uname.':'.$udom);
6930: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 6931: &logthis($logmsg);
1.134 albertel 6932: return 'ok';
1.80 www 6933: }
6934:
1.81 www 6935: # -------------------------------------------------------------- Modify student
1.80 www 6936:
1.81 www 6937: sub modifystudent {
6938: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6939: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6940: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6941: if (!$cid) {
1.620 albertel 6942: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6943: return 'not_in_class';
6944: }
1.80 www 6945: }
6946: # --------------------------------------------------------------- Make the user
1.81 www 6947: my $reply=&modifyuser
1.209 matthew 6948: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6949: $desiredhome,$email,$inststatus);
1.80 www 6950: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6951: # This will cause &modify_student_enrollment to get the uid from the
6952: # students environment
6953: $uid = undef if (!$forceid);
1.455 albertel 6954: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6955: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6956: return $reply;
6957: }
6958:
6959: sub modify_student_enrollment {
1.957 raeburn 6960: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6961: my ($cdom,$cnum,$chome);
6962: if (!$cid) {
1.620 albertel 6963: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6964: return 'not_in_class';
6965: }
1.620 albertel 6966: $cdom=$env{'course.'.$cid.'.domain'};
6967: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6968: } else {
6969: ($cdom,$cnum)=split(/_/,$cid);
6970: }
1.620 albertel 6971: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6972: if (!$chome) {
1.457 raeburn 6973: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6974: }
1.455 albertel 6975: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6976: # Make sure the user exists
1.81 www 6977: my $uhome=&homeserver($uname,$udom);
6978: if (($uhome eq '') || ($uhome eq 'no_host')) {
6979: return 'error: no such user';
6980: }
1.297 matthew 6981: # Get student data if we were not given enough information
6982: if (!defined($first) || $first eq '' ||
6983: !defined($last) || $last eq '' ||
6984: !defined($uid) || $uid eq '' ||
6985: !defined($middle) || $middle eq '' ||
6986: !defined($gene) || $gene eq '') {
1.294 matthew 6987: # They did not supply us with enough data to enroll the student, so
6988: # we need to pick up more information.
1.297 matthew 6989: my %tmp = &get('environment',
1.294 matthew 6990: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6991: ,$udom,$uname);
6992:
1.800 albertel 6993: #foreach my $key (keys(%tmp)) {
6994: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6995: #}
1.294 matthew 6996: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6997: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6998: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6999: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7000: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7001: }
1.556 albertel 7002: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 7003: my $reply=cput('classlist',
7004: {"$uname:$udom" =>
1.515 raeburn 7005: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7006: $cdom,$cnum);
1.81 www 7007: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7008: return 'error: '.$reply;
1.652 albertel 7009: } else {
7010: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 7011: }
1.297 matthew 7012: # Add student role to user
1.83 www 7013: my $uurl='/'.$cid;
1.81 www 7014: $uurl=~s/\_/\//g;
7015: if ($usec) {
7016: $uurl.='/'.$usec;
7017: }
1.957 raeburn 7018: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 7019: }
7020:
1.556 albertel 7021: sub format_name {
7022: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7023: my $name;
7024: if ($first ne 'lastname') {
7025: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7026: } else {
7027: if ($lastname=~/\S/) {
7028: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7029: $name=~s/\s+,/,/;
7030: } else {
7031: $name.= $firstname.' '.$middlename.' '.$generation;
7032: }
7033: }
7034: $name=~s/^\s+//;
7035: $name=~s/\s+$//;
7036: $name=~s/\s+/ /g;
7037: return $name;
7038: }
7039:
1.84 www 7040: # ------------------------------------------------- Write to course preferences
7041:
7042: sub writecoursepref {
7043: my ($courseid,%prefs)=@_;
7044: $courseid=~s/^\///;
7045: $courseid=~s/\_/\//g;
7046: my ($cdomain,$cnum)=split(/\//,$courseid);
7047: my $chome=homeserver($cnum,$cdomain);
7048: if (($chome eq '') || ($chome eq 'no_host')) {
7049: return 'error: no such course';
7050: }
7051: my $cstring='';
1.800 albertel 7052: foreach my $pref (keys(%prefs)) {
7053: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7054: }
1.84 www 7055: $cstring=~s/\&$//;
7056: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7057: }
7058:
7059: # ---------------------------------------------------------- Make/modify course
7060:
7061: sub createcourse {
1.741 raeburn 7062: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7063: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7064: $url=&declutter($url);
7065: my $cid='';
1.1028 raeburn 7066: if ($context eq 'requestcourses') {
7067: my $can_create = 0;
7068: my ($ownername,$ownerdom) = split(':',$course_owner);
7069: if ($udom eq $ownerdom) {
7070: if (&usertools_access($ownername,$ownerdom,$category,undef,
7071: $context)) {
7072: $can_create = 1;
7073: }
7074: } else {
7075: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7076: $category);
7077: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7078: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7079: if (@curr > 0) {
7080: my @options = qw(approval validate autolimit);
7081: my $optregex = join('|',@options);
7082: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7083: $can_create = 1;
7084: }
7085: }
7086: }
7087: }
7088: if ($can_create) {
7089: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7090: unless (&allowed('ccc',$udom)) {
7091: return 'refused';
7092: }
1.1017 raeburn 7093: }
7094: } else {
7095: return 'refused';
7096: }
1.1028 raeburn 7097: } elsif (!&allowed('ccc',$udom)) {
7098: return 'refused';
1.84 www 7099: }
1.1011 raeburn 7100: # --------------------------------------------------------------- Get Unique ID
7101: my $uname;
7102: if ($cnum =~ /^$match_courseid$/) {
7103: my $chome=&homeserver($cnum,$udom,'true');
7104: if (($chome eq '') || ($chome eq 'no_host')) {
7105: $uname = $cnum;
7106: } else {
1.1038 raeburn 7107: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7108: }
7109: } else {
1.1038 raeburn 7110: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7111: }
7112: return $uname if ($uname =~ /^error/);
7113: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7114: if (!defined($course_server)) {
7115: if (defined(&domain($udom,'primary'))) {
7116: $course_server = &domain($udom,'primary');
7117: } else {
7118: $course_server = $env{'user.home'};
7119: }
7120: }
7121: my %host_servers =
7122: &Apache::lonnet::get_servers($udom,'library');
7123: unless ($host_servers{$course_server}) {
7124: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7125: }
1.84 www 7126: # ------------------------------------------------------------- Make the course
7127: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7128: $course_server);
1.84 www 7129: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7130: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7131: if (($uhome eq '') || ($uhome eq 'no_host')) {
7132: return 'error: no such course';
7133: }
1.271 www 7134: # ----------------------------------------------------------------- Course made
1.516 raeburn 7135: # log existence
1.1029 raeburn 7136: my $now = time;
1.918 raeburn 7137: my $newcourse = {
7138: $udom.'_'.$uname => {
1.921 raeburn 7139: description => $description,
7140: inst_code => $inst_code,
7141: owner => $course_owner,
7142: type => $crstype,
1.1029 raeburn 7143: creator => $env{'user.name'}.':'.
7144: $env{'user.domain'},
7145: created => $now,
7146: context => $context,
1.918 raeburn 7147: },
7148: };
1.921 raeburn 7149: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7150: # set toplevel url
1.271 www 7151: my $topurl=$url;
7152: unless ($nonstandard) {
7153: # ------------------------------------------ For standard courses, make top url
7154: my $mapurl=&clutter($url);
1.278 www 7155: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7156: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7157: <map>
7158: <resource id="1" type="start"></resource>
7159: <resource id="2" src="$mapurl"></resource>
7160: <resource id="3" type="finish"></resource>
7161: <link index="1" from="1" to="2"></link>
7162: <link index="2" from="2" to="3"></link>
7163: </map>
7164: ENDINITMAP
7165: $topurl=&declutter(
1.638 albertel 7166: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7167: );
7168: }
7169: # ----------------------------------------------------------- Write preferences
1.84 www 7170: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7171: ('description' => $description,
7172: 'url' => $topurl,
7173: 'internal.creator' => $env{'user.name'}.':'.
7174: $env{'user.domain'},
7175: 'internal.created' => $now,
7176: 'internal.creationcontext' => $context)
7177: );
1.84 www 7178: return '/'.$udom.'/'.$uname;
7179: }
7180:
1.1011 raeburn 7181: # ------------------------------------------------------------------- Create ID
7182: sub generate_coursenum {
1.1038 raeburn 7183: my ($udom,$crstype) = @_;
1.1011 raeburn 7184: my $domdesc = &domain($udom);
7185: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7186: my $first;
7187: if ($crstype eq 'Community') {
7188: $first = '0';
7189: } else {
7190: $first = int(1+rand(9));
7191: }
7192: my $uname=$first.
1.1011 raeburn 7193: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7194: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7195: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7196: # ----------------------------------------------- Make sure that does not exist
7197: my $uhome=&homeserver($uname,$udom,'true');
7198: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7199: if ($crstype eq 'Community') {
7200: $first = '0';
7201: } else {
7202: $first = int(1+rand(9));
7203: }
7204: $uname=$first.
1.1011 raeburn 7205: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7206: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7207: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7208: $uhome=&homeserver($uname,$udom,'true');
7209: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7210: return 'error: unable to generate unique course-ID';
7211: }
7212: }
7213: return $uname;
7214: }
7215:
1.813 albertel 7216: sub is_course {
7217: my ($cdom,$cnum) = @_;
7218: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7219: undef,'.');
1.813 albertel 7220: if (exists($courses{$cdom.'_'.$cnum})) {
7221: return 1;
7222: }
7223: return 0;
7224: }
7225:
1.1015 raeburn 7226: sub store_userdata {
7227: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7228: my $result;
1.1016 raeburn 7229: if ($datakey ne '') {
1.1013 raeburn 7230: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7231: if ($udom eq '' || $uname eq '') {
7232: $udom = $env{'user.domain'};
7233: $uname = $env{'user.name'};
7234: }
7235: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7236: if (($uhome eq '') || ($uhome eq 'no_host')) {
7237: $result = 'error: no_host';
7238: } else {
7239: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7240: $storehash->{'host'} = $perlvar{'lonHostID'};
7241:
7242: my $namevalue='';
7243: foreach my $key (keys(%{$storehash})) {
7244: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7245: }
7246: $namevalue=~s/\&$//;
7247: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 7248: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 7249: }
7250: } else {
7251: $result = 'error: data to store was not a hash reference';
7252: }
7253: } else {
7254: $result= 'error: invalid requestkey';
7255: }
7256: return $result;
7257: }
7258:
1.21 www 7259: # ---------------------------------------------------------- Assign Custom Role
7260:
7261: sub assigncustomrole {
1.957 raeburn 7262: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7263: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7264: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7265: }
7266:
7267: # ----------------------------------------------------------------- Revoke Role
7268:
7269: sub revokerole {
1.957 raeburn 7270: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7271: my $now=time;
1.965 raeburn 7272: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7273: }
7274:
7275: # ---------------------------------------------------------- Revoke Custom Role
7276:
7277: sub revokecustomrole {
1.957 raeburn 7278: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7279: my $now=time;
1.357 www 7280: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7281: $deleteflag,$selfenroll,$context);
1.17 www 7282: }
7283:
1.533 banghart 7284: # ------------------------------------------------------------ Disk usage
1.535 albertel 7285: sub diskusage {
1.955 raeburn 7286: my ($udom,$uname,$directorypath,$getpropath)=@_;
7287: $directorypath =~ s/\/$//;
7288: my $listing=&reply('du2:'.&escape($directorypath).':'
7289: .&escape($getpropath).':'.&escape($uname).':'
7290: .&escape($udom),homeserver($uname,$udom));
7291: if ($listing eq 'unknown_cmd') {
7292: if ($getpropath) {
7293: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7294: }
7295: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7296: }
1.514 albertel 7297: return $listing;
1.512 banghart 7298: }
7299:
1.566 banghart 7300: sub is_locked {
1.1096 raeburn 7301: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 7302: my @check;
7303: my $is_locked;
1.1093 raeburn 7304: push (@check,$file_name);
1.613 albertel 7305: my %locked = &get('file_permissions',\@check,
1.620 albertel 7306: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7307: my ($tmp)=keys(%locked);
7308: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7309:
1.566 banghart 7310: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7311: $is_locked = 'false';
7312: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 7313: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7314: $is_locked = 'true';
1.1096 raeburn 7315: if (ref($which) eq 'ARRAY') {
7316: push(@{$which},$entry);
7317: } else {
7318: last;
7319: }
1.745 raeburn 7320: }
7321: }
1.566 banghart 7322: } else {
7323: $is_locked = 'false';
7324: }
1.1093 raeburn 7325: return $is_locked;
1.566 banghart 7326: }
7327:
1.759 albertel 7328: sub declutter_portfile {
7329: my ($file) = @_;
1.833 albertel 7330: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7331: return $file;
7332: }
7333:
1.559 banghart 7334: # ------------------------------------------------------------- Mark as Read Only
7335:
7336: sub mark_as_readonly {
7337: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7338: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7339: my ($tmp)=keys(%current_permissions);
7340: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7341: foreach my $file (@{$files}) {
1.759 albertel 7342: $file = &declutter_portfile($file);
1.561 banghart 7343: push(@{$current_permissions{$file}},$what);
1.559 banghart 7344: }
1.613 albertel 7345: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7346: return;
7347: }
7348:
1.572 banghart 7349: # ------------------------------------------------------------Save Selected Files
7350:
7351: sub save_selected_files {
7352: my ($user, $path, @files) = @_;
7353: my $filename = $user."savedfiles";
1.573 banghart 7354: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7355: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7356: foreach my $file (@files) {
1.620 albertel 7357: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7358: }
7359: foreach my $file (@other_files) {
1.574 banghart 7360: print (OUT $file."\n");
1.572 banghart 7361: }
1.574 banghart 7362: close (OUT);
1.572 banghart 7363: return 'ok';
7364: }
7365:
1.574 banghart 7366: sub clear_selected_files {
7367: my ($user) = @_;
7368: my $filename = $user."savedfiles";
7369: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7370: print (OUT undef);
7371: close (OUT);
7372: return ("ok");
7373: }
7374:
1.572 banghart 7375: sub files_in_path {
7376: my ($user, $path) = @_;
7377: my $filename = $user."savedfiles";
7378: my %return_files;
1.574 banghart 7379: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7380: while (my $line_in = <IN>) {
1.574 banghart 7381: chomp ($line_in);
7382: my @paths_and_file = split (m!/!, $line_in);
7383: my $file_part = pop (@paths_and_file);
7384: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7385: $path_part.='/';
7386: my $path_and_file = $path_part.$file_part;
7387: if ($path_part eq $path) {
7388: $return_files{$file_part}= 'selected';
7389: }
7390: }
1.574 banghart 7391: close (IN);
7392: return (\%return_files);
1.572 banghart 7393: }
7394:
7395: # called in portfolio select mode, to show files selected NOT in current directory
7396: sub files_not_in_path {
7397: my ($user, $path) = @_;
7398: my $filename = $user."savedfiles";
7399: my @return_files;
7400: my $path_part;
1.800 albertel 7401: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7402: while (my $line = <IN>) {
1.572 banghart 7403: #ok, I know it's clunky, but I want it to work
1.800 albertel 7404: my @paths_and_file = split(m|/|, $line);
7405: my $file_part = pop(@paths_and_file);
7406: chomp($file_part);
7407: my $path_part = join('/', @paths_and_file);
1.572 banghart 7408: $path_part .= '/';
7409: my $path_and_file = $path_part.$file_part;
7410: if ($path_part ne $path) {
1.800 albertel 7411: push(@return_files, ($path_and_file));
1.572 banghart 7412: }
7413: }
1.800 albertel 7414: close(OUT);
1.574 banghart 7415: return (@return_files);
1.572 banghart 7416: }
7417:
1.745 raeburn 7418: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7419:
1.745 raeburn 7420: sub get_portfile_permissions {
7421: my ($domain,$user) = @_;
1.613 albertel 7422: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7423: my ($tmp)=keys(%current_permissions);
7424: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7425: return \%current_permissions;
7426: }
7427:
7428: #---------------------------------------------Get portfolio file access controls
7429:
1.749 raeburn 7430: sub get_access_controls {
1.745 raeburn 7431: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7432: my %access;
7433: my $real_file = $file;
7434: $file =~ s/\.meta$//;
1.745 raeburn 7435: if (defined($file)) {
1.749 raeburn 7436: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7437: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7438: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7439: }
7440: }
1.745 raeburn 7441: } else {
1.749 raeburn 7442: foreach my $key (keys(%{$current_permissions})) {
7443: if ($key =~ /\0accesscontrol$/) {
7444: if (defined($group)) {
7445: if ($key !~ m-^\Q$group\E/-) {
7446: next;
7447: }
7448: }
7449: my ($fullpath) = split(/\0/,$key);
7450: if (ref($$current_permissions{$key}) eq 'HASH') {
7451: foreach my $control (keys(%{$$current_permissions{$key}})) {
7452: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7453: }
7454: }
7455: }
7456: }
7457: }
7458: return %access;
7459: }
7460:
7461: sub modify_access_controls {
7462: my ($file_name,$changes,$domain,$user)=@_;
7463: my ($outcome,$deloutcome);
7464: my %store_permissions;
7465: my %new_values;
7466: my %new_control;
7467: my %translation;
7468: my @deletions = ();
7469: my $now = time;
7470: if (exists($$changes{'activate'})) {
7471: if (ref($$changes{'activate'}) eq 'HASH') {
7472: my @newitems = sort(keys(%{$$changes{'activate'}}));
7473: my $numnew = scalar(@newitems);
7474: for (my $i=0; $i<$numnew; $i++) {
7475: my $newkey = $newitems[$i];
7476: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7477: if ($newkey =~ /^\d+:/) {
7478: $newkey =~ s/^(\d+)/$newid/;
7479: $translation{$1} = $newid;
7480: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7481: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7482: $translation{$1} = $newid;
7483: }
1.749 raeburn 7484: $new_values{$file_name."\0".$newkey} =
7485: $$changes{'activate'}{$newitems[$i]};
7486: $new_control{$newkey} = $now;
7487: }
7488: }
7489: }
7490: my %todelete;
7491: my %changed_items;
7492: foreach my $action ('delete','update') {
7493: if (exists($$changes{$action})) {
7494: if (ref($$changes{$action}) eq 'HASH') {
7495: foreach my $key (keys(%{$$changes{$action}})) {
7496: my ($itemnum) = ($key =~ /^([^:]+):/);
7497: if ($action eq 'delete') {
7498: $todelete{$itemnum} = 1;
7499: } else {
7500: $changed_items{$itemnum} = $key;
7501: }
7502: }
1.745 raeburn 7503: }
7504: }
1.749 raeburn 7505: }
7506: # get lock on access controls for file.
7507: my $lockhash = {
7508: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7509: ':'.$env{'user.domain'},
7510: };
7511: my $tries = 0;
7512: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7513:
7514: while (($gotlock ne 'ok') && $tries <3) {
7515: $tries ++;
7516: sleep 1;
7517: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7518: }
7519: if ($gotlock eq 'ok') {
7520: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7521: my ($tmp)=keys(%curr_permissions);
7522: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7523: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7524: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7525: if (ref($curr_controls) eq 'HASH') {
7526: foreach my $control_item (keys(%{$curr_controls})) {
7527: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7528: if (defined($todelete{$itemnum})) {
7529: push(@deletions,$file_name."\0".$control_item);
7530: } else {
7531: if (defined($changed_items{$itemnum})) {
7532: $new_control{$changed_items{$itemnum}} = $now;
7533: push(@deletions,$file_name."\0".$control_item);
7534: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7535: } else {
7536: $new_control{$control_item} = $$curr_controls{$control_item};
7537: }
7538: }
1.745 raeburn 7539: }
7540: }
7541: }
1.970 raeburn 7542: my ($group);
7543: if (&is_course($domain,$user)) {
7544: ($group,my $file) = split(/\//,$file_name,2);
7545: }
1.749 raeburn 7546: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7547: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7548: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7549: # remove lock
7550: my @del_lock = ($file_name."\0".'locked_access_records');
7551: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7552: my $sqlresult =
1.970 raeburn 7553: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7554: $group);
1.749 raeburn 7555: } else {
7556: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7557: }
1.749 raeburn 7558: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7559: }
7560:
1.827 raeburn 7561: sub make_public_indefinitely {
7562: my ($requrl) = @_;
7563: my $now = time;
7564: my $action = 'activate';
7565: my $aclnum = 0;
7566: if (&is_portfolio_url($requrl)) {
7567: my (undef,$udom,$unum,$file_name,$group) =
7568: &parse_portfolio_url($requrl);
7569: my $current_perms = &get_portfile_permissions($udom,$unum);
7570: my %access_controls = &get_access_controls($current_perms,
7571: $group,$file_name);
7572: foreach my $key (keys(%{$access_controls{$file_name}})) {
7573: my ($num,$scope,$end,$start) =
7574: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7575: if ($scope eq 'public') {
7576: if ($start <= $now && $end == 0) {
7577: $action = 'none';
7578: } else {
7579: $action = 'update';
7580: $aclnum = $num;
7581: }
7582: last;
7583: }
7584: }
7585: if ($action eq 'none') {
7586: return 'ok';
7587: } else {
7588: my %changes;
7589: my $newend = 0;
7590: my $newstart = $now;
7591: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7592: $changes{$action}{$newkey} = {
7593: type => 'public',
7594: time => {
7595: start => $newstart,
7596: end => $newend,
7597: },
7598: };
7599: my ($outcome,$deloutcome,$new_values,$translation) =
7600: &modify_access_controls($file_name,\%changes,$udom,$unum);
7601: return $outcome;
7602: }
7603: } else {
7604: return 'invalid';
7605: }
7606: }
7607:
1.745 raeburn 7608: #------------------------------------------------------Get Marked as Read Only
7609:
7610: sub get_marked_as_readonly {
7611: my ($domain,$user,$what,$group) = @_;
7612: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7613: my @readonly_files;
1.629 banghart 7614: my $cmp1=$what;
7615: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7616: while (my ($file_name,$value) = each(%{$current_permissions})) {
7617: if (defined($group)) {
7618: if ($file_name !~ m-^\Q$group\E/-) {
7619: next;
7620: }
7621: }
1.561 banghart 7622: if (ref($value) eq "ARRAY"){
7623: foreach my $stored_what (@{$value}) {
1.629 banghart 7624: my $cmp2=$stored_what;
1.759 albertel 7625: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7626: $cmp2=join('',@{$stored_what});
1.745 raeburn 7627: }
1.629 banghart 7628: if ($cmp1 eq $cmp2) {
1.561 banghart 7629: push(@readonly_files, $file_name);
1.745 raeburn 7630: last;
1.563 banghart 7631: } elsif (!defined($what)) {
7632: push(@readonly_files, $file_name);
1.745 raeburn 7633: last;
1.561 banghart 7634: }
7635: }
1.745 raeburn 7636: }
1.561 banghart 7637: }
7638: return @readonly_files;
7639: }
1.577 banghart 7640: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7641:
1.577 banghart 7642: sub get_marked_as_readonly_hash {
1.745 raeburn 7643: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7644: my %readonly_files;
1.745 raeburn 7645: while (my ($file_name,$value) = each(%{$current_permissions})) {
7646: if (defined($group)) {
7647: if ($file_name !~ m-^\Q$group\E/-) {
7648: next;
7649: }
7650: }
1.577 banghart 7651: if (ref($value) eq "ARRAY"){
7652: foreach my $stored_what (@{$value}) {
1.745 raeburn 7653: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7654: foreach my $lock_descriptor(@{$stored_what}) {
7655: if ($lock_descriptor eq 'graded') {
7656: $readonly_files{$file_name} = 'graded';
7657: } elsif ($lock_descriptor eq 'handback') {
7658: $readonly_files{$file_name} = 'handback';
7659: } else {
7660: if (!exists($readonly_files{$file_name})) {
7661: $readonly_files{$file_name} = 'locked';
7662: }
7663: }
1.745 raeburn 7664: }
1.750 banghart 7665: }
1.577 banghart 7666: }
7667: }
7668: }
7669: return %readonly_files;
7670: }
1.559 banghart 7671: # ------------------------------------------------------------ Unmark as Read Only
7672:
7673: sub unmark_as_readonly {
1.629 banghart 7674: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7675: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7676: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7677: $file_name = &declutter_portfile($file_name);
1.634 albertel 7678: my $symb_crs = $what;
7679: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7680: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7681: my ($tmp)=keys(%current_permissions);
7682: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7683: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7684: foreach my $file (@readonly_files) {
1.759 albertel 7685: my $clean_file = &declutter_portfile($file);
7686: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7687: my $current_locks = $current_permissions{$file};
1.563 banghart 7688: my @new_locks;
7689: my @del_keys;
7690: if (ref($current_locks) eq "ARRAY"){
7691: foreach my $locker (@{$current_locks}) {
1.632 albertel 7692: my $compare=$locker;
1.749 raeburn 7693: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7694: $compare=join('',@{$locker});
1.746 raeburn 7695: if ($compare ne $symb_crs) {
7696: push(@new_locks, $locker);
7697: }
1.563 banghart 7698: }
7699: }
1.650 albertel 7700: if (scalar(@new_locks) > 0) {
1.563 banghart 7701: $current_permissions{$file} = \@new_locks;
7702: } else {
7703: push(@del_keys, $file);
1.613 albertel 7704: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7705: delete($current_permissions{$file});
1.563 banghart 7706: }
7707: }
1.561 banghart 7708: }
1.613 albertel 7709: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7710: return;
7711: }
1.512 banghart 7712:
1.17 www 7713: # ------------------------------------------------------------ Directory lister
7714:
7715: sub dirlist {
1.955 raeburn 7716: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7717: $uri=~s/^\///;
7718: $uri=~s/\/$//;
1.253 stredwic 7719: my ($udom, $uname);
1.955 raeburn 7720: if ($getuserdir) {
1.253 stredwic 7721: $udom = $userdomain;
7722: $uname = $username;
1.955 raeburn 7723: } else {
7724: (undef,$udom,$uname)=split(/\//,$uri);
7725: if(defined($userdomain)) {
7726: $udom = $userdomain;
7727: }
7728: if(defined($username)) {
7729: $uname = $username;
7730: }
1.253 stredwic 7731: }
1.955 raeburn 7732: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7733:
1.955 raeburn 7734: $dirRoot = $perlvar{'lonDocRoot'};
7735: if (defined($getpropath)) {
7736: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7737: $dirRoot =~ s/\/$//;
1.955 raeburn 7738: } elsif (defined($getuserdir)) {
7739: my $subdir=$uname.'__';
7740: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7741: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7742: ."/$udom/$subdir/$uname";
7743: } elsif (defined($alternateRoot)) {
7744: $dirRoot = $alternateRoot;
1.751 banghart 7745: }
1.253 stredwic 7746:
7747: if($udom) {
7748: if($uname) {
1.955 raeburn 7749: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7750: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7751: .':'.&escape($uname).':'.&escape($udom),
7752: &homeserver($uname,$udom));
7753: if ($listing eq 'unknown_cmd') {
7754: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7755: &homeserver($uname,$udom));
7756: } else {
7757: @listing_results = map { &unescape($_); } split(/:/,$listing);
7758: }
1.605 matthew 7759: if ($listing eq 'unknown_cmd') {
1.800 albertel 7760: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7761: &homeserver($uname,$udom));
1.605 matthew 7762: @listing_results = split(/:/,$listing);
7763: } else {
7764: @listing_results = map { &unescape($_); } split(/:/,$listing);
7765: }
7766: return @listing_results;
1.955 raeburn 7767: } elsif(!$alternateRoot) {
1.800 albertel 7768: my %allusers;
1.841 albertel 7769: my %servers = &get_servers($udom,'library');
1.955 raeburn 7770: foreach my $tryserver (keys(%servers)) {
7771: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7772: &escape($udom),$tryserver);
7773: if ($listing eq 'unknown_cmd') {
7774: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7775: $udom, $tryserver);
7776: } else {
7777: @listing_results = map { &unescape($_); } split(/:/,$listing);
7778: }
1.841 albertel 7779: if ($listing eq 'unknown_cmd') {
7780: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7781: $udom, $tryserver);
7782: @listing_results = split(/:/,$listing);
7783: } else {
7784: @listing_results =
7785: map { &unescape($_); } split(/:/,$listing);
7786: }
7787: if ($listing_results[0] ne 'no_such_dir' &&
7788: $listing_results[0] ne 'empty' &&
7789: $listing_results[0] ne 'con_lost') {
7790: foreach my $line (@listing_results) {
7791: my ($entry) = split(/&/,$line,2);
7792: $allusers{$entry} = 1;
7793: }
7794: }
1.253 stredwic 7795: }
7796: my $alluserstr='';
1.800 albertel 7797: foreach my $user (sort(keys(%allusers))) {
7798: $alluserstr.=$user.'&user:';
1.253 stredwic 7799: }
7800: $alluserstr=~s/:$//;
7801: return split(/:/,$alluserstr);
7802: } else {
1.800 albertel 7803: return ('missing user name');
1.253 stredwic 7804: }
1.955 raeburn 7805: } elsif(!defined($getpropath)) {
1.841 albertel 7806: my @all_domains = sort(&all_domains());
1.955 raeburn 7807: foreach my $domain (@all_domains) {
7808: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7809: }
7810: return @all_domains;
7811: } else {
1.800 albertel 7812: return ('missing domain');
1.275 stredwic 7813: }
7814: }
7815:
7816: # --------------------------------------------- GetFileTimestamp
7817: # This function utilizes dirlist and returns the date stamp for
7818: # when it was last modified. It will also return an error of -1
7819: # if an error occurs
7820:
7821: sub GetFileTimestamp {
1.955 raeburn 7822: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7823: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7824: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7825: my ($fileStat) =
7826: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7827: undef,$getuserdir);
1.275 stredwic 7828: my @stats = split('&', $fileStat);
7829: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7830: # @stats contains first the filename, then the stat output
7831: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7832: } else {
7833: return -1;
1.253 stredwic 7834: }
1.26 www 7835: }
7836:
1.712 albertel 7837: sub stat_file {
7838: my ($uri) = @_;
1.787 albertel 7839: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7840:
1.955 raeburn 7841: my ($udom,$uname,$file);
1.712 albertel 7842: if ($uri =~ m-^/(uploaded|editupload)/-) {
7843: ($udom,$uname,$file) =
1.811 albertel 7844: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7845: $file = 'userfiles/'.$file;
7846: }
7847: if ($uri =~ m-^/res/-) {
7848: ($udom,$uname) =
1.807 albertel 7849: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7850: $file = $uri;
7851: }
7852:
7853: if (!$udom || !$uname || !$file) {
7854: # unable to handle the uri
7855: return ();
7856: }
1.956 raeburn 7857: my $getpropath;
7858: if ($file =~ /^userfiles\//) {
7859: $getpropath = 1;
7860: }
1.955 raeburn 7861: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7862: my @stats = split('&', $result);
1.721 banghart 7863:
1.712 albertel 7864: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7865: shift(@stats); #filename is first
7866: return @stats;
7867: }
7868: return ();
7869: }
7870:
1.26 www 7871: # -------------------------------------------------------- Value of a Condition
7872:
1.713 albertel 7873: # gets the value of a specific preevaluated condition
7874: # stored in the string $env{user.state.<cid>}
7875: # or looks up a condition reference in the bighash and if if hasn't
7876: # already been evaluated recurses into docondval to get the value of
7877: # the condition, then memoizing it to
7878: # $env{user.state.<cid>.<condition>}
1.40 www 7879: sub directcondval {
7880: my $number=shift;
1.620 albertel 7881: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7882: &Apache::lonuserstate::evalstate();
7883: }
1.713 albertel 7884: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7885: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7886: } elsif ($number =~ /^_/) {
7887: my $sub_condition;
7888: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7889: &GDBM_READER(),0640)) {
7890: $sub_condition=$bighash{'conditions'.$number};
7891: untie(%bighash);
7892: }
7893: my $value = &docondval($sub_condition);
1.949 raeburn 7894: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7895: return $value;
7896: }
1.620 albertel 7897: if ($env{'user.state.'.$env{'request.course.id'}}) {
7898: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7899: } else {
7900: return 2;
7901: }
7902: }
7903:
1.713 albertel 7904: # get the collection of conditions for this resource
1.26 www 7905: sub condval {
7906: my $condidx=shift;
1.54 www 7907: my $allpathcond='';
1.713 albertel 7908: foreach my $cond (split(/\|/,$condidx)) {
7909: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7910: $allpathcond.=
7911: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7912: }
1.191 harris41 7913: }
1.54 www 7914: $allpathcond=~s/\|$//;
1.713 albertel 7915: return &docondval($allpathcond);
7916: }
7917:
7918: #evaluates an expression of conditions
7919: sub docondval {
7920: my ($allpathcond) = @_;
7921: my $result=0;
7922: if ($env{'request.course.id'}
7923: && defined($allpathcond)) {
7924: my $operand='|';
7925: my @stack;
7926: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7927: if ($chunk eq '(') {
7928: push @stack,($operand,$result);
7929: } elsif ($chunk eq ')') {
7930: my $before=pop @stack;
7931: if (pop @stack eq '&') {
7932: $result=$result>$before?$before:$result;
7933: } else {
7934: $result=$result>$before?$result:$before;
7935: }
7936: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7937: $operand=$chunk;
7938: } else {
7939: my $new=directcondval($chunk);
7940: if ($operand eq '&') {
7941: $result=$result>$new?$new:$result;
7942: } else {
7943: $result=$result>$new?$result:$new;
7944: }
7945: }
7946: }
1.26 www 7947: }
7948: return $result;
1.421 albertel 7949: }
7950:
7951: # ---------------------------------------------------- Devalidate courseresdata
7952:
7953: sub devalidatecourseresdata {
7954: my ($coursenum,$coursedomain)=@_;
7955: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7956: &devalidate_cache_new('courseres',$hashid);
1.28 www 7957: }
7958:
1.763 www 7959:
1.200 www 7960: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7961: #
7962: # Parameters:
7963: # $coursenum - Number of the course.
7964: # $coursedomain - Domain at which the course was created.
7965: # Returns:
7966: # A hash of the course parameters along (I think) with timestamps
7967: # and version info.
1.877 foxr 7968:
1.624 albertel 7969: sub get_courseresdata {
7970: my ($coursenum,$coursedomain)=@_;
1.200 www 7971: my $coursehom=&homeserver($coursenum,$coursedomain);
7972: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7973: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7974: my %dumpreply;
1.417 albertel 7975: unless (defined($cached)) {
1.624 albertel 7976: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7977: $result=\%dumpreply;
1.251 albertel 7978: my ($tmp) = keys(%dumpreply);
7979: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7980: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7981: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7982: return $tmp;
1.416 albertel 7983: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7984: $result=undef;
1.599 albertel 7985: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7986: }
7987: }
1.624 albertel 7988: return $result;
7989: }
7990:
1.633 albertel 7991: sub devalidateuserresdata {
7992: my ($uname,$udom)=@_;
7993: my $hashid="$udom:$uname";
7994: &devalidate_cache_new('userres',$hashid);
7995: }
7996:
1.624 albertel 7997: sub get_userresdata {
7998: my ($uname,$udom)=@_;
7999: #most student don\'t have any data set, check if there is some data
8000: if (&EXT_cache_status($udom,$uname)) { return undef; }
8001:
8002: my $hashid="$udom:$uname";
8003: my ($result,$cached)=&is_cached_new('userres',$hashid);
8004: if (!defined($cached)) {
8005: my %resourcedata=&dump('resourcedata',$udom,$uname);
8006: $result=\%resourcedata;
8007: &do_cache_new('userres',$hashid,$result,600);
8008: }
8009: my ($tmp)=keys(%$result);
8010: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8011: return $result;
8012: }
8013: #error 2 occurs when the .db doesn't exist
8014: if ($tmp!~/error: 2 /) {
1.672 albertel 8015: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8016: " Trying to get resource data for ".
8017: $uname." at ".$udom.": ".
8018: $tmp."</font>");
8019: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8020: #&EXT_cache_set($udom,$uname);
8021: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8022: undef($tmp); # not really an error so don't send it back
1.624 albertel 8023: }
8024: return $tmp;
8025: }
1.879 foxr 8026: #----------------------------------------------- resdata - return resource data
8027: # Purpose:
8028: # Return resource data for either users or for a course.
8029: # Parameters:
8030: # $name - Course/user name.
8031: # $domain - Name of the domain the user/course is registered on.
8032: # $type - Type of thing $name is (must be 'course' or 'user'
8033: # @which - Array of names of resources desired.
8034: # Returns:
8035: # The value of the first reasource in @which that is found in the
8036: # resource hash.
8037: # Exceptional Conditions:
8038: # If the $type passed in is not valid (not the string 'course' or
8039: # 'user', an undefined reference is returned.
8040: # If none of the resources are found, an undef is returned
1.624 albertel 8041: sub resdata {
8042: my ($name,$domain,$type,@which)=@_;
8043: my $result;
8044: if ($type eq 'course') {
8045: $result=&get_courseresdata($name,$domain);
8046: } elsif ($type eq 'user') {
8047: $result=&get_userresdata($name,$domain);
8048: }
8049: if (!ref($result)) { return $result; }
1.251 albertel 8050: foreach my $item (@which) {
1.927 albertel 8051: if (defined($result->{$item->[0]})) {
8052: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8053: }
1.250 albertel 8054: }
1.291 albertel 8055: return undef;
1.200 www 8056: }
8057:
1.379 matthew 8058: #
8059: # EXT resource caching routines
8060: #
8061:
8062: sub clear_EXT_cache_status {
1.383 albertel 8063: &delenv('cache.EXT.');
1.379 matthew 8064: }
8065:
8066: sub EXT_cache_status {
8067: my ($target_domain,$target_user) = @_;
1.383 albertel 8068: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8069: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8070: # We know already the user has no data
8071: return 1;
8072: } else {
8073: return 0;
8074: }
8075: }
8076:
8077: sub EXT_cache_set {
8078: my ($target_domain,$target_user) = @_;
1.383 albertel 8079: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8080: #&appenv({$cachename => time});
1.379 matthew 8081: }
8082:
1.28 www 8083: # --------------------------------------------------------- Value of a Variable
1.58 www 8084: sub EXT {
1.715 albertel 8085:
1.395 albertel 8086: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8087: unless ($varname) { return ''; }
1.218 albertel 8088: #get real user name/domain, courseid and symb
8089: my $courseid;
1.359 albertel 8090: my $publicuser;
1.427 www 8091: if ($symbparm) {
8092: $symbparm=&get_symb_from_alias($symbparm);
8093: }
1.218 albertel 8094: if (!($uname && $udom)) {
1.790 albertel 8095: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8096: if (!$symbparm) { $symbparm=$cursymb; }
8097: } else {
1.620 albertel 8098: $courseid=$env{'request.course.id'};
1.218 albertel 8099: }
1.48 www 8100: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8101: my $rest;
1.320 albertel 8102: if (defined($therest[0])) {
1.48 www 8103: $rest=join('.',@therest);
8104: } else {
8105: $rest='';
8106: }
1.320 albertel 8107:
1.57 www 8108: my $qualifierrest=$qualifier;
8109: if ($rest) { $qualifierrest.='.'.$rest; }
8110: my $spacequalifierrest=$space;
8111: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8112: if ($realm eq 'user') {
1.48 www 8113: # --------------------------------------------------------------- user.resource
8114: if ($space eq 'resource') {
1.651 albertel 8115: if ( (defined($Apache::lonhomework::parsing_a_problem)
8116: || defined($Apache::lonhomework::parsing_a_task))
8117: &&
1.744 albertel 8118: ($symbparm eq &symbread()) ) {
8119: # if we are in the middle of processing the resource the
8120: # get the value we are planning on committing
8121: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8122: return $Apache::lonhomework::results{$qualifierrest};
8123: } else {
8124: return $Apache::lonhomework::history{$qualifierrest};
8125: }
1.335 albertel 8126: } else {
1.359 albertel 8127: my %restored;
1.620 albertel 8128: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8129: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8130: } else {
8131: %restored=&restore($symbparm,$courseid,$udom,$uname);
8132: }
1.335 albertel 8133: return $restored{$qualifierrest};
8134: }
1.48 www 8135: # ----------------------------------------------------------------- user.access
8136: } elsif ($space eq 'access') {
1.218 albertel 8137: # FIXME - not supporting calls for a specific user
1.48 www 8138: return &allowed($qualifier,$rest);
8139: # ------------------------------------------ user.preferences, user.environment
8140: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8141: if (($uname eq $env{'user.name'}) &&
8142: ($udom eq $env{'user.domain'})) {
8143: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8144: } else {
1.359 albertel 8145: my %returnhash;
8146: if (!$publicuser) {
8147: %returnhash=&userenvironment($udom,$uname,
8148: $qualifierrest);
8149: }
1.218 albertel 8150: return $returnhash{$qualifierrest};
8151: }
1.48 www 8152: # ----------------------------------------------------------------- user.course
8153: } elsif ($space eq 'course') {
1.218 albertel 8154: # FIXME - not supporting calls for a specific user
1.620 albertel 8155: return $env{join('.',('request.course',$qualifier))};
1.48 www 8156: # ------------------------------------------------------------------- user.role
8157: } elsif ($space eq 'role') {
1.218 albertel 8158: # FIXME - not supporting calls for a specific user
1.620 albertel 8159: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8160: if ($qualifier eq 'value') {
8161: return $role;
8162: } elsif ($qualifier eq 'extent') {
8163: return $where;
8164: }
8165: # ----------------------------------------------------------------- user.domain
8166: } elsif ($space eq 'domain') {
1.218 albertel 8167: return $udom;
1.48 www 8168: # ------------------------------------------------------------------- user.name
8169: } elsif ($space eq 'name') {
1.218 albertel 8170: return $uname;
1.48 www 8171: # ---------------------------------------------------- Any other user namespace
1.29 www 8172: } else {
1.359 albertel 8173: my %reply;
8174: if (!$publicuser) {
8175: %reply=&get($space,[$qualifierrest],$udom,$uname);
8176: }
8177: return $reply{$qualifierrest};
1.48 www 8178: }
1.236 www 8179: } elsif ($realm eq 'query') {
8180: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8181: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8182: [$spacequalifierrest]);
1.620 albertel 8183: return $env{'form.'.$spacequalifierrest};
1.236 www 8184: } elsif ($realm eq 'request') {
1.48 www 8185: # ------------------------------------------------------------- request.browser
8186: if ($space eq 'browser') {
1.430 www 8187: if ($qualifier eq 'textremote') {
1.676 albertel 8188: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8189: return 1;
8190: } else {
8191: return 0;
8192: }
8193: } else {
1.620 albertel 8194: return $env{'browser.'.$qualifier};
1.430 www 8195: }
1.57 www 8196: # ------------------------------------------------------------ request.filename
8197: } else {
1.620 albertel 8198: return $env{'request.'.$spacequalifierrest};
1.29 www 8199: }
1.28 www 8200: } elsif ($realm eq 'course') {
1.48 www 8201: # ---------------------------------------------------------- course.description
1.620 albertel 8202: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8203: } elsif ($realm eq 'resource') {
1.165 www 8204:
1.620 albertel 8205: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8206: if (!$symbparm) { $symbparm=&symbread(); }
8207: }
1.693 albertel 8208:
8209: if ($space eq 'title') {
8210: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8211: return &gettitle($symbparm);
8212: }
8213:
8214: if ($space eq 'map') {
8215: my ($map) = &decode_symb($symbparm);
8216: return &symbread($map);
8217: }
1.905 albertel 8218: if ($space eq 'filename') {
8219: if ($symbparm) {
8220: return &clutter((&decode_symb($symbparm))[2]);
8221: }
8222: return &hreflocation('',$env{'request.filename'});
8223: }
1.693 albertel 8224:
8225: my ($section, $group, @groups);
1.593 albertel 8226: my ($courselevelm,$courselevel);
1.539 albertel 8227: if ($symbparm && defined($courseid) &&
1.620 albertel 8228: $courseid eq $env{'request.course.id'}) {
1.165 www 8229:
1.218 albertel 8230: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8231:
1.60 www 8232: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8233: my $symbp=$symbparm;
1.735 albertel 8234: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8235:
8236: my $symbparm=$symbp.'.'.$spacequalifierrest;
8237: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8238:
1.620 albertel 8239: if (($env{'user.name'} eq $uname) &&
8240: ($env{'user.domain'} eq $udom)) {
8241: $section=$env{'request.course.sec'};
1.733 raeburn 8242: @groups = split(/:/,$env{'request.course.groups'});
8243: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8244: } else {
1.539 albertel 8245: if (! defined($usection)) {
1.551 albertel 8246: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8247: } else {
8248: $section = $usection;
8249: }
1.733 raeburn 8250: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8251: }
8252:
8253: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8254: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8255: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8256:
1.593 albertel 8257: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8258: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8259: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8260:
1.60 www 8261: # ----------------------------------------------------------- first, check user
1.624 albertel 8262:
8263: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8264: ([$courselevelr,'resource'],
8265: [$courselevelm,'map' ],
8266: [$courselevel, 'course' ]));
1.931 albertel 8267: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8268:
1.594 albertel 8269: # ------------------------------------------------ second, check some of course
1.684 raeburn 8270: my $coursereply;
1.691 raeburn 8271: if (@groups > 0) {
8272: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8273: $mapparm,$spacequalifierrest);
1.927 albertel 8274: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8275: }
1.96 www 8276:
1.684 raeburn 8277: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8278: $env{'course.'.$courseid.'.domain'},
8279: 'course',
8280: ([$seclevelr, 'resource'],
8281: [$seclevelm, 'map' ],
8282: [$seclevel, 'course' ],
8283: [$courselevelr,'resource']));
8284: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8285:
1.60 www 8286: # ------------------------------------------------------ third, check map parms
1.218 albertel 8287: my %parmhash=();
8288: my $thisparm='';
8289: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8290: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8291: &GDBM_READER(),0640)) {
1.218 albertel 8292: $thisparm=$parmhash{$symbparm};
8293: untie(%parmhash);
8294: }
1.927 albertel 8295: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8296: }
1.594 albertel 8297: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8298:
1.218 albertel 8299: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8300: my $filename;
8301: if (!$symbparm) { $symbparm=&symbread(); }
8302: if ($symbparm) {
1.409 www 8303: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8304: } else {
1.620 albertel 8305: $filename=$env{'request.filename'};
1.282 albertel 8306: }
8307: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8308: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8309: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8310: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8311:
1.927 albertel 8312: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8313: if ($symbparm && defined($courseid) &&
1.620 albertel 8314: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8315: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8316: $env{'course.'.$courseid.'.domain'},
8317: 'course',
1.927 albertel 8318: ([$courselevelm,'map' ],
8319: [$courselevel, 'course']));
8320: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8321: }
1.145 www 8322: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8323: unless ($space eq '0') {
1.336 albertel 8324: my @parts=split(/_/,$space);
8325: my $id=pop(@parts);
8326: my $part=join('_',@parts);
8327: if ($part eq '') { $part='0'; }
1.927 albertel 8328: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8329: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8330: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8331: }
1.395 albertel 8332: if ($recurse) { return undef; }
8333: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8334: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8335: # ---------------------------------------------------- Any other user namespace
8336: } elsif ($realm eq 'environment') {
8337: # ----------------------------------------------------------------- environment
1.620 albertel 8338: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8339: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8340: } else {
1.770 albertel 8341: if ($uname eq 'anonymous' && $udom eq '') {
8342: return '';
8343: }
1.219 albertel 8344: my %returnhash=&userenvironment($udom,$uname,
8345: $spacequalifierrest);
8346: return $returnhash{$spacequalifierrest};
8347: }
1.28 www 8348: } elsif ($realm eq 'system') {
1.48 www 8349: # ----------------------------------------------------------------- system.time
8350: if ($space eq 'time') {
8351: return time;
8352: }
1.696 albertel 8353: } elsif ($realm eq 'server') {
8354: # ----------------------------------------------------------------- system.time
8355: if ($space eq 'name') {
8356: return $ENV{'SERVER_NAME'};
8357: }
1.28 www 8358: }
1.48 www 8359: return '';
1.61 www 8360: }
8361:
1.927 albertel 8362: sub get_reply {
8363: my ($reply_value) = @_;
1.940 raeburn 8364: if (ref($reply_value) eq 'ARRAY') {
8365: if (wantarray) {
8366: return @$reply_value;
8367: }
8368: return $reply_value->[0];
8369: } else {
8370: return $reply_value;
1.927 albertel 8371: }
8372: }
8373:
1.691 raeburn 8374: sub check_group_parms {
8375: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8376: my @groupitems = ();
8377: my $resultitem;
1.927 albertel 8378: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8379: foreach my $group (@{$groups}) {
8380: foreach my $level (@levels) {
1.927 albertel 8381: my $item = $courseid.'.['.$group.'].'.$level->[0];
8382: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8383: }
8384: }
8385: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8386: $env{'course.'.$courseid.'.domain'},
8387: 'course',@groupitems);
8388: return $coursereply;
8389: }
8390:
8391: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8392: my ($courseid,@groups) = @_;
8393: @groups = sort(@groups);
1.691 raeburn 8394: return @groups;
8395: }
8396:
1.395 albertel 8397: sub packages_tab_default {
8398: my ($uri,$varname)=@_;
8399: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8400:
8401: my (@extension,@specifics,$do_default);
8402: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8403: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8404: if ($pack_type eq 'default') {
8405: $do_default=1;
8406: } elsif ($pack_type eq 'extension') {
8407: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8408: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8409: # only look at packages defaults for packages that this id is
1.738 albertel 8410: push(@specifics,[$package,$pack_type,$pack_part]);
8411: }
8412: }
8413: # first look for a package that matches the requested part id
8414: foreach my $package (@specifics) {
8415: my (undef,$pack_type,$pack_part)=@{$package};
8416: next if ($pack_part ne $part);
8417: if (defined($packagetab{"$pack_type&$name&default"})) {
8418: return $packagetab{"$pack_type&$name&default"};
8419: }
8420: }
8421: # look for any possible matching non extension_ package
8422: foreach my $package (@specifics) {
8423: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8424: if (defined($packagetab{"$pack_type&$name&default"})) {
8425: return $packagetab{"$pack_type&$name&default"};
8426: }
1.585 albertel 8427: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8428: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8429: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8430: }
8431: }
1.738 albertel 8432: # look for any posible extension_ match
8433: foreach my $package (@extension) {
8434: my ($package,$pack_type)=@{$package};
8435: if (defined($packagetab{"$pack_type&$name&default"})) {
8436: return $packagetab{"$pack_type&$name&default"};
8437: }
8438: if (defined($packagetab{$package."&$name&default"})) {
8439: return $packagetab{$package."&$name&default"};
8440: }
8441: }
8442: # look for a global default setting
8443: if ($do_default && defined($packagetab{"default&$name&default"})) {
8444: return $packagetab{"default&$name&default"};
8445: }
1.395 albertel 8446: return undef;
8447: }
8448:
1.334 albertel 8449: sub add_prefix_and_part {
8450: my ($prefix,$part)=@_;
8451: my $keyroot;
8452: if (defined($prefix) && $prefix !~ /^__/) {
8453: # prefix that has a part already
8454: $keyroot=$prefix;
8455: } elsif (defined($prefix)) {
8456: # prefix that is missing a part
8457: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8458: } else {
8459: # no prefix at all
8460: if (defined($part)) { $keyroot='_'.$part; }
8461: }
8462: return $keyroot;
8463: }
8464:
1.71 www 8465: # ---------------------------------------------------------------- Get metadata
8466:
1.599 albertel 8467: my %metaentry;
1.1070 www 8468: my %importedpartids;
1.71 www 8469: sub metadata {
1.176 www 8470: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8471: $uri=&declutter($uri);
1.288 albertel 8472: # if it is a non metadata possible uri return quickly
1.529 albertel 8473: if (($uri eq '') ||
8474: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8475: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1100 raeburn 8476: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$}) || ($uri =~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.924 albertel 8477: return undef;
8478: }
8479: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8480: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8481: return undef;
1.288 albertel 8482: }
1.73 www 8483: my $filename=$uri;
8484: $uri=~s/\.meta$//;
1.172 www 8485: #
8486: # Is the metadata already cached?
1.177 www 8487: # Look at timestamp of caching
1.172 www 8488: # Everything is cached by the main uri, libraries are never directly cached
8489: #
1.428 albertel 8490: if (!defined($liburi)) {
1.599 albertel 8491: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8492: if (defined($cached)) { return $result->{':'.$what}; }
8493: }
8494: {
1.1069 www 8495: # Imported parts would go here
1.1070 www 8496: my %importedids=();
8497: my @origfileimportpartids=();
1.1069 www 8498: my $importedparts=0;
1.172 www 8499: #
8500: # Is this a recursive call for a library?
8501: #
1.599 albertel 8502: # if (! exists($metacache{$uri})) {
8503: # $metacache{$uri}={};
8504: # }
1.924 albertel 8505: my $cachetime = 60*60;
1.171 www 8506: if ($liburi) {
8507: $liburi=&declutter($liburi);
8508: $filename=$liburi;
1.401 bowersj2 8509: } else {
1.599 albertel 8510: &devalidate_cache_new('meta',$uri);
8511: undef(%metaentry);
1.401 bowersj2 8512: }
1.140 www 8513: my %metathesekeys=();
1.73 www 8514: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8515: my $metastring;
1.924 albertel 8516: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8517: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8518: $metastring =
1.929 albertel 8519: &Apache::lonnet::ssi_body($which,
1.924 albertel 8520: ('grade_target' => 'meta'));
8521: $cachetime = 1; # only want this cached in the child not long term
8522: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8523: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8524: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8525: $metastring=&getfile($file);
1.489 albertel 8526: }
1.208 albertel 8527: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8528: my $token;
1.140 www 8529: undef %metathesekeys;
1.71 www 8530: while ($token=$parser->get_token) {
1.339 albertel 8531: if ($token->[0] eq 'S') {
8532: if (defined($token->[2]->{'package'})) {
1.172 www 8533: #
8534: # This is a package - get package info
8535: #
1.339 albertel 8536: my $package=$token->[2]->{'package'};
8537: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8538: if (defined($token->[2]->{'id'})) {
8539: $keyroot.='_'.$token->[2]->{'id'};
8540: }
1.599 albertel 8541: if ($metaentry{':packages'}) {
8542: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8543: } else {
1.599 albertel 8544: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8545: }
1.736 albertel 8546: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8547: my $part=$keyroot;
8548: $part=~s/^\_//;
1.736 albertel 8549: if ($pack_entry=~/^\Q$package\E\&/ ||
8550: $pack_entry=~/^\Q$package\E_0\&/) {
8551: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8552: # ignore package.tab specified default values
8553: # here &package_tab_default() will fetch those
8554: if ($subp eq 'default') { next; }
1.736 albertel 8555: my $value=$packagetab{$pack_entry};
1.432 albertel 8556: my $unikey;
8557: if ($pack =~ /_0$/) {
8558: $unikey='parameter_0_'.$name;
8559: $part=0;
8560: } else {
8561: $unikey='parameter'.$keyroot.'_'.$name;
8562: }
1.339 albertel 8563: if ($subp eq 'display') {
8564: $value.=' [Part: '.$part.']';
8565: }
1.599 albertel 8566: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8567: $metathesekeys{$unikey}=1;
1.599 albertel 8568: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8569: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8570: }
1.599 albertel 8571: if (defined($metaentry{':'.$unikey.'.default'})) {
8572: $metaentry{':'.$unikey}=
8573: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8574: }
1.339 albertel 8575: }
8576: }
8577: } else {
1.172 www 8578: #
8579: # This is not a package - some other kind of start tag
1.339 albertel 8580: #
8581: my $entry=$token->[1];
1.1068 www 8582: my $unikey='';
1.175 www 8583:
1.339 albertel 8584: if ($entry eq 'import') {
1.175 www 8585: #
8586: # Importing a library here
1.339 albertel 8587: #
1.1067 www 8588: my $location=$parser->get_text('/import');
8589: my $dir=$filename;
8590: $dir=~s|[^/]*$||;
8591: $location=&filelocation($dir,$location);
1.1069 www 8592:
1.1068 www 8593: my $importmode=$token->[2]->{'importmode'};
8594: if ($importmode eq 'problem') {
1.1069 www 8595: # Import as problem/response
1.1068 www 8596: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8597: } elsif ($importmode eq 'part') {
8598: # Import as part(s)
1.1069 www 8599: $importedparts=1;
8600: # We need to get the original file and the imported file to get the part order correct
8601: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
8602: # Load and inspect original file
1.1070 www 8603: if ($#origfileimportpartids<0) {
8604: undef(%importedpartids);
8605: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
8606: my $origfile=&getfile($origfilelocation);
8607: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8608: }
8609:
1.1069 www 8610: # Load and inspect imported file
8611: my $impfile=&getfile($location);
8612: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8613: if ($#impfilepartids>=0) {
8614: # This problem had parts
1.1070 www 8615: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 8616: } else {
8617: # Importing by turning a single problem into a problem part
8618: # It gets the import-tags ID as part-ID
8619: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 8620: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 8621: }
1.1068 www 8622: } else {
8623: # Normal import
8624: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8625: if (defined($token->[2]->{'id'})) {
8626: $unikey.='_'.$token->[2]->{'id'};
8627: }
1.1067 www 8628: }
8629:
1.339 albertel 8630: if ($depthcount<20) {
1.736 albertel 8631: my $metadata =
8632: &metadata($uri,'keys', $location,$unikey,
8633: $depthcount+1);
8634: foreach my $meta (split(',',$metadata)) {
8635: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8636: $metathesekeys{$meta}=1;
1.339 albertel 8637: }
1.1068 www 8638:
8639: }
1.1067 www 8640: } else {
8641: #
8642: # Not importing, some other kind of non-package, non-library start tag
8643: #
8644: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
8645: if (defined($token->[2]->{'id'})) {
8646: $unikey.='_'.$token->[2]->{'id'};
8647: }
1.339 albertel 8648: if (defined($token->[2]->{'name'})) {
8649: $unikey.='_'.$token->[2]->{'name'};
8650: }
8651: $metathesekeys{$unikey}=1;
1.736 albertel 8652: foreach my $param (@{$token->[3]}) {
8653: $metaentry{':'.$unikey.'.'.$param} =
8654: $token->[2]->{$param};
1.339 albertel 8655: }
8656: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8657: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8658: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8659: # only ws inside the tag, and not in default, so use default
8660: # as value
1.599 albertel 8661: $metaentry{':'.$unikey}=$default;
1.908 albertel 8662: } elsif ( $internaltext =~ /\S/ ) {
8663: # something interesting inside the tag
8664: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8665: } else {
1.908 albertel 8666: # no interesting values, don't set a default
1.339 albertel 8667: }
1.172 www 8668: # end of not-a-package not-a-library import
1.339 albertel 8669: }
1.172 www 8670: # end of not-a-package start tag
1.339 albertel 8671: }
1.172 www 8672: # the next is the end of "start tag"
1.339 albertel 8673: }
8674: }
1.483 albertel 8675: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8676: $extension = lc($extension);
8677: if ($extension eq 'htm') { $extension='html'; }
8678:
1.737 albertel 8679: foreach my $key (keys(%packagetab)) {
1.483 albertel 8680: #no specific packages #how's our extension
8681: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8682: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8683: \%metathesekeys);
8684: }
1.883 albertel 8685:
8686: if (!exists($metaentry{':packages'})
8687: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8688: foreach my $key (keys(%packagetab)) {
1.483 albertel 8689: #no specific packages well let's get default then
8690: if ($key!~/^default&/) { next; }
1.488 albertel 8691: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8692: \%metathesekeys);
8693: }
8694: }
1.338 www 8695: # are there custom rights to evaluate
1.599 albertel 8696: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8697:
1.338 www 8698: #
8699: # Importing a rights file here
1.339 albertel 8700: #
8701: unless ($depthcount) {
1.599 albertel 8702: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8703: my $dir=$filename;
8704: $dir=~s|[^/]*$||;
8705: $location=&filelocation($dir,$location);
1.736 albertel 8706: my $rights_metadata =
8707: &metadata($uri,'keys',$location,'_rights',
8708: $depthcount+1);
8709: foreach my $rights (split(',',$rights_metadata)) {
8710: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8711: $metathesekeys{$rights}=1;
1.339 albertel 8712: }
8713: }
8714: }
1.737 albertel 8715: # uniqifiy package listing
8716: my %seen;
8717: my @uniq_packages =
8718: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8719: $metaentry{':packages'} = join(',',@uniq_packages);
8720:
1.1070 www 8721: if ($importedparts) {
8722: # We had imported parts and need to rebuild partorder
8723: $metaentry{':partorder'}='';
8724: $metathesekeys{'partorder'}=1;
8725: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
8726: if ($origfileimportpartids[$index] eq 'part') {
8727: # original part, part of the problem
8728: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
8729: } else {
8730: # we have imported parts at this position
8731: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
8732: }
8733: }
8734: $metaentry{':partorder'}=~s/^\,//;
8735: }
8736:
1.737 albertel 8737: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8738: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8739: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8740: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8741: # this is the end of "was not already recently cached
1.71 www 8742: }
1.599 albertel 8743: return $metaentry{':'.$what};
1.261 albertel 8744: }
8745:
1.488 albertel 8746: sub metadata_create_package_def {
1.483 albertel 8747: my ($uri,$key,$package,$metathesekeys)=@_;
8748: my ($pack,$name,$subp)=split(/\&/,$key);
8749: if ($subp eq 'default') { next; }
8750:
1.599 albertel 8751: if (defined($metaentry{':packages'})) {
8752: $metaentry{':packages'}.=','.$package;
1.483 albertel 8753: } else {
1.599 albertel 8754: $metaentry{':packages'}=$package;
1.483 albertel 8755: }
8756: my $value=$packagetab{$key};
8757: my $unikey;
8758: $unikey='parameter_0_'.$name;
1.599 albertel 8759: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8760: $$metathesekeys{$unikey}=1;
1.599 albertel 8761: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8762: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8763: }
1.599 albertel 8764: if (defined($metaentry{':'.$unikey.'.default'})) {
8765: $metaentry{':'.$unikey}=
8766: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8767: }
8768: }
8769:
1.261 albertel 8770: sub metadata_generate_part0 {
8771: my ($metadata,$metacache,$uri) = @_;
8772: my %allnames;
1.737 albertel 8773: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8774: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8775: my $part=$$metacache{':'.$metakey.'.part'};
8776: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8777: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8778: $allnames{$name}=$part;
8779: }
8780: }
8781: }
8782: foreach my $name (keys(%allnames)) {
8783: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8784: my $key=":parameter_0_$name";
1.261 albertel 8785: $$metacache{"$key.part"}='0';
8786: $$metacache{"$key.name"}=$name;
1.428 albertel 8787: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8788: $allnames{$name}.'_'.$name.
8789: '.type'};
1.428 albertel 8790: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8791: '.display'};
1.644 www 8792: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8793: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8794: $$metacache{"$key.display"}=$olddis;
8795: }
1.71 www 8796: }
8797:
1.764 albertel 8798: # ------------------------------------------------------ Devalidate title cache
8799:
8800: sub devalidate_title_cache {
8801: my ($url)=@_;
8802: if (!$env{'request.course.id'}) { return; }
8803: my $symb=&symbread($url);
8804: if (!$symb) { return; }
8805: my $key=$env{'request.course.id'}."\0".$symb;
8806: &devalidate_cache_new('title',$key);
8807: }
8808:
1.1014 droeschl 8809: # ------------------------------------------------- Get the title of a course
8810:
8811: sub current_course_title {
8812: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8813: }
1.301 www 8814: # ------------------------------------------------- Get the title of a resource
8815:
8816: sub gettitle {
8817: my $urlsymb=shift;
8818: my $symb=&symbread($urlsymb);
1.534 albertel 8819: if ($symb) {
1.620 albertel 8820: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8821: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8822: if (defined($cached)) {
8823: return $result;
8824: }
1.534 albertel 8825: my ($map,$resid,$url)=&decode_symb($symb);
8826: my $title='';
1.907 albertel 8827: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8828: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8829: } else {
8830: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8831: &GDBM_READER(),0640)) {
8832: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8833: $title=$bighash{'title_'.$mapid.'.'.$resid};
8834: untie(%bighash);
8835: }
1.534 albertel 8836: }
8837: $title=~s/\&colon\;/\:/gs;
8838: if ($title) {
1.599 albertel 8839: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8840: }
8841: $urlsymb=$url;
8842: }
8843: my $title=&metadata($urlsymb,'title');
8844: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8845: return $title;
1.301 www 8846: }
1.613 albertel 8847:
1.614 albertel 8848: sub get_slot {
8849: my ($which,$cnum,$cdom)=@_;
8850: if (!$cnum || !$cdom) {
1.790 albertel 8851: (undef,my $courseid)=&whichuser();
1.620 albertel 8852: $cdom=$env{'course.'.$courseid.'.domain'};
8853: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8854: }
1.703 albertel 8855: my $key=join("\0",'slots',$cdom,$cnum,$which);
8856: my %slotinfo;
8857: if (exists($remembered{$key})) {
8858: $slotinfo{$which} = $remembered{$key};
8859: } else {
8860: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8861: &Apache::lonhomework::showhash(%slotinfo);
8862: my ($tmp)=keys(%slotinfo);
8863: if ($tmp=~/^error:/) { return (); }
8864: $remembered{$key} = $slotinfo{$which};
8865: }
1.616 albertel 8866: if (ref($slotinfo{$which}) eq 'HASH') {
8867: return %{$slotinfo{$which}};
8868: }
8869: return $slotinfo{$which};
1.614 albertel 8870: }
1.31 www 8871: # ------------------------------------------------- Update symbolic store links
8872:
8873: sub symblist {
8874: my ($mapname,%newhash)=@_;
1.438 www 8875: $mapname=&deversion(&declutter($mapname));
1.31 www 8876: my %hash;
1.620 albertel 8877: if (($env{'request.course.fn'}) && (%newhash)) {
8878: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8879: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8880: foreach my $url (keys(%newhash)) {
1.711 albertel 8881: next if ($url eq 'last_known'
8882: && $env{'form.no_update_last_known'});
8883: $hash{declutter($url)}=&encode_symb($mapname,
8884: $newhash{$url}->[1],
8885: $newhash{$url}->[0]);
1.191 harris41 8886: }
1.31 www 8887: if (untie(%hash)) {
8888: return 'ok';
8889: }
8890: }
8891: }
8892: return 'error';
1.212 www 8893: }
8894:
8895: # --------------------------------------------------------------- Verify a symb
8896:
8897: sub symbverify {
1.510 www 8898: my ($symb,$thisurl)=@_;
8899: my $thisfn=$thisurl;
1.439 www 8900: $thisfn=&declutter($thisfn);
1.215 www 8901: # direct jump to resource in page or to a sequence - will construct own symbs
8902: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8903: # check URL part
1.409 www 8904: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8905:
1.431 www 8906: unless ($url eq $thisfn) { return 0; }
1.213 www 8907:
1.216 www 8908: $symb=&symbclean($symb);
1.510 www 8909: $thisurl=&deversion($thisurl);
1.439 www 8910: $thisfn=&deversion($thisfn);
1.213 www 8911:
8912: my %bighash;
8913: my $okay=0;
1.431 www 8914:
1.620 albertel 8915: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8916: &GDBM_READER(),0640)) {
1.1032 raeburn 8917: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8918: $thisurl =~ s/\?.+$//;
8919: }
1.510 www 8920: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8921: unless ($ids) {
1.510 www 8922: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8923: }
8924: if ($ids) {
8925: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8926: foreach my $id (split(/\,/,$ids)) {
8927: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8928: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8929: $symb =~ s/\?.+$//;
8930: }
1.216 www 8931: if (
8932: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8933: eq $symb) {
1.620 albertel 8934: if (($env{'request.role.adv'}) ||
1.1101 ! raeburn 8935: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
! 8936: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 8937: $okay=1;
8938: }
8939: }
1.216 www 8940: }
8941: }
1.213 www 8942: untie(%bighash);
8943: }
8944: return $okay;
1.31 www 8945: }
8946:
1.210 www 8947: # --------------------------------------------------------------- Clean-up symb
8948:
8949: sub symbclean {
8950: my $symb=shift;
1.568 albertel 8951: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8952: # remove version from map
8953: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8954:
1.210 www 8955: # remove version from URL
8956: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8957:
1.507 www 8958: # remove wrapper
8959:
1.510 www 8960: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8961: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8962: return $symb;
1.409 www 8963: }
8964:
8965: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8966:
8967: sub encode_symb {
8968: my ($map,$resid,$url)=@_;
8969: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8970: }
1.409 www 8971:
8972: sub decode_symb {
1.568 albertel 8973: my $symb=shift;
8974: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8975: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8976: return (&fixversion($map),$resid,&fixversion($url));
8977: }
8978:
8979: sub fixversion {
8980: my $fn=shift;
1.609 banghart 8981: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8982: my %bighash;
8983: my $uri=&clutter($fn);
1.620 albertel 8984: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8985: # is this cached?
1.599 albertel 8986: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8987: if (defined($cached)) { return $result; }
8988: # unfortunately not cached, or expired
1.620 albertel 8989: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8990: &GDBM_READER(),0640)) {
8991: if ($bighash{'version_'.$uri}) {
8992: my $version=$bighash{'version_'.$uri};
1.444 www 8993: unless (($version eq 'mostrecent') ||
8994: ($version==&getversion($uri))) {
1.440 www 8995: $uri=~s/\.(\w+)$/\.$version\.$1/;
8996: }
8997: }
8998: untie %bighash;
1.413 www 8999: }
1.599 albertel 9000: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9001: }
9002:
9003: sub deversion {
9004: my $url=shift;
9005: $url=~s/\.\d+\.(\w+)$/\.$1/;
9006: return $url;
1.210 www 9007: }
9008:
1.31 www 9009: # ------------------------------------------------------ Return symb list entry
9010:
9011: sub symbread {
1.249 www 9012: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9013: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9014: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9015: # no filename provided? try from environment
1.44 www 9016: unless ($thisfn) {
1.620 albertel 9017: if ($env{'request.symb'}) {
9018: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9019: }
1.620 albertel 9020: $thisfn=$env{'request.filename'};
1.44 www 9021: }
1.569 albertel 9022: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9023: # is that filename actually a symb? Verify, clean, and return
9024: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9025: if (&symbverify($thisfn,$1)) {
1.620 albertel 9026: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9027: }
1.242 www 9028: }
1.44 www 9029: $thisfn=declutter($thisfn);
1.31 www 9030: my %hash;
1.37 www 9031: my %bighash;
9032: my $syval='';
1.620 albertel 9033: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9034: my $targetfn = $thisfn;
1.609 banghart 9035: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9036: $targetfn = 'adm/wrapper/'.$thisfn;
9037: }
1.687 albertel 9038: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9039: $targetfn=$1;
9040: }
1.620 albertel 9041: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9042: &GDBM_READER(),0640)) {
1.481 raeburn 9043: $syval=$hash{$targetfn};
1.37 www 9044: untie(%hash);
9045: }
9046: # ---------------------------------------------------------- There was an entry
9047: if ($syval) {
1.601 albertel 9048: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9049: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9050: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9051: #return $env{$cache_str}='';
1.601 albertel 9052: #}
9053: #$syval.=$1;
9054: #}
1.37 www 9055: } else {
9056: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9057: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9058: &GDBM_READER(),0640)) {
1.37 www 9059: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9060: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9061: unless ($ids) {
9062: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9063: }
9064: unless ($ids) {
9065: # alias?
9066: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9067: }
1.37 www 9068: if ($ids) {
9069: # ------------------------------------------------------------------- Has ID(s)
9070: my @possibilities=split(/\,/,$ids);
1.39 www 9071: if ($#possibilities==0) {
9072: # ----------------------------------------------- There is only one possibility
1.37 www 9073: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9074: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9075: $resid,$thisfn);
1.249 www 9076: } elsif (!$donotrecurse) {
1.39 www 9077: # ------------------------------------------ There is more than one possibility
9078: my $realpossible=0;
1.800 albertel 9079: foreach my $id (@possibilities) {
9080: my $file=$bighash{'src_'.$id};
1.39 www 9081: if (&allowed('bre',$file)) {
1.800 albertel 9082: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9083: if ($bighash{'map_type_'.$mapid} ne 'page') {
9084: $realpossible++;
1.626 albertel 9085: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9086: $resid,$thisfn);
1.39 www 9087: }
9088: }
1.191 harris41 9089: }
1.39 www 9090: if ($realpossible!=1) { $syval=''; }
1.249 www 9091: } else {
9092: $syval='';
1.37 www 9093: }
9094: }
9095: untie(%bighash)
1.481 raeburn 9096: }
1.31 www 9097: }
1.62 www 9098: if ($syval) {
1.620 albertel 9099: return $env{$cache_str}=$syval;
1.62 www 9100: }
1.31 www 9101: }
1.949 raeburn 9102: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9103: return $env{$cache_str}='';
1.31 www 9104: }
9105:
9106: # ---------------------------------------------------------- Return random seed
9107:
1.32 www 9108: sub numval {
9109: my $txt=shift;
9110: $txt=~tr/A-J/0-9/;
9111: $txt=~tr/a-j/0-9/;
9112: $txt=~tr/K-T/0-9/;
9113: $txt=~tr/k-t/0-9/;
9114: $txt=~tr/U-Z/0-5/;
9115: $txt=~tr/u-z/0-5/;
9116: $txt=~s/\D//g;
1.564 albertel 9117: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9118: return int($txt);
1.368 albertel 9119: }
9120:
1.484 albertel 9121: sub numval2 {
9122: my $txt=shift;
9123: $txt=~tr/A-J/0-9/;
9124: $txt=~tr/a-j/0-9/;
9125: $txt=~tr/K-T/0-9/;
9126: $txt=~tr/k-t/0-9/;
9127: $txt=~tr/U-Z/0-5/;
9128: $txt=~tr/u-z/0-5/;
9129: $txt=~s/\D//g;
9130: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9131: my $total;
9132: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9133: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9134: return int($total);
9135: }
9136:
1.575 albertel 9137: sub numval3 {
9138: use integer;
9139: my $txt=shift;
9140: $txt=~tr/A-J/0-9/;
9141: $txt=~tr/a-j/0-9/;
9142: $txt=~tr/K-T/0-9/;
9143: $txt=~tr/k-t/0-9/;
9144: $txt=~tr/U-Z/0-5/;
9145: $txt=~tr/u-z/0-5/;
9146: $txt=~s/\D//g;
9147: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9148: my $total;
9149: foreach my $val (@txts) { $total+=$val; }
9150: if ($_64bit) { $total=(($total<<32)>>32); }
9151: return $total;
9152: }
9153:
1.675 albertel 9154: sub digest {
9155: my ($data)=@_;
9156: my $digest=&Digest::MD5::md5($data);
9157: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9158: my ($e,$f);
9159: {
9160: use integer;
9161: $e=($a+$b);
9162: $f=($c+$d);
9163: if ($_64bit) {
9164: $e=(($e<<32)>>32);
9165: $f=(($f<<32)>>32);
9166: }
9167: }
9168: if (wantarray) {
9169: return ($e,$f);
9170: } else {
9171: my $g;
9172: {
9173: use integer;
9174: $g=($e+$f);
9175: if ($_64bit) {
9176: $g=(($g<<32)>>32);
9177: }
9178: }
9179: return $g;
9180: }
9181: }
9182:
1.368 albertel 9183: sub latest_rnd_algorithm_id {
1.675 albertel 9184: return '64bit5';
1.366 albertel 9185: }
1.32 www 9186:
1.503 albertel 9187: sub get_rand_alg {
9188: my ($courseid)=@_;
1.790 albertel 9189: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9190: if ($courseid) {
1.620 albertel 9191: return $env{"course.$courseid.rndseed"};
1.503 albertel 9192: }
9193: return &latest_rnd_algorithm_id();
9194: }
9195:
1.562 albertel 9196: sub validCODE {
9197: my ($CODE)=@_;
9198: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9199: return 0;
9200: }
9201:
1.491 albertel 9202: sub getCODE {
1.620 albertel 9203: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9204: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9205: defined($Apache::lonhomework::parsing_a_task) ) &&
9206: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9207: return $Apache::lonhomework::history{'resource.CODE'};
9208: }
9209: return undef;
9210: }
9211:
1.31 www 9212: sub rndseed {
1.155 albertel 9213: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9214: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9215: if (!defined($symb)) {
1.366 albertel 9216: unless ($symb=$wsymb) { return time; }
9217: }
9218: if (!$courseid) { $courseid=$wcourseid; }
9219: if (!$domain) { $domain=$wdomain; }
9220: if (!$username) { $username=$wusername }
1.503 albertel 9221: my $which=&get_rand_alg();
1.803 albertel 9222:
1.491 albertel 9223: if (defined(&getCODE())) {
1.675 albertel 9224: if ($which eq '64bit5') {
9225: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9226: } elsif ($which eq '64bit4') {
1.575 albertel 9227: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9228: } else {
9229: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9230: }
1.675 albertel 9231: } elsif ($which eq '64bit5') {
9232: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9233: } elsif ($which eq '64bit4') {
9234: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9235: } elsif ($which eq '64bit3') {
9236: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9237: } elsif ($which eq '64bit2') {
9238: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9239: } elsif ($which eq '64bit') {
9240: return &rndseed_64bit($symb,$courseid,$domain,$username);
9241: }
9242: return &rndseed_32bit($symb,$courseid,$domain,$username);
9243: }
9244:
9245: sub rndseed_32bit {
9246: my ($symb,$courseid,$domain,$username)=@_;
9247: {
9248: use integer;
9249: my $symbchck=unpack("%32C*",$symb) << 27;
9250: my $symbseed=numval($symb) << 22;
9251: my $namechck=unpack("%32C*",$username) << 17;
9252: my $nameseed=numval($username) << 12;
9253: my $domainseed=unpack("%32C*",$domain) << 7;
9254: my $courseseed=unpack("%32C*",$courseid);
9255: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9256: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9257: #&logthis("rndseed :$num:$symb");
1.564 albertel 9258: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9259: return $num;
9260: }
9261: }
9262:
9263: sub rndseed_64bit {
9264: my ($symb,$courseid,$domain,$username)=@_;
9265: {
9266: use integer;
9267: my $symbchck=unpack("%32S*",$symb) << 21;
9268: my $symbseed=numval($symb) << 10;
9269: my $namechck=unpack("%32S*",$username);
9270:
9271: my $nameseed=numval($username) << 21;
9272: my $domainseed=unpack("%32S*",$domain) << 10;
9273: my $courseseed=unpack("%32S*",$courseid);
9274:
9275: my $num1=$symbchck+$symbseed+$namechck;
9276: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9277: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9278: #&logthis("rndseed :$num:$symb");
1.564 albertel 9279: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9280: return "$num1,$num2";
1.155 albertel 9281: }
1.366 albertel 9282: }
9283:
1.443 albertel 9284: sub rndseed_64bit2 {
9285: my ($symb,$courseid,$domain,$username)=@_;
9286: {
9287: use integer;
9288: # strings need to be an even # of cahracters long, it it is odd the
9289: # last characters gets thrown away
9290: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9291: my $symbseed=numval($symb) << 10;
9292: my $namechck=unpack("%32S*",$username.' ');
9293:
9294: my $nameseed=numval($username) << 21;
1.501 albertel 9295: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9296: my $courseseed=unpack("%32S*",$courseid.' ');
9297:
9298: my $num1=$symbchck+$symbseed+$namechck;
9299: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9300: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9301: #&logthis("rndseed :$num:$symb");
1.803 albertel 9302: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9303: return "$num1,$num2";
9304: }
9305: }
9306:
9307: sub rndseed_64bit3 {
9308: my ($symb,$courseid,$domain,$username)=@_;
9309: {
9310: use integer;
9311: # strings need to be an even # of cahracters long, it it is odd the
9312: # last characters gets thrown away
9313: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9314: my $symbseed=numval2($symb) << 10;
9315: my $namechck=unpack("%32S*",$username.' ');
9316:
9317: my $nameseed=numval2($username) << 21;
1.443 albertel 9318: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9319: my $courseseed=unpack("%32S*",$courseid.' ');
9320:
9321: my $num1=$symbchck+$symbseed+$namechck;
9322: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9323: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9324: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9325: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9326:
1.503 albertel 9327: return "$num1:$num2";
1.443 albertel 9328: }
9329: }
9330:
1.575 albertel 9331: sub rndseed_64bit4 {
9332: my ($symb,$courseid,$domain,$username)=@_;
9333: {
9334: use integer;
9335: # strings need to be an even # of cahracters long, it it is odd the
9336: # last characters gets thrown away
9337: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9338: my $symbseed=numval3($symb) << 10;
9339: my $namechck=unpack("%32S*",$username.' ');
9340:
9341: my $nameseed=numval3($username) << 21;
9342: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9343: my $courseseed=unpack("%32S*",$courseid.' ');
9344:
9345: my $num1=$symbchck+$symbseed+$namechck;
9346: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9347: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9348: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9349: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9350:
9351: return "$num1:$num2";
9352: }
9353: }
9354:
1.675 albertel 9355: sub rndseed_64bit5 {
9356: my ($symb,$courseid,$domain,$username)=@_;
9357: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9358: return "$num1:$num2";
9359: }
9360:
1.366 albertel 9361: sub rndseed_CODE_64bit {
9362: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9363: {
1.366 albertel 9364: use integer;
1.443 albertel 9365: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9366: my $symbseed=numval2($symb);
1.491 albertel 9367: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9368: my $CODEseed=numval(&getCODE());
1.443 albertel 9369: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9370: my $num1=$symbseed+$CODEchck;
9371: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9372: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9373: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9374: if ($_64bit) { $num1=(($num1<<32)>>32); }
9375: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9376: return "$num1:$num2";
1.366 albertel 9377: }
9378: }
9379:
1.575 albertel 9380: sub rndseed_CODE_64bit4 {
9381: my ($symb,$courseid,$domain,$username)=@_;
9382: {
9383: use integer;
9384: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9385: my $symbseed=numval3($symb);
9386: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9387: my $CODEseed=numval3(&getCODE());
9388: my $courseseed=unpack("%32S*",$courseid.' ');
9389: my $num1=$symbseed+$CODEchck;
9390: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9391: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9392: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9393: if ($_64bit) { $num1=(($num1<<32)>>32); }
9394: if ($_64bit) { $num2=(($num2<<32)>>32); }
9395: return "$num1:$num2";
9396: }
9397: }
9398:
1.675 albertel 9399: sub rndseed_CODE_64bit5 {
9400: my ($symb,$courseid,$domain,$username)=@_;
9401: my $code = &getCODE();
9402: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9403: return "$num1:$num2";
9404: }
9405:
1.366 albertel 9406: sub setup_random_from_rndseed {
9407: my ($rndseed)=@_;
1.503 albertel 9408: if ($rndseed =~/([,:])/) {
9409: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9410: &Math::Random::random_set_seed(abs($num1),abs($num2));
9411: } else {
9412: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9413: }
1.36 albertel 9414: }
9415:
1.474 albertel 9416: sub latest_receipt_algorithm_id {
1.835 albertel 9417: return 'receipt3';
1.474 albertel 9418: }
9419:
1.480 www 9420: sub recunique {
9421: my $fucourseid=shift;
9422: my $unique;
1.835 albertel 9423: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9424: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9425: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9426: } else {
9427: $unique=$perlvar{'lonReceipt'};
9428: }
9429: return unpack("%32C*",$unique);
9430: }
9431:
9432: sub recprefix {
9433: my $fucourseid=shift;
9434: my $prefix;
1.835 albertel 9435: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9436: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9437: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9438: } else {
9439: $prefix=$perlvar{'lonHostID'};
9440: }
9441: return unpack("%32C*",$prefix);
9442: }
9443:
1.76 www 9444: sub ireceipt {
1.474 albertel 9445: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9446:
9447: my $return =&recprefix($fucourseid).'-';
9448:
9449: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9450: $env{'request.state'} eq 'construct') {
9451: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9452: return $return;
9453: }
9454:
1.76 www 9455: my $cuname=unpack("%32C*",$funame);
9456: my $cudom=unpack("%32C*",$fudom);
9457: my $cucourseid=unpack("%32C*",$fucourseid);
9458: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9459: my $cunique=&recunique($fucourseid);
1.474 albertel 9460: my $cpart=unpack("%32S*",$part);
1.835 albertel 9461: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9462:
1.790 albertel 9463: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9464:
9465: $return.= ($cunique%$cuname+
9466: $cunique%$cudom+
9467: $cusymb%$cuname+
9468: $cusymb%$cudom+
9469: $cucourseid%$cuname+
9470: $cucourseid%$cudom+
9471: $cpart%$cuname+
9472: $cpart%$cudom);
9473: } else {
9474: $return.= ($cunique%$cuname+
9475: $cunique%$cudom+
9476: $cusymb%$cuname+
9477: $cusymb%$cudom+
9478: $cucourseid%$cuname+
9479: $cucourseid%$cudom);
9480: }
9481: return $return;
1.76 www 9482: }
9483:
9484: sub receipt {
1.474 albertel 9485: my ($part)=@_;
1.790 albertel 9486: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9487: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9488: }
1.260 ng 9489:
1.790 albertel 9490: sub whichuser {
9491: my ($passedsymb)=@_;
9492: my ($symb,$courseid,$domain,$name,$publicuser);
9493: if (defined($env{'form.grade_symb'})) {
9494: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9495: my $allowed=&allowed('vgr',$tmp_courseid);
9496: if (!$allowed &&
9497: exists($env{'request.course.sec'}) &&
9498: $env{'request.course.sec'} !~ /^\s*$/) {
9499: $allowed=&allowed('vgr',$tmp_courseid.
9500: '/'.$env{'request.course.sec'});
9501: }
9502: if ($allowed) {
9503: ($symb)=&get_env_multiple('form.grade_symb');
9504: $courseid=$tmp_courseid;
9505: ($domain)=&get_env_multiple('form.grade_domain');
9506: ($name)=&get_env_multiple('form.grade_username');
9507: return ($symb,$courseid,$domain,$name,$publicuser);
9508: }
9509: }
9510: if (!$passedsymb) {
9511: $symb=&symbread();
9512: } else {
9513: $symb=$passedsymb;
9514: }
9515: $courseid=$env{'request.course.id'};
9516: $domain=$env{'user.domain'};
9517: $name=$env{'user.name'};
9518: if ($name eq 'public' && $domain eq 'public') {
9519: if (!defined($env{'form.username'})) {
9520: $env{'form.username'}.=time.rand(10000000);
9521: }
9522: $name.=$env{'form.username'};
9523: }
9524: return ($symb,$courseid,$domain,$name,$publicuser);
9525:
9526: }
9527:
1.36 albertel 9528: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9529: # returns either the contents of the file or
9530: # -1 if the file doesn't exist
1.481 raeburn 9531: #
9532: # if the target is a file that was uploaded via DOCS,
9533: # a check will be made to see if a current copy exists on the local server,
9534: # if it does this will be served, otherwise a copy will be retrieved from
9535: # the home server for the course and stored in /home/httpd/html/userfiles on
9536: # the local server.
1.472 albertel 9537:
1.36 albertel 9538: sub getfile {
1.538 albertel 9539: my ($file) = @_;
1.609 banghart 9540: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9541: &repcopy($file);
9542: return &readfile($file);
9543: }
9544:
9545: sub repcopy_userfile {
9546: my ($file)=@_;
1.609 banghart 9547: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9548: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9549: my ($cdom,$cnum,$filename) =
1.811 albertel 9550: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9551: my $uri="/uploaded/$cdom/$cnum/$filename";
9552: if (-e "$file") {
1.828 www 9553: # we already have a local copy, check it out
1.538 albertel 9554: my @fileinfo = stat($file);
1.828 www 9555: my $rtncode;
9556: my $info;
1.538 albertel 9557: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9558: if ($lwpresp ne 'ok') {
1.828 www 9559: # there is no such file anymore, even though we had a local copy
1.482 albertel 9560: if ($rtncode eq '404') {
1.538 albertel 9561: unlink($file);
1.482 albertel 9562: }
9563: return -1;
9564: }
9565: if ($info < $fileinfo[9]) {
1.828 www 9566: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9567: return 'ok';
1.828 www 9568: } else {
9569: # the file is outdated, get rid of it
9570: unlink($file);
1.482 albertel 9571: }
1.828 www 9572: }
9573: # one way or the other, at this point, we don't have the file
9574: # construct the correct path for the file
9575: my @parts = ($cdom,$cnum);
9576: if ($filename =~ m|^(.+)/[^/]+$|) {
9577: push @parts, split(/\//,$1);
9578: }
9579: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9580: foreach my $part (@parts) {
9581: $path .= '/'.$part;
9582: if (!-e $path) {
9583: mkdir($path,0770);
1.482 albertel 9584: }
9585: }
1.828 www 9586: # now the path exists for sure
9587: # get a user agent
9588: my $ua=new LWP::UserAgent;
9589: my $transferfile=$file.'.in.transfer';
9590: # FIXME: this should flock
9591: if (-e $transferfile) { return 'ok'; }
9592: my $request;
9593: $uri=~s/^\///;
1.980 raeburn 9594: my $homeserver = &homeserver($cnum,$cdom);
9595: my $protocol = $protocol{$homeserver};
9596: $protocol = 'http' if ($protocol ne 'https');
9597: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9598: my $response=$ua->request($request,$transferfile);
9599: # did it work?
9600: if ($response->is_error()) {
9601: unlink($transferfile);
9602: &logthis("Userfile repcopy failed for $uri");
9603: return -1;
9604: }
9605: # worked, rename the transfer file
9606: rename($transferfile,$file);
1.607 raeburn 9607: return 'ok';
1.481 raeburn 9608: }
9609:
1.517 albertel 9610: sub tokenwrapper {
9611: my $uri=shift;
1.980 raeburn 9612: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9613: $uri=~s|^/||;
1.620 albertel 9614: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9615: my $token=$1;
1.552 albertel 9616: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9617: if ($udom && $uname && $file) {
9618: $file=~s|(\?\.*)*$||;
1.949 raeburn 9619: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9620: my $homeserver = &homeserver($uname,$udom);
9621: my $protocol = $protocol{$homeserver};
9622: $protocol = 'http' if ($protocol ne 'https');
9623: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9624: (($uri=~/\?/)?'&':'?').'token='.$token.
9625: '&tokenissued='.$perlvar{'lonHostID'};
9626: } else {
9627: return '/adm/notfound.html';
9628: }
9629: }
9630:
1.828 www 9631: # call with reqtype HEAD: get last modification time
9632: # call with reqtype GET: get the file contents
9633: # Do not call this with reqtype GET for large files! It loads everything into memory
9634: #
1.481 raeburn 9635: sub getuploaded {
9636: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9637: $uri=~s/^\///;
1.980 raeburn 9638: my $homeserver = &homeserver($cnum,$cdom);
9639: my $protocol = $protocol{$homeserver};
9640: $protocol = 'http' if ($protocol ne 'https');
9641: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9642: my $ua=new LWP::UserAgent;
9643: my $request=new HTTP::Request($reqtype,$uri);
9644: my $response=$ua->request($request);
9645: $$rtncode = $response->code;
1.482 albertel 9646: if (! $response->is_success()) {
9647: return 'failed';
9648: }
9649: if ($reqtype eq 'HEAD') {
1.486 www 9650: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9651: } elsif ($reqtype eq 'GET') {
9652: $$info = $response->content;
1.472 albertel 9653: }
1.482 albertel 9654: return 'ok';
1.36 albertel 9655: }
9656:
1.481 raeburn 9657: sub readfile {
9658: my $file = shift;
9659: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9660: my $fh;
9661: open($fh,"<$file");
9662: my $a='';
1.800 albertel 9663: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9664: return $a;
9665: }
9666:
1.36 albertel 9667: sub filelocation {
1.590 banghart 9668: my ($dir,$file) = @_;
9669: my $location;
9670: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9671:
9672: if ($file =~ m-^/adm/-) {
9673: $file=~s-^/adm/wrapper/-/-;
9674: $file=~s-^/adm/coursedocs/showdoc/-/-;
9675: }
1.882 albertel 9676:
1.590 banghart 9677: if ($file=~m:^/~:) { # is a contruction space reference
9678: $location = $file;
9679: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9680: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9681: # is a correct contruction space reference
9682: $location = $file;
1.956 raeburn 9683: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9684: $location = $file;
1.609 banghart 9685: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9686: my ($udom,$uname,$filename)=
1.811 albertel 9687: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9688: my $home=&homeserver($uname,$udom);
9689: my $is_me=0;
9690: my @ids=¤t_machine_ids();
9691: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9692: if ($is_me) {
1.955 raeburn 9693: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9694: } else {
9695: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9696: $udom.'/'.$uname.'/'.$filename;
9697: }
1.882 albertel 9698: } elsif ($file =~ m-^/adm/-) {
9699: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9700: } else {
9701: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9702: $file=~s:^/res/:/:;
9703: if ( !( $file =~ m:^/:) ) {
9704: $location = $dir. '/'.$file;
9705: } else {
9706: $location = '/home/httpd/html/res'.$file;
9707: }
1.59 albertel 9708: }
1.590 banghart 9709: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9710: while ($location=~m{/\.\./}) {
9711: if ($location =~ m{/[^/]+/\.\./}) {
9712: $location=~ s{/[^/]+/\.\./}{/}g;
9713: } else {
9714: $location=~ s{/\.\./}{/}g;
9715: }
9716: } #remove dir/..
1.590 banghart 9717: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9718: return $location;
1.46 www 9719: }
1.36 albertel 9720:
1.46 www 9721: sub hreflocation {
9722: my ($dir,$file)=@_;
1.980 raeburn 9723: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9724: $file=filelocation($dir,$file);
1.700 albertel 9725: } elsif ($file=~m-^/adm/-) {
9726: $file=~s-^/adm/wrapper/-/-;
9727: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9728: }
9729: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9730: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9731: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9732: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9733: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9734: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9735: -/uploaded/$1/$2/-x;
1.46 www 9736: }
1.913 albertel 9737: if ($file=~ m{^/userfiles/}) {
9738: $file =~ s{^/userfiles/}{/uploaded/};
9739: }
1.462 albertel 9740: return $file;
1.465 albertel 9741: }
9742:
9743: sub current_machine_domains {
1.853 albertel 9744: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9745: }
9746:
9747: sub machine_domains {
9748: my ($hostname) = @_;
1.465 albertel 9749: my @domains;
1.838 albertel 9750: my %hostname = &all_hostnames();
1.465 albertel 9751: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9752: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9753: if ($hostname eq $name) {
1.844 albertel 9754: push(@domains,&host_domain($id));
1.465 albertel 9755: }
9756: }
9757: return @domains;
9758: }
9759:
9760: sub current_machine_ids {
1.853 albertel 9761: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9762: }
9763:
9764: sub machine_ids {
9765: my ($hostname) = @_;
9766: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9767: my @ids;
1.888 albertel 9768: my %name_to_host = &all_names();
1.889 albertel 9769: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9770: return @{ $name_to_host{$hostname} };
9771: }
9772: return;
1.31 www 9773: }
9774:
1.824 raeburn 9775: sub additional_machine_domains {
9776: my @domains;
9777: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9778: while( my $line = <$fh>) {
9779: $line =~ s/\s//g;
9780: push(@domains,$line);
9781: }
9782: return @domains;
9783: }
9784:
9785: sub default_login_domain {
9786: my $domain = $perlvar{'lonDefDomain'};
9787: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9788: foreach my $posdom (¤t_machine_domains(),
9789: &additional_machine_domains()) {
9790: if (lc($posdom) eq lc($testdomain)) {
9791: $domain=$posdom;
9792: last;
9793: }
9794: }
9795: return $domain;
9796: }
9797:
1.31 www 9798: # ------------------------------------------------------------- Declutters URLs
9799:
9800: sub declutter {
9801: my $thisfn=shift;
1.569 albertel 9802: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9803: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9804: $thisfn=~s/^\///;
1.697 albertel 9805: $thisfn=~s|^adm/wrapper/||;
9806: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9807: $thisfn=~s/^res\///;
1.1032 raeburn 9808: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9809: $thisfn=~s/\?.+$//;
9810: }
1.268 www 9811: return $thisfn;
9812: }
9813:
9814: # ------------------------------------------------------------- Clutter up URLs
9815:
9816: sub clutter {
9817: my $thisfn='/'.&declutter(shift);
1.887 albertel 9818: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9819: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9820: $thisfn='/res'.$thisfn;
9821: }
1.1031 raeburn 9822: if ($thisfn !~m|^/adm|) {
9823: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9824: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9825: } else {
9826: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9827: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9828: if ($embstyle eq 'ssi'
9829: || ($embstyle eq 'hdn')
9830: || ($embstyle eq 'rat')
9831: || ($embstyle eq 'prv')
9832: || ($embstyle eq 'ign')) {
9833: #do nothing with these
9834: } elsif (($embstyle eq 'img')
1.695 albertel 9835: || ($embstyle eq 'emb')
9836: || ($embstyle eq 'wrp')) {
9837: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9838: } elsif ($embstyle eq 'unk'
9839: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9840: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9841: } else {
1.718 www 9842: # &logthis("Got a blank emb style");
1.695 albertel 9843: }
1.694 albertel 9844: }
9845: }
1.31 www 9846: return $thisfn;
1.12 www 9847: }
9848:
1.787 albertel 9849: sub clutter_with_no_wrapper {
9850: my $uri = &clutter(shift);
9851: if ($uri =~ m-^/adm/-) {
9852: $uri =~ s-^/adm/wrapper/-/-;
9853: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9854: }
9855: return $uri;
9856: }
9857:
1.557 albertel 9858: sub freeze_escape {
9859: my ($value)=@_;
9860: if (ref($value)) {
9861: $value=&nfreeze($value);
9862: return '__FROZEN__'.&escape($value);
9863: }
9864: return &escape($value);
9865: }
9866:
1.11 www 9867:
1.557 albertel 9868: sub thaw_unescape {
9869: my ($value)=@_;
9870: if ($value =~ /^__FROZEN__/) {
9871: substr($value,0,10,undef);
9872: $value=&unescape($value);
9873: return &thaw($value);
9874: }
9875: return &unescape($value);
9876: }
9877:
1.436 albertel 9878: sub correct_line_ends {
9879: my ($result)=@_;
9880: $$result =~s/\r\n/\n/mg;
9881: $$result =~s/\r/\n/mg;
1.415 albertel 9882: }
1.1 albertel 9883: # ================================================================ Main Program
9884:
1.184 www 9885: sub goodbye {
1.204 albertel 9886: &logthis("Starting Shut down");
1.443 albertel 9887: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9888: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9889: #converted
1.599 albertel 9890: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9891: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9892: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9893: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9894: #1.1 only
1.870 albertel 9895: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9896: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9897: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9898: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9899: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9900: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9901: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9902: &flushcourselogs();
9903: &logthis("Shutting down");
9904: }
9905:
1.852 albertel 9906: sub get_dns {
1.869 albertel 9907: my ($url,$func,$ignore_cache) = @_;
9908: if (!$ignore_cache) {
9909: my ($content,$cached)=
9910: &Apache::lonnet::is_cached_new('dns',$url);
9911: if ($cached) {
9912: &$func($content);
9913: return;
9914: }
9915: }
9916:
9917: my %alldns;
1.852 albertel 9918: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9919: foreach my $dns (<$config>) {
9920: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9921: my $line = $1;
9922: my ($host,$protocol) = split(/:/,$line);
9923: if ($protocol ne 'https') {
9924: $protocol = 'http';
9925: }
9926: $alldns{$host} = $protocol;
1.869 albertel 9927: }
9928: while (%alldns) {
9929: my ($dns) = keys(%alldns);
1.852 albertel 9930: my $ua=new LWP::UserAgent;
1.979 raeburn 9931: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9932: my $response=$ua->request($request);
1.979 raeburn 9933: delete($alldns{$dns});
1.852 albertel 9934: next if ($response->is_error());
9935: my @content = split("\n",$response->content);
1.869 albertel 9936: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9937: &$func(\@content);
1.869 albertel 9938: return;
1.852 albertel 9939: }
9940: close($config);
1.871 albertel 9941: my $which = (split('/',$url))[3];
9942: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9943: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9944: my @content = <$config>;
9945: &$func(\@content);
9946: return;
1.852 albertel 9947: }
1.327 albertel 9948: # ------------------------------------------------------------ Read domain file
9949: {
1.852 albertel 9950: my $loaded;
1.846 albertel 9951: my %domain;
9952:
1.852 albertel 9953: sub parse_domain_tab {
9954: my ($lines) = @_;
9955: foreach my $line (@$lines) {
9956: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9957:
1.846 albertel 9958: chomp($line);
1.852 albertel 9959: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9960: my %this_domain;
9961: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9962: 'lang_def', 'city', 'longi', 'lati',
9963: 'primary') {
9964: $this_domain{$field} = shift(@elements);
9965: }
9966: $domain{$name} = \%this_domain;
1.852 albertel 9967: }
9968: }
1.864 albertel 9969:
9970: sub reset_domain_info {
9971: undef($loaded);
9972: undef(%domain);
9973: }
9974:
1.852 albertel 9975: sub load_domain_tab {
1.869 albertel 9976: my ($ignore_cache) = @_;
9977: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9978: my $fh;
9979: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9980: my @lines = <$fh>;
9981: &parse_domain_tab(\@lines);
1.448 albertel 9982: }
1.852 albertel 9983: close($fh);
9984: $loaded = 1;
1.327 albertel 9985: }
1.846 albertel 9986:
9987: sub domain {
1.852 albertel 9988: &load_domain_tab() if (!$loaded);
9989:
1.846 albertel 9990: my ($name,$what) = @_;
9991: return if ( !exists($domain{$name}) );
9992:
9993: if (!$what) {
9994: return $domain{$name}{'description'};
9995: }
9996: return $domain{$name}{$what};
9997: }
1.974 raeburn 9998:
9999: sub domain_info {
10000: &load_domain_tab() if (!$loaded);
10001: return %domain;
10002: }
10003:
1.327 albertel 10004: }
10005:
10006:
1.1 albertel 10007: # ------------------------------------------------------------- Read hosts file
10008: {
1.838 albertel 10009: my %hostname;
1.844 albertel 10010: my %hostdom;
1.845 albertel 10011: my %libserv;
1.852 albertel 10012: my $loaded;
1.888 albertel 10013: my %name_to_host;
1.1074 raeburn 10014: my %internetdom;
1.852 albertel 10015:
10016: sub parse_hosts_tab {
10017: my ($file) = @_;
10018: foreach my $configline (@$file) {
10019: next if ($configline =~ /^(\#|\s*$ )/x);
10020: next if ($configline =~ /^\^/);
10021: chomp($configline);
1.1074 raeburn 10022: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10023: $name=~s/\s//g;
10024: if ($id && $domain && $role && $name) {
10025: $hostname{$id}=$name;
1.888 albertel 10026: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10027: $hostdom{$id}=$domain;
10028: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10029: if (defined($protocol)) {
10030: if ($protocol eq 'https') {
10031: $protocol{$id} = $protocol;
10032: } else {
10033: $protocol{$id} = 'http';
10034: }
1.968 raeburn 10035: } else {
1.969 raeburn 10036: $protocol{$id} = 'http';
1.968 raeburn 10037: }
1.1074 raeburn 10038: if (defined($intdom)) {
10039: $internetdom{$id} = $intdom;
10040: }
1.852 albertel 10041: }
10042: }
10043: }
1.864 albertel 10044:
10045: sub reset_hosts_info {
1.897 albertel 10046: &purge_remembered();
1.864 albertel 10047: &reset_domain_info();
10048: &reset_hosts_ip_info();
1.892 albertel 10049: undef(%name_to_host);
1.864 albertel 10050: undef(%hostname);
10051: undef(%hostdom);
10052: undef(%libserv);
10053: undef($loaded);
10054: }
1.1 albertel 10055:
1.852 albertel 10056: sub load_hosts_tab {
1.869 albertel 10057: my ($ignore_cache) = @_;
10058: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10059: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10060: my @config = <$config>;
10061: &parse_hosts_tab(\@config);
10062: close($config);
10063: $loaded=1;
1.1 albertel 10064: }
1.852 albertel 10065:
1.838 albertel 10066: sub hostname {
1.852 albertel 10067: &load_hosts_tab() if (!$loaded);
10068:
1.838 albertel 10069: my ($lonid) = @_;
10070: return $hostname{$lonid};
10071: }
1.845 albertel 10072:
1.838 albertel 10073: sub all_hostnames {
1.852 albertel 10074: &load_hosts_tab() if (!$loaded);
10075:
1.838 albertel 10076: return %hostname;
10077: }
1.845 albertel 10078:
1.888 albertel 10079: sub all_names {
10080: &load_hosts_tab() if (!$loaded);
10081:
10082: return %name_to_host;
10083: }
10084:
1.974 raeburn 10085: sub all_host_domain {
10086: &load_hosts_tab() if (!$loaded);
10087: return %hostdom;
10088: }
10089:
1.845 albertel 10090: sub is_library {
1.852 albertel 10091: &load_hosts_tab() if (!$loaded);
10092:
1.845 albertel 10093: return exists($libserv{$_[0]});
10094: }
10095:
10096: sub all_library {
1.852 albertel 10097: &load_hosts_tab() if (!$loaded);
10098:
1.845 albertel 10099: return %libserv;
10100: }
10101:
1.1062 droeschl 10102: sub unique_library {
10103: #2x reverse removes all hostnames that appear more than once
10104: my %unique = reverse &all_library();
10105: return reverse %unique;
10106: }
10107:
1.841 albertel 10108: sub get_servers {
1.852 albertel 10109: &load_hosts_tab() if (!$loaded);
10110:
1.841 albertel 10111: my ($domain,$type) = @_;
10112: my %possible_hosts = ($type eq 'library') ? %libserv
10113: : %hostname;
10114: my %result;
1.842 albertel 10115: if (ref($domain) eq 'ARRAY') {
10116: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10117: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10118: $result{$host} = $hostname;
10119: }
10120: }
10121: } else {
10122: while ( my ($host,$hostname) = each(%possible_hosts)) {
10123: if ($hostdom{$host} eq $domain) {
10124: $result{$host} = $hostname;
10125: }
1.841 albertel 10126: }
10127: }
10128: return %result;
10129: }
1.845 albertel 10130:
1.1062 droeschl 10131: sub get_unique_servers {
10132: my %unique = reverse &get_servers(@_);
10133: return reverse %unique;
10134: }
10135:
1.844 albertel 10136: sub host_domain {
1.852 albertel 10137: &load_hosts_tab() if (!$loaded);
10138:
1.844 albertel 10139: my ($lonid) = @_;
10140: return $hostdom{$lonid};
10141: }
10142:
1.841 albertel 10143: sub all_domains {
1.852 albertel 10144: &load_hosts_tab() if (!$loaded);
10145:
1.841 albertel 10146: my %seen;
10147: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10148: return @uniq;
10149: }
1.1074 raeburn 10150:
10151: sub internet_dom {
10152: &load_hosts_tab() if (!$loaded);
10153:
10154: my ($lonid) = @_;
10155: return $internetdom{$lonid};
10156: }
1.1 albertel 10157: }
10158:
1.847 albertel 10159: {
10160: my %iphost;
1.856 albertel 10161: my %name_to_ip;
10162: my %lonid_to_ip;
1.869 albertel 10163:
1.847 albertel 10164: sub get_hosts_from_ip {
10165: my ($ip) = @_;
10166: my %iphosts = &get_iphost();
10167: if (ref($iphosts{$ip})) {
10168: return @{$iphosts{$ip}};
10169: }
10170: return;
1.839 albertel 10171: }
1.864 albertel 10172:
10173: sub reset_hosts_ip_info {
10174: undef(%iphost);
10175: undef(%name_to_ip);
10176: undef(%lonid_to_ip);
10177: }
1.856 albertel 10178:
10179: sub get_host_ip {
10180: my ($lonid) = @_;
10181: if (exists($lonid_to_ip{$lonid})) {
10182: return $lonid_to_ip{$lonid};
10183: }
10184: my $name=&hostname($lonid);
10185: my $ip = gethostbyname($name);
10186: return if (!$ip || length($ip) ne 4);
10187: $ip=inet_ntoa($ip);
10188: $name_to_ip{$name} = $ip;
10189: $lonid_to_ip{$lonid} = $ip;
10190: return $ip;
10191: }
1.847 albertel 10192:
10193: sub get_iphost {
1.869 albertel 10194: my ($ignore_cache) = @_;
1.894 albertel 10195:
1.869 albertel 10196: if (!$ignore_cache) {
10197: if (%iphost) {
10198: return %iphost;
10199: }
10200: my ($ip_info,$cached)=
10201: &Apache::lonnet::is_cached_new('iphost','iphost');
10202: if ($cached) {
10203: %iphost = %{$ip_info->[0]};
10204: %name_to_ip = %{$ip_info->[1]};
10205: %lonid_to_ip = %{$ip_info->[2]};
10206: return %iphost;
10207: }
10208: }
1.894 albertel 10209:
10210: # get yesterday's info for fallback
10211: my %old_name_to_ip;
10212: my ($ip_info,$cached)=
10213: &Apache::lonnet::is_cached_new('iphost','iphost');
10214: if ($cached) {
10215: %old_name_to_ip = %{$ip_info->[1]};
10216: }
10217:
1.888 albertel 10218: my %name_to_host = &all_names();
10219: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10220: my $ip;
10221: if (!exists($name_to_ip{$name})) {
10222: $ip = gethostbyname($name);
10223: if (!$ip || length($ip) ne 4) {
1.894 albertel 10224: if (defined($old_name_to_ip{$name})) {
10225: $ip = $old_name_to_ip{$name};
10226: &logthis("Can't find $name defaulting to old $ip");
10227: } else {
10228: &logthis("Name $name no IP found");
10229: next;
10230: }
10231: } else {
10232: $ip=inet_ntoa($ip);
1.847 albertel 10233: }
10234: $name_to_ip{$name} = $ip;
10235: } else {
10236: $ip = $name_to_ip{$name};
1.653 albertel 10237: }
1.888 albertel 10238: foreach my $id (@{ $name_to_host{$name} }) {
10239: $lonid_to_ip{$id} = $ip;
10240: }
10241: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10242: }
1.869 albertel 10243: &Apache::lonnet::do_cache_new('iphost','iphost',
10244: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10245: 48*60*60);
1.869 albertel 10246:
1.847 albertel 10247: return %iphost;
1.598 albertel 10248: }
10249:
1.992 raeburn 10250: #
10251: # Given a DNS returns the loncapa host name for that DNS
10252: #
10253: sub host_from_dns {
10254: my ($dns) = @_;
10255: my @hosts;
10256: my $ip;
10257:
1.993 raeburn 10258: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10259: $ip = $name_to_ip{$dns};
10260: }
10261: if (!$ip) {
10262: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10263: if (length($ip) == 4) {
10264: $ip = &IO::Socket::inet_ntoa($ip);
10265: }
10266: }
10267: if ($ip) {
10268: @hosts = get_hosts_from_ip($ip);
10269: return $hosts[0];
10270: }
10271: return undef;
1.986 foxr 10272: }
1.992 raeburn 10273:
1.1074 raeburn 10274: sub get_internet_names {
10275: my ($lonid) = @_;
10276: return if ($lonid eq '');
10277: my ($idnref,$cached)=
10278: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10279: if ($cached) {
10280: return $idnref;
10281: }
10282: my $ip = &get_host_ip($lonid);
10283: my @hosts = &get_hosts_from_ip($ip);
10284: my %iphost = &get_iphost();
10285: my (@idns,%seen);
10286: foreach my $id (@hosts) {
10287: my $dom = &host_domain($id);
10288: my $prim_id = &domain($dom,'primary');
10289: my $prim_ip = &get_host_ip($prim_id);
10290: next if ($seen{$prim_ip});
10291: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10292: foreach my $id (@{$iphost{$prim_ip}}) {
10293: my $intdom = &internet_dom($id);
10294: unless (grep(/^\Q$intdom\E$/,@idns)) {
10295: push(@idns,$intdom);
10296: }
10297: }
10298: }
10299: $seen{$prim_ip} = 1;
10300: }
10301: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10302: }
10303:
1.986 foxr 10304: }
10305:
1.1079 raeburn 10306: sub all_loncaparevs {
10307: 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);
10308: }
10309:
1.862 albertel 10310: BEGIN {
10311:
10312: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10313: unless ($readit) {
10314: {
10315: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10316: %perlvar = (%perlvar,%{$configvars});
10317: }
10318:
10319:
1.1 albertel 10320: # ------------------------------------------------------ Read spare server file
10321: {
1.448 albertel 10322: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10323:
10324: while (my $configline=<$config>) {
10325: chomp($configline);
1.284 matthew 10326: if ($configline) {
1.784 albertel 10327: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10328: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10329: push(@{ $spareid{$type} }, $host);
1.1 albertel 10330: }
10331: }
1.448 albertel 10332: close($config);
1.1 albertel 10333: }
1.11 www 10334: # ------------------------------------------------------------ Read permissions
10335: {
1.448 albertel 10336: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10337:
10338: while (my $configline=<$config>) {
1.448 albertel 10339: chomp($configline);
10340: if ($configline) {
10341: my ($role,$perm)=split(/ /,$configline);
10342: if ($perm ne '') { $pr{$role}=$perm; }
10343: }
1.11 www 10344: }
1.448 albertel 10345: close($config);
1.11 www 10346: }
10347:
10348: # -------------------------------------------- Read plain texts for permissions
10349: {
1.448 albertel 10350: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10351:
10352: while (my $configline=<$config>) {
1.448 albertel 10353: chomp($configline);
10354: if ($configline) {
1.742 raeburn 10355: my ($short,@plain)=split(/:/,$configline);
10356: %{$prp{$short}} = ();
10357: if (@plain > 0) {
10358: $prp{$short}{'std'} = $plain[0];
10359: for (my $i=1; $i<@plain; $i++) {
10360: $prp{$short}{'alt'.$i} = $plain[$i];
10361: }
10362: }
1.448 albertel 10363: }
1.135 www 10364: }
1.448 albertel 10365: close($config);
1.135 www 10366: }
10367:
10368: # ---------------------------------------------------------- Read package table
10369: {
1.448 albertel 10370: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10371:
10372: while (my $configline=<$config>) {
1.483 albertel 10373: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10374: chomp($configline);
10375: my ($short,$plain)=split(/:/,$configline);
10376: my ($pack,$name)=split(/\&/,$short);
10377: if ($plain ne '') {
10378: $packagetab{$pack.'&'.$name.'&name'}=$name;
10379: $packagetab{$short}=$plain;
10380: }
1.11 www 10381: }
1.448 albertel 10382: close($config);
1.329 matthew 10383: }
10384:
1.1073 raeburn 10385: # ---------------------------------------------------------- Read loncaparev table
10386: {
10387: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10388: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10389: while (my $configline=<$config>) {
10390: chomp($configline);
10391: my ($hostid,$loncaparev)=split(/:/,$configline);
10392: $loncaparevs{$hostid}=$loncaparev;
10393: }
10394: close($config);
10395: }
10396: }
10397: }
10398:
1.1074 raeburn 10399: # ---------------------------------------------------------- Read serverhostID table
10400: {
10401: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10402: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10403: while (my $configline=<$config>) {
10404: chomp($configline);
10405: my ($name,$id)=split(/:/,$configline);
10406: $serverhomeIDs{$name}=$id;
10407: }
10408: close($config);
10409: }
10410: }
10411: }
10412:
1.1079 raeburn 10413: {
10414: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10415: if (-e $file) {
10416: my $parser = HTML::LCParser->new($file);
10417: while (my $token = $parser->get_token()) {
10418: if ($token->[0] eq 'S') {
10419: my $item = $token->[1];
10420: my $name = $token->[2]{'name'};
10421: my $value = $token->[2]{'value'};
10422: if ($item ne '' && $name ne '' && $value ne '') {
10423: my $release = $parser->get_text();
10424: $release =~ s/(^\s*|\s*$ )//gx;
10425: $needsrelease{$item.':'.$name.':'.$value} = $release;
10426: }
10427: }
10428: }
10429: }
1.1073 raeburn 10430: }
10431:
1.329 matthew 10432: # ------------- set up temporary directory
10433: {
10434: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10435:
1.11 www 10436: }
10437:
1.794 albertel 10438: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10439: 'compress_threshold'=> 20_000,
10440: });
1.185 www 10441:
1.281 www 10442: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10443: $dumpcount=0;
1.958 www 10444: $locknum=0;
1.22 www 10445:
1.163 harris41 10446: &logtouch();
1.672 albertel 10447: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10448: $readit=1;
1.564 albertel 10449: {
10450: use integer;
10451: my $test=(2**32)+1;
1.568 albertel 10452: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10453: &logthis(" Detected 64bit platform ($_64bit)");
10454: }
1.195 www 10455: }
1.1 albertel 10456: }
1.179 www 10457:
1.1 albertel 10458: 1;
1.191 harris41 10459: __END__
10460:
1.243 albertel 10461: =pod
10462:
1.191 harris41 10463: =head1 NAME
10464:
1.243 albertel 10465: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10466:
10467: =head1 SYNOPSIS
10468:
1.243 albertel 10469: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10470:
10471: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10472:
1.243 albertel 10473: Common parameters:
10474:
10475: =over 4
10476:
10477: =item *
10478:
10479: $uname : an internal username (if $cname expecting a course Id specifically)
10480:
10481: =item *
10482:
10483: $udom : a domain (if $cdom expecting a course's domain specifically)
10484:
10485: =item *
10486:
10487: $symb : a resource instance identifier
10488:
10489: =item *
10490:
10491: $namespace : the name of a .db file that contains the data needed or
10492: being set.
10493:
10494: =back
10495:
1.394 bowersj2 10496: =head1 OVERVIEW
1.191 harris41 10497:
1.394 bowersj2 10498: lonnet provides subroutines which interact with the
10499: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10500: about classes, users, and resources.
1.243 albertel 10501:
10502: For many of these objects you can also use this to store data about
10503: them or modify them in various ways.
1.191 harris41 10504:
1.394 bowersj2 10505: =head2 Symbs
1.191 harris41 10506:
1.394 bowersj2 10507: To identify a specific instance of a resource, LON-CAPA uses symbols
10508: or "symbs"X<symb>. These identifiers are built from the URL of the
10509: map, the resource number of the resource in the map, and the URL of
10510: the resource itself. The latter is somewhat redundant, but might help
10511: if maps change.
10512:
10513: An example is
10514:
10515: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10516:
10517: The respective map entry is
10518:
10519: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10520: title="Problem 2">
10521: </resource>
10522:
10523: Symbs are used by the random number generator, as well as to store and
10524: restore data specific to a certain instance of for example a problem.
10525:
10526: =head2 Storing And Retrieving Data
10527:
10528: X<store()>X<cstore()>X<restore()>Three of the most important functions
10529: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10530: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10531: is is the non-critical message twin of cstore. These functions are for
10532: handlers to store a perl hash to a user's permanent data space in an
10533: easy manner, and to retrieve it again on another call. It is expected
10534: that a handler would use this once at the beginning to retrieve data,
10535: and then again once at the end to send only the new data back.
10536:
10537: The data is stored in the user's data directory on the user's
10538: homeserver under the ID of the course.
10539:
10540: The hash that is returned by restore will have all of the previous
10541: value for all of the elements of the hash.
10542:
10543: Example:
10544:
10545: #creating a hash
10546: my %hash;
10547: $hash{'foo'}='bar';
10548:
10549: #storing it
10550: &Apache::lonnet::cstore(\%hash);
10551:
10552: #changing a value
10553: $hash{'foo'}='notbar';
10554:
10555: #adding a new value
10556: $hash{'bar'}='foo';
10557: &Apache::lonnet::cstore(\%hash);
10558:
10559: #retrieving the hash
10560: my %history=&Apache::lonnet::restore();
10561:
10562: #print the hash
10563: foreach my $key (sort(keys(%history))) {
10564: print("\%history{$key} = $history{$key}");
10565: }
10566:
10567: Will print out:
1.191 harris41 10568:
1.394 bowersj2 10569: %history{1:foo} = bar
10570: %history{1:keys} = foo:timestamp
10571: %history{1:timestamp} = 990455579
10572: %history{2:bar} = foo
10573: %history{2:foo} = notbar
10574: %history{2:keys} = foo:bar:timestamp
10575: %history{2:timestamp} = 990455580
10576: %history{bar} = foo
10577: %history{foo} = notbar
10578: %history{timestamp} = 990455580
10579: %history{version} = 2
10580:
10581: Note that the special hash entries C<keys>, C<version> and
10582: C<timestamp> were added to the hash. C<version> will be equal to the
10583: total number of versions of the data that have been stored. The
10584: C<timestamp> attribute will be the UNIX time the hash was
10585: stored. C<keys> is available in every historical section to list which
10586: keys were added or changed at a specific historical revision of a
10587: hash.
10588:
10589: B<Warning>: do not store the hash that restore returns directly. This
10590: will cause a mess since it will restore the historical keys as if the
10591: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10592:
1.394 bowersj2 10593: Calling convention:
1.191 harris41 10594:
1.394 bowersj2 10595: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10596: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10597:
1.394 bowersj2 10598: For more detailed information, see lonnet specific documentation.
1.191 harris41 10599:
1.394 bowersj2 10600: =head1 RETURN MESSAGES
1.191 harris41 10601:
1.394 bowersj2 10602: =over 4
1.191 harris41 10603:
1.394 bowersj2 10604: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10605:
1.394 bowersj2 10606: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10607: when the connection is brought back up
1.191 harris41 10608:
1.394 bowersj2 10609: =item * B<con_failed>: unable to contact remote host and unable to save message
10610: for later delivery
1.191 harris41 10611:
1.967 bisitz 10612: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10613:
1.394 bowersj2 10614: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10615: that was requested
1.191 harris41 10616:
1.243 albertel 10617: =back
1.191 harris41 10618:
1.243 albertel 10619: =head1 PUBLIC SUBROUTINES
1.191 harris41 10620:
1.243 albertel 10621: =head2 Session Environment Functions
1.191 harris41 10622:
1.243 albertel 10623: =over 4
1.191 harris41 10624:
1.394 bowersj2 10625: =item *
10626: X<appenv()>
1.949 raeburn 10627: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10628: the user envirnoment file, and will be restored for each access this
1.620 albertel 10629: user makes during this session, also modifies the %env for the current
1.949 raeburn 10630: process. Optional rolesarrayref - if defined contains a reference to an array
10631: of roles which are exempt from the restriction on modifying user.role entries
10632: in the user's environment.db and in %env.
1.191 harris41 10633:
10634: =item *
1.394 bowersj2 10635: X<delenv()>
1.987 raeburn 10636: B<delenv($delthis,$regexp)>: removes all items from the session
10637: environment file that begin with $delthis. If the
10638: optional second arg - $regexp - is true, $delthis is treated as a
10639: regular expression, otherwise \Q$delthis\E is used.
10640: The values are also deleted from the current processes %env.
1.191 harris41 10641:
1.795 albertel 10642: =item * get_env_multiple($name)
10643:
10644: gets $name from the %env hash, it seemlessly handles the cases where multiple
10645: values may be defined and end up as an array ref.
10646:
10647: returns an array of values
10648:
1.243 albertel 10649: =back
10650:
10651: =head2 User Information
1.191 harris41 10652:
1.243 albertel 10653: =over 4
1.191 harris41 10654:
10655: =item *
1.394 bowersj2 10656: X<queryauthenticate()>
10657: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10658: authentication scheme
10659:
10660: =item *
1.394 bowersj2 10661: X<authenticate()>
1.1073 raeburn 10662: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10663: authenticate user from domain's lib servers (first use the current
10664: one). C<$upass> should be the users password.
1.1073 raeburn 10665: $checkdefauth is optional (value is 1 if a check should be made to
10666: authenticate user using default authentication method, and allow
10667: account creation if username does not have account in the domain).
10668: $clientcancheckhost is optional (value is 1 if checking whether the
10669: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10670:
10671: =item *
1.394 bowersj2 10672: X<homeserver()>
10673: B<homeserver($uname,$udom)>: find the server which has
10674: the user's directory and files (there must be only one), this caches
10675: the answer, and also caches if there is a borken connection.
1.191 harris41 10676:
10677: =item *
1.394 bowersj2 10678: X<idget()>
10679: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10680: (IDs are a unique resource in a domain, there must be only 1 ID per
10681: username, and only 1 username per ID in a specific domain) (returns
10682: hash: id=>name,id=>name)
1.191 harris41 10683:
10684: =item *
1.394 bowersj2 10685: X<idrget()>
10686: B<idrget($udom,@unames)>: find the IDs behind a list of
10687: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10688:
10689: =item *
1.394 bowersj2 10690: X<idput()>
10691: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10692:
10693: =item *
1.394 bowersj2 10694: X<rolesinit()>
10695: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10696:
10697: =item *
1.551 albertel 10698: X<getsection()>
10699: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10700: course $cname, return section name/number or '' for "not in course"
10701: and '-1' for "no section"
10702:
10703: =item *
1.394 bowersj2 10704: X<userenvironment()>
10705: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10706: passed in @what from the requested user's environment, returns a hash
10707:
1.858 raeburn 10708: =item *
10709: X<userlog_query()>
1.859 albertel 10710: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10711: activity.log file. %filters defines filters applied when parsing the
10712: log file. These can be start or end timestamps, or the type of action
10713: - log to look for Login or Logout events, check for Checkin or
10714: Checkout, role for role selection. The response is in the form
10715: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10716: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10717:
1.243 albertel 10718: =back
10719:
10720: =head2 User Roles
10721:
10722: =over 4
10723:
10724: =item *
10725:
1.810 raeburn 10726: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10727: F: full access
10728: U,I,K: authentication modes (cxx only)
10729: '': forbidden
10730: 1: user needs to choose course
10731: 2: browse allowed
1.766 albertel 10732: A: passphrase authentication needed
1.243 albertel 10733:
10734: =item *
10735:
10736: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10737: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10738: and course level
10739:
10740: =item *
10741:
1.988 raeburn 10742: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10743: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10744: $type is Course (default) or Community.
1.988 raeburn 10745: If $forcedefault evaluates to true, text returned will be default
10746: text for $type. Otherwise, if this is a course, the text returned
10747: will be a custom name for the role (if defined in the course's
10748: environment). If no custom name is defined the default is returned.
10749:
1.832 raeburn 10750: =item *
10751:
1.935 raeburn 10752: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10753: All arguments are optional. Returns a hash of a roles, either for
10754: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10755: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10756: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10757: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10758: For each key, value is set to colon-separated start and end times for
10759: the role. If no username and domain are specified, will default to
1.934 raeburn 10760: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10761: of role statuses (active, future or previous), roles
10762: (e.g., cc,in, st etc.) and domains of the roles which can be used
10763: to restrict the list of roles reported. If no array ref is
10764: provided for types, will default to return only active roles.
1.834 albertel 10765:
1.243 albertel 10766: =back
10767:
10768: =head2 User Modification
10769:
10770: =over 4
10771:
10772: =item *
10773:
1.957 raeburn 10774: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10775: user for the level given by URL. Optional start and end dates (leave empty
10776: string or zero for "no date")
1.191 harris41 10777:
10778: =item *
10779:
1.243 albertel 10780: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10781: change a users, password, possible return values are: ok,
10782: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10783: refused
1.191 harris41 10784:
10785: =item *
10786:
1.243 albertel 10787: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10788:
10789: =item *
10790:
1.1058 raeburn 10791: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10792: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10793:
10794: will update user information (firstname,middlename,lastname,generation,
10795: permanentemail), and if forceid is true, student/employee ID also.
10796: A user's institutional affiliation(s) can also be updated.
10797: User information fields will not be overwritten with empty entries
10798: unless the field is included in the $candelete array reference.
10799: This array is included when a single user is modified via "Manage Users",
10800: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10801:
10802: =item *
10803:
1.286 matthew 10804: modifystudent
10805:
1.957 raeburn 10806: modify a student's enrollment and identification information.
1.286 matthew 10807: The course id is resolved based on the current users environment.
10808: This means the envoking user must be a course coordinator or otherwise
10809: associated with a course.
10810:
1.297 matthew 10811: This call is essentially a wrapper for lonnet::modifyuser and
10812: lonnet::modify_student_enrollment
1.286 matthew 10813:
10814: Inputs:
10815:
10816: =over 4
10817:
1.957 raeburn 10818: =item B<$udom> Student's loncapa domain
1.286 matthew 10819:
1.957 raeburn 10820: =item B<$uname> Student's loncapa login name
1.286 matthew 10821:
1.964 bisitz 10822: =item B<$uid> Student/Employee ID
1.286 matthew 10823:
1.957 raeburn 10824: =item B<$umode> Student's authentication mode
1.286 matthew 10825:
1.957 raeburn 10826: =item B<$upass> Student's password
1.286 matthew 10827:
1.957 raeburn 10828: =item B<$first> Student's first name
1.286 matthew 10829:
1.957 raeburn 10830: =item B<$middle> Student's middle name
1.286 matthew 10831:
1.957 raeburn 10832: =item B<$last> Student's last name
1.286 matthew 10833:
1.957 raeburn 10834: =item B<$gene> Student's generation
1.286 matthew 10835:
1.957 raeburn 10836: =item B<$usec> Student's section in course
1.286 matthew 10837:
10838: =item B<$end> Unix time of the roles expiration
10839:
10840: =item B<$start> Unix time of the roles start date
10841:
10842: =item B<$forceid> If defined, allow $uid to be changed
10843:
10844: =item B<$desiredhome> server to use as home server for student
10845:
1.957 raeburn 10846: =item B<$email> Student's permanent e-mail address
10847:
10848: =item B<$type> Type of enrollment (auto or manual)
10849:
1.963 raeburn 10850: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10851:
10852: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10853:
1.963 raeburn 10854: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10855:
1.963 raeburn 10856: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10857:
1.963 raeburn 10858: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10859:
1.286 matthew 10860: =back
1.297 matthew 10861:
10862: =item *
10863:
10864: modify_student_enrollment
10865:
10866: Change a students enrollment status in a class. The environment variable
10867: 'role.request.course' must be defined for this function to proceed.
10868:
10869: Inputs:
10870:
10871: =over 4
10872:
10873: =item $udom, students domain
10874:
10875: =item $uname, students name
10876:
10877: =item $uid, students user id
10878:
10879: =item $first, students first name
10880:
10881: =item $middle
10882:
10883: =item $last
10884:
10885: =item $gene
10886:
10887: =item $usec
10888:
10889: =item $end
10890:
10891: =item $start
10892:
1.957 raeburn 10893: =item $type
10894:
10895: =item $locktype
10896:
10897: =item $cid
10898:
10899: =item $selfenroll
10900:
10901: =item $context
10902:
1.297 matthew 10903: =back
10904:
1.191 harris41 10905:
10906: =item *
10907:
1.243 albertel 10908: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10909: custom role; give a custom role to a user for the level given by URL. Specify
10910: name and domain of role author, and role name
1.191 harris41 10911:
10912: =item *
10913:
1.243 albertel 10914: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10915:
10916: =item *
10917:
1.243 albertel 10918: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10919:
10920: =back
10921:
10922: =head2 Course Infomation
10923:
10924: =over 4
1.191 harris41 10925:
10926: =item *
10927:
1.631 albertel 10928: coursedescription($courseid) : returns a hash of information about the
10929: specified course id, including all environment settings for the
10930: course, the description of the course will be in the hash under the
10931: key 'description'
1.191 harris41 10932:
10933: =item *
10934:
1.624 albertel 10935: resdata($name,$domain,$type,@which) : request for current parameter
10936: setting for a specific $type, where $type is either 'course' or 'user',
10937: @what should be a list of parameters to ask about. This routine caches
10938: answers for 5 minutes.
1.243 albertel 10939:
1.877 foxr 10940: =item *
10941:
10942: get_courseresdata($courseid, $domain) : dump the entire course resource
10943: data base, returning a hash that is keyed by the resource name and has
10944: values that are the resource value. I believe that the timestamps and
10945: versions are also returned.
10946:
10947:
1.243 albertel 10948: =back
10949:
10950: =head2 Course Modification
10951:
10952: =over 4
1.191 harris41 10953:
10954: =item *
10955:
1.243 albertel 10956: writecoursepref($courseid,%prefs) : write preferences (environment
10957: database) for a course
1.191 harris41 10958:
10959: =item *
10960:
1.1011 raeburn 10961: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10962:
10963: =item *
10964:
1.1038 raeburn 10965: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10966:
10967: =back
10968:
10969: =head2 Resource Subroutines
10970:
10971: =over 4
1.191 harris41 10972:
10973: =item *
10974:
1.243 albertel 10975: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10976:
10977: =item *
10978:
1.243 albertel 10979: repcopy($filename) : subscribes to the requested file, and attempts to
10980: replicate from the owning library server, Might return
1.607 raeburn 10981: 'unavailable', 'not_found', 'forbidden', 'ok', or
10982: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10983: resource. Expects the local filesystem pathname
10984: (/home/httpd/html/res/....)
10985:
10986: =back
10987:
10988: =head2 Resource Information
10989:
10990: =over 4
1.191 harris41 10991:
10992: =item *
10993:
1.243 albertel 10994: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10995: a vairety of different possible values, $varname should be a request
10996: string, and the other parameters can be used to specify who and what
10997: one is asking about.
10998:
10999: Possible values for $varname are environment.lastname (or other item
11000: from the envirnment hash), user.name (or someother aspect about the
11001: user), resource.0.maxtries (or some other part and parameter of a
11002: resource)
1.204 albertel 11003:
11004: =item *
11005:
1.243 albertel 11006: directcondval($number) : get current value of a condition; reads from a state
11007: string
1.204 albertel 11008:
11009: =item *
11010:
1.243 albertel 11011: condval($condidx) : value of condition index based on state
1.204 albertel 11012:
11013: =item *
11014:
1.243 albertel 11015: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11016: resource's metadata, $what should be either a specific key, or either
11017: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11018: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11019:
11020: this function automatically caches all requests
1.191 harris41 11021:
11022: =item *
11023:
1.243 albertel 11024: metadata_query($query,$custom,$customshow) : make a metadata query against the
11025: network of library servers; returns file handle of where SQL and regex results
11026: will be stored for query
1.191 harris41 11027:
11028: =item *
11029:
1.243 albertel 11030: symbread($filename) : return symbolic list entry (filename argument optional);
11031: returns the data handle
1.191 harris41 11032:
11033: =item *
11034:
1.243 albertel 11035: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11036: a possible symb for the URL in $thisfn, and if is an encryypted
11037: resource that the user accessed using /enc/ returns a 1 on success, 0
11038: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11039: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11040:
1.191 harris41 11041:
11042: =item *
11043:
1.243 albertel 11044: symbclean($symb) : removes versions numbers from a symb, returns the
11045: cleaned symb
1.191 harris41 11046:
11047: =item *
11048:
1.243 albertel 11049: is_on_map($uri) : checks if the $uri is somewhere on the current
11050: course map, user must be in a course for it to work.
1.191 harris41 11051:
11052: =item *
11053:
1.243 albertel 11054: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11055:
11056: =item *
11057:
1.243 albertel 11058: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11059: a random seed, all arguments are optional, if they aren't sent it uses the
11060: environment to derive them. Note: if symb isn't sent and it can't get one
11061: from &symbread it will use the current time as its return value
1.191 harris41 11062:
11063: =item *
11064:
1.243 albertel 11065: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11066: unfakeable, receipt
1.191 harris41 11067:
11068: =item *
11069:
1.620 albertel 11070: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11071:
11072: =item *
11073:
1.243 albertel 11074: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11075:
11076: =item *
11077:
1.243 albertel 11078: 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 11079:
11080: =item *
11081:
1.243 albertel 11082: 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 11083:
11084: =item *
11085:
1.243 albertel 11086: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11087:
11088: =item *
11089:
1.243 albertel 11090: devalidate($symb) : devalidate temporary spreadsheet calculations,
11091: forcing spreadsheet to reevaluate the resource scores next time.
11092:
11093: =back
11094:
11095: =head2 Storing/Retreiving Data
11096:
11097: =over 4
1.191 harris41 11098:
11099: =item *
11100:
1.243 albertel 11101: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11102: for this url; hashref needs to be given and should be a \%hashname; the
11103: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11104: be derived from the env
1.191 harris41 11105:
11106: =item *
11107:
1.243 albertel 11108: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11109: uses critical subroutine
1.191 harris41 11110:
11111: =item *
11112:
1.243 albertel 11113: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11114: all args are optional
1.191 harris41 11115:
11116: =item *
11117:
1.717 albertel 11118: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11119: dumps the complete (or key matching regexp) namespace into a hash
11120: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11121: normally &store()ed into
11122:
11123: $range should be either an integer '100' (give me the first 100
11124: matching records)
11125: or be two integers sperated by a - with no spaces
11126: '30-50' (give me the 30th through the 50th matching
11127: records)
11128:
11129:
11130: =item *
11131:
11132: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11133: replaces a &store() version of data with a replacement set of data
11134: for a particular resource in a namespace passed in the $storehash hash
11135: reference
11136:
11137: =item *
11138:
1.243 albertel 11139: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11140: works very similar to store/cstore, but all data is stored in a
11141: temporary location and can be reset using tmpreset, $storehash should
11142: be a hash reference, returns nothing on success
1.191 harris41 11143:
11144: =item *
11145:
1.243 albertel 11146: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11147: similar to restore, but all data is stored in a temporary location and
11148: can be reset using tmpreset. Returns a hash of values on success,
11149: error string otherwise.
1.191 harris41 11150:
11151: =item *
11152:
1.243 albertel 11153: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11154: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11155:
11156: =item *
11157:
1.243 albertel 11158: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11159: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11160:
11161: =item *
11162:
1.243 albertel 11163: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11164: namesp ($udom and $uname are optional)
1.191 harris41 11165:
11166: =item *
11167:
1.702 albertel 11168: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11169: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11170: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11171:
1.702 albertel 11172: $range should be either an integer '100' (give me the first 100
11173: matching records)
11174: or be two integers sperated by a - with no spaces
11175: '30-50' (give me the 30th through the 50th matching
11176: records)
1.449 matthew 11177: =item *
11178:
11179: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11180: $store can be a scalar, an array reference, or if the amount to be
11181: incremented is > 1, a hash reference.
11182:
11183: ($udom and $uname are optional)
1.191 harris41 11184:
11185: =item *
11186:
1.243 albertel 11187: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11188: ($udom and $uname are optional)
1.191 harris41 11189:
11190: =item *
11191:
1.243 albertel 11192: cput($namespace,$storehash,$udom,$uname) : critical put
11193: ($udom and $uname are optional)
1.191 harris41 11194:
11195: =item *
11196:
1.748 albertel 11197: newput($namespace,$storehash,$udom,$uname) :
11198:
11199: Attempts to store the items in the $storehash, but only if they don't
11200: currently exist, if this succeeds you can be certain that you have
11201: successfully created a new key value pair in the $namespace db.
11202:
11203:
11204: Args:
11205: $namespace: name of database to store values to
11206: $storehash: hashref to store to the db
11207: $udom: (optional) domain of user containing the db
11208: $uname: (optional) name of user caontaining the db
11209:
11210: Returns:
11211: 'ok' -> succeeded in storing all keys of $storehash
11212: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11213: least <key> already existed in the db (other
11214: requested keys may also already exist)
1.967 bisitz 11215: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11216: 'con_lost' -> unable to contact request server
11217: 'refused' -> action was not allowed by remote machine
11218:
11219:
11220: =item *
11221:
1.243 albertel 11222: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11223: reference filled in from namesp (encrypts the return communication)
11224: ($udom and $uname are optional)
1.191 harris41 11225:
11226: =item *
11227:
1.243 albertel 11228: log($udom,$name,$home,$message) : write to permanent log for user; use
11229: critical subroutine
11230:
1.806 raeburn 11231: =item *
11232:
1.860 raeburn 11233: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11234: array reference filled in from namespace found in domain level on either
11235: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11236:
11237: =item *
11238:
1.860 raeburn 11239: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11240: domain level either on specified domain server ($uhome) or primary domain
11241: server ($udom and $uhome are optional)
1.806 raeburn 11242:
1.943 raeburn 11243: =item *
11244:
11245: get_domain_defaults($target_domain) : returns hash with defaults for
11246: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11247: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11248: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11249: Values are retrieved from cache (if current), or from domain's configuration.db
11250: (if available), or lastly from values in lonTabs/dns_domain,tab,
11251: or lonTabs/domain.tab.
11252:
11253: %domdefaults = &get_auth_defaults($target_domain);
11254:
1.243 albertel 11255: =back
11256:
11257: =head2 Network Status Functions
11258:
11259: =over 4
1.191 harris41 11260:
11261: =item *
11262:
11263: dirlist($uri) : return directory list based on URI
11264:
11265: =item *
11266:
1.243 albertel 11267: spareserver() : find server with least workload from spare.tab
11268:
1.986 foxr 11269:
11270: =item *
11271:
11272: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11273: if there is no corresponding loncapa host.
11274:
1.243 albertel 11275: =back
11276:
1.986 foxr 11277:
1.243 albertel 11278: =head2 Apache Request
11279:
11280: =over 4
1.191 harris41 11281:
11282: =item *
11283:
1.243 albertel 11284: ssi($url,%hash) : server side include, does a complete request cycle on url to
11285: localhost, posts hash
11286:
11287: =back
11288:
11289: =head2 Data to String to Data
11290:
11291: =over 4
1.191 harris41 11292:
11293: =item *
11294:
1.243 albertel 11295: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11296: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11297:
11298: =item *
11299:
1.243 albertel 11300: hashref2str($hashref) : convert a hashref into a string complete with
11301: escaping and '=' and '&' separators, supports elements that are
11302: arrayrefs and hashrefs
1.191 harris41 11303:
11304: =item *
11305:
1.243 albertel 11306: arrayref2str($arrayref) : convert an arrayref into a string complete
11307: with escaping and '&' separators, supports elements that are arrayrefs
11308: and hashrefs
1.191 harris41 11309:
11310: =item *
11311:
1.243 albertel 11312: str2hash($string) : convert string to hash using unescaping and
11313: splitting on '=' and '&', supports elements that are arrayrefs and
11314: hashrefs
1.191 harris41 11315:
11316: =item *
11317:
1.243 albertel 11318: str2array($string) : convert string to hash using unescaping and
11319: splitting on '&', supports elements that are arrayrefs and hashrefs
11320:
11321: =back
11322:
11323: =head2 Logging Routines
11324:
11325: =over 4
11326:
11327: These routines allow one to make log messages in the lonnet.log and
11328: lonnet.perm logfiles.
1.191 harris41 11329:
11330: =item *
11331:
1.243 albertel 11332: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11333:
11334: =item *
11335:
1.243 albertel 11336: logthis() : append message to the normal lonnet.log file, it gets
11337: preiodically rolled over and deleted.
1.191 harris41 11338:
11339: =item *
11340:
1.243 albertel 11341: logperm() : append a permanent message to lonnet.perm.log, this log
11342: file never gets deleted by any automated portion of the system, only
11343: messages of critical importance should go in here.
11344:
11345: =back
11346:
11347: =head2 General File Helper Routines
11348:
11349: =over 4
1.191 harris41 11350:
11351: =item *
11352:
1.481 raeburn 11353: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11354: (a) files in /uploaded
11355: (i) If a local copy of the file exists -
11356: compares modification date of local copy with last-modified date for
11357: definitive version stored on home server for course. If local copy is
11358: stale, requests a new version from the home server and stores it.
11359: If the original has been removed from the home server, then local copy
11360: is unlinked.
11361: (ii) If local copy does not exist -
11362: requests the file from the home server and stores it.
11363:
11364: If $caller is 'uploadrep':
11365: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11366: for request for files originally uploaded via DOCS.
11367: - returns 'ok' if fresh local copy now available, -1 otherwise.
11368:
11369: Otherwise:
11370: This indicates a call from the content generation phase of the request.
11371: - returns the entire contents of the file or -1.
11372:
11373: (b) files in /res
11374: - returns the entire contents of a file or -1;
11375: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11376:
1.712 albertel 11377:
11378: =item *
11379:
11380: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11381: reference
11382:
11383: returns either a stat() list of data about the file or an empty list
11384: if the file doesn't exist or couldn't find out about it (connection
11385: problems or user unknown)
11386:
1.191 harris41 11387: =item *
11388:
1.243 albertel 11389: filelocation($dir,$file) : returns file system location of a file
11390: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11391: directory that relative $file lookups are to looked in ($dir of /a/dir
11392: and a file of ../bob will become /a/bob)
1.191 harris41 11393:
11394: =item *
11395:
11396: hreflocation($dir,$file) : returns file system location or a URL; same as
11397: filelocation except for hrefs
11398:
11399: =item *
11400:
11401: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11402:
1.243 albertel 11403: =back
11404:
1.608 albertel 11405: =head2 Usererfile file routines (/uploaded*)
11406:
11407: =over 4
11408:
11409: =item *
11410:
11411: userfileupload(): main rotine for putting a file in a user or course's
11412: filespace, arguments are,
11413:
1.620 albertel 11414: formname - required - this is the name of the element in $env where the
1.608 albertel 11415: filename, and the contents of the file to create/modifed exist
1.620 albertel 11416: the filename is in $env{'form.'.$formname.'.filename'} and the
11417: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 11418: context - if coursedoc, store the file in the course of the active role
11419: of the current user;
11420: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
11421: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 11422: subdir - required - subdirectory to put the file in under ../userfiles/
11423: if undefined, it will be placed in "unknown"
11424:
11425: (This routine calls clean_filename() to remove any dangerous
11426: characters from the filename, and then calls finuserfileupload() to
11427: complete the transaction)
11428:
11429: returns either the url of the uploaded file (/uploaded/....) if successful
11430: and /adm/notfound.html if unsuccessful
11431:
11432: =item *
11433:
11434: clean_filename(): routine for cleaing a filename up for storage in
11435: userfile space, argument is:
11436:
11437: filename - proposed filename
11438:
11439: returns: the new clean filename
11440:
11441: =item *
11442:
1.1090 raeburn 11443: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 11444: userspace, probably shouldn't be called directly
11445:
11446: docuname: username or courseid of destination for the file
11447: docudom: domain of user/course of destination for the file
11448: formname: same as for userfileupload()
1.1090 raeburn 11449: fname: filename (including subdirectories) for the file
11450: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
11451: allfiles: reference to hash used to store objects found by parser
11452: codebase: reference to hash used for codebases of java objects found by parser
11453: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
11454: thumbheight: height (pixels) of thumbnail to be created for uploaded image
11455: resizewidth: width to be used to resize image using resizeImage from ImageMagick
11456: resizeheight: height to be used to resize image using resizeImage from ImageMagick
11457: context: if 'overwrite', will move the uploaded file from its temporary location to
11458: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 11459: mimetype: reference to scalar to accommodate mime type determined
11460: from File::MMagic if $parser = parse.
1.608 albertel 11461:
11462: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 11463: and /adm/notfound.html if unsuccessful (or an error message if context
11464: was 'overwrite').
11465:
1.608 albertel 11466:
11467: =item *
11468:
11469: renameuserfile(): renames an existing userfile to a new name
11470:
11471: Args:
11472: docuname: username or courseid of destination for the file
11473: docudom: domain of user/course of destination for the file
11474: old: current file name (including any subdirs under userfiles)
11475: new: desired file name (including any subdirs under userfiles)
11476:
11477: =item *
11478:
11479: mkdiruserfile(): creates a directory is a userfiles dir
11480:
11481: Args:
11482: docuname: username or courseid of destination for the file
11483: docudom: domain of user/course of destination for the file
11484: dir: dir to create (including any subdirs under userfiles)
11485:
11486: =item *
11487:
11488: removeuserfile(): removes a file that exists in userfiles
11489:
11490: Args:
11491: docuname: username or courseid of destination for the file
11492: docudom: domain of user/course of destination for the file
11493: fname: filname to delete (including any subdirs under userfiles)
11494:
11495: =item *
11496:
11497: removeuploadedurl(): convience function for removeuserfile()
11498:
11499: Args:
11500: url: a full /uploaded/... url to delete
11501:
1.747 albertel 11502: =item *
11503:
11504: get_portfile_permissions():
11505: Args:
11506: domain: domain of user or course contain the portfolio files
11507: user: name of user or num of course contain the portfolio files
11508: Returns:
11509: hashref of a dump of the proper file_permissions.db
11510:
11511:
11512: =item *
11513:
11514: get_access_controls():
11515:
11516: Args:
11517: current_permissions: the hash ref returned from get_portfile_permissions()
11518: group: (optional) the group you want the files associated with
11519: file: (optional) the file you want access info on
11520:
11521: Returns:
1.749 raeburn 11522: a hash (keys are file names) of hashes containing
11523: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11524: values are XML containing access control settings (see below)
1.747 albertel 11525:
11526: Internal notes:
11527:
1.749 raeburn 11528: access controls are stored in file_permissions.db as key=value pairs.
11529: key -> path to file/file_name\0uniqueID:scope_end_start
11530: where scope -> public,guest,course,group,domains or users.
11531: end -> UNIX time for end of access (0 -> no end date)
11532: start -> UNIX time for start of access
11533:
11534: value -> XML description of access control
11535: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11536: <start></start>
11537: <end></end>
11538:
11539: <password></password> for scope type = guest
11540:
11541: <domain></domain> for scope type = course or group
11542: <number></number>
11543: <roles id="">
11544: <role></role>
11545: <access></access>
11546: <section></section>
11547: <group></group>
11548: </roles>
11549:
11550: <dom></dom> for scope type = domains
11551:
11552: <users> for scope type = users
11553: <user>
11554: <uname></uname>
11555: <udom></udom>
11556: </user>
11557: </users>
11558: </scope>
11559:
11560: Access data is also aggregated for each file in an additional key=value pair:
11561: key -> path to file/file_name\0accesscontrol
11562: value -> reference to hash
11563: hash contains key = value pairs
11564: where key = uniqueID:scope_end_start
11565: value = UNIX time record was last updated
11566:
11567: Used to improve speed of look-ups of access controls for each file.
11568:
11569: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11570:
11571: modify_access_controls():
11572:
11573: Modifies access controls for a portfolio file
11574: Args
11575: 1. file name
11576: 2. reference to hash of required changes,
11577: 3. domain
11578: 4. username
11579: where domain,username are the domain of the portfolio owner
11580: (either a user or a course)
11581:
11582: Returns:
11583: 1. result of additions or updates ('ok' or 'error', with error message).
11584: 2. result of deletions ('ok' or 'error', with error message).
11585: 3. reference to hash of any new or updated access controls.
11586: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11587: key = integer (inbound ID)
11588: value = uniqueID
1.747 albertel 11589:
1.608 albertel 11590: =back
11591:
1.243 albertel 11592: =head2 HTTP Helper Routines
11593:
11594: =over 4
11595:
1.191 harris41 11596: =item *
11597:
11598: escape() : unpack non-word characters into CGI-compatible hex codes
11599:
11600: =item *
11601:
11602: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11603:
1.243 albertel 11604: =back
11605:
11606: =head1 PRIVATE SUBROUTINES
11607:
11608: =head2 Underlying communication routines (Shouldn't call)
11609:
11610: =over 4
11611:
11612: =item *
11613:
11614: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11615:
11616: =item *
11617:
11618: reply() : uses subreply to send a message to remote machine, logs all failures
11619:
11620: =item *
11621:
11622: critical() : passes a critical message to another server; if cannot
11623: get through then place message in connection buffer directory and
11624: returns con_delayed, if incapable of saving message, returns
11625: con_failed
11626:
11627: =item *
11628:
11629: reconlonc() : tries to reconnect lonc client processes.
11630:
11631: =back
11632:
11633: =head2 Resource Access Logging
11634:
11635: =over 4
11636:
11637: =item *
11638:
11639: flushcourselogs() : flush (save) buffer logs and access logs
11640:
11641: =item *
11642:
11643: courselog($what) : save message for course in hash
11644:
11645: =item *
11646:
11647: courseacclog($what) : save message for course using &courselog(). Perform
11648: special processing for specific resource types (problems, exams, quizzes, etc).
11649:
1.191 harris41 11650: =item *
11651:
11652: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11653: as a PerlChildExitHandler
1.243 albertel 11654:
11655: =back
11656:
11657: =head2 Other
11658:
11659: =over 4
11660:
11661: =item *
11662:
11663: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11664:
11665: =back
11666:
11667: =cut
1.877 foxr 11668:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>