Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1056.4.13
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1056.4.13! raeburn 4: # $Id: lonnet.pm,v 1.1056.4.12 2010/10/05 12:24:13 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1056.4.5 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.1024 raeburn 95: use File::MMagic;
1.807 albertel 96: use LONCAPA qw(:DEFAULT :match);
1.740 www 97: use LONCAPA::Configuration;
1.1056.4.13! 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.1056.4.3 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.1056.4.3 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.1056.4.7 raeburn 226: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3 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.1056.4.8 raeburn 234: $ua->timeout(4);
1.1056.4.3 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.1056.4.7 raeburn 242: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1056.4.3 raeburn 243: $loncaparev = $1;
244: }
245: }
246: } else {
247: $loncaparev = $loncaparevs{$lonhost};
248: }
1.1056.4.7 raeburn 249: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1056.4.3 raeburn 250: $loncaparev = $1;
251: }
252: }
253: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
254: }
255: }
256:
257: sub get_server_homeID {
258: my ($hostname,$ignore_cache,$caller) = @_;
259: unless ($ignore_cache) {
260: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
1.993 raeburn 261: if (defined($cached)) {
1.1056.4.3 raeburn 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: }
1.993 raeburn 275: }
1.1056.4.3 raeburn 276: if ($serverhomeID eq '') {
277: $serverhomeID = $machine_ids[-1];
278: }
279: } else {
280: $serverhomeID = $serverhomeIDs{$hostname};
1.993 raeburn 281: }
1.1056.4.3 raeburn 282: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
1.993 raeburn 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:
728: # ------------------------------------------ Fight off request when overloaded
729:
730: sub overloaderror {
731: my ($r,$checkserver)=@_;
732: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
733: my $loadavg;
734: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 735: open(my $loadfile,'/proc/loadavg');
1.283 www 736: $loadavg=<$loadfile>;
737: $loadavg =~ s/\s.*//g;
1.285 matthew 738: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 739: close($loadfile);
1.283 www 740: } else {
741: $loadavg=&reply('load',$checkserver);
742: }
1.285 matthew 743: my $overload=$loadavg-100;
1.283 www 744: if ($overload>0) {
1.285 matthew 745: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 746: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 747: return 413;
1.283 www 748: }
749: return '';
1.5 www 750: }
1.1 albertel 751:
752: # ------------------------------ Find server with least workload from spare.tab
1.11 www 753:
1.1 albertel 754: sub spareserver {
1.670 albertel 755: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 756: my $spare_server;
1.370 albertel 757: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 758: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
759: : $userloadpercent;
1.1056.4.8 raeburn 760: my ($uint_dom,$remotesessions);
761: if ($env{'user.domain'}) {
762: my $uprimary_id = &Apache::lonnet::domain($env{'user.domain'},'primary');
763: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
764: my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
765: $remotesessions = $udomdefaults{'remotesessions'};
766: }
1.784 albertel 767: foreach my $try_server (@{ $spareid{'primary'} }) {
1.1056.4.8 raeburn 768: if ($uint_dom) {
769: next unless (&spare_can_host($env{'user.domain'},$uint_dom,
770: $remotesessions,$try_server));
771: }
1.784 albertel 772: ($spare_server, $lowest_load) =
773: &compare_server_load($try_server, $spare_server, $lowest_load);
774: }
775:
776: my $found_server = ($spare_server ne '' && $lowest_load < 100);
777:
778: if (!$found_server) {
779: foreach my $try_server (@{ $spareid{'default'} }) {
1.1056.4.8 raeburn 780: if ($uint_dom) {
781: next unless (&spare_can_host($env{'user.domain'},$uint_dom,
782: $remotesessions,$try_server));
783: }
1.784 albertel 784: ($spare_server, $lowest_load) =
785: &compare_server_load($try_server, $spare_server, $lowest_load);
786: }
787: }
788:
789: if (!$want_server_name) {
1.968 raeburn 790: my $protocol = 'http';
791: if ($protocol{$spare_server} eq 'https') {
792: $protocol = $protocol{$spare_server};
793: }
1.1001 raeburn 794: if (defined($spare_server)) {
795: my $hostname = &hostname($spare_server);
1.1056.4.8 raeburn 796: if (defined($hostname)) {
1.1001 raeburn 797: $spare_server = $protocol.'://'.$hostname;
798: }
799: }
1.784 albertel 800: }
801: return $spare_server;
802: }
803:
804: sub compare_server_load {
805: my ($try_server, $spare_server, $lowest_load) = @_;
806:
807: my $loadans = &reply('load', $try_server);
808: my $userloadans = &reply('userload',$try_server);
809:
810: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1056.4.3 raeburn 811: return; #didn't get a number from the server
1.784 albertel 812: }
813:
814: my $load;
815: if ($loadans =~ /\d/) {
816: if ($userloadans =~ /\d/) {
817: #both are numbers, pick the bigger one
818: $load = ($loadans > $userloadans) ? $loadans
819: : $userloadans;
1.411 albertel 820: } else {
1.784 albertel 821: $load = $loadans;
1.411 albertel 822: }
1.784 albertel 823: } else {
824: $load = $userloadans;
825: }
826:
827: if (($load =~ /\d/) && ($load < $lowest_load)) {
828: $spare_server = $try_server;
829: $lowest_load = $load;
1.370 albertel 830: }
1.784 albertel 831: return ($spare_server,$lowest_load);
1.202 matthew 832: }
1.914 albertel 833:
834: # --------------------------- ask offload servers if user already has a session
835: sub find_existing_session {
836: my ($udom,$uname) = @_;
837: foreach my $try_server (@{ $spareid{'primary'} },
838: @{ $spareid{'default'} }) {
839: return $try_server if (&has_user_session($try_server, $udom, $uname));
840: }
841: return;
842: }
843:
844: # -------------------------------- ask if server already has a session for user
845: sub has_user_session {
846: my ($lonid,$udom,$uname) = @_;
847: my $result = &reply(join(':','userhassession',
848: map {&escape($_)} ($udom,$uname)),$lonid);
849: return 1 if ($result eq 'ok');
850:
851: return 0;
852: }
853:
1.1056.4.3 raeburn 854: # --------- determine least loaded server in a user's domain which allows login
855:
856: sub choose_server {
857: my ($udom) = @_;
858: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
859: my %servers = &get_servers($udom);
860: my $lowest_load = 30000;
861: my ($login_host,$hostname);
862: foreach my $lonhost (keys(%servers)) {
863: my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
864: if ($loginvia eq '') {
865: ($login_host, $lowest_load) =
866: &compare_server_load($lonhost, $login_host, $lowest_load);
867: }
868: }
869: if ($login_host ne '') {
870: $hostname = $servers{$login_host};
871: }
872: return ($login_host,$hostname);
873: }
874:
1.202 matthew 875: # --------------------------------------------- Try to change a user's password
876:
877: sub changepass {
1.799 raeburn 878: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 879: $currentpass = &escape($currentpass);
880: $newpass = &escape($newpass);
1.1030 raeburn 881: my $lonhost = $perlvar{'lonHostID'};
882: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 883: $server);
884: if (! $answer) {
885: &logthis("No reply on password change request to $server ".
886: "by $uname in domain $udom.");
887: } elsif ($answer =~ "^ok") {
888: &logthis("$uname in $udom successfully changed their password ".
889: "on $server.");
890: } elsif ($answer =~ "^pwchange_failure") {
891: &logthis("$uname in $udom was unable to change their password ".
892: "on $server. The action was blocked by either lcpasswd ".
893: "or pwchange");
894: } elsif ($answer =~ "^non_authorized") {
895: &logthis("$uname in $udom did not get their password correct when ".
896: "attempting to change it on $server.");
897: } elsif ($answer =~ "^auth_mode_error") {
898: &logthis("$uname in $udom attempted to change their password despite ".
899: "not being locally or internally authenticated on $server.");
900: } elsif ($answer =~ "^unknown_user") {
901: &logthis("$uname in $udom attempted to change their password ".
902: "on $server but were unable to because $server is not ".
903: "their home server.");
904: } elsif ($answer =~ "^refused") {
905: &logthis("$server refused to change $uname in $udom password because ".
906: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 907: } elsif ($answer =~ "invalid_client") {
908: &logthis("$server refused to change $uname in $udom password because ".
909: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 910: }
911: return $answer;
1.1 albertel 912: }
913:
1.169 harris41 914: # ----------------------- Try to determine user's current authentication scheme
915:
916: sub queryauthenticate {
917: my ($uname,$udom)=@_;
1.456 albertel 918: my $uhome=&homeserver($uname,$udom);
919: if (!$uhome) {
920: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
921: return 'no_host';
922: }
923: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
924: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
925: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 926: }
1.456 albertel 927: return $answer;
1.169 harris41 928: }
929:
1.1 albertel 930: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 931:
1.1 albertel 932: sub authenticate {
1.1056.4.3 raeburn 933: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 934: $upass=&escape($upass);
935: $uname= &LONCAPA::clean_username($uname);
1.836 www 936: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 937: my $newhome;
1.836 www 938: if ((!$uhome) || ($uhome eq 'no_host')) {
939: # Maybe the machine was offline and only re-appeared again recently?
940: &reconlonc();
941: # One more
1.952 raeburn 942: $uhome=&homeserver($uname,$udom,1);
943: if (($uhome eq 'no_host') && $checkdefauth) {
944: if (defined(&domain($udom,'primary'))) {
945: $newhome=&domain($udom,'primary');
946: }
947: if ($newhome ne '') {
948: $uhome = $newhome;
949: }
950: }
1.836 www 951: if ((!$uhome) || ($uhome eq 'no_host')) {
952: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 953: return 'no_host';
954: }
1.1 albertel 955: }
1.1056.4.3 raeburn 956: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 957: if ($answer eq 'authorized') {
1.952 raeburn 958: if ($newhome) {
959: &logthis("User $uname at $udom authorized by $uhome, but needs account");
960: return 'no_account_on_host';
961: } else {
962: &logthis("User $uname at $udom authorized by $uhome");
963: return $uhome;
964: }
1.471 albertel 965: }
966: if ($answer eq 'non_authorized') {
967: &logthis("User $uname at $udom rejected by $uhome");
968: return 'no_host';
1.9 www 969: }
1.471 albertel 970: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 971: return 'no_host';
972: }
973:
1.1056.4.3 raeburn 974: sub can_host_session {
975: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
976: my $canhost = 1;
977: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
978: if (ref($remotesessions) eq 'HASH') {
979: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
980: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
981: $canhost = 0;
982: } else {
983: $canhost = 1;
984: }
985: }
986: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
987: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
988: $canhost = 1;
989: } else {
990: $canhost = 0;
991: }
992: }
993: if ($canhost) {
994: if ($remotesessions->{'version'} ne '') {
995: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
996: if ($reqmajor ne '' && $reqminor ne '') {
997: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
998: my $major = $1;
999: my $minor = $2;
1000: if (($major < $reqmajor ) ||
1001: (($major == $reqmajor) && ($minor < $reqminor))) {
1002: $canhost = 0;
1003: }
1004: } else {
1005: $canhost = 0;
1006: }
1007: }
1008: }
1009: }
1010: }
1011: if ($canhost) {
1012: if (ref($hostedsessions) eq 'HASH') {
1013: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1014: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
1015: $canhost = 0;
1016: } else {
1017: $canhost = 1;
1018: }
1019: }
1020: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1021: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
1022: $canhost = 1;
1023: } else {
1024: $canhost = 0;
1025: }
1026: }
1027: }
1028: }
1029: return $canhost;
1030: }
1031:
1.1056.4.8 raeburn 1032: sub spare_can_host {
1033: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1034: my $canhost=1;
1035: my @intdoms;
1036: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1037: if (ref($internet_names) eq 'ARRAY') {
1038: @intdoms = @{$internet_names};
1039: }
1040: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1041: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1042: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1043: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1044: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1045: $canhost = &can_host_session($udom,$try_server,$remoterev,
1046: $remotesessions,
1047: $defdomdefaults{'hostedsessions'});
1048: }
1049: return $canhost;
1050: }
1051:
1.1 albertel 1052: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1053:
1.599 albertel 1054: my %homecache;
1.1 albertel 1055: sub homeserver {
1.230 stredwic 1056: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1057: my $index="$uname:$udom";
1.426 albertel 1058:
1.599 albertel 1059: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1060:
1061: my %servers = &get_servers($udom,'library');
1062: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1063: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1064: exists($badServerCache{$tryserver}));
1.841 albertel 1065:
1066: my $answer=reply("home:$udom:$uname",$tryserver);
1067: if ($answer eq 'found') {
1068: delete($badServerCache{$tryserver});
1069: return $homecache{$index}=$tryserver;
1070: } elsif ($answer eq 'no_host') {
1071: $badServerCache{$tryserver}=1;
1072: }
1.1 albertel 1073: }
1074: return 'no_host';
1.70 www 1075: }
1076:
1077: # ------------------------------------- Find the usernames behind a list of IDs
1078:
1079: sub idget {
1080: my ($udom,@ids)=@_;
1081: my %returnhash=();
1082:
1.841 albertel 1083: my %servers = &get_servers($udom,'library');
1084: foreach my $tryserver (keys(%servers)) {
1085: my $idlist=join('&',@ids);
1086: $idlist=~tr/A-Z/a-z/;
1087: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1088: my @answer=();
1089: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1090: @answer=split(/\&/,$reply);
1091: } ;
1092: my $i;
1093: for ($i=0;$i<=$#ids;$i++) {
1094: if ($answer[$i]) {
1095: $returnhash{$ids[$i]}=$answer[$i];
1096: }
1097: }
1098: }
1.70 www 1099: return %returnhash;
1100: }
1101:
1102: # ------------------------------------- Find the IDs behind a list of usernames
1103:
1104: sub idrget {
1105: my ($udom,@unames)=@_;
1106: my %returnhash=();
1.800 albertel 1107: foreach my $uname (@unames) {
1108: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1109: }
1.70 www 1110: return %returnhash;
1111: }
1112:
1113: # ------------------------------- Store away a list of names and associated IDs
1114:
1115: sub idput {
1116: my ($udom,%ids)=@_;
1117: my %servers=();
1.800 albertel 1118: foreach my $uname (keys(%ids)) {
1119: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1120: my $uhom=&homeserver($uname,$udom);
1.70 www 1121: if ($uhom ne 'no_host') {
1.800 albertel 1122: my $id=&escape($ids{$uname});
1.70 www 1123: $id=~tr/A-Z/a-z/;
1.800 albertel 1124: my $esc_unam=&escape($uname);
1.70 www 1125: if ($servers{$uhom}) {
1.800 albertel 1126: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1127: } else {
1.800 albertel 1128: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1129: }
1130: }
1.191 harris41 1131: }
1.800 albertel 1132: foreach my $server (keys(%servers)) {
1133: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1134: }
1.344 www 1135: }
1136:
1.1023 raeburn 1137: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1138: sub dump_dom {
1.1023 raeburn 1139: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1140: if (!$udom) {
1141: $udom=$env{'user.domain'};
1142: }
1143: my %returnhash;
1.1023 raeburn 1144: if ($udom) {
1145: my $uname = &get_domainconfiguser($udom);
1146: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1147: }
1148: return %returnhash;
1149: }
1150:
1.1023 raeburn 1151: # ------------------------------------------ get items from domain db files
1.806 raeburn 1152:
1153: sub get_dom {
1.860 raeburn 1154: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1155: my $items='';
1156: foreach my $item (@$storearr) {
1157: $items.=&escape($item).'&';
1158: }
1159: $items=~s/\&$//;
1.860 raeburn 1160: if (!$udom) {
1161: $udom=$env{'user.domain'};
1162: if (defined(&domain($udom,'primary'))) {
1163: $uhome=&domain($udom,'primary');
1164: } else {
1.874 albertel 1165: undef($uhome);
1.860 raeburn 1166: }
1167: } else {
1168: if (!$uhome) {
1169: if (defined(&domain($udom,'primary'))) {
1170: $uhome=&domain($udom,'primary');
1171: }
1172: }
1173: }
1174: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1175: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1176: my %returnhash;
1.875 albertel 1177: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1178: return %returnhash;
1179: }
1.806 raeburn 1180: my @pairs=split(/\&/,$rep);
1181: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1182: return @pairs;
1183: }
1184: my $i=0;
1185: foreach my $item (@$storearr) {
1186: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1187: $i++;
1188: }
1189: return %returnhash;
1190: } else {
1.880 banghart 1191: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1192: }
1193: }
1194:
1195: # -------------------------------------------- put items in domain db files
1196:
1197: sub put_dom {
1.860 raeburn 1198: my ($namespace,$storehash,$udom,$uhome)=@_;
1199: if (!$udom) {
1200: $udom=$env{'user.domain'};
1201: if (defined(&domain($udom,'primary'))) {
1202: $uhome=&domain($udom,'primary');
1203: } else {
1.874 albertel 1204: undef($uhome);
1.860 raeburn 1205: }
1206: } else {
1207: if (!$uhome) {
1208: if (defined(&domain($udom,'primary'))) {
1209: $uhome=&domain($udom,'primary');
1210: }
1211: }
1212: }
1213: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1214: my $items='';
1215: foreach my $item (keys(%$storehash)) {
1216: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1217: }
1218: $items=~s/\&$//;
1219: return &reply("putdom:$udom:$namespace:$items",$uhome);
1220: } else {
1.860 raeburn 1221: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1222: }
1223: }
1224:
1.1023 raeburn 1225: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1226: sub newput_dom {
1.1023 raeburn 1227: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1228: my $result;
1229: if (!$udom) {
1230: $udom=$env{'user.domain'};
1231: }
1.1023 raeburn 1232: if ($udom) {
1233: my $uname = &get_domainconfiguser($udom);
1234: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1235: }
1236: return $result;
1237: }
1238:
1.1023 raeburn 1239: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1240: sub del_dom {
1.1023 raeburn 1241: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1242: if (ref($storearr) eq 'ARRAY') {
1243: if (!$udom) {
1244: $udom=$env{'user.domain'};
1245: }
1.1023 raeburn 1246: if ($udom) {
1247: my $uname = &get_domainconfiguser($udom);
1248: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1249: }
1250: }
1251: }
1252:
1.1023 raeburn 1253: # ----------------------------------construct domainconfig user for a domain
1254: sub get_domainconfiguser {
1255: my ($udom) = @_;
1256: return $udom.'-domainconfig';
1257: }
1258:
1.837 raeburn 1259: sub retrieve_inst_usertypes {
1260: my ($udom) = @_;
1261: my (%returnhash,@order);
1.989 raeburn 1262: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1263: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1264: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1265: %returnhash = %{$domdefs{'inststatustypes'}};
1266: @order = @{$domdefs{'inststatusorder'}};
1267: } else {
1268: if (defined(&domain($udom,'primary'))) {
1269: my $uhome=&domain($udom,'primary');
1270: my $rep=&reply("inst_usertypes:$udom",$uhome);
1271: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1272: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1273: return (\%returnhash,\@order);
1274: }
1275: my ($hashitems,$orderitems) = split(/:/,$rep);
1276: my @pairs=split(/\&/,$hashitems);
1277: foreach my $item (@pairs) {
1278: my ($key,$value)=split(/=/,$item,2);
1279: $key = &unescape($key);
1280: next if ($key =~ /^error: 2 /);
1281: $returnhash{$key}=&thaw_unescape($value);
1282: }
1283: my @esc_order = split(/\&/,$orderitems);
1284: foreach my $item (@esc_order) {
1285: push(@order,&unescape($item));
1286: }
1287: } else {
1288: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1289: }
1290: }
1291: return (\%returnhash,\@order);
1292: }
1293:
1.868 raeburn 1294: sub is_domainimage {
1295: my ($url) = @_;
1296: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1297: if (&domain($1) ne '') {
1298: return '1';
1299: }
1300: }
1301: return;
1302: }
1303:
1.899 raeburn 1304: sub inst_directory_query {
1305: my ($srch) = @_;
1306: my $udom = $srch->{'srchdomain'};
1307: my %results;
1308: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1309: my $outcome;
1.899 raeburn 1310: if ($homeserver ne '') {
1.904 albertel 1311: my $queryid=&reply("querysend:instdirsearch:".
1312: &escape($srch->{'srchby'}).':'.
1313: &escape($srch->{'srchterm'}).':'.
1314: &escape($srch->{'srchtype'}),$homeserver);
1315: my $host=&hostname($homeserver);
1316: if ($queryid !~/^\Q$host\E\_/) {
1317: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1318: return;
1319: }
1320: my $response = &get_query_reply($queryid);
1321: my $maxtries = 5;
1322: my $tries = 1;
1323: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1324: $response = &get_query_reply($queryid);
1325: $tries ++;
1326: }
1327:
1328: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1329: if ($response eq 'unavailable') {
1330: $outcome = $response;
1331: } else {
1332: $outcome = 'ok';
1333: my @matches = split(/\n/,$response);
1334: foreach my $match (@matches) {
1335: my ($key,$value) = split(/=/,$match);
1336: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1337: }
1.899 raeburn 1338: }
1339: }
1340: }
1.909 raeburn 1341: return ($outcome,%results);
1.899 raeburn 1342: }
1343:
1344: sub usersearch {
1345: my ($srch) = @_;
1346: my $dom = $srch->{'srchdomain'};
1347: my %results;
1348: my %libserv = &all_library();
1349: my $query = 'usersearch';
1350: foreach my $tryserver (keys(%libserv)) {
1351: if (&host_domain($tryserver) eq $dom) {
1352: my $host=&hostname($tryserver);
1353: my $queryid=
1.911 raeburn 1354: &reply("querysend:".&escape($query).':'.
1355: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1356: &escape($srch->{'srchtype'}).':'.
1357: &escape($srch->{'srchterm'}),$tryserver);
1358: if ($queryid !~/^\Q$host\E\_/) {
1359: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1360: next;
1.899 raeburn 1361: }
1362: my $reply = &get_query_reply($queryid);
1363: my $maxtries = 1;
1364: my $tries = 1;
1365: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1366: $reply = &get_query_reply($queryid);
1367: $tries ++;
1368: }
1369: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1370: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1371: } else {
1.911 raeburn 1372: my @matches;
1373: if ($reply =~ /\n/) {
1374: @matches = split(/\n/,$reply);
1375: } else {
1376: @matches = split(/\&/,$reply);
1377: }
1.899 raeburn 1378: foreach my $match (@matches) {
1379: my ($uname,$udom,%userhash);
1.911 raeburn 1380: foreach my $entry (split(/:/,$match)) {
1381: my ($key,$value) =
1382: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1383: $userhash{$key} = $value;
1384: if ($key eq 'username') {
1385: $uname = $value;
1386: } elsif ($key eq 'domain') {
1387: $udom = $value;
1.911 raeburn 1388: }
1.899 raeburn 1389: }
1390: $results{$uname.':'.$udom} = \%userhash;
1391: }
1392: }
1393: }
1394: }
1395: return %results;
1396: }
1397:
1.912 raeburn 1398: sub get_instuser {
1399: my ($udom,$uname,$id) = @_;
1400: my $homeserver = &domain($udom,'primary');
1401: my ($outcome,%results);
1402: if ($homeserver ne '') {
1403: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1404: &escape($id).':'.&escape($udom),$homeserver);
1405: my $host=&hostname($homeserver);
1406: if ($queryid !~/^\Q$host\E\_/) {
1407: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1408: return;
1409: }
1410: my $response = &get_query_reply($queryid);
1411: my $maxtries = 5;
1412: my $tries = 1;
1413: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1414: $response = &get_query_reply($queryid);
1415: $tries ++;
1416: }
1417: if (!&error($response) && $response ne 'refused') {
1418: if ($response eq 'unavailable') {
1419: $outcome = $response;
1420: } else {
1421: $outcome = 'ok';
1422: my @matches = split(/\n/,$response);
1423: foreach my $match (@matches) {
1424: my ($key,$value) = split(/=/,$match);
1425: $results{&unescape($key)} = &thaw_unescape($value);
1426: }
1427: }
1428: }
1429: }
1430: my %userinfo;
1431: if (ref($results{$uname}) eq 'HASH') {
1432: %userinfo = %{$results{$uname}};
1433: }
1434: return ($outcome,%userinfo);
1435: }
1436:
1437: sub inst_rulecheck {
1.923 raeburn 1438: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1439: my %returnhash;
1440: if ($udom ne '') {
1441: if (ref($rules) eq 'ARRAY') {
1442: @{$rules} = map {&escape($_);} (@{$rules});
1443: my $rulestr = join(':',@{$rules});
1444: my $homeserver=&domain($udom,'primary');
1445: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1446: my $response;
1447: if ($item eq 'username') {
1448: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1449: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1450: $homeserver));
1.923 raeburn 1451: } elsif ($item eq 'id') {
1452: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1453: ':'.&escape($id).':'.$rulestr,
1454: $homeserver));
1.945 raeburn 1455: } elsif ($item eq 'selfcreate') {
1456: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1457: &escape($udom).':'.&escape($uname).
1458: ':'.$rulestr,$homeserver));
1.923 raeburn 1459: }
1.912 raeburn 1460: if ($response ne 'refused') {
1461: my @pairs=split(/\&/,$response);
1462: foreach my $item (@pairs) {
1463: my ($key,$value)=split(/=/,$item,2);
1464: $key = &unescape($key);
1465: next if ($key =~ /^error: 2 /);
1466: $returnhash{$key}=&thaw_unescape($value);
1467: }
1468: }
1469: }
1470: }
1471: }
1472: return %returnhash;
1473: }
1474:
1475: sub inst_userrules {
1.923 raeburn 1476: my ($udom,$check) = @_;
1.912 raeburn 1477: my (%ruleshash,@ruleorder);
1478: if ($udom ne '') {
1479: my $homeserver=&domain($udom,'primary');
1480: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1481: my $response;
1482: if ($check eq 'id') {
1483: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1484: $homeserver);
1.943 raeburn 1485: } elsif ($check eq 'email') {
1486: $response=&reply('instemailrules:'.&escape($udom),
1487: $homeserver);
1.923 raeburn 1488: } else {
1489: $response=&reply('instuserrules:'.&escape($udom),
1490: $homeserver);
1491: }
1.912 raeburn 1492: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1493: ($response ne 'unknown_cmd') &&
1.912 raeburn 1494: ($response ne 'no_such_host')) {
1495: my ($hashitems,$orderitems) = split(/:/,$response);
1496: my @pairs=split(/\&/,$hashitems);
1497: foreach my $item (@pairs) {
1498: my ($key,$value)=split(/=/,$item,2);
1499: $key = &unescape($key);
1500: next if ($key =~ /^error: 2 /);
1501: $ruleshash{$key}=&thaw_unescape($value);
1502: }
1503: my @esc_order = split(/\&/,$orderitems);
1504: foreach my $item (@esc_order) {
1505: push(@ruleorder,&unescape($item));
1506: }
1507: }
1508: }
1509: }
1510: return (\%ruleshash,\@ruleorder);
1511: }
1512:
1.976 raeburn 1513: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1514:
1515: sub get_domain_defaults {
1516: my ($domain) = @_;
1517: my $cachetime = 60*60*24;
1518: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1519: if (defined($cached)) {
1520: if (ref($result) eq 'HASH') {
1521: return %{$result};
1522: }
1523: }
1524: my %domdefaults;
1525: my %domconfig =
1.989 raeburn 1526: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1527: 'requestcourses','inststatus',
1.1056.4.3 raeburn 1528: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1529: if (ref($domconfig{'defaults'}) eq 'HASH') {
1530: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1531: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1532: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1533: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1534: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1535: } else {
1536: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1537: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1538: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1539: }
1.976 raeburn 1540: if (ref($domconfig{'quotas'}) eq 'HASH') {
1541: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1542: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1543: } else {
1544: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1545: }
1546: my @usertools = ('aboutme','blog','portfolio');
1547: foreach my $item (@usertools) {
1548: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1549: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1550: }
1551: }
1552: }
1.985 raeburn 1553: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1554: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1555: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1556: }
1557: }
1.989 raeburn 1558: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1559: foreach my $item ('inststatustypes','inststatusorder') {
1560: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1561: }
1562: }
1.1047 raeburn 1563: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1564: foreach my $item ('canuse_pdfforms') {
1565: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1566: }
1567: }
1.1056.4.3 raeburn 1568: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1569: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1570: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1571: }
1572: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1573: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1574: }
1575: }
1.943 raeburn 1576: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1577: $cachetime);
1578: return %domdefaults;
1579: }
1580:
1.344 www 1581: # --------------------------------------------------- Assign a key to a student
1582:
1583: sub assign_access_key {
1.364 www 1584: #
1585: # a valid key looks like uname:udom#comments
1586: # comments are being appended
1587: #
1.498 www 1588: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1589: $kdom=
1.620 albertel 1590: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1591: $knum=
1.620 albertel 1592: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1593: $cdom=
1.620 albertel 1594: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1595: $cnum=
1.620 albertel 1596: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1597: $udom=$env{'user.name'} unless (defined($udom));
1598: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1599: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1600: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1601: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1602: # assigned to this person
1603: # - this should not happen,
1.345 www 1604: # unless something went wrong
1605: # the first time around
1606: # ready to assign
1.364 www 1607: $logentry=$1.'; '.$logentry;
1.496 www 1608: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1609: $kdom,$knum) eq 'ok') {
1.345 www 1610: # key now belongs to user
1.346 www 1611: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1612: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1613: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1614: return 'ok';
1615: } else {
1616: return
1617: 'error: Count not permanently assign key, will need to be re-entered later.';
1618: }
1619: } else {
1620: return 'error: Could not assign key, try again later.';
1621: }
1.364 www 1622: } elsif (!$existing{$ckey}) {
1.345 www 1623: # the key does not exist
1624: return 'error: The key does not exist';
1625: } else {
1626: # the key is somebody else's
1627: return 'error: The key is already in use';
1628: }
1.344 www 1629: }
1630:
1.364 www 1631: # ------------------------------------------ put an additional comment on a key
1632:
1633: sub comment_access_key {
1634: #
1635: # a valid key looks like uname:udom#comments
1636: # comments are being appended
1637: #
1638: my ($ckey,$cdom,$cnum,$logentry)=@_;
1639: $cdom=
1.620 albertel 1640: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1641: $cnum=
1.620 albertel 1642: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1643: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1644: if ($existing{$ckey}) {
1645: $existing{$ckey}.='; '.$logentry;
1646: # ready to assign
1.367 www 1647: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1648: $cdom,$cnum) eq 'ok') {
1649: return 'ok';
1650: } else {
1651: return 'error: Count not store comment.';
1652: }
1653: } else {
1654: # the key does not exist
1655: return 'error: The key does not exist';
1656: }
1657: }
1658:
1.344 www 1659: # ------------------------------------------------------ Generate a set of keys
1660:
1661: sub generate_access_keys {
1.364 www 1662: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1663: $cdom=
1.620 albertel 1664: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1665: $cnum=
1.620 albertel 1666: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1667: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1668: unless (($cdom) && ($cnum)) { return 0; }
1669: if ($number>10000) { return 0; }
1670: sleep(2); # make sure don't get same seed twice
1671: srand(time()^($$+($$<<15))); # from "Programming Perl"
1672: my $total=0;
1673: for (my $i=1;$i<=$number;$i++) {
1674: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1675: sprintf("%lx",int(100000*rand)).'-'.
1676: sprintf("%lx",int(100000*rand));
1677: $newkey=~s/1/g/g; # folks mix up 1 and l
1678: $newkey=~s/0/h/g; # and also 0 and O
1679: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1680: if ($existing{$newkey}) {
1681: $i--;
1682: } else {
1.364 www 1683: if (&put('accesskeys',
1684: { $newkey => '# generated '.localtime().
1.620 albertel 1685: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1686: '; '.$logentry },
1687: $cdom,$cnum) eq 'ok') {
1.344 www 1688: $total++;
1689: }
1690: }
1691: }
1.620 albertel 1692: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1693: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1694: return $total;
1695: }
1696:
1697: # ------------------------------------------------------- Validate an accesskey
1698:
1699: sub validate_access_key {
1700: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1701: $cdom=
1.620 albertel 1702: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1703: $cnum=
1.620 albertel 1704: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1705: $udom=$env{'user.domain'} unless (defined($udom));
1706: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1707: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1708: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1709: }
1710:
1711: # ------------------------------------- Find the section of student in a course
1.652 albertel 1712: sub devalidate_getsection_cache {
1713: my ($udom,$unam,$courseid)=@_;
1714: my $hashid="$udom:$unam:$courseid";
1715: &devalidate_cache_new('getsection',$hashid);
1716: }
1.298 matthew 1717:
1.815 albertel 1718: sub courseid_to_courseurl {
1719: my ($courseid) = @_;
1720: #already url style courseid
1721: return $courseid if ($courseid =~ m{^/});
1722:
1723: if (exists($env{'course.'.$courseid.'.num'})) {
1724: my $cnum = $env{'course.'.$courseid.'.num'};
1725: my $cdom = $env{'course.'.$courseid.'.domain'};
1726: return "/$cdom/$cnum";
1727: }
1728:
1729: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1730: if (exists($courseinfo{'num'})) {
1731: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1732: }
1733:
1734: return undef;
1735: }
1736:
1.298 matthew 1737: sub getsection {
1738: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1739: my $cachetime=1800;
1.551 albertel 1740:
1741: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1742: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1743: if (defined($cached)) { return $result; }
1744:
1.298 matthew 1745: my %Pending;
1746: my %Expired;
1747: #
1748: # Each role can either have not started yet (pending), be active,
1749: # or have expired.
1750: #
1751: # If there is an active role, we are done.
1752: #
1753: # If there is more than one role which has not started yet,
1754: # choose the one which will start sooner
1755: # If there is one role which has not started yet, return it.
1756: #
1757: # If there is more than one expired role, choose the one which ended last.
1758: # If there is a role which has expired, return it.
1759: #
1.815 albertel 1760: $courseid = &courseid_to_courseurl($courseid);
1.1056.4.10 raeburn 1761: my $extra = &freeze_escape({'skipcheck' => 1});
1762: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 1763: foreach my $key (keys(%roleshash)) {
1.479 albertel 1764: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1765: my $section=$1;
1766: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1767: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1768: my $now=time;
1.548 albertel 1769: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1770: $Expired{$end}=$section;
1771: next;
1772: }
1.548 albertel 1773: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1774: $Pending{$start}=$section;
1775: next;
1776: }
1.599 albertel 1777: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1778: }
1779: #
1780: # Presumedly there will be few matching roles from the above
1781: # loop and the sorting time will be negligible.
1782: if (scalar(keys(%Pending))) {
1783: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1784: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1785: }
1786: if (scalar(keys(%Expired))) {
1787: my @sorted = sort {$a <=> $b} keys(%Expired);
1788: my $time = pop(@sorted);
1.599 albertel 1789: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1790: }
1.599 albertel 1791: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1792: }
1.70 www 1793:
1.599 albertel 1794: sub save_cache {
1795: &purge_remembered();
1.722 albertel 1796: #&Apache::loncommon::validate_page();
1.620 albertel 1797: undef(%env);
1.780 albertel 1798: undef($env_loaded);
1.599 albertel 1799: }
1.452 albertel 1800:
1.599 albertel 1801: my $to_remember=-1;
1802: my %remembered;
1803: my %accessed;
1804: my $kicks=0;
1805: my $hits=0;
1.849 albertel 1806: sub make_key {
1807: my ($name,$id) = @_;
1.872 albertel 1808: if (length($id) > 65
1809: && length(&escape($id)) > 200) {
1810: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1811: }
1.849 albertel 1812: return &escape($name.':'.$id);
1813: }
1814:
1.599 albertel 1815: sub devalidate_cache_new {
1816: my ($name,$id,$debug) = @_;
1817: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1818: $id=&make_key($name,$id);
1.599 albertel 1819: $memcache->delete($id);
1820: delete($remembered{$id});
1821: delete($accessed{$id});
1822: }
1823:
1824: sub is_cached_new {
1825: my ($name,$id,$debug) = @_;
1.849 albertel 1826: $id=&make_key($name,$id);
1.599 albertel 1827: if (exists($remembered{$id})) {
1828: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1829: $accessed{$id}=[&gettimeofday()];
1830: $hits++;
1831: return ($remembered{$id},1);
1832: }
1833: my $value = $memcache->get($id);
1834: if (!(defined($value))) {
1835: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1836: return (undef,undef);
1.416 albertel 1837: }
1.599 albertel 1838: if ($value eq '__undef__') {
1839: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1840: $value=undef;
1841: }
1842: &make_room($id,$value,$debug);
1843: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1844: return ($value,1);
1845: }
1846:
1847: sub do_cache_new {
1848: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1849: $id=&make_key($name,$id);
1.599 albertel 1850: my $setvalue=$value;
1851: if (!defined($setvalue)) {
1852: $setvalue='__undef__';
1853: }
1.623 albertel 1854: if (!defined($time) ) {
1855: $time=600;
1856: }
1.599 albertel 1857: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1858: my $result = $memcache->set($id,$setvalue,$time);
1859: if (! $result) {
1.872 albertel 1860: &logthis("caching of id -> $id failed");
1.910 albertel 1861: $memcache->disconnect_all();
1.872 albertel 1862: }
1.600 albertel 1863: # need to make a copy of $value
1.919 albertel 1864: &make_room($id,$value,$debug);
1.599 albertel 1865: return $value;
1866: }
1867:
1868: sub make_room {
1869: my ($id,$value,$debug)=@_;
1.919 albertel 1870:
1871: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1872: : $value;
1.599 albertel 1873: if ($to_remember<0) { return; }
1874: $accessed{$id}=[&gettimeofday()];
1875: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1876: my $to_kick;
1877: my $max_time=0;
1878: foreach my $other (keys(%accessed)) {
1879: if (&tv_interval($accessed{$other}) > $max_time) {
1880: $to_kick=$other;
1881: $max_time=&tv_interval($accessed{$other});
1882: }
1883: }
1884: delete($remembered{$to_kick});
1885: delete($accessed{$to_kick});
1886: $kicks++;
1887: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1888: return;
1889: }
1890:
1.599 albertel 1891: sub purge_remembered {
1.604 albertel 1892: #&logthis("Tossing ".scalar(keys(%remembered)));
1893: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1894: undef(%remembered);
1895: undef(%accessed);
1.428 albertel 1896: }
1.70 www 1897: # ------------------------------------- Read an entry from a user's environment
1898:
1899: sub userenvironment {
1900: my ($udom,$unam,@what)=@_;
1.976 raeburn 1901: my $items;
1902: foreach my $item (@what) {
1903: $items.=&escape($item).'&';
1904: }
1905: $items=~s/\&$//;
1.70 www 1906: my %returnhash=();
1.1009 raeburn 1907: my $uhome = &homeserver($unam,$udom);
1908: unless ($uhome eq 'no_host') {
1909: my @answer=split(/\&/,
1910: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1911: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1912: return %returnhash;
1913: }
1.1009 raeburn 1914: my $i;
1915: for ($i=0;$i<=$#what;$i++) {
1916: $returnhash{$what[$i]}=&unescape($answer[$i]);
1917: }
1.70 www 1918: }
1919: return %returnhash;
1.1 albertel 1920: }
1921:
1.617 albertel 1922: # ---------------------------------------------------------- Get a studentphoto
1923: sub studentphoto {
1924: my ($udom,$unam,$ext) = @_;
1925: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1926: if (defined($env{'request.course.id'})) {
1.708 raeburn 1927: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1928: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1929: return(&retrievestudentphoto($udom,$unam,$ext));
1930: } else {
1931: my ($result,$perm_reqd)=
1.707 albertel 1932: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1933: if ($result eq 'ok') {
1934: if (!($perm_reqd eq 'yes')) {
1935: return(&retrievestudentphoto($udom,$unam,$ext));
1936: }
1937: }
1938: }
1939: }
1940: } else {
1941: my ($result,$perm_reqd) =
1.707 albertel 1942: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1943: if ($result eq 'ok') {
1944: if (!($perm_reqd eq 'yes')) {
1945: return(&retrievestudentphoto($udom,$unam,$ext));
1946: }
1947: }
1948: }
1949: return '/adm/lonKaputt/lonlogo_broken.gif';
1950: }
1951:
1952: sub retrievestudentphoto {
1953: my ($udom,$unam,$ext,$type) = @_;
1954: my $home=&Apache::lonnet::homeserver($unam,$udom);
1955: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1956: if ($ret eq 'ok') {
1957: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1958: if ($type eq 'thumbnail') {
1959: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1960: }
1961: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1962: return $tokenurl;
1963: } else {
1964: if ($type eq 'thumbnail') {
1965: return '/adm/lonKaputt/genericstudent_tn.gif';
1966: } else {
1967: return '/adm/lonKaputt/lonlogo_broken.gif';
1968: }
1.617 albertel 1969: }
1970: }
1971:
1.263 www 1972: # -------------------------------------------------------------------- New chat
1973:
1974: sub chatsend {
1.724 raeburn 1975: my ($newentry,$anon,$group)=@_;
1.620 albertel 1976: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1977: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1978: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1979: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1980: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1981: &escape($newentry)).':'.$group,$chome);
1.292 www 1982: }
1983:
1984: # ------------------------------------------ Find current version of a resource
1985:
1986: sub getversion {
1987: my $fname=&clutter(shift);
1988: unless ($fname=~/^\/res\//) { return -1; }
1989: return ¤tversion(&filelocation('',$fname));
1990: }
1991:
1992: sub currentversion {
1993: my $fname=shift;
1.599 albertel 1994: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1995: if (defined($cached)) { return $result; }
1.292 www 1996: my $author=$fname;
1997: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1998: my ($udom,$uname)=split(/\//,$author);
1999: my $home=homeserver($uname,$udom);
2000: if ($home eq 'no_host') {
2001: return -1;
2002: }
2003: my $answer=reply("currentversion:$fname",$home);
2004: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2005: return -1;
2006: }
1.599 albertel 2007: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 2008: }
2009:
1.1 albertel 2010: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2011:
1.1 albertel 2012: sub subscribe {
2013: my $fname=shift;
1.761 raeburn 2014: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2015: $fname=~s/[\n\r]//g;
1.1 albertel 2016: my $author=$fname;
2017: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2018: my ($udom,$uname)=split(/\//,$author);
2019: my $home=homeserver($uname,$udom);
1.335 albertel 2020: if ($home eq 'no_host') {
2021: return 'not_found';
1.1 albertel 2022: }
2023: my $answer=reply("sub:$fname",$home);
1.64 www 2024: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2025: $answer.=' by '.$home;
2026: }
1.1 albertel 2027: return $answer;
2028: }
2029:
1.8 www 2030: # -------------------------------------------------------------- Replicate file
2031:
2032: sub repcopy {
2033: my $filename=shift;
1.23 www 2034: $filename=~s/\/+/\//g;
1.607 raeburn 2035: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2036: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2037: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2038: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2039: return &repcopy_userfile($filename);
2040: }
1.532 albertel 2041: $filename=~s/[\n\r]//g;
1.8 www 2042: my $transname="$filename.in.transfer";
1.828 www 2043: # FIXME: this should flock
1.607 raeburn 2044: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2045: my $remoteurl=subscribe($filename);
1.64 www 2046: if ($remoteurl =~ /^con_lost by/) {
2047: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2048: return 'unavailable';
1.8 www 2049: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2050: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2051: return 'not_found';
1.64 www 2052: } elsif ($remoteurl =~ /^rejected by/) {
2053: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2054: return 'forbidden';
1.20 www 2055: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2056: return 'ok';
1.8 www 2057: } else {
1.290 www 2058: my $author=$filename;
2059: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2060: my ($udom,$uname)=split(/\//,$author);
2061: my $home=homeserver($uname,$udom);
2062: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2063: my @parts=split(/\//,$filename);
2064: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2065: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2066: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2067: return 'bad_request';
1.8 www 2068: }
2069: my $count;
2070: for ($count=5;$count<$#parts;$count++) {
2071: $path.="/$parts[$count]";
2072: if ((-e $path)!=1) {
2073: mkdir($path,0777);
2074: }
2075: }
2076: my $ua=new LWP::UserAgent;
2077: my $request=new HTTP::Request('GET',"$remoteurl");
2078: my $response=$ua->request($request,$transname);
2079: if ($response->is_error()) {
2080: unlink($transname);
2081: my $message=$response->status_line;
1.672 albertel 2082: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2083: ." LWP get: $message: $filename</font>");
1.607 raeburn 2084: return 'unavailable';
1.8 www 2085: } else {
1.16 www 2086: if ($remoteurl!~/\.meta$/) {
2087: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2088: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2089: if ($mresponse->is_error()) {
2090: unlink($filename.'.meta');
2091: &logthis(
1.672 albertel 2092: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2093: }
2094: }
1.8 www 2095: rename($transname,$filename);
1.607 raeburn 2096: return 'ok';
1.8 www 2097: }
1.290 www 2098: }
1.8 www 2099: }
1.330 www 2100: }
2101:
2102: # ------------------------------------------------ Get server side include body
2103: sub ssi_body {
1.381 albertel 2104: my ($filelink,%form)=@_;
1.606 matthew 2105: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2106: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2107: }
1.953 www 2108: my $output='';
2109: my $response;
1.980 raeburn 2110: if ($filelink=~/^https?\:/) {
1.954 raeburn 2111: ($output,$response)=&externalssi($filelink);
1.953 www 2112: } else {
1.1004 droeschl 2113: $filelink .= $filelink=~/\?/ ? '&' : '?';
2114: $filelink .= 'inhibitmenu=yes';
1.953 www 2115: ($output,$response)=&ssi($filelink,%form);
2116: }
1.778 albertel 2117: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2118: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2119: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2120: if (wantarray) {
2121: return ($output, $response);
2122: } else {
2123: return $output;
2124: }
1.8 www 2125: }
2126:
1.15 www 2127: # --------------------------------------------------------- Server Side Include
2128:
1.782 albertel 2129: sub absolute_url {
2130: my ($host_name) = @_;
2131: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2132: if ($host_name eq '') {
2133: $host_name = $ENV{'SERVER_NAME'};
2134: }
2135: return $protocol.$host_name;
2136: }
2137:
1.942 foxr 2138: #
2139: # Server side include.
2140: # Parameters:
2141: # fn Possibly encrypted resource name/id.
2142: # form Hash that describes how the rendering should be done
2143: # and other things.
1.944 foxr 2144: # Returns:
1.950 raeburn 2145: # Scalar context: The content of the response.
2146: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2147: #
1.15 www 2148: sub ssi {
2149:
1.944 foxr 2150: my ($fn,%form)=@_;
1.15 www 2151: my $ua=new LWP::UserAgent;
1.23 www 2152: my $request;
1.711 albertel 2153:
2154: $form{'no_update_last_known'}=1;
1.895 albertel 2155: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2156: if (%form) {
1.782 albertel 2157: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2158: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2159: } else {
1.782 albertel 2160: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2161: }
2162:
1.15 www 2163: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2164: my $response=$ua->request($request);
2165:
1.944 foxr 2166: if (wantarray) {
2167: return ($response->content, $response);
2168: } else {
2169: return $response->content;
1.942 foxr 2170: }
1.324 www 2171: }
2172:
2173: sub externalssi {
2174: my ($url)=@_;
2175: my $ua=new LWP::UserAgent;
2176: my $request=new HTTP::Request('GET',$url);
2177: my $response=$ua->request($request);
1.954 raeburn 2178: if (wantarray) {
2179: return ($response->content, $response);
2180: } else {
2181: return $response->content;
2182: }
1.15 www 2183: }
1.254 www 2184:
1.492 albertel 2185: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2186:
2187: sub allowuploaded {
2188: my ($srcurl,$url)=@_;
2189: $url=&clutter(&declutter($url));
2190: my $dir=$url;
2191: $dir=~s/\/[^\/]+$//;
2192: my %httpref=();
2193: my $httpurl=&hreflocation('',$url);
2194: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2195: &Apache::lonnet::appenv(\%httpref);
1.254 www 2196: }
1.477 raeburn 2197:
1.478 albertel 2198: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2199: # input: action, courseID, current domain, intended
1.637 raeburn 2200: # path to file, source of file, instruction to parse file for objects,
2201: # ref to hash for embedded objects,
2202: # ref to hash for codebase of java objects.
2203: #
1.485 raeburn 2204: # output: url to file (if action was uploaddoc),
2205: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2206: #
1.478 albertel 2207: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2208: # course.
1.477 raeburn 2209: #
1.478 albertel 2210: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2211: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2212: # course's home server.
1.477 raeburn 2213: #
1.478 albertel 2214: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2215: # be copied from $source (current location) to
2216: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2217: # and will then be copied to
2218: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2219: # course's home server.
1.485 raeburn 2220: #
1.481 raeburn 2221: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2222: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2223: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2224: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2225: # in course's home server.
1.637 raeburn 2226: #
1.477 raeburn 2227:
2228: sub process_coursefile {
1.638 albertel 2229: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 2230: my $fetchresult;
1.638 albertel 2231: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2232: if ($action eq 'propagate') {
1.638 albertel 2233: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2234: $home);
1.481 raeburn 2235: } else {
1.477 raeburn 2236: my $fpath = '';
2237: my $fname = $file;
1.478 albertel 2238: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2239: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2240: my $filepath = &build_filepath($fpath);
1.481 raeburn 2241: if ($action eq 'copy') {
2242: if ($source eq '') {
2243: $fetchresult = 'no source file';
2244: return $fetchresult;
2245: } else {
2246: my $destination = $filepath.'/'.$fname;
2247: rename($source,$destination);
2248: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2249: $home);
1.481 raeburn 2250: }
2251: } elsif ($action eq 'uploaddoc') {
2252: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2253: print $fh $env{'form.'.$source};
1.481 raeburn 2254: close($fh);
1.637 raeburn 2255: if ($parser eq 'parse') {
1.1024 raeburn 2256: my $mm = new File::MMagic;
2257: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2258: if ($mime_type eq 'text/html') {
2259: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2260: unless ($parse_result eq 'ok') {
2261: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2262: }
1.637 raeburn 2263: }
2264: }
1.477 raeburn 2265: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2266: $home);
1.481 raeburn 2267: if ($fetchresult eq 'ok') {
2268: return '/uploaded/'.$fpath.'/'.$fname;
2269: } else {
2270: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2271: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2272: return '/adm/notfound.html';
2273: }
1.477 raeburn 2274: }
2275: }
1.485 raeburn 2276: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2277: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2278: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2279: }
2280: return $fetchresult;
2281: }
2282:
1.637 raeburn 2283: sub build_filepath {
2284: my ($fpath) = @_;
2285: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2286: unless ($fpath eq '') {
2287: my @parts=split('/',$fpath);
2288: foreach my $part (@parts) {
2289: $filepath.= '/'.$part;
2290: if ((-e $filepath)!=1) {
2291: mkdir($filepath,0777);
2292: }
2293: }
2294: }
2295: return $filepath;
2296: }
2297:
2298: sub store_edited_file {
1.638 albertel 2299: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2300: my $file = $primary_url;
2301: $file =~ s#^/uploaded/$docudom/$docuname/##;
2302: my $fpath = '';
2303: my $fname = $file;
2304: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2305: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2306: my $filepath = &build_filepath($fpath);
2307: open(my $fh,'>'.$filepath.'/'.$fname);
2308: print $fh $content;
2309: close($fh);
1.638 albertel 2310: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2311: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2312: $home);
1.637 raeburn 2313: if ($$fetchresult eq 'ok') {
2314: return '/uploaded/'.$fpath.'/'.$fname;
2315: } else {
1.638 albertel 2316: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2317: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2318: return '/adm/notfound.html';
2319: }
2320: }
2321:
1.531 albertel 2322: sub clean_filename {
1.831 albertel 2323: my ($fname,$args)=@_;
1.315 www 2324: # Replace Windows backslashes by forward slashes
1.257 www 2325: $fname=~s/\\/\//g;
1.831 albertel 2326: if (!$args->{'keep_path'}) {
2327: # Get rid of everything but the actual filename
2328: $fname=~s/^.*\/([^\/]+)$/$1/;
2329: }
1.315 www 2330: # Replace spaces by underscores
2331: $fname=~s/\s+/\_/g;
2332: # Replace all other weird characters by nothing
1.831 albertel 2333: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2334: # Replace all .\d. sequences with _\d. so they no longer look like version
2335: # numbers
2336: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2337: return $fname;
2338: }
1.1051 raeburn 2339: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2340: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2341: # image with the same aspect ratio as the original, but with dimensions which do
2342: # not exceed $resizewidth and $resizeheight.
2343:
1.984 neumanie 2344: sub resizeImage {
1.1051 raeburn 2345: my ($img_path,$resizewidth,$resizeheight) = @_;
2346: my $ima = Image::Magick->new;
2347: my $resized;
2348: if (-e $img_path) {
2349: $ima->Read($img_path);
2350: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2351: my $width = $ima->Get('width');
2352: my $height = $ima->Get('height');
2353: if ($width > $resizewidth) {
2354: my $factor = $width/$resizewidth;
2355: my $newheight = $height/$factor;
2356: $ima->Scale(width=>$resizewidth,height=>$newheight);
2357: $resized = 1;
2358: }
2359: }
2360: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2361: my $width = $ima->Get('width');
2362: my $height = $ima->Get('height');
2363: if ($height > $resizeheight) {
2364: my $factor = $height/$resizeheight;
2365: my $newwidth = $width/$factor;
2366: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2367: $resized = 1;
2368: }
2369: }
2370: if ($resized) {
2371: $ima->Write($img_path);
2372: }
2373: }
2374: return;
1.977 amueller 2375: }
2376:
1.608 albertel 2377: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2378: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1056.4.13! raeburn 2379: # the desired filename is in $env{"form.$formname.filename"}
! 2380: # $context - possible values: coursedoc, existingfile, overwrite,
! 2381: # canceloverwrite, or ''.
! 2382: # if 'coursedoc': upload to the current course
! 2383: # if 'existingfile': write file to tmp/overwrites directory
! 2384: # if 'canceloverwrite': delete file written to tmp/overwrites directory
! 2385: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2386: # $subdir - directory in userfile to store the file into
1.858 raeburn 2387: # $parser - instruction to parse file for objects ($parser = parse)
2388: # $allfiles - reference to hash for embedded objects
2389: # $codebase - reference to hash for codebase of java objects
2390: # $desuname - username for permanent storage of uploaded file
2391: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2392: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2393: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2394: # $resizewidth - width (pixels) to which to resize uploaded image
2395: # $resizeheight - height (pixels) to which to resize uploaded image
1.858 raeburn 2396: #
1.686 albertel 2397: # output: url of file in userspace, or error: <message>
2398: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2399:
1.531 albertel 2400: sub userfileupload {
1.1056.4.13! raeburn 2401: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1051 raeburn 2402: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
1.531 albertel 2403: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2404: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2405: $fname=&clean_filename($fname);
1.1056.4.13! raeburn 2406: # See if there is anything left
1.257 www 2407: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 2408: chop($env{'form.'.$formname});
1.1056.4.13! raeburn 2409: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
! 2410: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
! 2411: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
! 2412: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2413: my $now = time;
1.1056.4.13! raeburn 2414: my $filepath;
! 2415: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
! 2416: $filepath = 'tmp/helprequests/'.$now;
! 2417: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
! 2418: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
! 2419: '_'.$env{'user.domain'}.'/pending';
! 2420: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
! 2421: my ($docuname,$docudom);
! 2422: if ($destudom) {
! 2423: $docudom = $destudom;
! 2424: } else {
! 2425: $docudom = $env{'user.domain'};
! 2426: }
! 2427: if ($destuname) {
! 2428: $docuname = $destuname;
! 2429: } else {
! 2430: $docuname = $env{'user.name'};
! 2431: }
! 2432: if (exists($env{'form.group'})) {
! 2433: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
! 2434: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
! 2435: }
! 2436: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
! 2437: if ($context eq 'canceloverwrite') {
! 2438: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
! 2439: if (-e $tempfile) {
! 2440: my @info = stat($tempfile);
! 2441: if ($info[9] eq $env{'form.timestamp'}) {
! 2442: unlink($tempfile);
! 2443: }
! 2444: }
! 2445: return;
1.523 raeburn 2446: }
2447: }
1.1056.4.13! raeburn 2448: # Create the directory if not present
1.741 raeburn 2449: my @parts=split(/\//,$filepath);
2450: my $fullpath = $perlvar{'lonDaemons'};
2451: for (my $i=0;$i<@parts;$i++) {
2452: $fullpath .= '/'.$parts[$i];
2453: if ((-e $fullpath)!=1) {
2454: mkdir($fullpath,0777);
2455: }
2456: }
2457: open(my $fh,'>'.$fullpath.'/'.$fname);
2458: print $fh $env{'form.'.$formname};
2459: close($fh);
1.1056.4.13! raeburn 2460: if ($context eq 'existingfile') {
! 2461: my @info = stat($fullpath.'/'.$fname);
! 2462: return ($fullpath.'/'.$fname,$info[9]);
! 2463: } else {
! 2464: return $fullpath.'/'.$fname;
! 2465: }
1.523 raeburn 2466: }
1.995 raeburn 2467: if ($subdir eq 'scantron') {
2468: $fname = 'scantron_orig_'.$fname;
2469: } else {
2470: $fname="$subdir/$fname";
2471: }
1.1056.4.13! raeburn 2472: if ($context eq 'coursedoc') {
1.638 albertel 2473: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2474: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2475: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2476: return &finishuserfileupload($docuname,$docudom,
2477: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2478: $codebase,$thumbwidth,$thumbheight,
1.1056.4.13! raeburn 2479: $resizewidth,$resizeheight,$context);
1.481 raeburn 2480: } else {
1.620 albertel 2481: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2482: return &process_coursefile('uploaddoc',$docuname,$docudom,
2483: $fname,$formname,$parser,
2484: $allfiles,$codebase);
1.481 raeburn 2485: }
1.719 banghart 2486: } elsif (defined($destuname)) {
2487: my $docuname=$destuname;
2488: my $docudom=$destudom;
1.860 raeburn 2489: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2490: $parser,$allfiles,$codebase,
1.1051 raeburn 2491: $thumbwidth,$thumbheight,
1.1056.4.13! raeburn 2492: $resizewidth,$resizeheight,$context);
1.259 www 2493: } else {
1.638 albertel 2494: my $docuname=$env{'user.name'};
2495: my $docudom=$env{'user.domain'};
1.714 raeburn 2496: if (exists($env{'form.group'})) {
2497: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2498: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2499: }
1.860 raeburn 2500: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2501: $parser,$allfiles,$codebase,
1.1051 raeburn 2502: $thumbwidth,$thumbheight,
1.1056.4.13! raeburn 2503: $resizewidth,$resizeheight,$context);
1.259 www 2504: }
1.271 www 2505: }
2506:
2507: sub finishuserfileupload {
1.860 raeburn 2508: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1056.4.13! raeburn 2509: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context) = @_;
1.477 raeburn 2510: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2511: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2512:
1.860 raeburn 2513: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2514: $file=$fname;
2515: if ($fname=~m|/|) {
2516: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2517: $path.=$fnamepath.'/';
2518: }
1.259 www 2519: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2520: my $count;
2521: for ($count=4;$count<=$#parts;$count++) {
2522: $filepath.="/$parts[$count]";
2523: if ((-e $filepath)!=1) {
2524: mkdir($filepath,0777);
2525: }
2526: }
1.984 neumanie 2527:
1.258 www 2528: # Save the file
2529: {
1.701 albertel 2530: if (!open(FH,'>'.$filepath.'/'.$file)) {
2531: &logthis('Failed to create '.$filepath.'/'.$file);
2532: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2533: return '/adm/notfound.html';
2534: }
1.1056.4.13! raeburn 2535: if ($context eq 'overwrite') {
! 2536: my $source = $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
! 2537: my $target = $filepath.'/'.$file;
! 2538: if (-e $source) {
! 2539: my @info = stat($source);
! 2540: if ($info[9] eq $env{'form.timestamp'}) {
! 2541: unless (&File::Copy::move($source,$target)) {
! 2542: &logthis('Failed to overwrite '.$filepath.'/'.$file);
! 2543: return "Moving from $source failed";
! 2544: }
! 2545: } else {
! 2546: return "Temporary file: $source had unexpected date/time for last modification";
! 2547: }
! 2548: } else {
! 2549: return "Temporary file: $source missing";
! 2550: }
! 2551: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2552: &logthis('Failed to write to '.$filepath.'/'.$file);
2553: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2554: return '/adm/notfound.html';
2555: }
1.570 albertel 2556: close(FH);
1.1051 raeburn 2557: if ($resizewidth && $resizeheight) {
2558: my $mm = new File::MMagic;
2559: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2560: if ($mime_type =~ m{^image/}) {
2561: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2562: }
1.977 amueller 2563: }
1.258 www 2564: }
1.637 raeburn 2565: if ($parser eq 'parse') {
1.1024 raeburn 2566: my $mm = new File::MMagic;
2567: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2568: if ($mime_type eq 'text/html') {
2569: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2570: $allfiles,$codebase);
2571: unless ($parse_result eq 'ok') {
2572: &logthis('Failed to parse '.$filepath.$file.
2573: ' for embedded media: '.$parse_result);
2574: }
1.637 raeburn 2575: }
2576: }
1.860 raeburn 2577: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2578: my $input = $filepath.'/'.$file;
2579: my $output = $filepath.'/'.'tn-'.$file;
2580: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2581: system("convert -sample $thumbsize $input $output");
2582: if (-e $filepath.'/'.'tn-'.$file) {
2583: $fetchthumb = 1;
2584: }
2585: }
1.858 raeburn 2586:
1.259 www 2587: # Notify homeserver to grep it
2588: #
1.984 neumanie 2589: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2590: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2591: if ($fetchresult eq 'ok') {
1.860 raeburn 2592: if ($fetchthumb) {
2593: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2594: if ($thumbresult ne 'ok') {
2595: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2596: $docuhome.': '.$thumbresult);
2597: }
2598: }
1.259 www 2599: #
1.258 www 2600: # Return the URL to it
1.494 albertel 2601: return '/uploaded/'.$path.$file;
1.263 www 2602: } else {
1.494 albertel 2603: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2604: ': '.$fetchresult);
1.263 www 2605: return '/adm/notfound.html';
1.858 raeburn 2606: }
1.493 albertel 2607: }
2608:
1.637 raeburn 2609: sub extract_embedded_items {
1.961 raeburn 2610: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2611: my @state = ();
2612: my %javafiles = (
2613: codebase => '',
2614: code => '',
2615: archive => ''
2616: );
2617: my %mediafiles = (
2618: src => '',
2619: movie => '',
2620: );
1.648 raeburn 2621: my $p;
2622: if ($content) {
2623: $p = HTML::LCParser->new($content);
2624: } else {
1.961 raeburn 2625: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2626: }
1.641 albertel 2627: while (my $t=$p->get_token()) {
1.640 albertel 2628: if ($t->[0] eq 'S') {
2629: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2630: push(@state, $tagname);
1.648 raeburn 2631: if (lc($tagname) eq 'allow') {
2632: &add_filetype($allfiles,$attr->{'src'},'src');
2633: }
1.640 albertel 2634: if (lc($tagname) eq 'img') {
2635: &add_filetype($allfiles,$attr->{'src'},'src');
2636: }
1.886 albertel 2637: if (lc($tagname) eq 'a') {
2638: &add_filetype($allfiles,$attr->{'href'},'href');
2639: }
1.645 raeburn 2640: if (lc($tagname) eq 'script') {
2641: if ($attr->{'archive'} =~ /\.jar$/i) {
2642: &add_filetype($allfiles,$attr->{'archive'},'archive');
2643: } else {
2644: &add_filetype($allfiles,$attr->{'src'},'src');
2645: }
2646: }
2647: if (lc($tagname) eq 'link') {
2648: if (lc($attr->{'rel'}) eq 'stylesheet') {
2649: &add_filetype($allfiles,$attr->{'href'},'href');
2650: }
2651: }
1.640 albertel 2652: if (lc($tagname) eq 'object' ||
2653: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2654: foreach my $item (keys(%javafiles)) {
2655: $javafiles{$item} = '';
2656: }
2657: }
2658: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2659: my $name = lc($attr->{'name'});
2660: foreach my $item (keys(%javafiles)) {
2661: if ($name eq $item) {
2662: $javafiles{$item} = $attr->{'value'};
2663: last;
2664: }
2665: }
2666: foreach my $item (keys(%mediafiles)) {
2667: if ($name eq $item) {
2668: &add_filetype($allfiles, $attr->{'value'}, 'value');
2669: last;
2670: }
2671: }
2672: }
2673: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2674: foreach my $item (keys(%javafiles)) {
2675: if ($attr->{$item}) {
2676: $javafiles{$item} = $attr->{$item};
2677: last;
2678: }
2679: }
2680: foreach my $item (keys(%mediafiles)) {
2681: if ($attr->{$item}) {
2682: &add_filetype($allfiles,$attr->{$item},$item);
2683: last;
2684: }
2685: }
2686: }
2687: } elsif ($t->[0] eq 'E') {
2688: my ($tagname) = ($t->[1]);
2689: if ($javafiles{'codebase'} ne '') {
2690: $javafiles{'codebase'} .= '/';
2691: }
2692: if (lc($tagname) eq 'applet' ||
2693: lc($tagname) eq 'object' ||
2694: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2695: ) {
2696: foreach my $item (keys(%javafiles)) {
2697: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2698: my $file=$javafiles{'codebase'}.$javafiles{$item};
2699: &add_filetype($allfiles,$file,$item);
2700: }
2701: }
2702: }
2703: pop @state;
2704: }
2705: }
1.637 raeburn 2706: return 'ok';
2707: }
2708:
1.639 albertel 2709: sub add_filetype {
2710: my ($allfiles,$file,$type)=@_;
2711: if (exists($allfiles->{$file})) {
2712: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2713: push(@{$allfiles->{$file}}, &escape($type));
2714: }
2715: } else {
2716: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2717: }
2718: }
2719:
1.493 albertel 2720: sub removeuploadedurl {
1.984 neumanie 2721: my ($url)=@_;
2722: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2723: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2724: }
2725:
2726: sub removeuserfile {
2727: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2728: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2729: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2730: if ($result eq 'ok') {
1.798 raeburn 2731: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2732: my $metafile = $fname.'.meta';
2733: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2734: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2735: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2736: my $sqlresult =
1.823 albertel 2737: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2738: 'portfolio_metadata',$group,
2739: 'delete');
1.798 raeburn 2740: }
2741: }
2742: return $result;
1.257 www 2743: }
1.15 www 2744:
1.530 albertel 2745: sub mkdiruserfile {
2746: my ($docuname,$docudom,$dir)=@_;
2747: my $home=&homeserver($docuname,$docudom);
2748: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2749: }
2750:
1.531 albertel 2751: sub renameuserfile {
2752: my ($docuname,$docudom,$old,$new)=@_;
2753: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2754: my $result = &reply("renameuserfile:$docudom:$docuname:".
2755: &escape("$old").':'.&escape("$new"),$home);
2756: if ($result eq 'ok') {
2757: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2758: my $oldmeta = $old.'.meta';
2759: my $newmeta = $new.'.meta';
2760: my $metaresult =
2761: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2762: my $url = "/uploaded/$docudom/$docuname/$old";
2763: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2764: my $sqlresult =
1.823 albertel 2765: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2766: 'portfolio_metadata',$group,
2767: 'delete');
1.798 raeburn 2768: }
2769: }
2770: return $result;
1.531 albertel 2771: }
2772:
1.14 www 2773: # ------------------------------------------------------------------------- Log
2774:
2775: sub log {
2776: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2777: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2778: }
2779:
2780: # ------------------------------------------------------------------ Course Log
1.352 www 2781: #
2782: # This routine flushes several buffers of non-mission-critical nature
2783: #
1.157 www 2784:
2785: sub flushcourselogs {
1.352 www 2786: &logthis('Flushing log buffers');
2787: #
2788: # course logs
2789: # This is a log of all transactions in a course, which can be used
2790: # for data mining purposes
2791: #
2792: # It also collects the courseid database, which lists last transaction
2793: # times and course titles for all courseids
2794: #
2795: my %courseidbuffer=();
1.921 raeburn 2796: foreach my $crsid (keys(%courselogs)) {
1.352 www 2797: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2798: &escape($courselogs{$crsid}),
2799: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2800: delete $courselogs{$crsid};
2801: } else {
2802: &logthis('Failed to flush log buffer for '.$crsid);
2803: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2804: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2805: " exceeded maximum size, deleting.</font>");
2806: delete $courselogs{$crsid};
2807: }
1.352 www 2808: }
1.920 raeburn 2809: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2810: 'description' => $coursedescrbuf{$crsid},
2811: 'inst_code' => $courseinstcodebuf{$crsid},
2812: 'type' => $coursetypebuf{$crsid},
2813: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2814: };
1.191 harris41 2815: }
1.352 www 2816: #
2817: # Write course id database (reverse lookup) to homeserver of courses
2818: # Is used in pickcourse
2819: #
1.840 albertel 2820: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2821: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2822: $courseidbuffer{$crs_home},
2823: $crs_home,'timeonly');
1.352 www 2824: }
2825: #
2826: # File accesses
2827: # Writes to the dynamic metadata of resources to get hit counts, etc.
2828: #
1.449 matthew 2829: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2830: if ($entry =~ /___count$/) {
2831: my ($dom,$name);
1.807 albertel 2832: ($dom,$name,undef)=
1.811 albertel 2833: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2834: if (! defined($dom) || $dom eq '' ||
2835: ! defined($name) || $name eq '') {
1.620 albertel 2836: my $cid = $env{'request.course.id'};
2837: $dom = $env{'request.'.$cid.'.domain'};
2838: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2839: }
1.450 matthew 2840: my $value = $accesshash{$entry};
2841: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2842: my %temphash=($url => $value);
1.449 matthew 2843: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2844: if ($result eq 'ok') {
2845: delete $accesshash{$entry};
2846: } elsif ($result eq 'unknown_cmd') {
2847: # Target server has old code running on it.
1.450 matthew 2848: my %temphash=($entry => $value);
1.449 matthew 2849: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2850: delete $accesshash{$entry};
2851: }
2852: }
2853: } else {
1.811 albertel 2854: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2855: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2856: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2857: delete $accesshash{$entry};
2858: }
1.185 www 2859: }
1.191 harris41 2860: }
1.352 www 2861: #
2862: # Roles
2863: # Reverse lookup of user roles for course faculty/staff and co-authorship
2864: #
1.800 albertel 2865: foreach my $entry (keys(%userrolehash)) {
1.351 www 2866: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2867: split(/\:/,$entry);
2868: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2869: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2870: $rudom,$runame) eq 'ok') {
2871: delete $userrolehash{$entry};
2872: }
2873: }
1.662 raeburn 2874: #
2875: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2876: #
2877: my %domrolebuffer = ();
1.1000 raeburn 2878: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2879: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2880: if ($domrolebuffer{$rudom}) {
2881: $domrolebuffer{$rudom}.='&'.&escape($entry).
2882: '='.&escape($domainrolehash{$entry});
2883: } else {
2884: $domrolebuffer{$rudom}.=&escape($entry).
2885: '='.&escape($domainrolehash{$entry});
2886: }
2887: delete $domainrolehash{$entry};
2888: }
2889: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2890: my %servers = &get_servers($dom,'library');
2891: foreach my $tryserver (keys(%servers)) {
2892: unless (&reply('domroleput:'.$dom.':'.
2893: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2894: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2895: }
1.662 raeburn 2896: }
2897: }
1.186 www 2898: $dumpcount++;
1.157 www 2899: }
2900:
2901: sub courselog {
2902: my $what=shift;
1.158 www 2903: $what=time.':'.$what;
1.620 albertel 2904: unless ($env{'request.course.id'}) { return ''; }
2905: $coursedombuf{$env{'request.course.id'}}=
2906: $env{'course.'.$env{'request.course.id'}.'.domain'};
2907: $coursenumbuf{$env{'request.course.id'}}=
2908: $env{'course.'.$env{'request.course.id'}.'.num'};
2909: $coursehombuf{$env{'request.course.id'}}=
2910: $env{'course.'.$env{'request.course.id'}.'.home'};
2911: $coursedescrbuf{$env{'request.course.id'}}=
2912: $env{'course.'.$env{'request.course.id'}.'.description'};
2913: $courseinstcodebuf{$env{'request.course.id'}}=
2914: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2915: $courseownerbuf{$env{'request.course.id'}}=
2916: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2917: $coursetypebuf{$env{'request.course.id'}}=
2918: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2919: if (defined $courselogs{$env{'request.course.id'}}) {
2920: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2921: } else {
1.620 albertel 2922: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2923: }
1.620 albertel 2924: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2925: &flushcourselogs();
2926: }
1.158 www 2927: }
2928:
2929: sub courseacclog {
2930: my $fnsymb=shift;
1.620 albertel 2931: unless ($env{'request.course.id'}) { return ''; }
2932: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2933: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2934: $what.=':POST';
1.583 matthew 2935: # FIXME: Probably ought to escape things....
1.800 albertel 2936: foreach my $key (keys(%env)) {
2937: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2938: my $formitem = $1;
2939: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2940: $what.=':'.$formitem.'='.$env{$key};
2941: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2942: $what.=':'.$formitem.'='.$env{$key};
2943: }
1.158 www 2944: }
1.191 harris41 2945: }
1.583 matthew 2946: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2947: # FIXME: We should not be depending on a form parameter that someone
2948: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2949: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2950: $what.= ':POST';
2951: # FIXME: Probably ought to escape things....
2952: foreach my $element ('courseexp','crsfulltext','crsrelated',
2953: 'crsdiscuss') {
1.620 albertel 2954: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2955: }
2956: }
1.158 www 2957: }
2958: &courselog($what);
1.149 www 2959: }
2960:
1.185 www 2961: sub countacc {
2962: my $url=&declutter(shift);
1.458 matthew 2963: return if (! defined($url) || $url eq '');
1.620 albertel 2964: unless ($env{'request.course.id'}) { return ''; }
2965: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2966: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2967: $accesshash{$key}++;
1.185 www 2968: }
1.349 www 2969:
1.361 www 2970: sub linklog {
2971: my ($from,$to)=@_;
2972: $from=&declutter($from);
2973: $to=&declutter($to);
2974: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2975: $accesshash{$to.'___'.$from.'___goto'}=1;
2976: }
2977:
1.349 www 2978: sub userrolelog {
2979: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2980: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2981: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2982: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2983: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2984: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2985: $userrolehash
2986: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2987: =$tend.':'.$tstart;
1.662 raeburn 2988: }
1.898 albertel 2989: if (($env{'request.role'} =~ /dc\./) &&
2990: (($trole=~/^au/) || ($trole=~/^in/) ||
2991: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2992: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2993: ($trole=~/^co/))) {
1.898 albertel 2994: $userrolehash
2995: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2996: =$tend.':'.$tstart;
2997: }
1.662 raeburn 2998: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2999: ($trole=~/^li/) || ($trole=~/^li/) ||
3000: ($trole=~/^au/) || ($trole=~/^dg/) ||
3001: ($trole=~/^sc/)) {
3002: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3003: $domainrolehash
3004: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3005: = $tend.':'.$tstart;
3006: }
1.351 www 3007: }
3008:
1.957 raeburn 3009: sub courserolelog {
3010: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3011: if (($trole eq 'cc') || ($trole eq 'in') ||
3012: ($trole eq 'ep') || ($trole eq 'ad') ||
3013: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3014: ($trole=~/^cr/) || ($trole eq 'gr') ||
3015: ($trole eq 'co')) {
1.957 raeburn 3016: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3017: my $cdom = $1;
3018: my $cnum = $2;
3019: my $sec = $3;
3020: my $namespace = 'rolelog';
3021: my %storehash = (
3022: role => $trole,
3023: start => $tstart,
3024: end => $tend,
3025: selfenroll => $selfenroll,
3026: context => $context,
3027: );
3028: if ($trole eq 'gr') {
3029: $namespace = 'groupslog';
3030: $storehash{'group'} = $sec;
3031: } else {
3032: $storehash{'section'} = $sec;
3033: }
3034: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3035: if (($trole ne 'st') || ($sec ne '')) {
3036: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3037: }
1.957 raeburn 3038: }
3039: }
3040: return;
3041: }
3042:
1.351 www 3043: sub get_course_adv_roles {
1.948 raeburn 3044: my ($cid,$codes) = @_;
1.620 albertel 3045: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3046: my %coursehash=&coursedescription($cid);
1.988 raeburn 3047: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3048: my %nothide=();
1.800 albertel 3049: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3050: if ($user !~ /:/) {
3051: $nothide{join(':',split(/[\@]/,$user))}=1;
3052: } else {
3053: $nothide{$user}=1;
3054: }
1.470 www 3055: }
1.351 www 3056: my %returnhash=();
3057: my %dumphash=
3058: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3059: my $now=time;
1.997 raeburn 3060: my %privileged;
1.1000 raeburn 3061: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3062: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3063: if (($tstart) && ($tstart<0)) { next; }
3064: if (($tend) && ($tend<$now)) { next; }
3065: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3066: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3067: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3068: unless (ref($privileged{$domain}) eq 'HASH') {
3069: my %dompersonnel =
1.998 raeburn 3070: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3071: $privileged{$domain} = {};
3072: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3073: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3074: foreach my $user (keys(%{$dompersonnel{$server}})) {
3075: my ($trole,$uname,$udom) = split(/:/,$user);
3076: $privileged{$udom}{$uname} = 1;
3077: }
3078: }
3079: }
3080: }
3081: if ((exists($privileged{$domain}{$username})) &&
3082: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3083: if ($role eq 'cr') { next; }
1.948 raeburn 3084: if ($codes) {
3085: if ($section) { $role .= ':'.$section; }
3086: if ($returnhash{$role}) {
3087: $returnhash{$role}.=','.$username.':'.$domain;
3088: } else {
3089: $returnhash{$role}=$username.':'.$domain;
3090: }
1.351 www 3091: } else {
1.988 raeburn 3092: my $key=&plaintext($role,$crstype);
1.973 bisitz 3093: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3094: if ($returnhash{$key}) {
3095: $returnhash{$key}.=','.$username.':'.$domain;
3096: } else {
3097: $returnhash{$key}=$username.':'.$domain;
3098: }
1.351 www 3099: }
1.948 raeburn 3100: }
1.400 www 3101: return %returnhash;
3102: }
3103:
3104: sub get_my_roles {
1.937 raeburn 3105: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3106: unless (defined($uname)) { $uname=$env{'user.name'}; }
3107: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3108: my (%dumphash,%nothide);
1.858 raeburn 3109: if ($context eq 'userroles') {
1.1056.4.10 raeburn 3110: my $extra = &freeze_escape({'skipcheck' => 1});
3111: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3112: } else {
3113: %dumphash=
1.400 www 3114: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3115: if ($hidepriv) {
3116: my %coursehash=&coursedescription($udom.'_'.$uname);
3117: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3118: if ($user !~ /:/) {
3119: $nothide{join(':',split(/[\@]/,$user))} = 1;
3120: } else {
3121: $nothide{$user} = 1;
3122: }
3123: }
3124: }
1.858 raeburn 3125: }
1.400 www 3126: my %returnhash=();
3127: my $now=time;
1.999 raeburn 3128: my %privileged;
1.800 albertel 3129: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3130: my ($role,$tend,$tstart);
3131: if ($context eq 'userroles') {
3132: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3133: } else {
3134: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3135: }
1.400 www 3136: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3137: my $status = 'active';
1.939 raeburn 3138: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3139: $status = 'previous';
3140: }
3141: if (($tstart) && ($now<$tstart)) {
3142: $status = 'future';
3143: }
3144: if (ref($types) eq 'ARRAY') {
3145: if (!grep(/^\Q$status\E$/,@{$types})) {
3146: next;
3147: }
3148: } else {
3149: if ($status ne 'active') {
3150: next;
3151: }
3152: }
1.867 raeburn 3153: my ($rolecode,$username,$domain,$section,$area);
3154: if ($context eq 'userroles') {
3155: ($area,$rolecode) = split(/_/,$entry);
3156: (undef,$domain,$username,$section) = split(/\//,$area);
3157: } else {
3158: ($role,$username,$domain,$section) = split(/\:/,$entry);
3159: }
1.832 raeburn 3160: if (ref($roledoms) eq 'ARRAY') {
3161: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3162: next;
3163: }
3164: }
3165: if (ref($roles) eq 'ARRAY') {
3166: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3167: if ($role =~ /^cr\//) {
3168: if (!grep(/^cr$/,@{$roles})) {
3169: next;
3170: }
3171: } else {
3172: next;
3173: }
1.832 raeburn 3174: }
1.867 raeburn 3175: }
1.937 raeburn 3176: if ($hidepriv) {
1.999 raeburn 3177: if ($context eq 'userroles') {
3178: if ((&privileged($username,$domain)) &&
3179: (!$nothide{$username.':'.$domain})) {
3180: next;
3181: }
3182: } else {
3183: unless (ref($privileged{$domain}) eq 'HASH') {
3184: my %dompersonnel =
3185: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3186: $privileged{$domain} = {};
3187: if (keys(%dompersonnel)) {
3188: foreach my $server (keys(%dompersonnel)) {
3189: if (ref($dompersonnel{$server}) eq 'HASH') {
3190: foreach my $user (keys(%{$dompersonnel{$server}})) {
3191: my ($trole,$uname,$udom) = split(/:/,$user);
3192: $privileged{$udom}{$uname} = $trole;
3193: }
3194: }
3195: }
3196: }
3197: }
3198: if (exists($privileged{$domain}{$username})) {
3199: if (!$nothide{$username.':'.$domain}) {
3200: next;
3201: }
3202: }
1.937 raeburn 3203: }
3204: }
1.933 raeburn 3205: if ($withsec) {
3206: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3207: $tstart.':'.$tend;
3208: } else {
3209: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3210: }
1.832 raeburn 3211: }
1.373 www 3212: return %returnhash;
1.399 www 3213: }
3214:
3215: # ----------------------------------------------------- Frontpage Announcements
3216: #
3217: #
3218:
3219: sub postannounce {
3220: my ($server,$text)=@_;
1.844 albertel 3221: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3222: unless ($text=~/\w/) { $text=''; }
3223: return &reply('setannounce:'.&escape($text),$server);
3224: }
3225:
3226: sub getannounce {
1.448 albertel 3227:
3228: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3229: my $announcement='';
1.800 albertel 3230: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3231: close($fh);
1.399 www 3232: if ($announcement=~/\w/) {
3233: return
3234: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3235: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3236: } else {
3237: return '';
3238: }
3239: } else {
3240: return '';
3241: }
1.351 www 3242: }
1.353 www 3243:
3244: # ---------------------------------------------------------- Course ID routines
3245: # Deal with domain's nohist_courseid.db files
3246: #
3247:
3248: sub courseidput {
1.921 raeburn 3249: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3250: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3251: my $outcome;
3252: if ($caller eq 'timeonly') {
3253: my $cids = '';
3254: foreach my $item (keys(%$storehash)) {
3255: $cids.=&escape($item).'&';
3256: }
3257: $cids=~s/\&$//;
3258: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3259: $coursehome);
3260: } else {
3261: my $items = '';
3262: foreach my $item (keys(%$storehash)) {
3263: $items.= &escape($item).'='.
3264: &freeze_escape($$storehash{$item}).'&';
3265: }
3266: $items=~s/\&$//;
3267: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3268: $coursehome);
1.918 raeburn 3269: }
3270: if ($outcome eq 'unknown_cmd') {
3271: my $what;
3272: foreach my $cid (keys(%$storehash)) {
3273: $what .= &escape($cid).'=';
1.921 raeburn 3274: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3275: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3276: }
3277: $what =~ s/\:$/&/;
3278: }
3279: $what =~ s/\&$//;
3280: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3281: } else {
3282: return $outcome;
3283: }
1.353 www 3284: }
3285:
3286: sub courseiddump {
1.921 raeburn 3287: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3288: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3289: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1056.4.3 raeburn 3290: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3291: my $as_hash = 1;
3292: my %returnhash;
3293: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3294: my %libserv = &all_library();
3295: foreach my $tryserver (keys(%libserv)) {
3296: if ( ( $hostidflag == 1
3297: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3298: || (!defined($hostidflag)) ) {
3299:
1.918 raeburn 3300: if (($domfilter eq '') ||
3301: (&host_domain($tryserver) eq $domfilter)) {
3302: my $rep =
3303: &reply('courseiddump:'.&host_domain($tryserver).':'.
3304: $sincefilter.':'.&escape($descfilter).':'.
3305: &escape($instcodefilter).':'.&escape($ownerfilter).
3306: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3307: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3308: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3309: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3310: &escape($cc_clone).':'.$cloneonly.':'.
3311: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1056.4.3 raeburn 3312: &escape($creationcontext).':'.$domcloner,
3313: $tryserver);
1.918 raeburn 3314: my @pairs=split(/\&/,$rep);
3315: foreach my $item (@pairs) {
3316: my ($key,$value)=split(/\=/,$item,2);
3317: $key = &unescape($key);
3318: next if ($key =~ /^error: 2 /);
3319: my $result = &thaw_unescape($value);
3320: if (ref($result) eq 'HASH') {
3321: $returnhash{$key}=$result;
3322: } else {
1.921 raeburn 3323: my @responses = split(/:/,$value);
3324: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3325: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3326: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3327: }
1.1008 raeburn 3328: }
1.353 www 3329: }
3330: }
3331: }
3332: }
3333: return %returnhash;
3334: }
3335:
1.1055 raeburn 3336: sub courselastaccess {
3337: my ($cdom,$cnum,$hostidref) = @_;
3338: my %returnhash;
3339: if ($cdom && $cnum) {
3340: my $chome = &homeserver($cnum,$cdom);
3341: if ($chome ne 'no_host') {
3342: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3343: &extract_lastaccess(\%returnhash,$rep);
3344: }
3345: } else {
3346: if (!$cdom) { $cdom=''; }
3347: my %libserv = &all_library();
3348: foreach my $tryserver (keys(%libserv)) {
3349: if (ref($hostidref) eq 'ARRAY') {
3350: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3351: }
3352: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3353: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3354: &extract_lastaccess(\%returnhash,$rep);
3355: }
3356: }
3357: }
3358: return %returnhash;
3359: }
3360:
3361: sub extract_lastaccess {
3362: my ($returnhash,$rep) = @_;
3363: if (ref($returnhash) eq 'HASH') {
3364: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3365: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3366: $rep eq '') {
3367: my @pairs=split(/\&/,$rep);
3368: foreach my $item (@pairs) {
3369: my ($key,$value)=split(/\=/,$item,2);
3370: $key = &unescape($key);
3371: next if ($key =~ /^error: 2 /);
3372: $returnhash->{$key} = &thaw_unescape($value);
3373: }
3374: }
3375: }
3376: return;
3377: }
3378:
1.658 raeburn 3379: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3380:
3381: sub dcmailput {
1.685 raeburn 3382: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3383: my $status = &Apache::lonnet::critical(
1.740 www 3384: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3385: &escape($message),$server);
1.662 raeburn 3386: return $status;
3387: }
3388:
1.658 raeburn 3389: sub dcmaildump {
3390: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3391: my %returnhash=();
1.846 albertel 3392:
3393: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3394: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3395: &escape($enddate).':';
3396: my @esc_senders=map { &escape($_)} @$senders;
3397: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3398: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3399: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3400: if (($key) && ($value)) {
3401: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3402: }
3403: }
3404: }
3405: return %returnhash;
3406: }
1.662 raeburn 3407: # ---------------------------------------------------------- Domain roles
3408:
3409: sub get_domain_roles {
3410: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3411: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3412: $startdate = '.';
3413: }
1.1018 raeburn 3414: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3415: $enddate = '.';
3416: }
1.922 raeburn 3417: my $rolelist;
3418: if (ref($roles) eq 'ARRAY') {
3419: $rolelist = join(':',@{$roles});
3420: }
1.662 raeburn 3421: my %personnel = ();
1.841 albertel 3422:
3423: my %servers = &get_servers($dom,'library');
3424: foreach my $tryserver (keys(%servers)) {
3425: %{$personnel{$tryserver}}=();
3426: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3427: &escape($startdate).':'.
3428: &escape($enddate).':'.
3429: &escape($rolelist), $tryserver))) {
3430: my ($key,$value) = split(/\=/,$line,2);
3431: if (($key) && ($value)) {
3432: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3433: }
3434: }
1.662 raeburn 3435: }
3436: return %personnel;
3437: }
1.658 raeburn 3438:
1.149 www 3439: # ----------------------------------------------------------- Check out an item
3440:
1.504 albertel 3441: sub get_first_access {
3442: my ($type,$argsymb)=@_;
1.790 albertel 3443: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3444: if ($argsymb) { $symb=$argsymb; }
3445: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3446: if ($type eq 'course') {
3447: $res='course';
3448: } elsif ($type eq 'map') {
1.588 albertel 3449: $res=&symbread($map);
3450: } else {
3451: $res=$symb;
3452: }
3453: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3454: return $times{"$courseid\0$res"};
1.504 albertel 3455: }
3456:
3457: sub set_first_access {
3458: my ($type)=@_;
1.790 albertel 3459: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3460: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3461: if ($type eq 'course') {
3462: $res='course';
3463: } elsif ($type eq 'map') {
1.588 albertel 3464: $res=&symbread($map);
3465: } else {
3466: $res=$symb;
3467: }
3468: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3469: if (!$firstaccess) {
1.588 albertel 3470: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3471: }
3472: return 'already_set';
1.504 albertel 3473: }
3474:
1.149 www 3475: sub checkout {
3476: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3477: my $now=time;
3478: my $lonhost=$perlvar{'lonHostID'};
3479: my $infostr=&escape(
1.234 www 3480: 'CHECKOUTTOKEN&'.
1.149 www 3481: $tuname.'&'.
3482: $tudom.'&'.
3483: $tcrsid.'&'.
3484: $symb.'&'.
3485: $now.'&'.$ENV{'REMOTE_ADDR'});
3486: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 3487: if ($token=~/^error\:/) {
1.672 albertel 3488: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3489: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3490: "</font>");
3491: return '';
3492: }
3493:
1.149 www 3494: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3495: $token=~tr/a-z/A-Z/;
3496:
1.153 www 3497: my %infohash=('resource.0.outtoken' => $token,
3498: 'resource.0.checkouttime' => $now,
3499: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 3500:
3501: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3502: return '';
1.151 www 3503: } else {
1.672 albertel 3504: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3505: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3506: "</font>");
1.149 www 3507: }
3508:
3509: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3510: &escape('Checkout '.$infostr.' - '.
3511: $token)) ne 'ok') {
3512: return '';
1.151 www 3513: } else {
1.672 albertel 3514: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 3515: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3516: "</font>");
1.149 www 3517: }
1.151 www 3518: return $token;
1.149 www 3519: }
3520:
3521: # ------------------------------------------------------------ Check in an item
3522:
3523: sub checkin {
3524: my $token=shift;
1.150 www 3525: my $now=time;
3526: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3527: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 3528: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 3529: $dtoken=~s/\W/\_/g;
1.234 www 3530: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 3531: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3532:
1.154 www 3533: unless (($tuname) && ($tudom)) {
3534: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3535: return '';
3536: }
3537:
3538: unless (&allowed('mgr',$tcrsid)) {
3539: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 3540: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 3541: return '';
3542: }
3543:
1.153 www 3544: my %infohash=('resource.0.intoken' => $token,
3545: 'resource.0.checkintime' => $now,
3546: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 3547:
3548: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3549: return '';
3550: }
3551:
3552: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3553: &escape('Checkin - '.$token)) ne 'ok') {
3554: return '';
3555: }
3556:
3557: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 3558: }
3559:
3560: # --------------------------------------------- Set Expire Date for Spreadsheet
3561:
3562: sub expirespread {
3563: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3564: my $cid=$env{'request.course.id'};
1.110 www 3565: if ($cid) {
3566: my $now=time;
3567: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3568: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3569: $env{'course.'.$cid.'.num'}.
1.110 www 3570: ':nohist_expirationdates:'.
3571: &escape($key).'='.$now,
1.620 albertel 3572: $env{'course.'.$cid.'.home'})
1.110 www 3573: }
3574: return 'ok';
1.14 www 3575: }
3576:
1.109 www 3577: # ----------------------------------------------------- Devalidate Spreadsheets
3578:
3579: sub devalidate {
1.325 www 3580: my ($symb,$uname,$udom)=@_;
1.620 albertel 3581: my $cid=$env{'request.course.id'};
1.109 www 3582: if ($cid) {
1.391 matthew 3583: # delete the stored spreadsheets for
3584: # - the student level sheet of this user in course's homespace
3585: # - the assessment level sheet for this resource
3586: # for this user in user's homespace
1.553 albertel 3587: # - current conditional state info
1.325 www 3588: my $key=$uname.':'.$udom.':';
1.109 www 3589: my $status=
1.299 matthew 3590: &del('nohist_calculatedsheets',
1.391 matthew 3591: [$key.'studentcalc:'],
1.620 albertel 3592: $env{'course.'.$cid.'.domain'},
3593: $env{'course.'.$cid.'.num'})
1.133 albertel 3594: .' '.
3595: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3596: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3597: unless ($status eq 'ok ok') {
3598: &logthis('Could not devalidate spreadsheet '.
1.325 www 3599: $uname.' at '.$udom.' for '.
1.109 www 3600: $symb.': '.$status);
1.133 albertel 3601: }
1.553 albertel 3602: &delenv('user.state.'.$cid);
1.109 www 3603: }
3604: }
3605:
1.265 albertel 3606: sub get_scalar {
3607: my ($string,$end) = @_;
3608: my $value;
3609: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3610: $value = $1;
3611: } elsif ($$string =~ s/^([^&]*?)&//) {
3612: $value = $1;
3613: }
3614: return &unescape($value);
3615: }
3616:
3617: sub array2str {
3618: my (@array) = @_;
3619: my $result=&arrayref2str(\@array);
3620: $result=~s/^__ARRAY_REF__//;
3621: $result=~s/__END_ARRAY_REF__$//;
3622: return $result;
3623: }
3624:
1.204 albertel 3625: sub arrayref2str {
3626: my ($arrayref) = @_;
1.265 albertel 3627: my $result='__ARRAY_REF__';
1.204 albertel 3628: foreach my $elem (@$arrayref) {
1.265 albertel 3629: if(ref($elem) eq 'ARRAY') {
3630: $result.=&arrayref2str($elem).'&';
3631: } elsif(ref($elem) eq 'HASH') {
3632: $result.=&hashref2str($elem).'&';
3633: } elsif(ref($elem)) {
3634: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3635: } else {
3636: $result.=&escape($elem).'&';
3637: }
3638: }
3639: $result=~s/\&$//;
1.265 albertel 3640: $result .= '__END_ARRAY_REF__';
1.204 albertel 3641: return $result;
3642: }
3643:
1.168 albertel 3644: sub hash2str {
1.204 albertel 3645: my (%hash) = @_;
3646: my $result=&hashref2str(\%hash);
1.265 albertel 3647: $result=~s/^__HASH_REF__//;
3648: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3649: return $result;
3650: }
3651:
3652: sub hashref2str {
3653: my ($hashref)=@_;
1.265 albertel 3654: my $result='__HASH_REF__';
1.800 albertel 3655: foreach my $key (sort(keys(%$hashref))) {
3656: if (ref($key) eq 'ARRAY') {
3657: $result.=&arrayref2str($key).'=';
3658: } elsif (ref($key) eq 'HASH') {
3659: $result.=&hashref2str($key).'=';
3660: } elsif (ref($key)) {
1.265 albertel 3661: $result.='=';
1.800 albertel 3662: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3663: } else {
1.800 albertel 3664: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3665: }
3666:
1.800 albertel 3667: if(ref($hashref->{$key}) eq 'ARRAY') {
3668: $result.=&arrayref2str($hashref->{$key}).'&';
3669: } elsif(ref($hashref->{$key}) eq 'HASH') {
3670: $result.=&hashref2str($hashref->{$key}).'&';
3671: } elsif(ref($hashref->{$key})) {
1.265 albertel 3672: $result.='&';
1.800 albertel 3673: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3674: } else {
1.800 albertel 3675: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3676: }
3677: }
1.168 albertel 3678: $result=~s/\&$//;
1.265 albertel 3679: $result .= '__END_HASH_REF__';
1.168 albertel 3680: return $result;
3681: }
3682:
3683: sub str2hash {
1.265 albertel 3684: my ($string)=@_;
3685: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3686: return %$hash;
3687: }
3688:
3689: sub str2hashref {
1.168 albertel 3690: my ($string) = @_;
1.265 albertel 3691:
3692: my %hash;
3693:
3694: if($string !~ /^__HASH_REF__/) {
3695: if (! ($string eq '' || !defined($string))) {
3696: $hash{'error'}='Not hash reference';
3697: }
3698: return (\%hash, $string);
3699: }
3700:
3701: $string =~ s/^__HASH_REF__//;
3702:
3703: while($string !~ /^__END_HASH_REF__/) {
3704: #key
3705: my $key='';
3706: if($string =~ /^__HASH_REF__/) {
3707: ($key, $string)=&str2hashref($string);
3708: if(defined($key->{'error'})) {
3709: $hash{'error'}='Bad data';
3710: return (\%hash, $string);
3711: }
3712: } elsif($string =~ /^__ARRAY_REF__/) {
3713: ($key, $string)=&str2arrayref($string);
3714: if($key->[0] eq 'Array reference error') {
3715: $hash{'error'}='Bad data';
3716: return (\%hash, $string);
3717: }
3718: } else {
3719: $string =~ s/^(.*?)=//;
1.267 albertel 3720: $key=&unescape($1);
1.265 albertel 3721: }
3722: $string =~ s/^=//;
3723:
3724: #value
3725: my $value='';
3726: if($string =~ /^__HASH_REF__/) {
3727: ($value, $string)=&str2hashref($string);
3728: if(defined($value->{'error'})) {
3729: $hash{'error'}='Bad data';
3730: return (\%hash, $string);
3731: }
3732: } elsif($string =~ /^__ARRAY_REF__/) {
3733: ($value, $string)=&str2arrayref($string);
3734: if($value->[0] eq 'Array reference error') {
3735: $hash{'error'}='Bad data';
3736: return (\%hash, $string);
3737: }
3738: } else {
3739: $value=&get_scalar(\$string,'__END_HASH_REF__');
3740: }
3741: $string =~ s/^&//;
3742:
3743: $hash{$key}=$value;
1.204 albertel 3744: }
1.265 albertel 3745:
3746: $string =~ s/^__END_HASH_REF__//;
3747:
3748: return (\%hash, $string);
1.204 albertel 3749: }
3750:
3751: sub str2array {
1.265 albertel 3752: my ($string)=@_;
3753: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3754: return @$array;
3755: }
3756:
3757: sub str2arrayref {
1.204 albertel 3758: my ($string) = @_;
1.265 albertel 3759: my @array;
3760:
3761: if($string !~ /^__ARRAY_REF__/) {
3762: if (! ($string eq '' || !defined($string))) {
3763: $array[0]='Array reference error';
3764: }
3765: return (\@array, $string);
3766: }
3767:
3768: $string =~ s/^__ARRAY_REF__//;
3769:
3770: while($string !~ /^__END_ARRAY_REF__/) {
3771: my $value='';
3772: if($string =~ /^__HASH_REF__/) {
3773: ($value, $string)=&str2hashref($string);
3774: if(defined($value->{'error'})) {
3775: $array[0] ='Array reference error';
3776: return (\@array, $string);
3777: }
3778: } elsif($string =~ /^__ARRAY_REF__/) {
3779: ($value, $string)=&str2arrayref($string);
3780: if($value->[0] eq 'Array reference error') {
3781: $array[0] ='Array reference error';
3782: return (\@array, $string);
3783: }
3784: } else {
3785: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3786: }
3787: $string =~ s/^&//;
3788:
3789: push(@array, $value);
1.191 harris41 3790: }
1.265 albertel 3791:
3792: $string =~ s/^__END_ARRAY_REF__//;
3793:
3794: return (\@array, $string);
1.168 albertel 3795: }
3796:
1.167 albertel 3797: # -------------------------------------------------------------------Temp Store
3798:
1.168 albertel 3799: sub tmpreset {
3800: my ($symb,$namespace,$domain,$stuname) = @_;
3801: if (!$symb) {
3802: $symb=&symbread();
1.620 albertel 3803: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3804: }
3805: $symb=escape($symb);
3806:
1.620 albertel 3807: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3808: $namespace=~s/\//\_/g;
3809: $namespace=~s/\W//g;
3810:
1.620 albertel 3811: if (!$domain) { $domain=$env{'user.domain'}; }
3812: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3813: if ($domain eq 'public' && $stuname eq 'public') {
3814: $stuname=$ENV{'REMOTE_ADDR'};
3815: }
1.168 albertel 3816: my $path=$perlvar{'lonDaemons'}.'/tmp';
3817: my %hash;
3818: if (tie(%hash,'GDBM_File',
3819: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3820: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3821: foreach my $key (keys(%hash)) {
1.180 albertel 3822: if ($key=~ /:$symb/) {
1.168 albertel 3823: delete($hash{$key});
3824: }
3825: }
3826: }
3827: }
3828:
1.167 albertel 3829: sub tmpstore {
1.168 albertel 3830: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3831:
3832: if (!$symb) {
3833: $symb=&symbread();
1.620 albertel 3834: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3835: }
3836: $symb=escape($symb);
3837:
3838: if (!$namespace) {
3839: # I don't think we would ever want to store this for a course.
3840: # it seems this will only be used if we don't have a course.
1.620 albertel 3841: #$namespace=$env{'request.course.id'};
1.168 albertel 3842: #if (!$namespace) {
1.620 albertel 3843: $namespace=$env{'request.state'};
1.168 albertel 3844: #}
3845: }
3846: $namespace=~s/\//\_/g;
3847: $namespace=~s/\W//g;
1.620 albertel 3848: if (!$domain) { $domain=$env{'user.domain'}; }
3849: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3850: if ($domain eq 'public' && $stuname eq 'public') {
3851: $stuname=$ENV{'REMOTE_ADDR'};
3852: }
1.168 albertel 3853: my $now=time;
3854: my %hash;
3855: my $path=$perlvar{'lonDaemons'}.'/tmp';
3856: if (tie(%hash,'GDBM_File',
3857: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3858: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3859: $hash{"version:$symb"}++;
3860: my $version=$hash{"version:$symb"};
3861: my $allkeys='';
3862: foreach my $key (keys(%$storehash)) {
3863: $allkeys.=$key.':';
1.591 albertel 3864: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3865: }
3866: $hash{"$version:$symb:timestamp"}=$now;
3867: $allkeys.='timestamp';
3868: $hash{"$version:keys:$symb"}=$allkeys;
3869: if (untie(%hash)) {
3870: return 'ok';
3871: } else {
3872: return "error:$!";
3873: }
3874: } else {
3875: return "error:$!";
3876: }
3877: }
1.167 albertel 3878:
1.168 albertel 3879: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3880:
1.168 albertel 3881: sub tmprestore {
3882: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3883:
1.168 albertel 3884: if (!$symb) {
3885: $symb=&symbread();
1.620 albertel 3886: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3887: }
3888: $symb=escape($symb);
3889:
1.620 albertel 3890: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3891:
1.620 albertel 3892: if (!$domain) { $domain=$env{'user.domain'}; }
3893: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3894: if ($domain eq 'public' && $stuname eq 'public') {
3895: $stuname=$ENV{'REMOTE_ADDR'};
3896: }
1.168 albertel 3897: my %returnhash;
3898: $namespace=~s/\//\_/g;
3899: $namespace=~s/\W//g;
3900: my %hash;
3901: my $path=$perlvar{'lonDaemons'}.'/tmp';
3902: if (tie(%hash,'GDBM_File',
3903: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3904: &GDBM_READER(),0640)) {
1.168 albertel 3905: my $version=$hash{"version:$symb"};
3906: $returnhash{'version'}=$version;
3907: my $scope;
3908: for ($scope=1;$scope<=$version;$scope++) {
3909: my $vkeys=$hash{"$scope:keys:$symb"};
3910: my @keys=split(/:/,$vkeys);
3911: my $key;
3912: $returnhash{"$scope:keys"}=$vkeys;
3913: foreach $key (@keys) {
1.591 albertel 3914: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3915: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3916: }
3917: }
1.168 albertel 3918: if (!(untie(%hash))) {
3919: return "error:$!";
3920: }
3921: } else {
3922: return "error:$!";
3923: }
3924: return %returnhash;
1.167 albertel 3925: }
3926:
1.9 www 3927: # ----------------------------------------------------------------------- Store
3928:
3929: sub store {
1.124 www 3930: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3931: my $home='';
3932:
1.168 albertel 3933: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3934:
1.213 www 3935: $symb=&symbclean($symb);
1.122 albertel 3936: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3937:
1.620 albertel 3938: if (!$domain) { $domain=$env{'user.domain'}; }
3939: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3940:
3941: &devalidate($symb,$stuname,$domain);
1.109 www 3942:
3943: $symb=escape($symb);
1.187 www 3944: if (!$namespace) {
1.620 albertel 3945: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3946: return '';
3947: }
3948: }
1.620 albertel 3949: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3950:
3951: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3952: $$storehash{'host'}=$perlvar{'lonHostID'};
3953:
1.12 www 3954: my $namevalue='';
1.800 albertel 3955: foreach my $key (keys(%$storehash)) {
3956: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3957: }
1.12 www 3958: $namevalue=~s/\&$//;
1.187 www 3959: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3960: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3961: }
3962:
1.47 www 3963: # -------------------------------------------------------------- Critical Store
3964:
3965: sub cstore {
1.124 www 3966: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3967: my $home='';
3968:
1.168 albertel 3969: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3970:
1.213 www 3971: $symb=&symbclean($symb);
1.122 albertel 3972: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3973:
1.620 albertel 3974: if (!$domain) { $domain=$env{'user.domain'}; }
3975: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3976:
3977: &devalidate($symb,$stuname,$domain);
1.109 www 3978:
3979: $symb=escape($symb);
1.187 www 3980: if (!$namespace) {
1.620 albertel 3981: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3982: return '';
3983: }
3984: }
1.620 albertel 3985: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3986:
3987: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3988: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3989:
1.47 www 3990: my $namevalue='';
1.800 albertel 3991: foreach my $key (keys(%$storehash)) {
3992: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3993: }
1.47 www 3994: $namevalue=~s/\&$//;
1.187 www 3995: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3996: return critical
3997: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3998: }
3999:
1.9 www 4000: # --------------------------------------------------------------------- Restore
4001:
4002: sub restore {
1.124 www 4003: my ($symb,$namespace,$domain,$stuname) = @_;
4004: my $home='';
4005:
1.168 albertel 4006: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4007:
1.122 albertel 4008: if (!$symb) {
4009: unless ($symb=escape(&symbread())) { return ''; }
4010: } else {
1.213 www 4011: $symb=&escape(&symbclean($symb));
1.122 albertel 4012: }
1.188 www 4013: if (!$namespace) {
1.620 albertel 4014: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4015: return '';
4016: }
4017: }
1.620 albertel 4018: if (!$domain) { $domain=$env{'user.domain'}; }
4019: if (!$stuname) { $stuname=$env{'user.name'}; }
4020: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4021: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4022:
1.12 www 4023: my %returnhash=();
1.800 albertel 4024: foreach my $line (split(/\&/,$answer)) {
4025: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4026: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4027: }
1.75 www 4028: my $version;
4029: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4030: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4031: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4032: }
1.75 www 4033: }
1.13 www 4034: return %returnhash;
1.34 www 4035: }
4036:
4037: # ---------------------------------------------------------- Course Description
4038:
4039: sub coursedescription {
1.731 albertel 4040: my ($courseid,$args)=@_;
1.34 www 4041: $courseid=~s/^\///;
1.49 www 4042: $courseid=~s/\_/\//g;
1.34 www 4043: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4044: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4045: my $normalid=$cdomain.'_'.$cnum;
4046: # need to always cache even if we get errors otherwise we keep
4047: # trying and trying and trying to get the course description.
4048: my %envhash=();
4049: my %returnhash=();
1.731 albertel 4050:
4051: my $expiretime=600;
4052: if ($env{'request.course.id'} eq $normalid) {
4053: $expiretime=120;
4054: }
4055:
4056: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4057: if (!$args->{'freshen_cache'}
4058: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4059: foreach my $key (keys(%env)) {
4060: next if ($key !~ /^\Q$prefix\E(.*)/);
4061: my ($setting) = $1;
4062: $returnhash{$setting} = $env{$key};
4063: }
4064: return %returnhash;
4065: }
4066:
4067: # get the data agin
4068: if (!$args->{'one_time'}) {
4069: $envhash{'course.'.$normalid.'.last_cache'}=time;
4070: }
1.811 albertel 4071:
1.34 www 4072: if ($chome ne 'no_host') {
1.302 albertel 4073: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4074: if (!exists($returnhash{'con_lost'})) {
4075: $returnhash{'home'}= $chome;
4076: $returnhash{'domain'} = $cdomain;
4077: $returnhash{'num'} = $cnum;
1.741 raeburn 4078: if (!defined($returnhash{'type'})) {
4079: $returnhash{'type'} = 'Course';
4080: }
1.130 albertel 4081: while (my ($name,$value) = each %returnhash) {
1.53 www 4082: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4083: }
1.270 www 4084: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 4085: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 4086: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 4087: $envhash{'course.'.$normalid.'.home'}=$chome;
4088: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4089: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4090: }
4091: }
1.731 albertel 4092: if (!$args->{'one_time'}) {
1.949 raeburn 4093: &appenv(\%envhash);
1.731 albertel 4094: }
1.302 albertel 4095: return %returnhash;
1.461 www 4096: }
4097:
1.1056.4.5 raeburn 4098: sub update_released_required {
4099: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4100: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4101: $cid = $env{'request.course.id'};
4102: $cdom = $env{'course.'.$cid.'.domain'};
4103: $cnum = $env{'course.'.$cid.'.num'};
4104: $chome = $env{'course.'.$cid.'.home'};
4105: }
4106: if ($needsrelease) {
4107: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4108: my $needsupdate;
4109: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4110: $needsupdate = 1;
4111: } else {
4112: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4113: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4114: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4115: $needsupdate = 1;
4116: }
4117: }
4118: if ($needsupdate) {
4119: my %needshash = (
4120: 'internal.releaserequired' => $needsrelease,
4121: );
4122: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4123: if ($putresult eq 'ok') {
4124: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4125: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4126: if (ref($crsinfo{$cid}) eq 'HASH') {
4127: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4128: &courseidput($cdom,\%crsinfo,$chome,'notime');
4129: }
4130: }
4131: }
4132: }
4133: return;
4134: }
4135:
1.461 www 4136: # -------------------------------------------------See if a user is privileged
4137:
4138: sub privileged {
4139: my ($username,$domain)=@_;
4140: my $rolesdump=&reply("dump:$domain:$username:roles",
4141: &homeserver($username,$domain));
1.1033 raeburn 4142: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4143: ($rolesdump =~ /^error:/)) {
4144: return 0;
4145: }
1.461 www 4146: my $now=time;
4147: if ($rolesdump ne '') {
1.800 albertel 4148: foreach my $entry (split(/&/,$rolesdump)) {
4149: if ($entry!~/^rolesdef_/) {
4150: my ($area,$role)=split(/=/,$entry);
1.461 www 4151: $area=~s/\_\w\w$//;
4152: my ($trole,$tend,$tstart)=split(/_/,$role);
4153: if (($trole eq 'dc') || ($trole eq 'su')) {
4154: my $active=1;
4155: if ($tend) {
4156: if ($tend<$now) { $active=0; }
4157: }
4158: if ($tstart) {
4159: if ($tstart>$now) { $active=0; }
4160: }
4161: if ($active) { return 1; }
4162: }
4163: }
4164: }
4165: }
4166: return 0;
1.9 www 4167: }
1.1 albertel 4168:
1.103 harris41 4169: # -------------------------------------------------------- Get user privileges
1.11 www 4170:
4171: sub rolesinit {
4172: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4173: my $now=time;
4174: my %userroles = ('user.login.time' => $now);
1.1056.4.10 raeburn 4175: my $extra = &freeze_escape({'skipcheck' => 1});
1.1056.4.3 raeburn 4176: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4177: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1056.4.3 raeburn 4178: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4179: return \%userroles;
4180: }
1.11 www 4181: my %allroles=();
1.678 raeburn 4182: my %allgroups=();
4183: my $group_privs;
1.11 www 4184:
4185: if ($rolesdump ne '') {
1.800 albertel 4186: foreach my $entry (split(/&/,$rolesdump)) {
4187: if ($entry!~/^rolesdef_/) {
4188: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4189: $area=~s/\_\w\w$//;
1.678 raeburn 4190: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4191: if ($role=~/^cr/) {
1.807 albertel 4192: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4193: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4194: ($tend,$tstart)=split('_',$trest);
4195: } else {
4196: $trole=$role;
4197: }
1.678 raeburn 4198: } elsif ($role =~ m|^gr/|) {
4199: ($trole,$tend,$tstart) = split(/_/,$role);
4200: ($trole,$group_privs) = split(/\//,$trole);
4201: $group_privs = &unescape($group_privs);
1.587 albertel 4202: } else {
4203: ($trole,$tend,$tstart)=split(/_/,$role);
4204: }
1.743 albertel 4205: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4206: $username);
4207: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4208: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4209: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4210: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4211: my $spec=$trole.'.'.$area;
4212: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4213: if ($trole =~ /^cr\//) {
1.567 raeburn 4214: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4215: } elsif ($trole eq 'gr') {
4216: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4217: } else {
1.567 raeburn 4218: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4219: }
1.12 www 4220: }
1.662 raeburn 4221: }
1.191 harris41 4222: }
1.743 albertel 4223: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4224: $userroles{'user.adv'} = $adv;
4225: $userroles{'user.author'} = $author;
1.620 albertel 4226: $env{'user.adv'}=$adv;
1.11 www 4227: }
1.743 albertel 4228: return \%userroles;
1.11 www 4229: }
4230:
1.567 raeburn 4231: sub set_arearole {
4232: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4233: # log the associated role with the area
4234: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4235: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4236: }
4237:
4238: sub custom_roleprivs {
4239: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4240: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4241: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4242: if (&hostname($homsvr) ne '') {
1.567 raeburn 4243: my ($rdummy,$roledef)=
4244: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4245: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4246: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4247: if (defined($syspriv)) {
1.1043 raeburn 4248: if ($trest =~ /^$match_community$/) {
4249: $syspriv =~ s/bre\&S//;
4250: }
1.567 raeburn 4251: $$allroles{'cm./'}.=':'.$syspriv;
4252: $$allroles{$spec.'./'}.=':'.$syspriv;
4253: }
4254: if ($tdomain ne '') {
4255: if (defined($dompriv)) {
4256: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4257: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4258: }
4259: if (($trest ne '') && (defined($coursepriv))) {
4260: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4261: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4262: }
4263: }
4264: }
4265: }
4266: }
4267:
1.678 raeburn 4268: sub group_roleprivs {
4269: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4270: my $access = 1;
4271: my $now = time;
4272: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4273: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4274: if ($access) {
1.811 albertel 4275: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4276: $$allgroups{$course}{$group} .=':'.$group_privs;
4277: }
4278: }
1.567 raeburn 4279:
4280: sub standard_roleprivs {
4281: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4282: if (defined($pr{$trole.':s'})) {
4283: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4284: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4285: }
4286: if ($tdomain ne '') {
4287: if (defined($pr{$trole.':d'})) {
4288: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4289: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4290: }
4291: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4292: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4293: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4294: }
4295: }
4296: }
4297:
4298: sub set_userprivs {
1.1056.4.2 raeburn 4299: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4300: my $author=0;
4301: my $adv=0;
1.678 raeburn 4302: my %grouproles = ();
4303: if (keys(%{$allgroups}) > 0) {
1.1056.4.2 raeburn 4304: my @groupkeys;
1.1000 raeburn 4305: foreach my $role (keys(%{$allroles})) {
1.1056.4.2 raeburn 4306: push(@groupkeys,$role);
4307: }
4308: if (ref($groups_roles) eq 'HASH') {
4309: foreach my $key (keys(%{$groups_roles})) {
4310: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4311: push(@groupkeys,$key);
4312: }
4313: }
4314: }
4315: if (@groupkeys > 0) {
4316: foreach my $role (@groupkeys) {
4317: my ($trole,$area,$sec,$extendedarea);
4318: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4319: $trole = $1;
4320: $area = $2;
4321: $sec = $3;
4322: $extendedarea = $area.$sec;
4323: if (exists($$allgroups{$area})) {
4324: foreach my $group (keys(%{$$allgroups{$area}})) {
4325: my $spec = $trole.'.'.$extendedarea;
4326: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4327: $$allgroups{$area}{$group};
1.1056.4.2 raeburn 4328: }
1.678 raeburn 4329: }
4330: }
4331: }
4332: }
4333: }
1.800 albertel 4334: foreach my $group (keys(%grouproles)) {
4335: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4336: }
1.800 albertel 4337: foreach my $role (keys(%{$allroles})) {
4338: my %thesepriv;
1.941 raeburn 4339: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4340: foreach my $item (split(/:/,$$allroles{$role})) {
4341: if ($item ne '') {
4342: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4343: if ($restrictions eq '') {
4344: $thesepriv{$privilege}='F';
4345: } elsif ($thesepriv{$privilege} ne 'F') {
4346: $thesepriv{$privilege}.=$restrictions;
4347: }
4348: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4349: }
4350: }
4351: my $thesestr='';
1.800 albertel 4352: foreach my $priv (keys(%thesepriv)) {
4353: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4354: }
4355: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4356: }
4357: return ($author,$adv);
4358: }
4359:
1.994 raeburn 4360: sub role_status {
1.1002 raeburn 4361: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4362: my @pwhere = ();
4363: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4364: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4365: unless (!defined($$role) || $$role eq '') {
4366: $$where=join('.',@pwhere);
4367: $$trolecode=$$role.'.'.$$where;
4368: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4369: $$tstatus='is';
4370: if ($$tstart && $$tstart>$then) {
4371: $$tstatus='future';
1.1034 raeburn 4372: if ($$tstart<$now) {
4373: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4374: if (($$where ne '') && ($$role ne '')) {
1.1056.4.2 raeburn 4375: my (%allroles,%allgroups,$group_privs,
4376: %groups_roles,@rolecodes);
1.1002 raeburn 4377: my %userroles = (
4378: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4379: );
1.1056.4.2 raeburn 4380: @rolecodes = ('cm');
1.1002 raeburn 4381: my $spec=$$role.'.'.$$where;
4382: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4383: if ($$role =~ /^cr\//) {
4384: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1056.4.2 raeburn 4385: push(@rolecodes,'cr');
1.1002 raeburn 4386: } elsif ($$role eq 'gr') {
1.1056.4.2 raeburn 4387: push(@rolecodes,$$role);
1.1002 raeburn 4388: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4389: $env{'user.name'});
1.1056.4.2 raeburn 4390: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4391: (undef,my $group_privs) = split(/\//,$trole);
4392: $group_privs = &unescape($group_privs);
4393: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1056.4.2 raeburn 4394: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4395: if (keys(%course_roles) > 0) {
4396: my ($tnum) = ($trest =~ /^($match_courseid)/);
4397: if ($tdomain ne '' && $tnum ne '') {
4398: foreach my $key (keys(%course_roles)) {
4399: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4400: my $crsrole = $1;
4401: my $crssec = $2;
4402: if ($crsrole =~ /^cr/) {
4403: unless (grep(/^cr$/,@rolecodes)) {
4404: push(@rolecodes,'cr');
4405: }
4406: } else {
4407: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4408: push(@rolecodes,$crsrole);
4409: }
4410: }
4411: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4412: if ($crssec ne '') {
4413: $rolekey .= '/'.$crssec;
4414: }
4415: $rolekey .= './';
4416: $groups_roles{$rolekey} = \@rolecodes;
4417: }
4418: }
4419: }
4420: }
1.1002 raeburn 4421: } else {
1.1056.4.2 raeburn 4422: push(@rolecodes,$$role);
1.1002 raeburn 4423: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4424: }
1.1056.4.2 raeburn 4425: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4426: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4427: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4428: }
4429: }
1.1034 raeburn 4430: $$tstatus = 'is';
1.1002 raeburn 4431: }
1.994 raeburn 4432: }
4433: if ($$tend) {
4434: if ($$tend<$then) {
4435: $$tstatus='expired';
4436: } elsif ($$tend<$now) {
4437: $$tstatus='will_not';
4438: }
4439: }
4440: }
4441: }
4442: }
4443:
4444: sub check_adhoc_privs {
1.1056.4.12 raeburn 4445: my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4446: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4447: if ($env{$cckey}) {
4448: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4449: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4450: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1056.4.12 raeburn 4451: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4452: }
4453: } else {
1.1056.4.12 raeburn 4454: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4455: }
4456: }
4457:
4458: sub set_adhoc_privileges {
4459: # role can be cc or ca
1.1056.4.12 raeburn 4460: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4461: my $area = '/'.$dcdom.'/'.$pickedcourse;
4462: my $spec = $role.'.'.$area;
4463: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4464: $env{'user.name'});
4465: my %ccrole = ();
4466: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4467: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4468: &appenv(\%userroles,[$role,'cm']);
4469: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1056.4.12 raeburn 4470: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4471: &appenv( {'request.role' => $spec,
4472: 'request.role.domain' => $dcdom,
4473: 'request.course.sec' => ''
4474: }
4475: );
4476: my $tadv=0;
4477: if (&allowed('adv') eq 'F') { $tadv=1; }
4478: &appenv({'request.role.adv' => $tadv});
4479: }
1.994 raeburn 4480: }
4481:
1.12 www 4482: # --------------------------------------------------------------- get interface
4483:
4484: sub get {
1.131 albertel 4485: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4486: my $items='';
1.800 albertel 4487: foreach my $item (@$storearr) {
4488: $items.=&escape($item).'&';
1.191 harris41 4489: }
1.12 www 4490: $items=~s/\&$//;
1.620 albertel 4491: if (!$udomain) { $udomain=$env{'user.domain'}; }
4492: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4493: my $uhome=&homeserver($uname,$udomain);
4494:
1.133 albertel 4495: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4496: my @pairs=split(/\&/,$rep);
1.273 albertel 4497: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4498: return @pairs;
4499: }
1.15 www 4500: my %returnhash=();
1.42 www 4501: my $i=0;
1.800 albertel 4502: foreach my $item (@$storearr) {
4503: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4504: $i++;
1.191 harris41 4505: }
1.15 www 4506: return %returnhash;
1.27 www 4507: }
4508:
4509: # --------------------------------------------------------------- del interface
4510:
4511: sub del {
1.133 albertel 4512: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4513: my $items='';
1.800 albertel 4514: foreach my $item (@$storearr) {
4515: $items.=&escape($item).'&';
1.191 harris41 4516: }
1.984 neumanie 4517:
1.27 www 4518: $items=~s/\&$//;
1.620 albertel 4519: if (!$udomain) { $udomain=$env{'user.domain'}; }
4520: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4521: my $uhome=&homeserver($uname,$udomain);
4522: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4523: }
4524:
4525: # -------------------------------------------------------------- dump interface
4526:
4527: sub dump {
1.1056.4.10 raeburn 4528: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4529: if (!$udomain) { $udomain=$env{'user.domain'}; }
4530: if (!$uname) { $uname=$env{'user.name'}; }
4531: my $uhome=&homeserver($uname,$udomain);
4532: if ($regexp) {
4533: $regexp=&escape($regexp);
4534: } else {
4535: $regexp='.';
4536: }
1.1056.4.10 raeburn 4537: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4538: my @pairs=split(/\&/,$rep);
4539: my %returnhash=();
4540: foreach my $item (@pairs) {
4541: my ($key,$value)=split(/=/,$item,2);
4542: $key = &unescape($key);
4543: next if ($key =~ /^error: 2 /);
4544: $returnhash{$key}=&thaw_unescape($value);
4545: }
4546: return %returnhash;
1.407 www 4547: }
4548:
1.717 albertel 4549: # --------------------------------------------------------- dumpstore interface
4550:
4551: sub dumpstore {
4552: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4553: if (!$udomain) { $udomain=$env{'user.domain'}; }
4554: if (!$uname) { $uname=$env{'user.name'}; }
4555: my $uhome=&homeserver($uname,$udomain);
4556: if ($regexp) {
4557: $regexp=&escape($regexp);
4558: } else {
4559: $regexp='.';
4560: }
4561: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4562: my @pairs=split(/\&/,$rep);
4563: my %returnhash=();
4564: foreach my $item (@pairs) {
4565: my ($key,$value)=split(/=/,$item,2);
4566: next if ($key =~ /^error: 2 /);
4567: $returnhash{$key}=&thaw_unescape($value);
4568: }
4569: return %returnhash;
1.717 albertel 4570: }
4571:
1.407 www 4572: # -------------------------------------------------------------- keys interface
4573:
4574: sub getkeys {
4575: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4576: if (!$udomain) { $udomain=$env{'user.domain'}; }
4577: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4578: my $uhome=&homeserver($uname,$udomain);
4579: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4580: my @keyarray=();
1.800 albertel 4581: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4582: next if ($key =~ /^error: 2 /);
1.800 albertel 4583: push(@keyarray,&unescape($key));
1.407 www 4584: }
4585: return @keyarray;
1.318 matthew 4586: }
4587:
1.319 matthew 4588: # --------------------------------------------------------------- currentdump
4589: sub currentdump {
1.328 matthew 4590: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4591: $courseid = $env{'request.course.id'} if (! defined($courseid));
4592: $sdom = $env{'user.domain'} if (! defined($sdom));
4593: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4594: my $uhome = &homeserver($sname,$sdom);
4595: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4596: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4597: #
1.318 matthew 4598: my %returnhash=();
1.319 matthew 4599: #
4600: if ($rep eq "unknown_cmd") {
4601: # an old lond will not know currentdump
4602: # Do a dump and make it look like a currentdump
1.822 albertel 4603: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4604: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4605: my %hash = @tmp;
4606: @tmp=();
1.424 matthew 4607: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4608: } else {
4609: my @pairs=split(/\&/,$rep);
1.800 albertel 4610: foreach my $pair (@pairs) {
4611: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4612: my ($symb,$param) = split(/:/,$key);
4613: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4614: &thaw_unescape($value);
1.319 matthew 4615: }
1.191 harris41 4616: }
1.12 www 4617: return %returnhash;
1.424 matthew 4618: }
4619:
4620: sub convert_dump_to_currentdump{
4621: my %hash = %{shift()};
4622: my %returnhash;
4623: # Code ripped from lond, essentially. The only difference
4624: # here is the unescaping done by lonnet::dump(). Conceivably
4625: # we might run in to problems with parameter names =~ /^v\./
4626: while (my ($key,$value) = each(%hash)) {
4627: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4628: $symb = &unescape($symb);
4629: $param = &unescape($param);
1.424 matthew 4630: next if ($v eq 'version' || $symb eq 'keys');
4631: next if (exists($returnhash{$symb}) &&
4632: exists($returnhash{$symb}->{$param}) &&
4633: $returnhash{$symb}->{'v.'.$param} > $v);
4634: $returnhash{$symb}->{$param}=$value;
4635: $returnhash{$symb}->{'v.'.$param}=$v;
4636: }
4637: #
4638: # Remove all of the keys in the hashes which keep track of
4639: # the version of the parameter.
4640: while (my ($symb,$param_hash) = each(%returnhash)) {
4641: # use a foreach because we are going to delete from the hash.
4642: foreach my $key (keys(%$param_hash)) {
4643: delete($param_hash->{$key}) if ($key =~ /^v\./);
4644: }
4645: }
4646: return \%returnhash;
1.12 www 4647: }
4648:
1.627 albertel 4649: # ------------------------------------------------------ critical inc interface
4650:
4651: sub cinc {
4652: return &inc(@_,'critical');
4653: }
4654:
1.449 matthew 4655: # --------------------------------------------------------------- inc interface
4656:
4657: sub inc {
1.627 albertel 4658: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4659: if (!$udomain) { $udomain=$env{'user.domain'}; }
4660: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4661: my $uhome=&homeserver($uname,$udomain);
4662: my $items='';
4663: if (! ref($store)) {
4664: # got a single value, so use that instead
4665: $items = &escape($store).'=&';
4666: } elsif (ref($store) eq 'SCALAR') {
4667: $items = &escape($$store).'=&';
4668: } elsif (ref($store) eq 'ARRAY') {
4669: $items = join('=&',map {&escape($_);} @{$store});
4670: } elsif (ref($store) eq 'HASH') {
4671: while (my($key,$value) = each(%{$store})) {
4672: $items.= &escape($key).'='.&escape($value).'&';
4673: }
4674: }
4675: $items=~s/\&$//;
1.627 albertel 4676: if ($critical) {
4677: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4678: } else {
4679: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4680: }
1.449 matthew 4681: }
4682:
1.12 www 4683: # --------------------------------------------------------------- put interface
4684:
4685: sub put {
1.134 albertel 4686: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4687: if (!$udomain) { $udomain=$env{'user.domain'}; }
4688: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4689: my $uhome=&homeserver($uname,$udomain);
1.12 www 4690: my $items='';
1.800 albertel 4691: foreach my $item (keys(%$storehash)) {
4692: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4693: }
1.12 www 4694: $items=~s/\&$//;
1.134 albertel 4695: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4696: }
4697:
1.631 albertel 4698: # ------------------------------------------------------------ newput interface
4699:
4700: sub newput {
4701: my ($namespace,$storehash,$udomain,$uname)=@_;
4702: if (!$udomain) { $udomain=$env{'user.domain'}; }
4703: if (!$uname) { $uname=$env{'user.name'}; }
4704: my $uhome=&homeserver($uname,$udomain);
4705: my $items='';
4706: foreach my $key (keys(%$storehash)) {
4707: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4708: }
4709: $items=~s/\&$//;
4710: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4711: }
4712:
4713: # --------------------------------------------------------- putstore interface
4714:
1.524 raeburn 4715: sub putstore {
1.715 albertel 4716: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4717: if (!$udomain) { $udomain=$env{'user.domain'}; }
4718: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4719: my $uhome=&homeserver($uname,$udomain);
4720: my $items='';
1.715 albertel 4721: foreach my $key (keys(%$storehash)) {
4722: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4723: }
1.715 albertel 4724: $items=~s/\&$//;
1.716 albertel 4725: my $esc_symb=&escape($symb);
4726: my $esc_v=&escape($version);
1.715 albertel 4727: my $reply =
1.716 albertel 4728: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4729: $uhome);
4730: if ($reply eq 'unknown_cmd') {
1.716 albertel 4731: # gfall back to way things use to be done
1.715 albertel 4732: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4733: $uname);
1.524 raeburn 4734: }
1.715 albertel 4735: return $reply;
4736: }
4737:
4738: sub old_putstore {
1.716 albertel 4739: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4740: if (!$udomain) { $udomain=$env{'user.domain'}; }
4741: if (!$uname) { $uname=$env{'user.name'}; }
4742: my $uhome=&homeserver($uname,$udomain);
4743: my %newstorehash;
1.800 albertel 4744: foreach my $item (keys(%$storehash)) {
4745: my $key = $version.':'.&escape($symb).':'.$item;
4746: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4747: }
4748: my $items='';
4749: my %allitems = ();
1.800 albertel 4750: foreach my $item (keys(%newstorehash)) {
4751: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4752: my $key = $1.':keys:'.$2;
4753: $allitems{$key} .= $3.':';
4754: }
1.800 albertel 4755: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4756: }
1.800 albertel 4757: foreach my $item (keys(%allitems)) {
4758: $allitems{$item} =~ s/\:$//;
4759: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4760: }
4761: $items=~s/\&$//;
4762: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4763: }
4764:
1.47 www 4765: # ------------------------------------------------------ critical put interface
4766:
4767: sub cput {
1.134 albertel 4768: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4769: if (!$udomain) { $udomain=$env{'user.domain'}; }
4770: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4771: my $uhome=&homeserver($uname,$udomain);
1.47 www 4772: my $items='';
1.800 albertel 4773: foreach my $item (keys(%$storehash)) {
4774: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4775: }
1.47 www 4776: $items=~s/\&$//;
1.134 albertel 4777: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4778: }
4779:
4780: # -------------------------------------------------------------- eget interface
4781:
4782: sub eget {
1.133 albertel 4783: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4784: my $items='';
1.800 albertel 4785: foreach my $item (@$storearr) {
4786: $items.=&escape($item).'&';
1.191 harris41 4787: }
1.12 www 4788: $items=~s/\&$//;
1.620 albertel 4789: if (!$udomain) { $udomain=$env{'user.domain'}; }
4790: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4791: my $uhome=&homeserver($uname,$udomain);
4792: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4793: my @pairs=split(/\&/,$rep);
4794: my %returnhash=();
1.42 www 4795: my $i=0;
1.800 albertel 4796: foreach my $item (@$storearr) {
4797: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4798: $i++;
1.191 harris41 4799: }
1.12 www 4800: return %returnhash;
4801: }
4802:
1.667 albertel 4803: # ------------------------------------------------------------ tmpput interface
4804: sub tmpput {
1.802 raeburn 4805: my ($storehash,$server,$context)=@_;
1.667 albertel 4806: my $items='';
1.800 albertel 4807: foreach my $item (keys(%$storehash)) {
4808: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4809: }
4810: $items=~s/\&$//;
1.802 raeburn 4811: if (defined($context)) {
4812: $items .= ':'.&escape($context);
4813: }
1.667 albertel 4814: return &reply("tmpput:$items",$server);
4815: }
4816:
4817: # ------------------------------------------------------------ tmpget interface
4818: sub tmpget {
1.688 albertel 4819: my ($token,$server)=@_;
4820: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4821: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4822: my %returnhash;
4823: foreach my $item (split(/\&/,$rep)) {
4824: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4825: next if ($key =~ /^error: 2 /);
1.667 albertel 4826: $returnhash{&unescape($key)}=&thaw_unescape($value);
4827: }
4828: return %returnhash;
4829: }
4830:
1.688 albertel 4831: # ------------------------------------------------------------ tmpget interface
4832: sub tmpdel {
4833: my ($token,$server)=@_;
4834: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4835: return &reply("tmpdel:$token",$server);
4836: }
4837:
1.765 albertel 4838: # -------------------------------------------------- portfolio access checking
4839:
4840: sub portfolio_access {
1.766 albertel 4841: my ($requrl) = @_;
1.765 albertel 4842: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4843: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4844: if ($result) {
4845: my %setters;
4846: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4847: my ($startblock,$endblock) =
4848: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4849: if ($startblock && $endblock) {
4850: return 'B';
4851: }
4852: } else {
4853: my ($startblock,$endblock) =
4854: &Apache::loncommon::blockcheck(\%setters,'port');
4855: if ($startblock && $endblock) {
4856: return 'B';
4857: }
4858: }
4859: }
1.765 albertel 4860: if ($result eq 'ok') {
1.766 albertel 4861: return 'F';
1.765 albertel 4862: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4863: return 'A';
1.765 albertel 4864: }
1.766 albertel 4865: return '';
1.765 albertel 4866: }
4867:
4868: sub get_portfolio_access {
1.767 albertel 4869: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4870:
4871: if (!ref($access_hash)) {
4872: my $current_perms = &get_portfile_permissions($udom,$unum);
4873: my %access_controls = &get_access_controls($current_perms,$group,
4874: $file_name);
4875: $access_hash = $access_controls{$file_name};
4876: }
4877:
1.765 albertel 4878: my ($public,$guest,@domains,@users,@courses,@groups);
4879: my $now = time;
4880: if (ref($access_hash) eq 'HASH') {
4881: foreach my $key (keys(%{$access_hash})) {
4882: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4883: if ($start > $now) {
4884: next;
4885: }
4886: if ($end && $end<$now) {
4887: next;
4888: }
4889: if ($scope eq 'public') {
4890: $public = $key;
4891: last;
4892: } elsif ($scope eq 'guest') {
4893: $guest = $key;
4894: } elsif ($scope eq 'domains') {
4895: push(@domains,$key);
4896: } elsif ($scope eq 'users') {
4897: push(@users,$key);
4898: } elsif ($scope eq 'course') {
4899: push(@courses,$key);
4900: } elsif ($scope eq 'group') {
4901: push(@groups,$key);
4902: }
4903: }
4904: if ($public) {
4905: return 'ok';
4906: }
4907: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4908: if ($guest) {
4909: return $guest;
4910: }
4911: } else {
4912: if (@domains > 0) {
4913: foreach my $domkey (@domains) {
4914: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4915: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4916: return 'ok';
4917: }
4918: }
4919: }
4920: }
4921: if (@users > 0) {
4922: foreach my $userkey (@users) {
1.865 raeburn 4923: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4924: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4925: if (ref($item) eq 'HASH') {
4926: if (($item->{'uname'} eq $env{'user.name'}) &&
4927: ($item->{'udom'} eq $env{'user.domain'})) {
4928: return 'ok';
4929: }
4930: }
4931: }
4932: }
1.765 albertel 4933: }
4934: }
4935: my %roleshash;
4936: my @courses_and_groups = @courses;
4937: push(@courses_and_groups,@groups);
4938: if (@courses_and_groups > 0) {
4939: my (%allgroups,%allroles);
4940: my ($start,$end,$role,$sec,$group);
4941: foreach my $envkey (%env) {
1.1056.4.1 raeburn 4942: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4943: my $cid = $2.'_'.$3;
4944: if ($1 eq 'gr') {
4945: $group = $4;
4946: $allgroups{$cid}{$group} = $env{$envkey};
4947: } else {
4948: if ($4 eq '') {
4949: $sec = 'none';
4950: } else {
4951: $sec = $4;
4952: }
4953: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4954: }
1.811 albertel 4955: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4956: my $cid = $2.'_'.$3;
4957: if ($4 eq '') {
4958: $sec = 'none';
4959: } else {
4960: $sec = $4;
4961: }
4962: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4963: }
4964: }
4965: if (keys(%allroles) == 0) {
4966: return;
4967: }
4968: foreach my $key (@courses_and_groups) {
4969: my %content = %{$$access_hash{$key}};
4970: my $cnum = $content{'number'};
4971: my $cdom = $content{'domain'};
4972: my $cid = $cdom.'_'.$cnum;
4973: if (!exists($allroles{$cid})) {
4974: next;
4975: }
4976: foreach my $role_id (keys(%{$content{'roles'}})) {
4977: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4978: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4979: my @status = @{$content{'roles'}{$role_id}{'access'}};
4980: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4981: foreach my $role (keys(%{$allroles{$cid}})) {
4982: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4983: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4984: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4985: if (grep/^all$/,@sections) {
4986: return 'ok';
4987: } else {
4988: if (grep/^$sec$/,@sections) {
4989: return 'ok';
4990: }
4991: }
4992: }
4993: }
4994: if (keys(%{$allgroups{$cid}}) == 0) {
4995: if (grep/^none$/,@groups) {
4996: return 'ok';
4997: }
4998: } else {
4999: if (grep/^all$/,@groups) {
5000: return 'ok';
5001: }
5002: foreach my $group (keys(%{$allgroups{$cid}})) {
5003: if (grep/^$group$/,@groups) {
5004: return 'ok';
5005: }
5006: }
5007: }
5008: }
5009: }
5010: }
5011: }
5012: }
5013: if ($guest) {
5014: return $guest;
5015: }
5016: }
5017: }
5018: return;
5019: }
5020:
5021: sub course_group_datechecker {
5022: my ($dates,$now,$status) = @_;
5023: my ($start,$end) = split(/\./,$dates);
5024: if (!$start && !$end) {
5025: return 'ok';
5026: }
5027: if (grep/^active$/,@{$status}) {
5028: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5029: return 'ok';
5030: }
5031: }
5032: if (grep/^previous$/,@{$status}) {
5033: if ($end > $now ) {
5034: return 'ok';
5035: }
5036: }
5037: if (grep/^future$/,@{$status}) {
5038: if ($start > $now) {
5039: return 'ok';
5040: }
5041: }
5042: return;
5043: }
5044:
5045: sub parse_portfolio_url {
5046: my ($url) = @_;
5047:
5048: my ($type,$udom,$unum,$group,$file_name);
5049:
1.823 albertel 5050: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5051: $type = 1;
5052: $udom = $1;
5053: $unum = $2;
5054: $file_name = $3;
1.823 albertel 5055: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5056: $type = 2;
5057: $udom = $1;
5058: $unum = $2;
5059: $group = $3;
5060: $file_name = $3.'/'.$4;
5061: }
5062: if (wantarray) {
5063: return ($type,$udom,$unum,$file_name,$group);
5064: }
5065: return $type;
5066: }
5067:
5068: sub is_portfolio_url {
5069: my ($url) = @_;
5070: return scalar(&parse_portfolio_url($url));
5071: }
5072:
1.798 raeburn 5073: sub is_portfolio_file {
5074: my ($file) = @_;
1.820 raeburn 5075: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5076: return 1;
5077: }
5078: return;
5079: }
5080:
1.976 raeburn 5081: sub usertools_access {
1.1056.4.9 raeburn 5082: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref) = @_;
1.985 raeburn 5083: my ($access,%tools);
5084: if ($context eq '') {
5085: $context = 'tools';
5086: }
5087: if ($context eq 'requestcourses') {
5088: %tools = (
5089: official => 1,
5090: unofficial => 1,
1.1006 raeburn 5091: community => 1,
1.985 raeburn 5092: );
5093: } else {
5094: %tools = (
5095: aboutme => 1,
5096: blog => 1,
5097: portfolio => 1,
5098: );
5099: }
1.976 raeburn 5100: return if (!defined($tools{$tool}));
5101:
5102: if ((!defined($udom)) || (!defined($uname))) {
5103: $udom = $env{'user.domain'};
5104: $uname = $env{'user.name'};
5105: }
5106:
1.978 raeburn 5107: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5108: if ($action ne 'reload') {
1.985 raeburn 5109: if ($context eq 'requestcourses') {
5110: return $env{'environment.canrequest.'.$tool};
5111: } else {
5112: return $env{'environment.availabletools.'.$tool};
5113: }
5114: }
1.976 raeburn 5115: }
5116:
5117: my ($toolstatus,$inststatus);
5118:
1.985 raeburn 5119: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5120: ($action ne 'reload')) {
5121: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5122: $inststatus = $env{'environment.inststatus'};
5123: } else {
1.1056.4.9 raeburn 5124: if (ref($userenvref) eq 'HASH') {
5125: $toolstatus = $userenvref->{$context.'.'.$tool};
5126: $inststatus = $userenvref->{'inststatus'};
5127: } else {
5128: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5129: $toolstatus = $userenv{$context.'.'.$tool};
5130: $inststatus = $userenv{'inststatus'};
5131: }
1.976 raeburn 5132: }
5133:
5134: if ($toolstatus ne '') {
5135: if ($toolstatus) {
5136: $access = 1;
5137: } else {
5138: $access = 0;
5139: }
5140: return $access;
5141: }
5142:
1.1056.4.9 raeburn 5143: my ($is_adv,%domdef);
5144: if (ref($is_advref) eq 'HASH') {
5145: $is_adv = $is_advref->{'is_adv'};
5146: } else {
5147: $is_adv = &is_advanced_user($udom,$uname);
5148: }
5149: if (ref($domdefref) eq 'HASH') {
5150: %domdef = %{$domdefref};
5151: } else {
5152: %domdef = &get_domain_defaults($udom);
5153: }
1.976 raeburn 5154: if (ref($domdef{$tool}) eq 'HASH') {
5155: if ($is_adv) {
5156: if ($domdef{$tool}{'_LC_adv'} ne '') {
5157: if ($domdef{$tool}{'_LC_adv'}) {
5158: $access = 1;
5159: } else {
5160: $access = 0;
5161: }
5162: return $access;
5163: }
5164: }
5165: if ($inststatus ne '') {
5166: my ($hasaccess,$hasnoaccess);
5167: foreach my $affiliation (split(/:/,$inststatus)) {
5168: if ($domdef{$tool}{$affiliation} ne '') {
5169: if ($domdef{$tool}{$affiliation}) {
5170: $hasaccess = 1;
5171: } else {
5172: $hasnoaccess = 1;
5173: }
5174: }
5175: }
5176: if ($hasaccess || $hasnoaccess) {
5177: if ($hasaccess) {
5178: $access = 1;
5179: } elsif ($hasnoaccess) {
5180: $access = 0;
5181: }
5182: return $access;
5183: }
5184: } else {
5185: if ($domdef{$tool}{'default'} ne '') {
5186: if ($domdef{$tool}{'default'}) {
5187: $access = 1;
5188: } elsif ($domdef{$tool}{'default'} == 0) {
5189: $access = 0;
5190: }
5191: return $access;
5192: }
5193: }
5194: } else {
1.985 raeburn 5195: if ($context eq 'tools') {
5196: $access = 1;
5197: } else {
5198: $access = 0;
5199: }
1.976 raeburn 5200: return $access;
5201: }
5202: }
5203:
1.1050 raeburn 5204: sub is_course_owner {
5205: my ($cdom,$cnum,$udom,$uname) = @_;
5206: if (($udom eq '') || ($uname eq '')) {
5207: $udom = $env{'user.domain'};
5208: $uname = $env{'user.name'};
5209: }
5210: unless (($udom eq '') || ($uname eq '')) {
5211: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5212: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5213: return 1;
5214: } else {
5215: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5216: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5217: return 1;
5218: }
5219: }
5220: }
5221: }
5222: return;
5223: }
5224:
1.976 raeburn 5225: sub is_advanced_user {
5226: my ($udom,$uname) = @_;
1.1056.4.10 raeburn 5227: if ($udom ne '' && $uname ne '') {
5228: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5229: return $env{'user.adv'};
5230: }
5231: }
1.976 raeburn 5232: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5233: my %allroles;
5234: my $is_adv;
5235: foreach my $role (keys(%roleshash)) {
5236: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5237: my $area = '/'.$tdomain.'/'.$trest;
5238: if ($sec ne '') {
5239: $area .= '/'.$sec;
5240: }
5241: if (($area ne '') && ($trole ne '')) {
5242: my $spec=$trole.'.'.$area;
5243: if ($trole =~ /^cr\//) {
5244: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5245: } elsif ($trole ne 'gr') {
5246: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5247: }
5248: }
5249: }
5250: foreach my $role (keys(%allroles)) {
5251: last if ($is_adv);
5252: foreach my $item (split(/:/,$allroles{$role})) {
5253: if ($item ne '') {
5254: my ($privilege,$restrictions)=split(/&/,$item);
5255: if ($privilege eq 'adv') {
5256: $is_adv = 1;
5257: last;
5258: }
5259: }
5260: }
5261: }
5262: return $is_adv;
5263: }
1.798 raeburn 5264:
1.1035 raeburn 5265: sub check_can_request {
1.1036 raeburn 5266: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5267: my $canreq = 0;
5268: my ($types,$typename) = &Apache::loncommon::course_types();
5269: my @options = ('approval','validate','autolimit');
5270: my $optregex = join('|',@options);
5271: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5272: foreach my $type (@{$types}) {
5273: if (&usertools_access($env{'user.name'},
5274: $env{'user.domain'},
5275: $type,undef,'requestcourses')) {
5276: $canreq ++;
1.1036 raeburn 5277: if (ref($request_domains) eq 'HASH') {
5278: push(@{$request_domains->{$type}},$env{'user.domain'});
5279: }
1.1035 raeburn 5280: if ($dom eq $env{'user.domain'}) {
5281: $can_request->{$type} = 1;
5282: }
5283: }
5284: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5285: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5286: if (@curr > 0) {
1.1036 raeburn 5287: foreach my $item (@curr) {
5288: if (ref($request_domains) eq 'HASH') {
5289: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5290: if ($otherdom ne '') {
5291: if (ref($request_domains->{$type}) eq 'ARRAY') {
5292: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5293: push(@{$request_domains->{$type}},$otherdom);
5294: }
5295: } else {
5296: push(@{$request_domains->{$type}},$otherdom);
5297: }
5298: }
5299: }
5300: }
5301: unless($dom eq $env{'user.domain'}) {
5302: $canreq ++;
1.1035 raeburn 5303: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5304: $can_request->{$type} = 1;
5305: }
5306: }
5307: }
5308: }
5309: }
5310: }
5311: return $canreq;
5312: }
5313:
1.341 www 5314: # ---------------------------------------------- Custom access rule evaluation
5315:
5316: sub customaccess {
5317: my ($priv,$uri)=@_;
1.807 albertel 5318: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5319: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5320: $udom = &LONCAPA::clean_domain($udom);
5321: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5322: my $access=0;
1.800 albertel 5323: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5324: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5325: if ($type eq 'user') {
5326: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5327: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5328: if ($tdom) {
5329: if ($tdom ne $env{'user.domain'}) { next; }
5330: }
1.896 albertel 5331: if ($tuname) {
5332: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5333: }
5334: $access=($effect eq 'allow');
5335: last;
5336: }
5337: } else {
5338: if ($role) {
5339: if ($role ne $urole) { next; }
5340: }
5341: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5342: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5343: if ($tdom) {
5344: if ($tdom ne $udom) { next; }
5345: }
5346: if ($tcrs) {
5347: if ($tcrs ne $ucrs) { next; }
5348: }
5349: if ($tsec) {
5350: if ($tsec ne $usec) { next; }
5351: }
5352: $access=($effect eq 'allow');
5353: last;
5354: }
5355: if ($realm eq '' && $role eq '') {
5356: $access=($effect eq 'allow');
5357: }
1.402 bowersj2 5358: }
1.341 www 5359: }
5360: return $access;
5361: }
5362:
1.103 harris41 5363: # ------------------------------------------------- Check for a user privilege
1.12 www 5364:
5365: sub allowed {
1.810 raeburn 5366: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5367: my $ver_orguri=$uri;
1.439 www 5368: $uri=&deversion($uri);
1.152 www 5369: my $orguri=$uri;
1.52 www 5370: $uri=&declutter($uri);
1.809 raeburn 5371:
1.810 raeburn 5372: if ($priv eq 'evb') {
5373: # Evade communication block restrictions for specified role in a course
5374: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5375: return $1;
5376: } else {
5377: return;
5378: }
5379: }
5380:
1.620 albertel 5381: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5382: # Free bre access to adm and meta resources
1.775 albertel 5383: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5384: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5385: && ($priv eq 'bre')) {
1.14 www 5386: return 'F';
1.159 www 5387: }
5388:
1.545 banghart 5389: # Free bre access to user's own portfolio contents
1.714 raeburn 5390: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5391: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5392: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5393: my %setters;
5394: my ($startblock,$endblock) =
5395: &Apache::loncommon::blockcheck(\%setters,'port');
5396: if ($startblock && $endblock) {
5397: return 'B';
5398: } else {
5399: return 'F';
5400: }
1.545 banghart 5401: }
5402:
1.762 raeburn 5403: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5404: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5405: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5406: if (exists($env{'request.course.id'})) {
5407: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5408: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5409: if (($domain eq $cdom) && ($name eq $cnum)) {
5410: my $courseprivid=$env{'request.course.id'};
5411: $courseprivid=~s/\_/\//;
5412: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5413: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5414: return $1;
1.762 raeburn 5415: } else {
5416: if ($env{'request.course.sec'}) {
5417: $courseprivid.='/'.$env{'request.course.sec'};
5418: }
5419: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5420: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5421: return $2;
5422: }
1.714 raeburn 5423: }
5424: }
5425: }
5426: }
5427:
1.159 www 5428: # Free bre to public access
5429:
5430: if ($priv eq 'bre') {
1.238 www 5431: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5432: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5433: return 'F';
5434: }
1.238 www 5435: if ($copyright eq 'priv') {
5436: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5437: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5438: return '';
5439: }
5440: }
5441: if ($copyright eq 'domain') {
5442: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5443: unless (($env{'user.domain'} eq $1) ||
5444: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5445: return '';
5446: }
1.262 matthew 5447: }
1.620 albertel 5448: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5449: # Library role, so allow browsing of resources in this domain.
5450: return 'F';
1.238 www 5451: }
1.341 www 5452: if ($copyright eq 'custom') {
5453: unless (&customaccess($priv,$uri)) { return ''; }
5454: }
1.14 www 5455: }
1.264 matthew 5456: # Domain coordinator is trying to create a course
1.620 albertel 5457: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5458: # uri is the requested domain in this case.
5459: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5460: # a role of dc for the domain in question.
1.620 albertel 5461: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5462: }
1.29 www 5463:
1.52 www 5464: my $thisallowed='';
5465: my $statecond=0;
5466: my $courseprivid='';
5467:
1.1039 raeburn 5468: my $ownaccess;
1.1043 raeburn 5469: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5470: if (($priv eq 'bro') && ($env{'user.author'})) {
5471: if ($uri eq '') {
5472: $ownaccess = 1;
5473: } else {
5474: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5475: my $udom = $env{'user.domain'};
5476: my $uname = $env{'user.name'};
5477: if ($uri =~ m{^\Q$udom\E/?$}) {
5478: $ownaccess = 1;
1.1040 raeburn 5479: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5480: unless ($uri =~ m{\.\./}) {
5481: $ownaccess = 1;
5482: }
5483: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5484: my $now = time;
5485: if ($uri =~ m{^([^/]+)/?$}) {
5486: my $adom = $1;
5487: foreach my $key (keys(%env)) {
1.1042 raeburn 5488: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5489: my ($start,$end) = split('.',$env{$key});
5490: if (($now >= $start) && (!$end || $end < $now)) {
5491: $ownaccess = 1;
5492: last;
5493: }
5494: }
5495: }
5496: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5497: my $adom = $1;
5498: my $aname = $2;
1.1042 raeburn 5499: foreach my $role ('ca','aa') {
5500: if ($env{"user.role.$role./$adom/$aname"}) {
5501: my ($start,$end) =
5502: split('.',$env{"user.role.$role./$adom/$aname"});
5503: if (($now >= $start) && (!$end || $end < $now)) {
5504: $ownaccess = 1;
5505: last;
5506: }
1.1039 raeburn 5507: }
5508: }
5509: }
5510: }
5511: }
5512: }
5513: }
5514:
1.52 www 5515: # Course
5516:
1.620 albertel 5517: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5518: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5519: $thisallowed.=$1;
5520: }
1.52 www 5521: }
1.29 www 5522:
1.52 www 5523: # Domain
5524:
1.620 albertel 5525: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5526: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5527: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5528: $thisallowed.=$1;
5529: }
1.12 www 5530: }
1.52 www 5531:
5532: # Course: uri itself is a course
1.66 www 5533: my $courseuri=$uri;
5534: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5535: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5536:
1.620 albertel 5537: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5538: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5539: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5540: $thisallowed.=$1;
5541: }
1.12 www 5542: }
1.29 www 5543:
1.665 albertel 5544: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5545: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5546: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5547: $thisallowed='';
1.671 raeburn 5548: my ($match)=&is_on_map($uri);
5549: if ($match) {
5550: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5551: =~/\Q$priv\E\&([^\:]*)/) {
5552: $thisallowed.=$1;
5553: }
5554: } else {
1.705 albertel 5555: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5556: if ($refuri) {
5557: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5558: $thisallowed='F';
1.671 raeburn 5559: } else {
5560: $refuri=&declutter($refuri);
5561: my ($match) = &is_on_map($refuri);
5562: if ($match) {
5563: $thisallowed='F';
5564: }
1.669 raeburn 5565: }
1.671 raeburn 5566: }
5567: }
1.314 www 5568: }
1.492 albertel 5569:
1.766 albertel 5570: if ($priv eq 'bre'
5571: && $thisallowed ne 'F'
5572: && $thisallowed ne '2'
5573: && &is_portfolio_url($uri)) {
5574: $thisallowed = &portfolio_access($uri);
5575: }
5576:
1.52 www 5577: # Full access at system, domain or course-wide level? Exit.
1.29 www 5578: if ($thisallowed=~/F/) {
5579: return 'F';
5580: }
5581:
1.52 www 5582: # If this is generating or modifying users, exit with special codes
1.29 www 5583:
1.643 www 5584: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5585: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5586: my ($audom,$auname)=split('/',$uri);
1.643 www 5587: # no author name given, so this just checks on the general right to make a co-author in this domain
5588: unless ($auname) { return $thisallowed; }
5589: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5590: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5591: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5592: ($audom ne $env{'request.role.domain'}))) { return ''; }
5593: }
1.52 www 5594: return $thisallowed;
5595: }
5596: #
1.103 harris41 5597: # Gathered so far: system, domain and course wide privileges
1.52 www 5598: #
5599: # Course: See if uri or referer is an individual resource that is part of
5600: # the course
5601:
1.620 albertel 5602: if ($env{'request.course.id'}) {
1.232 www 5603:
1.620 albertel 5604: $courseprivid=$env{'request.course.id'};
5605: if ($env{'request.course.sec'}) {
5606: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5607: }
5608: $courseprivid=~s/\_/\//;
5609: my $checkreferer=1;
1.232 www 5610: my ($match,$cond)=&is_on_map($uri);
5611: if ($match) {
5612: $statecond=$cond;
1.620 albertel 5613: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5614: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5615: $thisallowed.=$1;
5616: $checkreferer=0;
5617: }
1.29 www 5618: }
1.83 www 5619:
1.148 www 5620: if ($checkreferer) {
1.620 albertel 5621: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5622: unless ($refuri) {
1.800 albertel 5623: foreach my $key (keys(%env)) {
5624: if ($key=~/^httpref\..*\*/) {
5625: my $pattern=$key;
1.156 www 5626: $pattern=~s/^httpref\.\/res\///;
1.148 www 5627: $pattern=~s/\*/\[\^\/\]\+/g;
5628: $pattern=~s/\//\\\//g;
1.152 www 5629: if ($orguri=~/$pattern/) {
1.800 albertel 5630: $refuri=$env{$key};
1.148 www 5631: }
5632: }
1.191 harris41 5633: }
1.148 www 5634: }
1.232 www 5635:
1.148 www 5636: if ($refuri) {
1.152 www 5637: $refuri=&declutter($refuri);
1.232 www 5638: my ($match,$cond)=&is_on_map($refuri);
5639: if ($match) {
5640: my $refstatecond=$cond;
1.620 albertel 5641: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5642: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5643: $thisallowed.=$1;
1.53 www 5644: $uri=$refuri;
5645: $statecond=$refstatecond;
1.52 www 5646: }
5647: }
1.148 www 5648: }
1.29 www 5649: }
1.52 www 5650: }
1.29 www 5651:
1.52 www 5652: #
1.103 harris41 5653: # Gathered now: all privileges that could apply, and condition number
1.52 www 5654: #
5655: #
5656: # Full or no access?
5657: #
1.29 www 5658:
1.52 www 5659: if ($thisallowed=~/F/) {
5660: return 'F';
5661: }
1.29 www 5662:
1.52 www 5663: unless ($thisallowed) {
5664: return '';
5665: }
1.29 www 5666:
1.52 www 5667: # Restrictions exist, deal with them
5668: #
5669: # C:according to course preferences
5670: # R:according to resource settings
5671: # L:unless locked
5672: # X:according to user session state
5673: #
5674:
5675: # Possibly locked functionality, check all courses
1.54 www 5676: # Locks might take effect only after 10 minutes cache expiration for other
5677: # courses, and 2 minutes for current course
1.52 www 5678:
5679: my $envkey;
5680: if ($thisallowed=~/L/) {
1.1000 raeburn 5681: foreach $envkey (keys(%env)) {
1.54 www 5682: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5683: my $courseid=$2;
5684: my $roleid=$1.'.'.$2;
1.92 www 5685: $courseid=~s/^\///;
1.54 www 5686: my $expiretime=600;
1.620 albertel 5687: if ($env{'request.role'} eq $roleid) {
1.54 www 5688: $expiretime=120;
5689: }
5690: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5691: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5692: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5693: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5694: }
1.620 albertel 5695: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5696: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5697: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5698: &log($env{'user.domain'},$env{'user.name'},
5699: $env{'user.home'},
1.57 www 5700: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5701: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5702: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5703: return '';
5704: }
5705: }
1.620 albertel 5706: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5707: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5708: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5709: &log($env{'user.domain'},$env{'user.name'},
5710: $env{'user.home'},
1.57 www 5711: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5712: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5713: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5714: return '';
5715: }
5716: }
5717: }
1.29 www 5718: }
1.52 www 5719: }
5720:
5721: #
5722: # Rest of the restrictions depend on selected course
5723: #
5724:
1.620 albertel 5725: unless ($env{'request.course.id'}) {
1.766 albertel 5726: if ($thisallowed eq 'A') {
5727: return 'A';
1.814 raeburn 5728: } elsif ($thisallowed eq 'B') {
5729: return 'B';
1.766 albertel 5730: } else {
5731: return '1';
5732: }
1.52 www 5733: }
1.29 www 5734:
1.52 www 5735: #
5736: # Now user is definitely in a course
5737: #
1.53 www 5738:
5739:
5740: # Course preferences
5741:
5742: if ($thisallowed=~/C/) {
1.620 albertel 5743: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5744: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5745: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5746: =~/\Q$rolecode\E/) {
1.689 albertel 5747: if ($priv ne 'pch') {
5748: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5749: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5750: $env{'request.course.id'});
5751: }
1.237 www 5752: return '';
5753: }
5754:
1.620 albertel 5755: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5756: =~/\Q$unamedom\E/) {
1.689 albertel 5757: if ($priv ne 'pch') {
5758: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5759: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5760: $env{'request.course.id'});
5761: }
1.54 www 5762: return '';
5763: }
1.53 www 5764: }
5765:
5766: # Resource preferences
5767:
5768: if ($thisallowed=~/R/) {
1.620 albertel 5769: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5770: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5771: if ($priv ne 'pch') {
5772: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5773: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5774: }
5775: return '';
1.54 www 5776: }
1.53 www 5777: }
1.30 www 5778:
1.246 www 5779: # Restricted by state or randomout?
1.30 www 5780:
1.52 www 5781: if ($thisallowed=~/X/) {
1.620 albertel 5782: if ($env{'acc.randomout'}) {
1.579 albertel 5783: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5784: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5785: return '';
5786: }
1.247 www 5787: }
5788: if (&condval($statecond)) {
1.52 www 5789: return '2';
5790: } else {
5791: return '';
5792: }
5793: }
1.30 www 5794:
1.766 albertel 5795: if ($thisallowed eq 'A') {
5796: return 'A';
1.814 raeburn 5797: } elsif ($thisallowed eq 'B') {
5798: return 'B';
1.766 albertel 5799: }
1.52 www 5800: return 'F';
1.232 www 5801: }
5802:
1.710 albertel 5803: sub split_uri_for_cond {
5804: my $uri=&deversion(&declutter(shift));
5805: my @uriparts=split(/\//,$uri);
5806: my $filename=pop(@uriparts);
5807: my $pathname=join('/',@uriparts);
5808: return ($pathname,$filename);
5809: }
1.232 www 5810: # --------------------------------------------------- Is a resource on the map?
5811:
5812: sub is_on_map {
1.710 albertel 5813: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5814: #Trying to find the conditional for the file
1.620 albertel 5815: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5816: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5817: if ($match) {
1.289 bowersj2 5818: return (1,$1);
5819: } else {
1.434 www 5820: return (0,0);
1.289 bowersj2 5821: }
1.12 www 5822: }
5823:
1.427 www 5824: # --------------------------------------------------------- Get symb from alias
5825:
5826: sub get_symb_from_alias {
5827: my $symb=shift;
5828: my ($map,$resid,$url)=&decode_symb($symb);
5829: # Already is a symb
5830: if ($url) { return $symb; }
5831: # Must be an alias
5832: my $aliassymb='';
5833: my %bighash;
1.620 albertel 5834: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5835: &GDBM_READER(),0640)) {
5836: my $rid=$bighash{'mapalias_'.$symb};
5837: if ($rid) {
5838: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5839: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5840: $resid,$bighash{'src_'.$rid});
1.427 www 5841: }
5842: untie %bighash;
5843: }
5844: return $aliassymb;
5845: }
5846:
1.12 www 5847: # ----------------------------------------------------------------- Define Role
5848:
5849: sub definerole {
5850: if (allowed('mcr','/')) {
5851: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5852: foreach my $role (split(':',$sysrole)) {
5853: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5854: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5855: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5856: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5857: return "refused:s:$crole&$cqual";
5858: }
5859: }
1.191 harris41 5860: }
1.800 albertel 5861: foreach my $role (split(':',$domrole)) {
5862: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5863: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5864: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5865: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5866: return "refused:d:$crole&$cqual";
5867: }
5868: }
1.191 harris41 5869: }
1.800 albertel 5870: foreach my $role (split(':',$courole)) {
5871: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5872: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5873: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5874: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5875: return "refused:c:$crole&$cqual";
5876: }
5877: }
1.191 harris41 5878: }
1.620 albertel 5879: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5880: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5881: "rolesdef_$rolename=".
5882: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5883: return reply($command,$env{'user.home'});
1.12 www 5884: } else {
5885: return 'refused';
5886: }
1.105 harris41 5887: }
5888:
5889: # ---------------- Make a metadata query against the network of library servers
5890:
5891: sub metadata_query {
1.244 matthew 5892: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5893: my %rhash;
1.845 albertel 5894: my %libserv = &all_library();
1.244 matthew 5895: my @server_list = (defined($server_array) ? @$server_array
5896: : keys(%libserv) );
5897: for my $server (@server_list) {
1.118 harris41 5898: unless ($custom or $customshow) {
5899: my $reply=&reply("querysend:".&escape($query),$server);
5900: $rhash{$server}=$reply;
5901: }
5902: else {
5903: my $reply=&reply("querysend:".&escape($query).':'.
5904: &escape($custom).':'.&escape($customshow),
5905: $server);
5906: $rhash{$server}=$reply;
5907: }
1.112 harris41 5908: }
1.118 harris41 5909: return \%rhash;
1.240 www 5910: }
5911:
5912: # ----------------------------------------- Send log queries and wait for reply
5913:
5914: sub log_query {
5915: my ($uname,$udom,$query,%filters)=@_;
5916: my $uhome=&homeserver($uname,$udom);
5917: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5918: my $uhost=&hostname($uhome);
1.800 albertel 5919: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5920: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5921: $uhome);
1.479 albertel 5922: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5923: return get_query_reply($queryid);
5924: }
5925:
1.818 raeburn 5926: # -------------------------- Update MySQL table for portfolio file
5927:
5928: sub update_portfolio_table {
1.821 raeburn 5929: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5930: if ($group ne '') {
5931: $file_name =~s /^\Q$group\E//;
5932: }
1.818 raeburn 5933: my $homeserver = &homeserver($uname,$udom);
5934: my $queryid=
1.821 raeburn 5935: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5936: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5937: my $reply = &get_query_reply($queryid);
5938: return $reply;
5939: }
5940:
1.899 raeburn 5941: # -------------------------- Update MySQL allusers table
5942:
5943: sub update_allusers_table {
5944: my ($uname,$udom,$names) = @_;
5945: my $homeserver = &homeserver($uname,$udom);
5946: my $queryid=
5947: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5948: 'lastname='.&escape($names->{'lastname'}).'%%'.
5949: 'firstname='.&escape($names->{'firstname'}).'%%'.
5950: 'middlename='.&escape($names->{'middlename'}).'%%'.
5951: 'generation='.&escape($names->{'generation'}).'%%'.
5952: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5953: 'id='.&escape($names->{'id'}),$homeserver);
1.1056.4.4 raeburn 5954: return;
1.899 raeburn 5955: }
5956:
1.508 raeburn 5957: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5958:
5959: sub fetch_enrollment_query {
1.511 raeburn 5960: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5961: my $homeserver;
1.547 raeburn 5962: my $maxtries = 1;
1.508 raeburn 5963: if ($context eq 'automated') {
5964: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5965: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5966: } else {
5967: $homeserver = &homeserver($cnum,$dom);
5968: }
1.838 albertel 5969: my $host=&hostname($homeserver);
1.506 raeburn 5970: my $cmd = '';
1.1000 raeburn 5971: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5972: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5973: }
5974: $cmd =~ s/%%$//;
5975: $cmd = &escape($cmd);
5976: my $query = 'fetchenrollment';
1.620 albertel 5977: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5978: unless ($queryid=~/^\Q$host\E\_/) {
5979: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5980: return 'error: '.$queryid;
5981: }
1.506 raeburn 5982: my $reply = &get_query_reply($queryid);
1.547 raeburn 5983: my $tries = 1;
5984: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5985: $reply = &get_query_reply($queryid);
5986: $tries ++;
5987: }
1.526 raeburn 5988: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5989: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5990: } else {
1.901 albertel 5991: my @responses = split(/:/,$reply);
1.515 raeburn 5992: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5993: foreach my $line (@responses) {
5994: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5995: $$replyref{$key} = $value;
5996: }
5997: } else {
1.506 raeburn 5998: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5999: foreach my $line (@responses) {
6000: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6001: $$replyref{$key} = $value;
6002: if ($value > 0) {
1.800 albertel 6003: foreach my $item (@{$$affiliatesref{$key}}) {
6004: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6005: my $destname = $pathname.'/'.$filename;
6006: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6007: if ($xml_classlist =~ /^error/) {
6008: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6009: } else {
1.506 raeburn 6010: if ( open(FILE,">$destname") ) {
6011: print FILE &unescape($xml_classlist);
6012: close(FILE);
1.526 raeburn 6013: } else {
6014: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6015: }
6016: }
6017: }
6018: }
6019: }
6020: }
6021: return 'ok';
6022: }
6023: return 'error';
6024: }
6025:
1.242 www 6026: sub get_query_reply {
6027: my $queryid=shift;
1.240 www 6028: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
6029: my $reply='';
6030: for (1..100) {
6031: sleep 2;
6032: if (-e $replyfile.'.end') {
1.448 albertel 6033: if (open(my $fh,$replyfile)) {
1.904 albertel 6034: $reply = join('',<$fh>);
6035: close($fh);
1.240 www 6036: } else { return 'error: reply_file_error'; }
1.242 www 6037: return &unescape($reply);
6038: }
1.240 www 6039: }
1.242 www 6040: return 'timeout:'.$queryid;
1.240 www 6041: }
6042:
6043: sub courselog_query {
1.241 www 6044: #
6045: # possible filters:
6046: # url: url or symb
6047: # username
6048: # domain
6049: # action: view, submit, grade
6050: # start: timestamp
6051: # end: timestamp
6052: #
1.240 www 6053: my (%filters)=@_;
1.620 albertel 6054: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6055: if ($filters{'url'}) {
6056: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6057: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6058: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6059: }
1.620 albertel 6060: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6061: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6062: return &log_query($cname,$cdom,'courselog',%filters);
6063: }
6064:
6065: sub userlog_query {
1.858 raeburn 6066: #
6067: # possible filters:
6068: # action: log check role
6069: # start: timestamp
6070: # end: timestamp
6071: #
1.240 www 6072: my ($uname,$udom,%filters)=@_;
6073: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6074: }
6075:
1.506 raeburn 6076: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6077:
6078: sub auto_run {
1.508 raeburn 6079: my ($cnum,$cdom) = @_;
1.876 raeburn 6080: my $response = 0;
6081: my $settings;
6082: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6083: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6084: $settings = $domconfig{'autoenroll'};
6085: if ($settings->{'run'} eq '1') {
6086: $response = 1;
6087: }
6088: } else {
1.934 raeburn 6089: my $homeserver;
6090: if (&is_course($cdom,$cnum)) {
6091: $homeserver = &homeserver($cnum,$cdom);
6092: } else {
6093: $homeserver = &domain($cdom,'primary');
6094: }
6095: if ($homeserver ne 'no_host') {
6096: $response = &reply('autorun:'.$cdom,$homeserver);
6097: }
1.876 raeburn 6098: }
1.506 raeburn 6099: return $response;
6100: }
1.776 albertel 6101:
1.506 raeburn 6102: sub auto_get_sections {
1.508 raeburn 6103: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6104: my $homeserver;
6105: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6106: $homeserver = &homeserver($cnum,$cdom);
6107: }
6108: if (!defined($homeserver)) {
6109: if ($cdom =~ /^$match_domain$/) {
6110: $homeserver = &domain($cdom,'primary');
6111: }
6112: }
6113: my @secs;
6114: if (defined($homeserver)) {
6115: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6116: unless ($response eq 'refused') {
6117: @secs = split(/:/,$response);
6118: }
1.506 raeburn 6119: }
6120: return @secs;
6121: }
1.776 albertel 6122:
1.506 raeburn 6123: sub auto_new_course {
1.508 raeburn 6124: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
6125: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 6126: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 6127: return $response;
6128: }
1.776 albertel 6129:
1.506 raeburn 6130: sub auto_validate_courseID {
1.508 raeburn 6131: my ($cnum,$cdom,$inst_course_id) = @_;
6132: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6133: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6134: return $response;
6135: }
1.776 albertel 6136:
1.1007 raeburn 6137: sub auto_validate_instcode {
1.1020 raeburn 6138: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6139: my ($homeserver,$response);
6140: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6141: $homeserver = &homeserver($cnum,$cdom);
6142: }
6143: if (!defined($homeserver)) {
6144: if ($cdom =~ /^$match_domain$/) {
6145: $homeserver = &domain($cdom,'primary');
6146: }
6147: }
1.1056.4.2 raeburn 6148: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6149: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6150: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6151: return ($outcome,$description);
1.1007 raeburn 6152: }
6153:
1.506 raeburn 6154: sub auto_create_password {
1.873 raeburn 6155: my ($cnum,$cdom,$authparam,$udom) = @_;
6156: my ($homeserver,$response);
1.506 raeburn 6157: my $create_passwd = 0;
6158: my $authchk = '';
1.873 raeburn 6159: if ($udom =~ /^$match_domain$/) {
6160: $homeserver = &domain($udom,'primary');
6161: }
6162: if ($homeserver eq '') {
6163: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6164: $homeserver = &homeserver($cnum,$cdom);
6165: }
6166: }
6167: if ($homeserver eq '') {
6168: $authchk = 'nodomain';
1.506 raeburn 6169: } else {
1.873 raeburn 6170: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6171: if ($response eq 'refused') {
6172: $authchk = 'refused';
6173: } else {
1.901 albertel 6174: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6175: }
1.506 raeburn 6176: }
6177: return ($authparam,$create_passwd,$authchk);
6178: }
6179:
1.706 raeburn 6180: sub auto_photo_permission {
6181: my ($cnum,$cdom,$students) = @_;
6182: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6183: my ($outcome,$perm_reqd,$conditions) =
6184: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6185: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6186: return (undef,undef);
6187: }
1.706 raeburn 6188: return ($outcome,$perm_reqd,$conditions);
6189: }
6190:
6191: sub auto_checkphotos {
6192: my ($uname,$udom,$pid) = @_;
6193: my $homeserver = &homeserver($uname,$udom);
6194: my ($result,$resulttype);
6195: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6196: &escape($uname).':'.&escape($pid),
6197: $homeserver));
1.709 albertel 6198: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6199: return (undef,undef);
6200: }
1.706 raeburn 6201: if ($outcome) {
6202: ($result,$resulttype) = split(/:/,$outcome);
6203: }
6204: return ($result,$resulttype);
6205: }
6206:
6207: sub auto_photochoice {
6208: my ($cnum,$cdom) = @_;
6209: my $homeserver = &homeserver($cnum,$cdom);
6210: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6211: &escape($cdom),
6212: $homeserver)));
1.709 albertel 6213: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6214: return (undef,undef);
6215: }
1.706 raeburn 6216: return ($update,$comment);
6217: }
6218:
6219: sub auto_photoupdate {
6220: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6221: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6222: my $host=&hostname($homeserver);
1.706 raeburn 6223: my $cmd = '';
6224: my $maxtries = 1;
1.800 albertel 6225: foreach my $affiliate (keys(%{$affiliatesref})) {
6226: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6227: }
6228: $cmd =~ s/%%$//;
6229: $cmd = &escape($cmd);
6230: my $query = 'institutionalphotos';
6231: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6232: unless ($queryid=~/^\Q$host\E\_/) {
6233: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6234: return 'error: '.$queryid;
6235: }
6236: my $reply = &get_query_reply($queryid);
6237: my $tries = 1;
6238: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6239: $reply = &get_query_reply($queryid);
6240: $tries ++;
6241: }
6242: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6243: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6244: } else {
6245: my @responses = split(/:/,$reply);
6246: my $outcome = shift(@responses);
6247: foreach my $item (@responses) {
6248: my ($key,$value) = split(/=/,$item);
6249: $$photo{$key} = $value;
6250: }
6251: return $outcome;
6252: }
6253: return 'error';
6254: }
6255:
1.521 raeburn 6256: sub auto_instcode_format {
1.793 albertel 6257: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6258: $cat_order) = @_;
1.521 raeburn 6259: my $courses = '';
1.772 raeburn 6260: my @homeservers;
1.521 raeburn 6261: if ($caller eq 'global') {
1.841 albertel 6262: my %servers = &get_servers($codedom,'library');
6263: foreach my $tryserver (keys(%servers)) {
6264: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6265: push(@homeservers,$tryserver);
6266: }
1.584 raeburn 6267: }
1.1022 raeburn 6268: } elsif ($caller eq 'requests') {
6269: if ($codedom =~ /^$match_domain$/) {
6270: my $chome = &domain($codedom,'primary');
6271: unless ($chome eq 'no_host') {
6272: push(@homeservers,$chome);
6273: }
6274: }
1.521 raeburn 6275: } else {
1.772 raeburn 6276: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6277: }
1.793 albertel 6278: foreach my $code (keys(%{$instcodes})) {
6279: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6280: }
6281: chop($courses);
1.772 raeburn 6282: my $ok_response = 0;
6283: my $response;
6284: while (@homeservers > 0 && $ok_response == 0) {
6285: my $server = shift(@homeservers);
6286: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6287: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6288: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6289: split(/:/,$response);
1.772 raeburn 6290: %{$codes} = (%{$codes},&str2hash($codes_str));
6291: push(@{$codetitles},&str2array($codetitles_str));
6292: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6293: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6294: $ok_response = 1;
6295: }
6296: }
6297: if ($ok_response) {
1.521 raeburn 6298: return 'ok';
1.772 raeburn 6299: } else {
6300: return $response;
1.521 raeburn 6301: }
6302: }
6303:
1.792 raeburn 6304: sub auto_instcode_defaults {
6305: my ($domain,$returnhash,$code_order) = @_;
6306: my @homeservers;
1.841 albertel 6307:
6308: my %servers = &get_servers($domain,'library');
6309: foreach my $tryserver (keys(%servers)) {
6310: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6311: push(@homeservers,$tryserver);
6312: }
1.792 raeburn 6313: }
1.841 albertel 6314:
1.792 raeburn 6315: my $response;
1.841 albertel 6316: foreach my $server (@homeservers) {
1.792 raeburn 6317: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6318: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6319:
6320: foreach my $pair (split(/\&/,$response)) {
6321: my ($name,$value)=split(/\=/,$pair);
6322: if ($name eq 'code_order') {
6323: @{$code_order} = split(/\&/,&unescape($value));
6324: } else {
6325: $returnhash->{&unescape($name)}=&unescape($value);
6326: }
6327: }
6328: return 'ok';
1.792 raeburn 6329: }
1.841 albertel 6330:
6331: return $response;
1.1003 raeburn 6332: }
6333:
6334: sub auto_possible_instcodes {
1.1007 raeburn 6335: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6336: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6337: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6338: return;
6339: }
1.1003 raeburn 6340: my (@homeservers,$uhome);
6341: if (defined(&domain($domain,'primary'))) {
6342: $uhome=&domain($domain,'primary');
6343: push(@homeservers,&domain($domain,'primary'));
6344: } else {
6345: my %servers = &get_servers($domain,'library');
6346: foreach my $tryserver (keys(%servers)) {
6347: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6348: push(@homeservers,$tryserver);
6349: }
6350: }
6351: }
6352: my $response;
6353: foreach my $server (@homeservers) {
6354: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6355: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6356: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6357: split(':',$response);
6358: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6359: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6360: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6361: my ($name,$value)=split('=',$item);
6362: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6363: }
6364: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6365: my ($name,$value)=split('=',$item);
6366: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6367: }
6368: return 'ok';
6369: }
6370: return $response;
6371: }
1.792 raeburn 6372:
1.1010 raeburn 6373: sub auto_courserequest_checks {
6374: my ($dom) = @_;
1.1020 raeburn 6375: my ($homeserver,%validations);
6376: if ($dom =~ /^$match_domain$/) {
6377: $homeserver = &domain($dom,'primary');
6378: }
6379: unless ($homeserver eq 'no_host') {
6380: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6381: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6382: my @items = split(/&/,$response);
6383: foreach my $item (@items) {
6384: my ($key,$value) = split('=',$item);
6385: $validations{&unescape($key)} = &thaw_unescape($value);
6386: }
6387: }
6388: }
1.1010 raeburn 6389: return %validations;
6390: }
6391:
1.1020 raeburn 6392: sub auto_courserequest_validation {
6393: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6394: my ($homeserver,$response);
6395: if ($dom =~ /^$match_domain$/) {
6396: $homeserver = &domain($dom,'primary');
6397: }
6398: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6399:
1.1020 raeburn 6400: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6401: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6402: ':'.&escape($instcode).':'.&escape($instseclist),
6403: $homeserver));
6404: }
6405: return $response;
6406: }
6407:
1.777 albertel 6408: sub auto_validate_class_sec {
1.918 raeburn 6409: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6410: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6411: my $ownerlist;
6412: if (ref($owners) eq 'ARRAY') {
6413: $ownerlist = join(',',@{$owners});
6414: } else {
6415: $ownerlist = $owners;
6416: }
1.773 raeburn 6417: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6418: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6419: return $response;
6420: }
6421:
1.679 raeburn 6422: # ------------------------------------------------------- Course Group routines
6423:
6424: sub get_coursegroups {
1.809 raeburn 6425: my ($cdom,$cnum,$group,$namespace) = @_;
6426: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6427: }
6428:
1.679 raeburn 6429: sub modify_coursegroup {
6430: my ($cdom,$cnum,$groupsettings) = @_;
6431: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6432: }
6433:
1.809 raeburn 6434: sub toggle_coursegroup_status {
6435: my ($cdom,$cnum,$group,$action) = @_;
6436: my ($from_namespace,$to_namespace);
6437: if ($action eq 'delete') {
6438: $from_namespace = 'coursegroups';
6439: $to_namespace = 'deleted_groups';
6440: } else {
6441: $from_namespace = 'deleted_groups';
6442: $to_namespace = 'coursegroups';
6443: }
6444: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6445: if (my $tmp = &error(%curr_group)) {
6446: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6447: return ('read error',$tmp);
6448: } else {
6449: my %savedsettings = %curr_group;
1.809 raeburn 6450: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6451: my $deloutcome;
6452: if ($result eq 'ok') {
1.809 raeburn 6453: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6454: } else {
6455: return ('write error',$result);
6456: }
6457: if ($deloutcome eq 'ok') {
6458: return 'ok';
6459: } else {
6460: return ('delete error',$deloutcome);
6461: }
6462: }
6463: }
6464:
1.679 raeburn 6465: sub modify_group_roles {
1.957 raeburn 6466: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6467: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6468: my $role = 'gr/'.&escape($userprivs);
6469: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6470: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6471: if ($result eq 'ok') {
6472: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6473: }
1.679 raeburn 6474: return $result;
6475: }
6476:
6477: sub modify_coursegroup_membership {
6478: my ($cdom,$cnum,$membership) = @_;
6479: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6480: return $result;
6481: }
6482:
1.682 raeburn 6483: sub get_active_groups {
6484: my ($udom,$uname,$cdom,$cnum) = @_;
6485: my $now = time;
6486: my %groups = ();
6487: foreach my $key (keys(%env)) {
1.811 albertel 6488: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6489: my ($start,$end) = split(/\./,$env{$key});
6490: if (($end!=0) && ($end<$now)) { next; }
6491: if (($start!=0) && ($start>$now)) { next; }
6492: if ($1 eq $cdom && $2 eq $cnum) {
6493: $groups{$3} = $env{$key} ;
6494: }
6495: }
6496: }
6497: return %groups;
6498: }
6499:
1.683 raeburn 6500: sub get_group_membership {
6501: my ($cdom,$cnum,$group) = @_;
6502: return(&dump('groupmembership',$cdom,$cnum,$group));
6503: }
6504:
6505: sub get_users_groups {
6506: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6507: my @usersgroups;
1.683 raeburn 6508: my $cachetime=1800;
6509:
6510: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6511: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6512: if (defined($cached)) {
1.734 albertel 6513: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6514: } else {
6515: $grouplist = '';
1.816 raeburn 6516: my $courseurl = &courseid_to_courseurl($courseid);
1.1056.4.10 raeburn 6517: my $extra = &freeze_escape({'skipcheck' => 1});
6518: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6519: my $access_end = $env{'course.'.$courseid.
6520: '.default_enrollment_end_date'};
6521: my $now = time;
6522: foreach my $key (keys(%roleshash)) {
6523: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6524: my $group = $1;
6525: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6526: my $start = $2;
6527: my $end = $1;
6528: if ($start == -1) { next; } # deleted from group
6529: if (($start!=0) && ($start>$now)) { next; }
6530: if (($end!=0) && ($end<$now)) {
6531: if ($access_end && $access_end < $now) {
6532: if ($access_end - $end < 86400) {
6533: push(@usersgroups,$group);
1.733 raeburn 6534: }
6535: }
1.817 raeburn 6536: next;
1.733 raeburn 6537: }
1.817 raeburn 6538: push(@usersgroups,$group);
1.683 raeburn 6539: }
6540: }
6541: }
1.817 raeburn 6542: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6543: $grouplist = join(':',@usersgroups);
6544: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6545: }
1.733 raeburn 6546: return @usersgroups;
1.683 raeburn 6547: }
6548:
6549: sub devalidate_getgroups_cache {
6550: my ($udom,$uname,$cdom,$cnum)=@_;
6551: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6552:
1.683 raeburn 6553: my $hashid="$udom:$uname:$courseid";
6554: &devalidate_cache_new('getgroups',$hashid);
6555: }
6556:
1.12 www 6557: # ------------------------------------------------------------------ Plain Text
6558:
6559: sub plaintext {
1.988 raeburn 6560: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6561: if ($short =~ m{^cr/}) {
1.758 albertel 6562: return (split('/',$short))[-1];
6563: }
1.742 raeburn 6564: if (!defined($cid)) {
6565: $cid = $env{'request.course.id'};
6566: }
6567: my %rolenames = (
1.1008 raeburn 6568: Course => 'std',
6569: Community => 'alt1',
1.742 raeburn 6570: );
1.1037 raeburn 6571: if ($cid ne '') {
6572: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6573: unless ($forcedefault) {
6574: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6575: &Apache::lonlocal::mt_escape(\$roletext);
6576: return &Apache::lonlocal::mt($roletext);
6577: }
6578: }
6579: }
6580: if ((defined($type)) && (defined($rolenames{$type})) &&
6581: (defined($rolenames{$type})) &&
6582: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6583: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6584: } elsif ($cid ne '') {
6585: my $crstype = $env{'course.'.$cid.'.type'};
6586: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6587: (defined($prp{$short}{$rolenames{$crstype}}))) {
6588: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6589: }
1.742 raeburn 6590: }
1.1037 raeburn 6591: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6592: }
6593:
6594: # ----------------------------------------------------------------- Assign Role
6595:
6596: sub assignrole {
1.957 raeburn 6597: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6598: $context)=@_;
1.21 www 6599: my $mrole;
6600: if ($role =~ /^cr\//) {
1.393 www 6601: my $cwosec=$url;
1.811 albertel 6602: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6603: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6604: my $refused = 1;
6605: if ($context eq 'requestcourses') {
6606: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6607: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6608: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6609: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6610: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6611: if ($crsenv{'internal.courseowner'} eq
6612: $env{'user.name'}.':'.$env{'user.domain'}) {
6613: $refused = '';
6614: }
6615: }
6616: }
6617: }
6618: }
6619: if ($refused) {
6620: &logthis('Refused custom assignrole: '.
6621: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6622: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6623: return 'refused';
6624: }
1.104 www 6625: }
1.21 www 6626: $mrole='cr';
1.678 raeburn 6627: } elsif ($role =~ /^gr\//) {
6628: my $cwogrp=$url;
1.811 albertel 6629: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6630: unless (&allowed('mdg',$cwogrp)) {
6631: &logthis('Refused group assignrole: '.
6632: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6633: $env{'user.name'}.' at '.$env{'user.domain'});
6634: return 'refused';
6635: }
6636: $mrole='gr';
1.21 www 6637: } else {
1.82 www 6638: my $cwosec=$url;
1.811 albertel 6639: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6640: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6641: my $refused;
6642: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6643: if (!(&allowed('c'.$role,$url))) {
6644: $refused = 1;
6645: }
6646: } else {
6647: $refused = 1;
6648: }
1.947 raeburn 6649: if ($refused) {
1.1045 raeburn 6650: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6651: if (!$selfenroll && $context eq 'course') {
6652: my %crsenv;
6653: if ($role eq 'cc' || $role eq 'co') {
6654: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6655: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6656: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6657: if ($crsenv{'internal.courseowner'} eq
6658: $env{'user.name'}.':'.$env{'user.domain'}) {
6659: $refused = '';
6660: }
6661: }
6662: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6663: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6664: if ($crsenv{'internal.courseowner'} eq
6665: $env{'user.name'}.':'.$env{'user.domain'}) {
6666: $refused = '';
6667: }
6668: }
6669: }
6670: }
6671: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6672: $refused = '';
1.1017 raeburn 6673: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6674: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6675: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6676: my $wrongcc;
6677: if ($cnum =~ /^$match_community$/) {
6678: $wrongcc = 1 if ($role eq 'cc');
6679: } else {
6680: $wrongcc = 1 if ($role eq 'co');
6681: }
6682: unless ($wrongcc) {
6683: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6684: if ($crsenv{'internal.courseowner'} eq
6685: $env{'user.name'}.':'.$env{'user.domain'}) {
6686: $refused = '';
6687: }
1.1017 raeburn 6688: }
6689: }
6690: }
6691: if ($refused) {
1.947 raeburn 6692: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6693: ' '.$role.' '.$end.' '.$start.' by '.
6694: $env{'user.name'}.' at '.$env{'user.domain'});
6695: return 'refused';
6696: }
1.932 raeburn 6697: }
1.104 www 6698: }
1.21 www 6699: $mrole=$role;
6700: }
1.620 albertel 6701: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6702: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6703: if ($end) { $command.='_'.$end; }
1.21 www 6704: if ($start) {
6705: if ($end) {
1.81 www 6706: $command.='_'.$start;
1.21 www 6707: } else {
1.81 www 6708: $command.='_0_'.$start;
1.21 www 6709: }
6710: }
1.739 raeburn 6711: my $origstart = $start;
6712: my $origend = $end;
1.957 raeburn 6713: my $delflag;
1.357 www 6714: # actually delete
6715: if ($deleteflag) {
1.373 www 6716: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6717: # modify command to delete the role
1.620 albertel 6718: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6719: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6720: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6721: # set start and finish to negative values for userrolelog
6722: $start=-1;
6723: $end=-1;
1.957 raeburn 6724: $delflag = 1;
1.357 www 6725: }
6726: }
6727: # send command
1.349 www 6728: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6729: # log new user role if status is ok
1.349 www 6730: if ($answer eq 'ok') {
1.663 raeburn 6731: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6732: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6733: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6734: unless ($role =~ /^gr/) {
6735: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6736: $origstart,$selfenroll,$context);
1.739 raeburn 6737: }
1.1053 raeburn 6738: if ($role eq 'cc') {
6739: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6740: }
1.349 www 6741: }
6742: return $answer;
1.169 harris41 6743: }
6744:
1.1053 raeburn 6745: sub autoupdate_coowners {
6746: my ($url,$end,$start,$uname,$udom) = @_;
6747: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6748: if (($cdom ne '') && ($cnum ne '')) {
6749: my $now = time;
6750: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6751: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6752: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6753: my $instcode = $coursehash{'internal.coursecode'};
6754: if ($instcode ne '') {
1.1056 raeburn 6755: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6756: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6757: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6758: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6759: if ($result eq 'valid') {
6760: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6761: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6762: push(@newcoowners,$coowner);
6763: }
6764: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6765: push(@newcoowners,$uname.':'.$udom);
6766: }
6767: @newcoowners = sort(@newcoowners);
6768: } else {
6769: push(@newcoowners,$uname.':'.$udom);
6770: }
6771: } else {
6772: if ($coursehash{'internal.co-owners'}) {
6773: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6774: unless ($coowner eq $uname.':'.$udom) {
6775: push(@newcoowners,$coowner);
6776: }
6777: }
6778: unless (@newcoowners > 0) {
6779: $delcoowners = 1;
6780: $coowners = '';
6781: }
6782: }
6783: }
6784: if (@newcoowners || $delcoowners) {
6785: &store_coowners($cdom,$cnum,$coursehash{'home'},
6786: $delcoowners,@newcoowners);
6787: }
6788: }
6789: }
6790: }
6791: }
6792: }
6793: }
6794:
6795: sub store_coowners {
6796: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6797: my $cid = $cdom.'_'.$cnum;
6798: my ($coowners,$delresult,$putresult);
6799: if (@newcoowners) {
6800: $coowners = join(',',@newcoowners);
6801: my %coownershash = (
6802: 'internal.co-owners' => $coowners,
6803: );
6804: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6805: if ($putresult eq 'ok') {
6806: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6807: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6808: }
6809: }
6810: }
6811: if ($delcoowners) {
6812: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6813: if ($delresult eq 'ok') {
6814: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6815: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6816: }
6817: }
6818: }
6819: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6820: my %crsinfo =
6821: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6822: if (ref($crsinfo{$cid}) eq 'HASH') {
6823: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6824: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6825: }
6826: }
6827: }
6828:
1.169 harris41 6829: # -------------------------------------------------- Modify user authentication
1.197 www 6830: # Overrides without validation
6831:
1.169 harris41 6832: sub modifyuserauth {
6833: my ($udom,$uname,$umode,$upass)=@_;
6834: my $uhome=&homeserver($uname,$udom);
1.197 www 6835: unless (&allowed('mau',$udom)) { return 'refused'; }
6836: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6837: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6838: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6839: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6840: &escape($upass),$uhome);
1.620 albertel 6841: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6842: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6843: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6844: &log($udom,,$uname,$uhome,
1.620 albertel 6845: 'Authentication changed by '.$env{'user.domain'}.', '.
6846: $env{'user.name'}.', '.$umode.
1.197 www 6847: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6848: unless ($reply eq 'ok') {
1.197 www 6849: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6850: return 'error: '.$reply;
6851: }
1.170 harris41 6852: return 'ok';
1.80 www 6853: }
6854:
1.81 www 6855: # --------------------------------------------------------------- Modify a user
1.80 www 6856:
1.81 www 6857: sub modifyuser {
1.206 matthew 6858: my ($udom, $uname, $uid,
6859: $umode, $upass, $first,
6860: $middle, $last, $gene,
1.1056.4.1 raeburn 6861: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6862: $udom= &LONCAPA::clean_domain($udom);
6863: $uname=&LONCAPA::clean_username($uname);
1.1056.4.1 raeburn 6864: my $showcandelete = 'none';
6865: if (ref($candelete) eq 'ARRAY') {
6866: if (@{$candelete} > 0) {
6867: $showcandelete = join(', ',@{$candelete});
6868: }
6869: }
1.81 www 6870: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6871: $umode.', '.$first.', '.$middle.', '.
1.1056.4.1 raeburn 6872: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6873: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6874: ' desiredhome not specified').
1.620 albertel 6875: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6876: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6877: my $uhome=&homeserver($uname,$udom,'true');
1.1056.4.4 raeburn 6878: my $newuser;
6879: if ($uhome eq 'no_host') {
6880: $newuser = 1;
6881: }
1.80 www 6882: # ----------------------------------------------------------------- Create User
1.406 albertel 6883: if (($uhome eq 'no_host') &&
6884: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6885: my $unhome='';
1.844 albertel 6886: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6887: $unhome = $desiredhome;
1.620 albertel 6888: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6889: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6890: } else { # load balancing routine for determining $unhome
1.81 www 6891: my $loadm=10000000;
1.841 albertel 6892: my %servers = &get_servers($udom,'library');
6893: foreach my $tryserver (keys(%servers)) {
6894: my $answer=reply('load',$tryserver);
6895: if (($answer=~/\d+/) && ($answer<$loadm)) {
6896: $loadm=$answer;
6897: $unhome=$tryserver;
6898: }
1.80 www 6899: }
6900: }
6901: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6902: return 'error: unable to find a home server for '.$uname.
6903: ' in domain '.$udom;
1.80 www 6904: }
6905: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6906: &escape($upass),$unhome);
6907: unless ($reply eq 'ok') {
6908: return 'error: '.$reply;
6909: }
1.230 stredwic 6910: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6911: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6912: return 'error: unable verify users home machine.';
1.80 www 6913: }
1.209 matthew 6914: } # End of creation of new user
1.80 www 6915: # ---------------------------------------------------------------------- Add ID
6916: if ($uid) {
6917: $uid=~tr/A-Z/a-z/;
6918: my %uidhash=&idrget($udom,$uname);
1.196 www 6919: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6920: && (!$forceid)) {
1.80 www 6921: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6922: return 'error: user id "'.$uid.'" does not match '.
6923: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6924: }
6925: } else {
6926: &idput($udom,($uname => $uid));
6927: }
6928: }
6929: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6930: my @tmp=&get('environment',
1.899 raeburn 6931: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6932: 'permanentemail','inststatus'],
1.134 albertel 6933: $udom,$uname);
1.1056.4.4 raeburn 6934: my (%names,%oldnames);
1.313 matthew 6935: if ($tmp[0] =~ m/^error:.*/) {
6936: %names=();
6937: } else {
6938: %names = @tmp;
1.1056.4.4 raeburn 6939: %oldnames = %names;
1.313 matthew 6940: }
1.1056.4.6 raeburn 6941: #
1.1056.4.1 raeburn 6942: # If name, email and/or uid are blank (e.g., because an uploaded file
6943: # of users did not contain them), do not overwrite existing values
6944: # unless field is in $candelete array ref.
6945: #
6946:
6947: my @fields = ('firstname','middlename','lastname','generation',
6948: 'permanentemail','id');
6949: my %newvalues;
6950: if (ref($candelete) eq 'ARRAY') {
6951: foreach my $field (@fields) {
6952: if (grep(/^\Q$field\E$/,@{$candelete})) {
6953: if ($field eq 'firstname') {
6954: $names{$field} = $first;
6955: } elsif ($field eq 'middlename') {
6956: $names{$field} = $middle;
6957: } elsif ($field eq 'lastname') {
6958: $names{$field} = $last;
6959: } elsif ($field eq 'generation') {
6960: $names{$field} = $gene;
6961: } elsif ($field eq 'permanentemail') {
6962: $names{$field} = $email;
6963: } elsif ($field eq 'id') {
6964: $names{$field} = $uid;
6965: }
6966: }
6967: }
6968: }
1.388 www 6969: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6970: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6971: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6972: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6973: if ($email) {
6974: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6975: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6976: }
1.899 raeburn 6977: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6978: if (defined($inststatus)) {
6979: $names{'inststatus'} = '';
6980: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6981: if (ref($usertypes) eq 'HASH') {
6982: my @okstatuses;
6983: foreach my $item (split(/:/,$inststatus)) {
6984: if (defined($usertypes->{$item})) {
6985: push(@okstatuses,$item);
6986: }
6987: }
6988: if (@okstatuses) {
6989: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6990: }
6991: }
6992: }
1.1056.4.4 raeburn 6993: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 6994: $umode.', '.$first.', '.$middle.', '.
1.1056.4.4 raeburn 6995: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 6996: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6997: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6998: } else {
6999: $logmsg .= ' during self creation';
7000: }
1.1056.4.4 raeburn 7001: my $changed;
7002: if ($newuser) {
7003: $changed = 1;
7004: } else {
7005: foreach my $field (@fields) {
7006: if ($names{$field} ne $oldnames{$field}) {
7007: $changed = 1;
7008: last;
7009: }
7010: }
7011: }
7012: unless ($changed) {
7013: $logmsg = 'No changes in user information needed for: '.$logmsg;
7014: &logthis($logmsg);
7015: return 'ok';
7016: }
7017: my $reply = &put('environment', \%names, $udom,$uname);
7018: if ($reply ne 'ok') {
7019: return 'error: '.$reply;
7020: }
1.1056.4.11 raeburn 7021: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7022: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7023: }
1.1056.4.4 raeburn 7024: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7025: &devalidate_cache_new('namescache',$uname.':'.$udom);
7026: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7027: &logthis($logmsg);
1.134 albertel 7028: return 'ok';
1.80 www 7029: }
7030:
1.81 www 7031: # -------------------------------------------------------------- Modify student
1.80 www 7032:
1.81 www 7033: sub modifystudent {
7034: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7035: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7036: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7037: if (!$cid) {
1.620 albertel 7038: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7039: return 'not_in_class';
7040: }
1.80 www 7041: }
7042: # --------------------------------------------------------------- Make the user
1.81 www 7043: my $reply=&modifyuser
1.209 matthew 7044: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7045: $desiredhome,$email,$inststatus);
1.80 www 7046: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7047: # This will cause &modify_student_enrollment to get the uid from the
7048: # students environment
7049: $uid = undef if (!$forceid);
1.455 albertel 7050: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7051: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7052: return $reply;
7053: }
7054:
7055: sub modify_student_enrollment {
1.957 raeburn 7056: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7057: my ($cdom,$cnum,$chome);
7058: if (!$cid) {
1.620 albertel 7059: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7060: return 'not_in_class';
7061: }
1.620 albertel 7062: $cdom=$env{'course.'.$cid.'.domain'};
7063: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7064: } else {
7065: ($cdom,$cnum)=split(/_/,$cid);
7066: }
1.620 albertel 7067: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7068: if (!$chome) {
1.457 raeburn 7069: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7070: }
1.455 albertel 7071: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7072: # Make sure the user exists
1.81 www 7073: my $uhome=&homeserver($uname,$udom);
7074: if (($uhome eq '') || ($uhome eq 'no_host')) {
7075: return 'error: no such user';
7076: }
1.297 matthew 7077: # Get student data if we were not given enough information
7078: if (!defined($first) || $first eq '' ||
7079: !defined($last) || $last eq '' ||
7080: !defined($uid) || $uid eq '' ||
7081: !defined($middle) || $middle eq '' ||
7082: !defined($gene) || $gene eq '') {
1.294 matthew 7083: # They did not supply us with enough data to enroll the student, so
7084: # we need to pick up more information.
1.297 matthew 7085: my %tmp = &get('environment',
1.294 matthew 7086: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7087: ,$udom,$uname);
7088:
1.800 albertel 7089: #foreach my $key (keys(%tmp)) {
7090: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7091: #}
1.294 matthew 7092: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7093: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7094: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7095: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7096: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7097: }
1.556 albertel 7098: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 7099: my $reply=cput('classlist',
7100: {"$uname:$udom" =>
1.515 raeburn 7101: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7102: $cdom,$cnum);
1.81 www 7103: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7104: return 'error: '.$reply;
1.652 albertel 7105: } else {
7106: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 7107: }
1.297 matthew 7108: # Add student role to user
1.83 www 7109: my $uurl='/'.$cid;
1.81 www 7110: $uurl=~s/\_/\//g;
7111: if ($usec) {
7112: $uurl.='/'.$usec;
7113: }
1.957 raeburn 7114: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 7115: }
7116:
1.556 albertel 7117: sub format_name {
7118: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7119: my $name;
7120: if ($first ne 'lastname') {
7121: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7122: } else {
7123: if ($lastname=~/\S/) {
7124: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7125: $name=~s/\s+,/,/;
7126: } else {
7127: $name.= $firstname.' '.$middlename.' '.$generation;
7128: }
7129: }
7130: $name=~s/^\s+//;
7131: $name=~s/\s+$//;
7132: $name=~s/\s+/ /g;
7133: return $name;
7134: }
7135:
1.84 www 7136: # ------------------------------------------------- Write to course preferences
7137:
7138: sub writecoursepref {
7139: my ($courseid,%prefs)=@_;
7140: $courseid=~s/^\///;
7141: $courseid=~s/\_/\//g;
7142: my ($cdomain,$cnum)=split(/\//,$courseid);
7143: my $chome=homeserver($cnum,$cdomain);
7144: if (($chome eq '') || ($chome eq 'no_host')) {
7145: return 'error: no such course';
7146: }
7147: my $cstring='';
1.800 albertel 7148: foreach my $pref (keys(%prefs)) {
7149: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7150: }
1.84 www 7151: $cstring=~s/\&$//;
7152: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7153: }
7154:
7155: # ---------------------------------------------------------- Make/modify course
7156:
7157: sub createcourse {
1.741 raeburn 7158: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7159: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7160: $url=&declutter($url);
7161: my $cid='';
1.1028 raeburn 7162: if ($context eq 'requestcourses') {
7163: my $can_create = 0;
7164: my ($ownername,$ownerdom) = split(':',$course_owner);
7165: if ($udom eq $ownerdom) {
7166: if (&usertools_access($ownername,$ownerdom,$category,undef,
7167: $context)) {
7168: $can_create = 1;
7169: }
7170: } else {
7171: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7172: $category);
7173: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7174: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7175: if (@curr > 0) {
7176: my @options = qw(approval validate autolimit);
7177: my $optregex = join('|',@options);
7178: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7179: $can_create = 1;
7180: }
7181: }
7182: }
7183: }
7184: if ($can_create) {
7185: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7186: unless (&allowed('ccc',$udom)) {
7187: return 'refused';
7188: }
1.1017 raeburn 7189: }
7190: } else {
7191: return 'refused';
7192: }
1.1028 raeburn 7193: } elsif (!&allowed('ccc',$udom)) {
7194: return 'refused';
1.84 www 7195: }
1.1011 raeburn 7196: # --------------------------------------------------------------- Get Unique ID
7197: my $uname;
7198: if ($cnum =~ /^$match_courseid$/) {
7199: my $chome=&homeserver($cnum,$udom,'true');
7200: if (($chome eq '') || ($chome eq 'no_host')) {
7201: $uname = $cnum;
7202: } else {
1.1038 raeburn 7203: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7204: }
7205: } else {
1.1038 raeburn 7206: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7207: }
7208: return $uname if ($uname =~ /^error/);
7209: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7210: if (!defined($course_server)) {
7211: if (defined(&domain($udom,'primary'))) {
7212: $course_server = &domain($udom,'primary');
7213: } else {
7214: $course_server = $env{'user.home'};
7215: }
7216: }
7217: my %host_servers =
7218: &Apache::lonnet::get_servers($udom,'library');
7219: unless ($host_servers{$course_server}) {
7220: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7221: }
1.84 www 7222: # ------------------------------------------------------------- Make the course
7223: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7224: $course_server);
1.84 www 7225: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7226: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7227: if (($uhome eq '') || ($uhome eq 'no_host')) {
7228: return 'error: no such course';
7229: }
1.271 www 7230: # ----------------------------------------------------------------- Course made
1.516 raeburn 7231: # log existence
1.1029 raeburn 7232: my $now = time;
1.918 raeburn 7233: my $newcourse = {
7234: $udom.'_'.$uname => {
1.921 raeburn 7235: description => $description,
7236: inst_code => $inst_code,
7237: owner => $course_owner,
7238: type => $crstype,
1.1029 raeburn 7239: creator => $env{'user.name'}.':'.
7240: $env{'user.domain'},
7241: created => $now,
7242: context => $context,
1.918 raeburn 7243: },
7244: };
1.921 raeburn 7245: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7246: # set toplevel url
1.271 www 7247: my $topurl=$url;
7248: unless ($nonstandard) {
7249: # ------------------------------------------ For standard courses, make top url
7250: my $mapurl=&clutter($url);
1.278 www 7251: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7252: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7253: <map>
7254: <resource id="1" type="start"></resource>
7255: <resource id="2" src="$mapurl"></resource>
7256: <resource id="3" type="finish"></resource>
7257: <link index="1" from="1" to="2"></link>
7258: <link index="2" from="2" to="3"></link>
7259: </map>
7260: ENDINITMAP
7261: $topurl=&declutter(
1.638 albertel 7262: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7263: );
7264: }
7265: # ----------------------------------------------------------- Write preferences
1.84 www 7266: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7267: ('description' => $description,
7268: 'url' => $topurl,
7269: 'internal.creator' => $env{'user.name'}.':'.
7270: $env{'user.domain'},
7271: 'internal.created' => $now,
7272: 'internal.creationcontext' => $context)
7273: );
1.84 www 7274: return '/'.$udom.'/'.$uname;
7275: }
7276:
1.1011 raeburn 7277: # ------------------------------------------------------------------- Create ID
7278: sub generate_coursenum {
1.1038 raeburn 7279: my ($udom,$crstype) = @_;
1.1011 raeburn 7280: my $domdesc = &domain($udom);
7281: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7282: my $first;
7283: if ($crstype eq 'Community') {
7284: $first = '0';
7285: } else {
7286: $first = int(1+rand(9));
7287: }
7288: my $uname=$first.
1.1011 raeburn 7289: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7290: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7291: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7292: # ----------------------------------------------- Make sure that does not exist
7293: my $uhome=&homeserver($uname,$udom,'true');
7294: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7295: if ($crstype eq 'Community') {
7296: $first = '0';
7297: } else {
7298: $first = int(1+rand(9));
7299: }
7300: $uname=$first.
1.1011 raeburn 7301: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7302: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7303: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7304: $uhome=&homeserver($uname,$udom,'true');
7305: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7306: return 'error: unable to generate unique course-ID';
7307: }
7308: }
7309: return $uname;
7310: }
7311:
1.813 albertel 7312: sub is_course {
7313: my ($cdom,$cnum) = @_;
7314: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7315: undef,'.');
1.813 albertel 7316: if (exists($courses{$cdom.'_'.$cnum})) {
7317: return 1;
7318: }
7319: return 0;
7320: }
7321:
1.1015 raeburn 7322: sub store_userdata {
7323: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7324: my $result;
1.1016 raeburn 7325: if ($datakey ne '') {
1.1013 raeburn 7326: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7327: if ($udom eq '' || $uname eq '') {
7328: $udom = $env{'user.domain'};
7329: $uname = $env{'user.name'};
7330: }
7331: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7332: if (($uhome eq '') || ($uhome eq 'no_host')) {
7333: $result = 'error: no_host';
7334: } else {
7335: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7336: $storehash->{'host'} = $perlvar{'lonHostID'};
7337:
7338: my $namevalue='';
7339: foreach my $key (keys(%{$storehash})) {
7340: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7341: }
7342: $namevalue=~s/\&$//;
7343: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 7344: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 7345: }
7346: } else {
7347: $result = 'error: data to store was not a hash reference';
7348: }
7349: } else {
7350: $result= 'error: invalid requestkey';
7351: }
7352: return $result;
7353: }
7354:
1.21 www 7355: # ---------------------------------------------------------- Assign Custom Role
7356:
7357: sub assigncustomrole {
1.957 raeburn 7358: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7359: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7360: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7361: }
7362:
7363: # ----------------------------------------------------------------- Revoke Role
7364:
7365: sub revokerole {
1.957 raeburn 7366: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7367: my $now=time;
1.965 raeburn 7368: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7369: }
7370:
7371: # ---------------------------------------------------------- Revoke Custom Role
7372:
7373: sub revokecustomrole {
1.957 raeburn 7374: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7375: my $now=time;
1.357 www 7376: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7377: $deleteflag,$selfenroll,$context);
1.17 www 7378: }
7379:
1.533 banghart 7380: # ------------------------------------------------------------ Disk usage
1.535 albertel 7381: sub diskusage {
1.955 raeburn 7382: my ($udom,$uname,$directorypath,$getpropath)=@_;
7383: $directorypath =~ s/\/$//;
7384: my $listing=&reply('du2:'.&escape($directorypath).':'
7385: .&escape($getpropath).':'.&escape($uname).':'
7386: .&escape($udom),homeserver($uname,$udom));
7387: if ($listing eq 'unknown_cmd') {
7388: if ($getpropath) {
7389: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7390: }
7391: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7392: }
1.514 albertel 7393: return $listing;
1.512 banghart 7394: }
7395:
1.566 banghart 7396: sub is_locked {
7397: my ($file_name, $domain, $user) = @_;
7398: my @check;
7399: my $is_locked;
7400: push @check, $file_name;
1.613 albertel 7401: my %locked = &get('file_permissions',\@check,
1.620 albertel 7402: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7403: my ($tmp)=keys(%locked);
7404: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7405:
1.566 banghart 7406: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7407: $is_locked = 'false';
7408: foreach my $entry (@{$locked{$file_name}}) {
7409: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7410: $is_locked = 'true';
7411: last;
1.745 raeburn 7412: }
7413: }
1.566 banghart 7414: } else {
7415: $is_locked = 'false';
7416: }
7417: }
7418:
1.759 albertel 7419: sub declutter_portfile {
7420: my ($file) = @_;
1.833 albertel 7421: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7422: return $file;
7423: }
7424:
1.559 banghart 7425: # ------------------------------------------------------------- Mark as Read Only
7426:
7427: sub mark_as_readonly {
7428: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7429: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7430: my ($tmp)=keys(%current_permissions);
7431: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7432: foreach my $file (@{$files}) {
1.759 albertel 7433: $file = &declutter_portfile($file);
1.561 banghart 7434: push(@{$current_permissions{$file}},$what);
1.559 banghart 7435: }
1.613 albertel 7436: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7437: return;
7438: }
7439:
1.572 banghart 7440: # ------------------------------------------------------------Save Selected Files
7441:
7442: sub save_selected_files {
7443: my ($user, $path, @files) = @_;
7444: my $filename = $user."savedfiles";
1.573 banghart 7445: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7446: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7447: foreach my $file (@files) {
1.620 albertel 7448: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7449: }
7450: foreach my $file (@other_files) {
1.574 banghart 7451: print (OUT $file."\n");
1.572 banghart 7452: }
1.574 banghart 7453: close (OUT);
1.572 banghart 7454: return 'ok';
7455: }
7456:
1.574 banghart 7457: sub clear_selected_files {
7458: my ($user) = @_;
7459: my $filename = $user."savedfiles";
7460: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7461: print (OUT undef);
7462: close (OUT);
7463: return ("ok");
7464: }
7465:
1.572 banghart 7466: sub files_in_path {
7467: my ($user, $path) = @_;
7468: my $filename = $user."savedfiles";
7469: my %return_files;
1.574 banghart 7470: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7471: while (my $line_in = <IN>) {
1.574 banghart 7472: chomp ($line_in);
7473: my @paths_and_file = split (m!/!, $line_in);
7474: my $file_part = pop (@paths_and_file);
7475: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7476: $path_part.='/';
7477: my $path_and_file = $path_part.$file_part;
7478: if ($path_part eq $path) {
7479: $return_files{$file_part}= 'selected';
7480: }
7481: }
1.574 banghart 7482: close (IN);
7483: return (\%return_files);
1.572 banghart 7484: }
7485:
7486: # called in portfolio select mode, to show files selected NOT in current directory
7487: sub files_not_in_path {
7488: my ($user, $path) = @_;
7489: my $filename = $user."savedfiles";
7490: my @return_files;
7491: my $path_part;
1.800 albertel 7492: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7493: while (my $line = <IN>) {
1.572 banghart 7494: #ok, I know it's clunky, but I want it to work
1.800 albertel 7495: my @paths_and_file = split(m|/|, $line);
7496: my $file_part = pop(@paths_and_file);
7497: chomp($file_part);
7498: my $path_part = join('/', @paths_and_file);
1.572 banghart 7499: $path_part .= '/';
7500: my $path_and_file = $path_part.$file_part;
7501: if ($path_part ne $path) {
1.800 albertel 7502: push(@return_files, ($path_and_file));
1.572 banghart 7503: }
7504: }
1.800 albertel 7505: close(OUT);
1.574 banghart 7506: return (@return_files);
1.572 banghart 7507: }
7508:
1.745 raeburn 7509: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7510:
1.745 raeburn 7511: sub get_portfile_permissions {
7512: my ($domain,$user) = @_;
1.613 albertel 7513: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7514: my ($tmp)=keys(%current_permissions);
7515: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7516: return \%current_permissions;
7517: }
7518:
7519: #---------------------------------------------Get portfolio file access controls
7520:
1.749 raeburn 7521: sub get_access_controls {
1.745 raeburn 7522: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7523: my %access;
7524: my $real_file = $file;
7525: $file =~ s/\.meta$//;
1.745 raeburn 7526: if (defined($file)) {
1.749 raeburn 7527: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7528: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7529: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7530: }
7531: }
1.745 raeburn 7532: } else {
1.749 raeburn 7533: foreach my $key (keys(%{$current_permissions})) {
7534: if ($key =~ /\0accesscontrol$/) {
7535: if (defined($group)) {
7536: if ($key !~ m-^\Q$group\E/-) {
7537: next;
7538: }
7539: }
7540: my ($fullpath) = split(/\0/,$key);
7541: if (ref($$current_permissions{$key}) eq 'HASH') {
7542: foreach my $control (keys(%{$$current_permissions{$key}})) {
7543: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7544: }
7545: }
7546: }
7547: }
7548: }
7549: return %access;
7550: }
7551:
7552: sub modify_access_controls {
7553: my ($file_name,$changes,$domain,$user)=@_;
7554: my ($outcome,$deloutcome);
7555: my %store_permissions;
7556: my %new_values;
7557: my %new_control;
7558: my %translation;
7559: my @deletions = ();
7560: my $now = time;
7561: if (exists($$changes{'activate'})) {
7562: if (ref($$changes{'activate'}) eq 'HASH') {
7563: my @newitems = sort(keys(%{$$changes{'activate'}}));
7564: my $numnew = scalar(@newitems);
7565: for (my $i=0; $i<$numnew; $i++) {
7566: my $newkey = $newitems[$i];
7567: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7568: if ($newkey =~ /^\d+:/) {
7569: $newkey =~ s/^(\d+)/$newid/;
7570: $translation{$1} = $newid;
7571: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7572: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7573: $translation{$1} = $newid;
7574: }
1.749 raeburn 7575: $new_values{$file_name."\0".$newkey} =
7576: $$changes{'activate'}{$newitems[$i]};
7577: $new_control{$newkey} = $now;
7578: }
7579: }
7580: }
7581: my %todelete;
7582: my %changed_items;
7583: foreach my $action ('delete','update') {
7584: if (exists($$changes{$action})) {
7585: if (ref($$changes{$action}) eq 'HASH') {
7586: foreach my $key (keys(%{$$changes{$action}})) {
7587: my ($itemnum) = ($key =~ /^([^:]+):/);
7588: if ($action eq 'delete') {
7589: $todelete{$itemnum} = 1;
7590: } else {
7591: $changed_items{$itemnum} = $key;
7592: }
7593: }
1.745 raeburn 7594: }
7595: }
1.749 raeburn 7596: }
7597: # get lock on access controls for file.
7598: my $lockhash = {
7599: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7600: ':'.$env{'user.domain'},
7601: };
7602: my $tries = 0;
7603: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7604:
7605: while (($gotlock ne 'ok') && $tries <3) {
7606: $tries ++;
7607: sleep 1;
7608: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7609: }
7610: if ($gotlock eq 'ok') {
7611: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7612: my ($tmp)=keys(%curr_permissions);
7613: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7614: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7615: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7616: if (ref($curr_controls) eq 'HASH') {
7617: foreach my $control_item (keys(%{$curr_controls})) {
7618: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7619: if (defined($todelete{$itemnum})) {
7620: push(@deletions,$file_name."\0".$control_item);
7621: } else {
7622: if (defined($changed_items{$itemnum})) {
7623: $new_control{$changed_items{$itemnum}} = $now;
7624: push(@deletions,$file_name."\0".$control_item);
7625: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7626: } else {
7627: $new_control{$control_item} = $$curr_controls{$control_item};
7628: }
7629: }
1.745 raeburn 7630: }
7631: }
7632: }
1.970 raeburn 7633: my ($group);
7634: if (&is_course($domain,$user)) {
7635: ($group,my $file) = split(/\//,$file_name,2);
7636: }
1.749 raeburn 7637: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7638: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7639: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7640: # remove lock
7641: my @del_lock = ($file_name."\0".'locked_access_records');
7642: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7643: my $sqlresult =
1.970 raeburn 7644: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7645: $group);
1.749 raeburn 7646: } else {
7647: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7648: }
1.749 raeburn 7649: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7650: }
7651:
1.827 raeburn 7652: sub make_public_indefinitely {
7653: my ($requrl) = @_;
7654: my $now = time;
7655: my $action = 'activate';
7656: my $aclnum = 0;
7657: if (&is_portfolio_url($requrl)) {
7658: my (undef,$udom,$unum,$file_name,$group) =
7659: &parse_portfolio_url($requrl);
7660: my $current_perms = &get_portfile_permissions($udom,$unum);
7661: my %access_controls = &get_access_controls($current_perms,
7662: $group,$file_name);
7663: foreach my $key (keys(%{$access_controls{$file_name}})) {
7664: my ($num,$scope,$end,$start) =
7665: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7666: if ($scope eq 'public') {
7667: if ($start <= $now && $end == 0) {
7668: $action = 'none';
7669: } else {
7670: $action = 'update';
7671: $aclnum = $num;
7672: }
7673: last;
7674: }
7675: }
7676: if ($action eq 'none') {
7677: return 'ok';
7678: } else {
7679: my %changes;
7680: my $newend = 0;
7681: my $newstart = $now;
7682: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7683: $changes{$action}{$newkey} = {
7684: type => 'public',
7685: time => {
7686: start => $newstart,
7687: end => $newend,
7688: },
7689: };
7690: my ($outcome,$deloutcome,$new_values,$translation) =
7691: &modify_access_controls($file_name,\%changes,$udom,$unum);
7692: return $outcome;
7693: }
7694: } else {
7695: return 'invalid';
7696: }
7697: }
7698:
1.745 raeburn 7699: #------------------------------------------------------Get Marked as Read Only
7700:
7701: sub get_marked_as_readonly {
7702: my ($domain,$user,$what,$group) = @_;
7703: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7704: my @readonly_files;
1.629 banghart 7705: my $cmp1=$what;
7706: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7707: while (my ($file_name,$value) = each(%{$current_permissions})) {
7708: if (defined($group)) {
7709: if ($file_name !~ m-^\Q$group\E/-) {
7710: next;
7711: }
7712: }
1.561 banghart 7713: if (ref($value) eq "ARRAY"){
7714: foreach my $stored_what (@{$value}) {
1.629 banghart 7715: my $cmp2=$stored_what;
1.759 albertel 7716: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7717: $cmp2=join('',@{$stored_what});
1.745 raeburn 7718: }
1.629 banghart 7719: if ($cmp1 eq $cmp2) {
1.561 banghart 7720: push(@readonly_files, $file_name);
1.745 raeburn 7721: last;
1.563 banghart 7722: } elsif (!defined($what)) {
7723: push(@readonly_files, $file_name);
1.745 raeburn 7724: last;
1.561 banghart 7725: }
7726: }
1.745 raeburn 7727: }
1.561 banghart 7728: }
7729: return @readonly_files;
7730: }
1.577 banghart 7731: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7732:
1.577 banghart 7733: sub get_marked_as_readonly_hash {
1.745 raeburn 7734: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7735: my %readonly_files;
1.745 raeburn 7736: while (my ($file_name,$value) = each(%{$current_permissions})) {
7737: if (defined($group)) {
7738: if ($file_name !~ m-^\Q$group\E/-) {
7739: next;
7740: }
7741: }
1.577 banghart 7742: if (ref($value) eq "ARRAY"){
7743: foreach my $stored_what (@{$value}) {
1.745 raeburn 7744: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7745: foreach my $lock_descriptor(@{$stored_what}) {
7746: if ($lock_descriptor eq 'graded') {
7747: $readonly_files{$file_name} = 'graded';
7748: } elsif ($lock_descriptor eq 'handback') {
7749: $readonly_files{$file_name} = 'handback';
7750: } else {
7751: if (!exists($readonly_files{$file_name})) {
7752: $readonly_files{$file_name} = 'locked';
7753: }
7754: }
1.745 raeburn 7755: }
1.750 banghart 7756: }
1.577 banghart 7757: }
7758: }
7759: }
7760: return %readonly_files;
7761: }
1.559 banghart 7762: # ------------------------------------------------------------ Unmark as Read Only
7763:
7764: sub unmark_as_readonly {
1.629 banghart 7765: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7766: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7767: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7768: $file_name = &declutter_portfile($file_name);
1.634 albertel 7769: my $symb_crs = $what;
7770: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7771: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7772: my ($tmp)=keys(%current_permissions);
7773: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7774: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7775: foreach my $file (@readonly_files) {
1.759 albertel 7776: my $clean_file = &declutter_portfile($file);
7777: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7778: my $current_locks = $current_permissions{$file};
1.563 banghart 7779: my @new_locks;
7780: my @del_keys;
7781: if (ref($current_locks) eq "ARRAY"){
7782: foreach my $locker (@{$current_locks}) {
1.632 albertel 7783: my $compare=$locker;
1.749 raeburn 7784: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7785: $compare=join('',@{$locker});
1.746 raeburn 7786: if ($compare ne $symb_crs) {
7787: push(@new_locks, $locker);
7788: }
1.563 banghart 7789: }
7790: }
1.650 albertel 7791: if (scalar(@new_locks) > 0) {
1.563 banghart 7792: $current_permissions{$file} = \@new_locks;
7793: } else {
7794: push(@del_keys, $file);
1.613 albertel 7795: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7796: delete($current_permissions{$file});
1.563 banghart 7797: }
7798: }
1.561 banghart 7799: }
1.613 albertel 7800: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7801: return;
7802: }
1.512 banghart 7803:
1.17 www 7804: # ------------------------------------------------------------ Directory lister
7805:
7806: sub dirlist {
1.955 raeburn 7807: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7808: $uri=~s/^\///;
7809: $uri=~s/\/$//;
1.253 stredwic 7810: my ($udom, $uname);
1.955 raeburn 7811: if ($getuserdir) {
1.253 stredwic 7812: $udom = $userdomain;
7813: $uname = $username;
1.955 raeburn 7814: } else {
7815: (undef,$udom,$uname)=split(/\//,$uri);
7816: if(defined($userdomain)) {
7817: $udom = $userdomain;
7818: }
7819: if(defined($username)) {
7820: $uname = $username;
7821: }
1.253 stredwic 7822: }
1.955 raeburn 7823: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7824:
1.955 raeburn 7825: $dirRoot = $perlvar{'lonDocRoot'};
7826: if (defined($getpropath)) {
7827: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7828: $dirRoot =~ s/\/$//;
1.955 raeburn 7829: } elsif (defined($getuserdir)) {
7830: my $subdir=$uname.'__';
7831: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7832: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7833: ."/$udom/$subdir/$uname";
7834: } elsif (defined($alternateRoot)) {
7835: $dirRoot = $alternateRoot;
1.751 banghart 7836: }
1.253 stredwic 7837:
7838: if($udom) {
7839: if($uname) {
1.955 raeburn 7840: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7841: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7842: .':'.&escape($uname).':'.&escape($udom),
7843: &homeserver($uname,$udom));
7844: if ($listing eq 'unknown_cmd') {
7845: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7846: &homeserver($uname,$udom));
7847: } else {
7848: @listing_results = map { &unescape($_); } split(/:/,$listing);
7849: }
1.605 matthew 7850: if ($listing eq 'unknown_cmd') {
1.800 albertel 7851: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7852: &homeserver($uname,$udom));
1.605 matthew 7853: @listing_results = split(/:/,$listing);
7854: } else {
7855: @listing_results = map { &unescape($_); } split(/:/,$listing);
7856: }
7857: return @listing_results;
1.955 raeburn 7858: } elsif(!$alternateRoot) {
1.800 albertel 7859: my %allusers;
1.841 albertel 7860: my %servers = &get_servers($udom,'library');
1.955 raeburn 7861: foreach my $tryserver (keys(%servers)) {
7862: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7863: &escape($udom),$tryserver);
7864: if ($listing eq 'unknown_cmd') {
7865: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7866: $udom, $tryserver);
7867: } else {
7868: @listing_results = map { &unescape($_); } split(/:/,$listing);
7869: }
1.841 albertel 7870: if ($listing eq 'unknown_cmd') {
7871: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7872: $udom, $tryserver);
7873: @listing_results = split(/:/,$listing);
7874: } else {
7875: @listing_results =
7876: map { &unescape($_); } split(/:/,$listing);
7877: }
7878: if ($listing_results[0] ne 'no_such_dir' &&
7879: $listing_results[0] ne 'empty' &&
7880: $listing_results[0] ne 'con_lost') {
7881: foreach my $line (@listing_results) {
7882: my ($entry) = split(/&/,$line,2);
7883: $allusers{$entry} = 1;
7884: }
7885: }
1.253 stredwic 7886: }
7887: my $alluserstr='';
1.800 albertel 7888: foreach my $user (sort(keys(%allusers))) {
7889: $alluserstr.=$user.'&user:';
1.253 stredwic 7890: }
7891: $alluserstr=~s/:$//;
7892: return split(/:/,$alluserstr);
7893: } else {
1.800 albertel 7894: return ('missing user name');
1.253 stredwic 7895: }
1.955 raeburn 7896: } elsif(!defined($getpropath)) {
1.841 albertel 7897: my @all_domains = sort(&all_domains());
1.955 raeburn 7898: foreach my $domain (@all_domains) {
7899: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7900: }
7901: return @all_domains;
7902: } else {
1.800 albertel 7903: return ('missing domain');
1.275 stredwic 7904: }
7905: }
7906:
7907: # --------------------------------------------- GetFileTimestamp
7908: # This function utilizes dirlist and returns the date stamp for
7909: # when it was last modified. It will also return an error of -1
7910: # if an error occurs
7911:
7912: sub GetFileTimestamp {
1.955 raeburn 7913: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7914: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7915: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7916: my ($fileStat) =
7917: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7918: undef,$getuserdir);
1.275 stredwic 7919: my @stats = split('&', $fileStat);
7920: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7921: # @stats contains first the filename, then the stat output
7922: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7923: } else {
7924: return -1;
1.253 stredwic 7925: }
1.26 www 7926: }
7927:
1.712 albertel 7928: sub stat_file {
7929: my ($uri) = @_;
1.787 albertel 7930: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7931:
1.955 raeburn 7932: my ($udom,$uname,$file);
1.712 albertel 7933: if ($uri =~ m-^/(uploaded|editupload)/-) {
7934: ($udom,$uname,$file) =
1.811 albertel 7935: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7936: $file = 'userfiles/'.$file;
7937: }
7938: if ($uri =~ m-^/res/-) {
7939: ($udom,$uname) =
1.807 albertel 7940: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7941: $file = $uri;
7942: }
7943:
7944: if (!$udom || !$uname || !$file) {
7945: # unable to handle the uri
7946: return ();
7947: }
1.956 raeburn 7948: my $getpropath;
7949: if ($file =~ /^userfiles\//) {
7950: $getpropath = 1;
7951: }
1.955 raeburn 7952: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7953: my @stats = split('&', $result);
1.721 banghart 7954:
1.712 albertel 7955: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7956: shift(@stats); #filename is first
7957: return @stats;
7958: }
7959: return ();
7960: }
7961:
1.26 www 7962: # -------------------------------------------------------- Value of a Condition
7963:
1.713 albertel 7964: # gets the value of a specific preevaluated condition
7965: # stored in the string $env{user.state.<cid>}
7966: # or looks up a condition reference in the bighash and if if hasn't
7967: # already been evaluated recurses into docondval to get the value of
7968: # the condition, then memoizing it to
7969: # $env{user.state.<cid>.<condition>}
1.40 www 7970: sub directcondval {
7971: my $number=shift;
1.620 albertel 7972: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7973: &Apache::lonuserstate::evalstate();
7974: }
1.713 albertel 7975: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7976: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7977: } elsif ($number =~ /^_/) {
7978: my $sub_condition;
7979: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7980: &GDBM_READER(),0640)) {
7981: $sub_condition=$bighash{'conditions'.$number};
7982: untie(%bighash);
7983: }
7984: my $value = &docondval($sub_condition);
1.949 raeburn 7985: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7986: return $value;
7987: }
1.620 albertel 7988: if ($env{'user.state.'.$env{'request.course.id'}}) {
7989: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7990: } else {
7991: return 2;
7992: }
7993: }
7994:
1.713 albertel 7995: # get the collection of conditions for this resource
1.26 www 7996: sub condval {
7997: my $condidx=shift;
1.54 www 7998: my $allpathcond='';
1.713 albertel 7999: foreach my $cond (split(/\|/,$condidx)) {
8000: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8001: $allpathcond.=
8002: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8003: }
1.191 harris41 8004: }
1.54 www 8005: $allpathcond=~s/\|$//;
1.713 albertel 8006: return &docondval($allpathcond);
8007: }
8008:
8009: #evaluates an expression of conditions
8010: sub docondval {
8011: my ($allpathcond) = @_;
8012: my $result=0;
8013: if ($env{'request.course.id'}
8014: && defined($allpathcond)) {
8015: my $operand='|';
8016: my @stack;
8017: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8018: if ($chunk eq '(') {
8019: push @stack,($operand,$result);
8020: } elsif ($chunk eq ')') {
8021: my $before=pop @stack;
8022: if (pop @stack eq '&') {
8023: $result=$result>$before?$before:$result;
8024: } else {
8025: $result=$result>$before?$result:$before;
8026: }
8027: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8028: $operand=$chunk;
8029: } else {
8030: my $new=directcondval($chunk);
8031: if ($operand eq '&') {
8032: $result=$result>$new?$new:$result;
8033: } else {
8034: $result=$result>$new?$result:$new;
8035: }
8036: }
8037: }
1.26 www 8038: }
8039: return $result;
1.421 albertel 8040: }
8041:
8042: # ---------------------------------------------------- Devalidate courseresdata
8043:
8044: sub devalidatecourseresdata {
8045: my ($coursenum,$coursedomain)=@_;
8046: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8047: &devalidate_cache_new('courseres',$hashid);
1.28 www 8048: }
8049:
1.763 www 8050:
1.200 www 8051: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8052: #
8053: # Parameters:
8054: # $coursenum - Number of the course.
8055: # $coursedomain - Domain at which the course was created.
8056: # Returns:
8057: # A hash of the course parameters along (I think) with timestamps
8058: # and version info.
1.877 foxr 8059:
1.624 albertel 8060: sub get_courseresdata {
8061: my ($coursenum,$coursedomain)=@_;
1.200 www 8062: my $coursehom=&homeserver($coursenum,$coursedomain);
8063: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8064: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8065: my %dumpreply;
1.417 albertel 8066: unless (defined($cached)) {
1.624 albertel 8067: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8068: $result=\%dumpreply;
1.251 albertel 8069: my ($tmp) = keys(%dumpreply);
8070: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8071: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8072: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8073: return $tmp;
1.416 albertel 8074: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8075: $result=undef;
1.599 albertel 8076: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8077: }
8078: }
1.624 albertel 8079: return $result;
8080: }
8081:
1.633 albertel 8082: sub devalidateuserresdata {
8083: my ($uname,$udom)=@_;
8084: my $hashid="$udom:$uname";
8085: &devalidate_cache_new('userres',$hashid);
8086: }
8087:
1.624 albertel 8088: sub get_userresdata {
8089: my ($uname,$udom)=@_;
8090: #most student don\'t have any data set, check if there is some data
8091: if (&EXT_cache_status($udom,$uname)) { return undef; }
8092:
8093: my $hashid="$udom:$uname";
8094: my ($result,$cached)=&is_cached_new('userres',$hashid);
8095: if (!defined($cached)) {
8096: my %resourcedata=&dump('resourcedata',$udom,$uname);
8097: $result=\%resourcedata;
8098: &do_cache_new('userres',$hashid,$result,600);
8099: }
8100: my ($tmp)=keys(%$result);
8101: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8102: return $result;
8103: }
8104: #error 2 occurs when the .db doesn't exist
8105: if ($tmp!~/error: 2 /) {
1.672 albertel 8106: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8107: " Trying to get resource data for ".
8108: $uname." at ".$udom.": ".
8109: $tmp."</font>");
8110: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8111: #&EXT_cache_set($udom,$uname);
8112: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8113: undef($tmp); # not really an error so don't send it back
1.624 albertel 8114: }
8115: return $tmp;
8116: }
1.879 foxr 8117: #----------------------------------------------- resdata - return resource data
8118: # Purpose:
8119: # Return resource data for either users or for a course.
8120: # Parameters:
8121: # $name - Course/user name.
8122: # $domain - Name of the domain the user/course is registered on.
8123: # $type - Type of thing $name is (must be 'course' or 'user'
8124: # @which - Array of names of resources desired.
8125: # Returns:
8126: # The value of the first reasource in @which that is found in the
8127: # resource hash.
8128: # Exceptional Conditions:
8129: # If the $type passed in is not valid (not the string 'course' or
8130: # 'user', an undefined reference is returned.
8131: # If none of the resources are found, an undef is returned
1.624 albertel 8132: sub resdata {
8133: my ($name,$domain,$type,@which)=@_;
8134: my $result;
8135: if ($type eq 'course') {
8136: $result=&get_courseresdata($name,$domain);
8137: } elsif ($type eq 'user') {
8138: $result=&get_userresdata($name,$domain);
8139: }
8140: if (!ref($result)) { return $result; }
1.251 albertel 8141: foreach my $item (@which) {
1.927 albertel 8142: if (defined($result->{$item->[0]})) {
8143: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8144: }
1.250 albertel 8145: }
1.291 albertel 8146: return undef;
1.200 www 8147: }
8148:
1.379 matthew 8149: #
8150: # EXT resource caching routines
8151: #
8152:
8153: sub clear_EXT_cache_status {
1.383 albertel 8154: &delenv('cache.EXT.');
1.379 matthew 8155: }
8156:
8157: sub EXT_cache_status {
8158: my ($target_domain,$target_user) = @_;
1.383 albertel 8159: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8160: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8161: # We know already the user has no data
8162: return 1;
8163: } else {
8164: return 0;
8165: }
8166: }
8167:
8168: sub EXT_cache_set {
8169: my ($target_domain,$target_user) = @_;
1.383 albertel 8170: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8171: #&appenv({$cachename => time});
1.379 matthew 8172: }
8173:
1.28 www 8174: # --------------------------------------------------------- Value of a Variable
1.58 www 8175: sub EXT {
1.715 albertel 8176:
1.395 albertel 8177: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8178: unless ($varname) { return ''; }
1.218 albertel 8179: #get real user name/domain, courseid and symb
8180: my $courseid;
1.359 albertel 8181: my $publicuser;
1.427 www 8182: if ($symbparm) {
8183: $symbparm=&get_symb_from_alias($symbparm);
8184: }
1.218 albertel 8185: if (!($uname && $udom)) {
1.790 albertel 8186: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8187: if (!$symbparm) { $symbparm=$cursymb; }
8188: } else {
1.620 albertel 8189: $courseid=$env{'request.course.id'};
1.218 albertel 8190: }
1.48 www 8191: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8192: my $rest;
1.320 albertel 8193: if (defined($therest[0])) {
1.48 www 8194: $rest=join('.',@therest);
8195: } else {
8196: $rest='';
8197: }
1.320 albertel 8198:
1.57 www 8199: my $qualifierrest=$qualifier;
8200: if ($rest) { $qualifierrest.='.'.$rest; }
8201: my $spacequalifierrest=$space;
8202: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8203: if ($realm eq 'user') {
1.48 www 8204: # --------------------------------------------------------------- user.resource
8205: if ($space eq 'resource') {
1.651 albertel 8206: if ( (defined($Apache::lonhomework::parsing_a_problem)
8207: || defined($Apache::lonhomework::parsing_a_task))
8208: &&
1.744 albertel 8209: ($symbparm eq &symbread()) ) {
8210: # if we are in the middle of processing the resource the
8211: # get the value we are planning on committing
8212: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8213: return $Apache::lonhomework::results{$qualifierrest};
8214: } else {
8215: return $Apache::lonhomework::history{$qualifierrest};
8216: }
1.335 albertel 8217: } else {
1.359 albertel 8218: my %restored;
1.620 albertel 8219: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8220: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8221: } else {
8222: %restored=&restore($symbparm,$courseid,$udom,$uname);
8223: }
1.335 albertel 8224: return $restored{$qualifierrest};
8225: }
1.48 www 8226: # ----------------------------------------------------------------- user.access
8227: } elsif ($space eq 'access') {
1.218 albertel 8228: # FIXME - not supporting calls for a specific user
1.48 www 8229: return &allowed($qualifier,$rest);
8230: # ------------------------------------------ user.preferences, user.environment
8231: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8232: if (($uname eq $env{'user.name'}) &&
8233: ($udom eq $env{'user.domain'})) {
8234: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8235: } else {
1.359 albertel 8236: my %returnhash;
8237: if (!$publicuser) {
8238: %returnhash=&userenvironment($udom,$uname,
8239: $qualifierrest);
8240: }
1.218 albertel 8241: return $returnhash{$qualifierrest};
8242: }
1.48 www 8243: # ----------------------------------------------------------------- user.course
8244: } elsif ($space eq 'course') {
1.218 albertel 8245: # FIXME - not supporting calls for a specific user
1.620 albertel 8246: return $env{join('.',('request.course',$qualifier))};
1.48 www 8247: # ------------------------------------------------------------------- user.role
8248: } elsif ($space eq 'role') {
1.218 albertel 8249: # FIXME - not supporting calls for a specific user
1.620 albertel 8250: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8251: if ($qualifier eq 'value') {
8252: return $role;
8253: } elsif ($qualifier eq 'extent') {
8254: return $where;
8255: }
8256: # ----------------------------------------------------------------- user.domain
8257: } elsif ($space eq 'domain') {
1.218 albertel 8258: return $udom;
1.48 www 8259: # ------------------------------------------------------------------- user.name
8260: } elsif ($space eq 'name') {
1.218 albertel 8261: return $uname;
1.48 www 8262: # ---------------------------------------------------- Any other user namespace
1.29 www 8263: } else {
1.359 albertel 8264: my %reply;
8265: if (!$publicuser) {
8266: %reply=&get($space,[$qualifierrest],$udom,$uname);
8267: }
8268: return $reply{$qualifierrest};
1.48 www 8269: }
1.236 www 8270: } elsif ($realm eq 'query') {
8271: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8272: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8273: [$spacequalifierrest]);
1.620 albertel 8274: return $env{'form.'.$spacequalifierrest};
1.236 www 8275: } elsif ($realm eq 'request') {
1.48 www 8276: # ------------------------------------------------------------- request.browser
8277: if ($space eq 'browser') {
1.430 www 8278: if ($qualifier eq 'textremote') {
1.676 albertel 8279: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8280: return 1;
8281: } else {
8282: return 0;
8283: }
8284: } else {
1.620 albertel 8285: return $env{'browser.'.$qualifier};
1.430 www 8286: }
1.57 www 8287: # ------------------------------------------------------------ request.filename
8288: } else {
1.620 albertel 8289: return $env{'request.'.$spacequalifierrest};
1.29 www 8290: }
1.28 www 8291: } elsif ($realm eq 'course') {
1.48 www 8292: # ---------------------------------------------------------- course.description
1.620 albertel 8293: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8294: } elsif ($realm eq 'resource') {
1.165 www 8295:
1.620 albertel 8296: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8297: if (!$symbparm) { $symbparm=&symbread(); }
8298: }
1.693 albertel 8299:
8300: if ($space eq 'title') {
8301: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8302: return &gettitle($symbparm);
8303: }
8304:
8305: if ($space eq 'map') {
8306: my ($map) = &decode_symb($symbparm);
8307: return &symbread($map);
8308: }
1.905 albertel 8309: if ($space eq 'filename') {
8310: if ($symbparm) {
8311: return &clutter((&decode_symb($symbparm))[2]);
8312: }
8313: return &hreflocation('',$env{'request.filename'});
8314: }
1.693 albertel 8315:
8316: my ($section, $group, @groups);
1.593 albertel 8317: my ($courselevelm,$courselevel);
1.539 albertel 8318: if ($symbparm && defined($courseid) &&
1.620 albertel 8319: $courseid eq $env{'request.course.id'}) {
1.165 www 8320:
1.218 albertel 8321: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8322:
1.60 www 8323: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8324: my $symbp=$symbparm;
1.735 albertel 8325: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8326:
8327: my $symbparm=$symbp.'.'.$spacequalifierrest;
8328: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8329:
1.620 albertel 8330: if (($env{'user.name'} eq $uname) &&
8331: ($env{'user.domain'} eq $udom)) {
8332: $section=$env{'request.course.sec'};
1.733 raeburn 8333: @groups = split(/:/,$env{'request.course.groups'});
8334: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8335: } else {
1.539 albertel 8336: if (! defined($usection)) {
1.551 albertel 8337: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8338: } else {
8339: $section = $usection;
8340: }
1.733 raeburn 8341: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8342: }
8343:
8344: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8345: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8346: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8347:
1.593 albertel 8348: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8349: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8350: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8351:
1.60 www 8352: # ----------------------------------------------------------- first, check user
1.624 albertel 8353:
8354: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8355: ([$courselevelr,'resource'],
8356: [$courselevelm,'map' ],
8357: [$courselevel, 'course' ]));
1.931 albertel 8358: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8359:
1.594 albertel 8360: # ------------------------------------------------ second, check some of course
1.684 raeburn 8361: my $coursereply;
1.691 raeburn 8362: if (@groups > 0) {
8363: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8364: $mapparm,$spacequalifierrest);
1.927 albertel 8365: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8366: }
1.96 www 8367:
1.684 raeburn 8368: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8369: $env{'course.'.$courseid.'.domain'},
8370: 'course',
8371: ([$seclevelr, 'resource'],
8372: [$seclevelm, 'map' ],
8373: [$seclevel, 'course' ],
8374: [$courselevelr,'resource']));
8375: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8376:
1.60 www 8377: # ------------------------------------------------------ third, check map parms
1.218 albertel 8378: my %parmhash=();
8379: my $thisparm='';
8380: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8381: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8382: &GDBM_READER(),0640)) {
1.218 albertel 8383: $thisparm=$parmhash{$symbparm};
8384: untie(%parmhash);
8385: }
1.927 albertel 8386: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8387: }
1.594 albertel 8388: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8389:
1.218 albertel 8390: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8391: my $filename;
8392: if (!$symbparm) { $symbparm=&symbread(); }
8393: if ($symbparm) {
1.409 www 8394: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8395: } else {
1.620 albertel 8396: $filename=$env{'request.filename'};
1.282 albertel 8397: }
8398: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8399: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8400: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8401: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8402:
1.927 albertel 8403: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8404: if ($symbparm && defined($courseid) &&
1.620 albertel 8405: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8406: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8407: $env{'course.'.$courseid.'.domain'},
8408: 'course',
1.927 albertel 8409: ([$courselevelm,'map' ],
8410: [$courselevel, 'course']));
8411: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8412: }
1.145 www 8413: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8414: unless ($space eq '0') {
1.336 albertel 8415: my @parts=split(/_/,$space);
8416: my $id=pop(@parts);
8417: my $part=join('_',@parts);
8418: if ($part eq '') { $part='0'; }
1.927 albertel 8419: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8420: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8421: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8422: }
1.395 albertel 8423: if ($recurse) { return undef; }
8424: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8425: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8426: # ---------------------------------------------------- Any other user namespace
8427: } elsif ($realm eq 'environment') {
8428: # ----------------------------------------------------------------- environment
1.620 albertel 8429: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8430: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8431: } else {
1.770 albertel 8432: if ($uname eq 'anonymous' && $udom eq '') {
8433: return '';
8434: }
1.219 albertel 8435: my %returnhash=&userenvironment($udom,$uname,
8436: $spacequalifierrest);
8437: return $returnhash{$spacequalifierrest};
8438: }
1.28 www 8439: } elsif ($realm eq 'system') {
1.48 www 8440: # ----------------------------------------------------------------- system.time
8441: if ($space eq 'time') {
8442: return time;
8443: }
1.696 albertel 8444: } elsif ($realm eq 'server') {
8445: # ----------------------------------------------------------------- system.time
8446: if ($space eq 'name') {
8447: return $ENV{'SERVER_NAME'};
8448: }
1.28 www 8449: }
1.48 www 8450: return '';
1.61 www 8451: }
8452:
1.927 albertel 8453: sub get_reply {
8454: my ($reply_value) = @_;
1.940 raeburn 8455: if (ref($reply_value) eq 'ARRAY') {
8456: if (wantarray) {
8457: return @$reply_value;
8458: }
8459: return $reply_value->[0];
8460: } else {
8461: return $reply_value;
1.927 albertel 8462: }
8463: }
8464:
1.691 raeburn 8465: sub check_group_parms {
8466: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8467: my @groupitems = ();
8468: my $resultitem;
1.927 albertel 8469: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8470: foreach my $group (@{$groups}) {
8471: foreach my $level (@levels) {
1.927 albertel 8472: my $item = $courseid.'.['.$group.'].'.$level->[0];
8473: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8474: }
8475: }
8476: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8477: $env{'course.'.$courseid.'.domain'},
8478: 'course',@groupitems);
8479: return $coursereply;
8480: }
8481:
8482: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8483: my ($courseid,@groups) = @_;
8484: @groups = sort(@groups);
1.691 raeburn 8485: return @groups;
8486: }
8487:
1.395 albertel 8488: sub packages_tab_default {
8489: my ($uri,$varname)=@_;
8490: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8491:
8492: my (@extension,@specifics,$do_default);
8493: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8494: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8495: if ($pack_type eq 'default') {
8496: $do_default=1;
8497: } elsif ($pack_type eq 'extension') {
8498: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8499: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8500: # only look at packages defaults for packages that this id is
1.738 albertel 8501: push(@specifics,[$package,$pack_type,$pack_part]);
8502: }
8503: }
8504: # first look for a package that matches the requested part id
8505: foreach my $package (@specifics) {
8506: my (undef,$pack_type,$pack_part)=@{$package};
8507: next if ($pack_part ne $part);
8508: if (defined($packagetab{"$pack_type&$name&default"})) {
8509: return $packagetab{"$pack_type&$name&default"};
8510: }
8511: }
8512: # look for any possible matching non extension_ package
8513: foreach my $package (@specifics) {
8514: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8515: if (defined($packagetab{"$pack_type&$name&default"})) {
8516: return $packagetab{"$pack_type&$name&default"};
8517: }
1.585 albertel 8518: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8519: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8520: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8521: }
8522: }
1.738 albertel 8523: # look for any posible extension_ match
8524: foreach my $package (@extension) {
8525: my ($package,$pack_type)=@{$package};
8526: if (defined($packagetab{"$pack_type&$name&default"})) {
8527: return $packagetab{"$pack_type&$name&default"};
8528: }
8529: if (defined($packagetab{$package."&$name&default"})) {
8530: return $packagetab{$package."&$name&default"};
8531: }
8532: }
8533: # look for a global default setting
8534: if ($do_default && defined($packagetab{"default&$name&default"})) {
8535: return $packagetab{"default&$name&default"};
8536: }
1.395 albertel 8537: return undef;
8538: }
8539:
1.334 albertel 8540: sub add_prefix_and_part {
8541: my ($prefix,$part)=@_;
8542: my $keyroot;
8543: if (defined($prefix) && $prefix !~ /^__/) {
8544: # prefix that has a part already
8545: $keyroot=$prefix;
8546: } elsif (defined($prefix)) {
8547: # prefix that is missing a part
8548: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8549: } else {
8550: # no prefix at all
8551: if (defined($part)) { $keyroot='_'.$part; }
8552: }
8553: return $keyroot;
8554: }
8555:
1.71 www 8556: # ---------------------------------------------------------------- Get metadata
8557:
1.599 albertel 8558: my %metaentry;
1.71 www 8559: sub metadata {
1.176 www 8560: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8561: $uri=&declutter($uri);
1.288 albertel 8562: # if it is a non metadata possible uri return quickly
1.529 albertel 8563: if (($uri eq '') ||
8564: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8565: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1056.4.13! raeburn 8566: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^\*uploaded\/.+\.sequence$/) ) {
1.924 albertel 8567: return undef;
8568: }
8569: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8570: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8571: return undef;
1.288 albertel 8572: }
1.73 www 8573: my $filename=$uri;
8574: $uri=~s/\.meta$//;
1.172 www 8575: #
8576: # Is the metadata already cached?
1.177 www 8577: # Look at timestamp of caching
1.172 www 8578: # Everything is cached by the main uri, libraries are never directly cached
8579: #
1.428 albertel 8580: if (!defined($liburi)) {
1.599 albertel 8581: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8582: if (defined($cached)) { return $result->{':'.$what}; }
8583: }
8584: {
1.172 www 8585: #
8586: # Is this a recursive call for a library?
8587: #
1.599 albertel 8588: # if (! exists($metacache{$uri})) {
8589: # $metacache{$uri}={};
8590: # }
1.924 albertel 8591: my $cachetime = 60*60;
1.171 www 8592: if ($liburi) {
8593: $liburi=&declutter($liburi);
8594: $filename=$liburi;
1.401 bowersj2 8595: } else {
1.599 albertel 8596: &devalidate_cache_new('meta',$uri);
8597: undef(%metaentry);
1.401 bowersj2 8598: }
1.140 www 8599: my %metathesekeys=();
1.73 www 8600: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8601: my $metastring;
1.924 albertel 8602: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8603: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8604: $metastring =
1.929 albertel 8605: &Apache::lonnet::ssi_body($which,
1.924 albertel 8606: ('grade_target' => 'meta'));
8607: $cachetime = 1; # only want this cached in the child not long term
8608: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8609: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8610: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8611: $metastring=&getfile($file);
1.489 albertel 8612: }
1.208 albertel 8613: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8614: my $token;
1.140 www 8615: undef %metathesekeys;
1.71 www 8616: while ($token=$parser->get_token) {
1.339 albertel 8617: if ($token->[0] eq 'S') {
8618: if (defined($token->[2]->{'package'})) {
1.172 www 8619: #
8620: # This is a package - get package info
8621: #
1.339 albertel 8622: my $package=$token->[2]->{'package'};
8623: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8624: if (defined($token->[2]->{'id'})) {
8625: $keyroot.='_'.$token->[2]->{'id'};
8626: }
1.599 albertel 8627: if ($metaentry{':packages'}) {
8628: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8629: } else {
1.599 albertel 8630: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8631: }
1.736 albertel 8632: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8633: my $part=$keyroot;
8634: $part=~s/^\_//;
1.736 albertel 8635: if ($pack_entry=~/^\Q$package\E\&/ ||
8636: $pack_entry=~/^\Q$package\E_0\&/) {
8637: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8638: # ignore package.tab specified default values
8639: # here &package_tab_default() will fetch those
8640: if ($subp eq 'default') { next; }
1.736 albertel 8641: my $value=$packagetab{$pack_entry};
1.432 albertel 8642: my $unikey;
8643: if ($pack =~ /_0$/) {
8644: $unikey='parameter_0_'.$name;
8645: $part=0;
8646: } else {
8647: $unikey='parameter'.$keyroot.'_'.$name;
8648: }
1.339 albertel 8649: if ($subp eq 'display') {
8650: $value.=' [Part: '.$part.']';
8651: }
1.599 albertel 8652: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8653: $metathesekeys{$unikey}=1;
1.599 albertel 8654: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8655: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8656: }
1.599 albertel 8657: if (defined($metaentry{':'.$unikey.'.default'})) {
8658: $metaentry{':'.$unikey}=
8659: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8660: }
1.339 albertel 8661: }
8662: }
8663: } else {
1.172 www 8664: #
8665: # This is not a package - some other kind of start tag
1.339 albertel 8666: #
8667: my $entry=$token->[1];
8668: my $unikey;
8669: if ($entry eq 'import') {
8670: $unikey='';
8671: } else {
8672: $unikey=$entry;
8673: }
8674: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8675:
8676: if (defined($token->[2]->{'id'})) {
8677: $unikey.='_'.$token->[2]->{'id'};
8678: }
1.175 www 8679:
1.339 albertel 8680: if ($entry eq 'import') {
1.175 www 8681: #
8682: # Importing a library here
1.339 albertel 8683: #
8684: if ($depthcount<20) {
8685: my $location=$parser->get_text('/import');
8686: my $dir=$filename;
8687: $dir=~s|[^/]*$||;
8688: $location=&filelocation($dir,$location);
1.736 albertel 8689: my $metadata =
8690: &metadata($uri,'keys', $location,$unikey,
8691: $depthcount+1);
8692: foreach my $meta (split(',',$metadata)) {
8693: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8694: $metathesekeys{$meta}=1;
1.339 albertel 8695: }
8696: }
8697: } else {
8698: if (defined($token->[2]->{'name'})) {
8699: $unikey.='_'.$token->[2]->{'name'};
8700: }
8701: $metathesekeys{$unikey}=1;
1.736 albertel 8702: foreach my $param (@{$token->[3]}) {
8703: $metaentry{':'.$unikey.'.'.$param} =
8704: $token->[2]->{$param};
1.339 albertel 8705: }
8706: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8707: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8708: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8709: # only ws inside the tag, and not in default, so use default
8710: # as value
1.599 albertel 8711: $metaentry{':'.$unikey}=$default;
1.908 albertel 8712: } elsif ( $internaltext =~ /\S/ ) {
8713: # something interesting inside the tag
8714: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8715: } else {
1.908 albertel 8716: # no interesting values, don't set a default
1.339 albertel 8717: }
1.172 www 8718: # end of not-a-package not-a-library import
1.339 albertel 8719: }
1.172 www 8720: # end of not-a-package start tag
1.339 albertel 8721: }
1.172 www 8722: # the next is the end of "start tag"
1.339 albertel 8723: }
8724: }
1.483 albertel 8725: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8726: $extension = lc($extension);
8727: if ($extension eq 'htm') { $extension='html'; }
8728:
1.737 albertel 8729: foreach my $key (keys(%packagetab)) {
1.483 albertel 8730: #no specific packages #how's our extension
8731: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8732: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8733: \%metathesekeys);
8734: }
1.883 albertel 8735:
8736: if (!exists($metaentry{':packages'})
8737: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8738: foreach my $key (keys(%packagetab)) {
1.483 albertel 8739: #no specific packages well let's get default then
8740: if ($key!~/^default&/) { next; }
1.488 albertel 8741: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8742: \%metathesekeys);
8743: }
8744: }
1.338 www 8745: # are there custom rights to evaluate
1.599 albertel 8746: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8747:
1.338 www 8748: #
8749: # Importing a rights file here
1.339 albertel 8750: #
8751: unless ($depthcount) {
1.599 albertel 8752: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8753: my $dir=$filename;
8754: $dir=~s|[^/]*$||;
8755: $location=&filelocation($dir,$location);
1.736 albertel 8756: my $rights_metadata =
8757: &metadata($uri,'keys',$location,'_rights',
8758: $depthcount+1);
8759: foreach my $rights (split(',',$rights_metadata)) {
8760: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8761: $metathesekeys{$rights}=1;
1.339 albertel 8762: }
8763: }
8764: }
1.737 albertel 8765: # uniqifiy package listing
8766: my %seen;
8767: my @uniq_packages =
8768: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8769: $metaentry{':packages'} = join(',',@uniq_packages);
8770:
8771: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8772: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8773: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8774: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8775: # this is the end of "was not already recently cached
1.71 www 8776: }
1.599 albertel 8777: return $metaentry{':'.$what};
1.261 albertel 8778: }
8779:
1.488 albertel 8780: sub metadata_create_package_def {
1.483 albertel 8781: my ($uri,$key,$package,$metathesekeys)=@_;
8782: my ($pack,$name,$subp)=split(/\&/,$key);
8783: if ($subp eq 'default') { next; }
8784:
1.599 albertel 8785: if (defined($metaentry{':packages'})) {
8786: $metaentry{':packages'}.=','.$package;
1.483 albertel 8787: } else {
1.599 albertel 8788: $metaentry{':packages'}=$package;
1.483 albertel 8789: }
8790: my $value=$packagetab{$key};
8791: my $unikey;
8792: $unikey='parameter_0_'.$name;
1.599 albertel 8793: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8794: $$metathesekeys{$unikey}=1;
1.599 albertel 8795: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8796: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8797: }
1.599 albertel 8798: if (defined($metaentry{':'.$unikey.'.default'})) {
8799: $metaentry{':'.$unikey}=
8800: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8801: }
8802: }
8803:
1.261 albertel 8804: sub metadata_generate_part0 {
8805: my ($metadata,$metacache,$uri) = @_;
8806: my %allnames;
1.737 albertel 8807: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8808: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8809: my $part=$$metacache{':'.$metakey.'.part'};
8810: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8811: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8812: $allnames{$name}=$part;
8813: }
8814: }
8815: }
8816: foreach my $name (keys(%allnames)) {
8817: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8818: my $key=":parameter_0_$name";
1.261 albertel 8819: $$metacache{"$key.part"}='0';
8820: $$metacache{"$key.name"}=$name;
1.428 albertel 8821: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8822: $allnames{$name}.'_'.$name.
8823: '.type'};
1.428 albertel 8824: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8825: '.display'};
1.644 www 8826: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8827: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8828: $$metacache{"$key.display"}=$olddis;
8829: }
1.71 www 8830: }
8831:
1.764 albertel 8832: # ------------------------------------------------------ Devalidate title cache
8833:
8834: sub devalidate_title_cache {
8835: my ($url)=@_;
8836: if (!$env{'request.course.id'}) { return; }
8837: my $symb=&symbread($url);
8838: if (!$symb) { return; }
8839: my $key=$env{'request.course.id'}."\0".$symb;
8840: &devalidate_cache_new('title',$key);
8841: }
8842:
1.1014 droeschl 8843: # ------------------------------------------------- Get the title of a course
8844:
8845: sub current_course_title {
8846: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8847: }
1.301 www 8848: # ------------------------------------------------- Get the title of a resource
8849:
8850: sub gettitle {
8851: my $urlsymb=shift;
8852: my $symb=&symbread($urlsymb);
1.534 albertel 8853: if ($symb) {
1.620 albertel 8854: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8855: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8856: if (defined($cached)) {
8857: return $result;
8858: }
1.534 albertel 8859: my ($map,$resid,$url)=&decode_symb($symb);
8860: my $title='';
1.907 albertel 8861: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8862: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8863: } else {
8864: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8865: &GDBM_READER(),0640)) {
8866: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8867: $title=$bighash{'title_'.$mapid.'.'.$resid};
8868: untie(%bighash);
8869: }
1.534 albertel 8870: }
8871: $title=~s/\&colon\;/\:/gs;
8872: if ($title) {
1.599 albertel 8873: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8874: }
8875: $urlsymb=$url;
8876: }
8877: my $title=&metadata($urlsymb,'title');
8878: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8879: return $title;
1.301 www 8880: }
1.613 albertel 8881:
1.614 albertel 8882: sub get_slot {
8883: my ($which,$cnum,$cdom)=@_;
8884: if (!$cnum || !$cdom) {
1.790 albertel 8885: (undef,my $courseid)=&whichuser();
1.620 albertel 8886: $cdom=$env{'course.'.$courseid.'.domain'};
8887: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8888: }
1.703 albertel 8889: my $key=join("\0",'slots',$cdom,$cnum,$which);
8890: my %slotinfo;
8891: if (exists($remembered{$key})) {
8892: $slotinfo{$which} = $remembered{$key};
8893: } else {
8894: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8895: &Apache::lonhomework::showhash(%slotinfo);
8896: my ($tmp)=keys(%slotinfo);
8897: if ($tmp=~/^error:/) { return (); }
8898: $remembered{$key} = $slotinfo{$which};
8899: }
1.616 albertel 8900: if (ref($slotinfo{$which}) eq 'HASH') {
8901: return %{$slotinfo{$which}};
8902: }
8903: return $slotinfo{$which};
1.614 albertel 8904: }
1.31 www 8905: # ------------------------------------------------- Update symbolic store links
8906:
8907: sub symblist {
8908: my ($mapname,%newhash)=@_;
1.438 www 8909: $mapname=&deversion(&declutter($mapname));
1.31 www 8910: my %hash;
1.620 albertel 8911: if (($env{'request.course.fn'}) && (%newhash)) {
8912: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8913: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8914: foreach my $url (keys(%newhash)) {
1.711 albertel 8915: next if ($url eq 'last_known'
8916: && $env{'form.no_update_last_known'});
8917: $hash{declutter($url)}=&encode_symb($mapname,
8918: $newhash{$url}->[1],
8919: $newhash{$url}->[0]);
1.191 harris41 8920: }
1.31 www 8921: if (untie(%hash)) {
8922: return 'ok';
8923: }
8924: }
8925: }
8926: return 'error';
1.212 www 8927: }
8928:
8929: # --------------------------------------------------------------- Verify a symb
8930:
8931: sub symbverify {
1.510 www 8932: my ($symb,$thisurl)=@_;
8933: my $thisfn=$thisurl;
1.439 www 8934: $thisfn=&declutter($thisfn);
1.215 www 8935: # direct jump to resource in page or to a sequence - will construct own symbs
8936: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8937: # check URL part
1.409 www 8938: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8939:
1.431 www 8940: unless ($url eq $thisfn) { return 0; }
1.213 www 8941:
1.216 www 8942: $symb=&symbclean($symb);
1.510 www 8943: $thisurl=&deversion($thisurl);
1.439 www 8944: $thisfn=&deversion($thisfn);
1.213 www 8945:
8946: my %bighash;
8947: my $okay=0;
1.431 www 8948:
1.620 albertel 8949: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8950: &GDBM_READER(),0640)) {
1.1032 raeburn 8951: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8952: $thisurl =~ s/\?.+$//;
8953: }
1.510 www 8954: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8955: unless ($ids) {
1.510 www 8956: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8957: }
8958: if ($ids) {
8959: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8960: foreach my $id (split(/\,/,$ids)) {
8961: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8962: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8963: $symb =~ s/\?.+$//;
8964: }
1.216 www 8965: if (
8966: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8967: eq $symb) {
1.620 albertel 8968: if (($env{'request.role.adv'}) ||
1.800 albertel 8969: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8970: $okay=1;
8971: }
8972: }
1.216 www 8973: }
8974: }
1.213 www 8975: untie(%bighash);
8976: }
8977: return $okay;
1.31 www 8978: }
8979:
1.210 www 8980: # --------------------------------------------------------------- Clean-up symb
8981:
8982: sub symbclean {
8983: my $symb=shift;
1.568 albertel 8984: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8985: # remove version from map
8986: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8987:
1.210 www 8988: # remove version from URL
8989: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8990:
1.507 www 8991: # remove wrapper
8992:
1.510 www 8993: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8994: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8995: return $symb;
1.409 www 8996: }
8997:
8998: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8999:
9000: sub encode_symb {
9001: my ($map,$resid,$url)=@_;
9002: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9003: }
1.409 www 9004:
9005: sub decode_symb {
1.568 albertel 9006: my $symb=shift;
9007: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9008: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9009: return (&fixversion($map),$resid,&fixversion($url));
9010: }
9011:
9012: sub fixversion {
9013: my $fn=shift;
1.609 banghart 9014: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9015: my %bighash;
9016: my $uri=&clutter($fn);
1.620 albertel 9017: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9018: # is this cached?
1.599 albertel 9019: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9020: if (defined($cached)) { return $result; }
9021: # unfortunately not cached, or expired
1.620 albertel 9022: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9023: &GDBM_READER(),0640)) {
9024: if ($bighash{'version_'.$uri}) {
9025: my $version=$bighash{'version_'.$uri};
1.444 www 9026: unless (($version eq 'mostrecent') ||
9027: ($version==&getversion($uri))) {
1.440 www 9028: $uri=~s/\.(\w+)$/\.$version\.$1/;
9029: }
9030: }
9031: untie %bighash;
1.413 www 9032: }
1.599 albertel 9033: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9034: }
9035:
9036: sub deversion {
9037: my $url=shift;
9038: $url=~s/\.\d+\.(\w+)$/\.$1/;
9039: return $url;
1.210 www 9040: }
9041:
1.31 www 9042: # ------------------------------------------------------ Return symb list entry
9043:
9044: sub symbread {
1.249 www 9045: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9046: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9047: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9048: # no filename provided? try from environment
1.44 www 9049: unless ($thisfn) {
1.620 albertel 9050: if ($env{'request.symb'}) {
9051: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9052: }
1.620 albertel 9053: $thisfn=$env{'request.filename'};
1.44 www 9054: }
1.569 albertel 9055: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9056: # is that filename actually a symb? Verify, clean, and return
9057: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9058: if (&symbverify($thisfn,$1)) {
1.620 albertel 9059: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9060: }
1.242 www 9061: }
1.44 www 9062: $thisfn=declutter($thisfn);
1.31 www 9063: my %hash;
1.37 www 9064: my %bighash;
9065: my $syval='';
1.620 albertel 9066: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9067: my $targetfn = $thisfn;
1.609 banghart 9068: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9069: $targetfn = 'adm/wrapper/'.$thisfn;
9070: }
1.687 albertel 9071: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9072: $targetfn=$1;
9073: }
1.620 albertel 9074: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9075: &GDBM_READER(),0640)) {
1.481 raeburn 9076: $syval=$hash{$targetfn};
1.37 www 9077: untie(%hash);
9078: }
9079: # ---------------------------------------------------------- There was an entry
9080: if ($syval) {
1.601 albertel 9081: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9082: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9083: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9084: #return $env{$cache_str}='';
1.601 albertel 9085: #}
9086: #$syval.=$1;
9087: #}
1.37 www 9088: } else {
9089: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9090: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9091: &GDBM_READER(),0640)) {
1.37 www 9092: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9093: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9094: unless ($ids) {
9095: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9096: }
9097: unless ($ids) {
9098: # alias?
9099: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9100: }
1.37 www 9101: if ($ids) {
9102: # ------------------------------------------------------------------- Has ID(s)
9103: my @possibilities=split(/\,/,$ids);
1.39 www 9104: if ($#possibilities==0) {
9105: # ----------------------------------------------- There is only one possibility
1.37 www 9106: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9107: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9108: $resid,$thisfn);
1.249 www 9109: } elsif (!$donotrecurse) {
1.39 www 9110: # ------------------------------------------ There is more than one possibility
9111: my $realpossible=0;
1.800 albertel 9112: foreach my $id (@possibilities) {
9113: my $file=$bighash{'src_'.$id};
1.39 www 9114: if (&allowed('bre',$file)) {
1.800 albertel 9115: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9116: if ($bighash{'map_type_'.$mapid} ne 'page') {
9117: $realpossible++;
1.626 albertel 9118: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9119: $resid,$thisfn);
1.39 www 9120: }
9121: }
1.191 harris41 9122: }
1.39 www 9123: if ($realpossible!=1) { $syval=''; }
1.249 www 9124: } else {
9125: $syval='';
1.37 www 9126: }
9127: }
9128: untie(%bighash)
1.481 raeburn 9129: }
1.31 www 9130: }
1.62 www 9131: if ($syval) {
1.620 albertel 9132: return $env{$cache_str}=$syval;
1.62 www 9133: }
1.31 www 9134: }
1.949 raeburn 9135: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9136: return $env{$cache_str}='';
1.31 www 9137: }
9138:
9139: # ---------------------------------------------------------- Return random seed
9140:
1.32 www 9141: sub numval {
9142: my $txt=shift;
9143: $txt=~tr/A-J/0-9/;
9144: $txt=~tr/a-j/0-9/;
9145: $txt=~tr/K-T/0-9/;
9146: $txt=~tr/k-t/0-9/;
9147: $txt=~tr/U-Z/0-5/;
9148: $txt=~tr/u-z/0-5/;
9149: $txt=~s/\D//g;
1.564 albertel 9150: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9151: return int($txt);
1.368 albertel 9152: }
9153:
1.484 albertel 9154: sub numval2 {
9155: my $txt=shift;
9156: $txt=~tr/A-J/0-9/;
9157: $txt=~tr/a-j/0-9/;
9158: $txt=~tr/K-T/0-9/;
9159: $txt=~tr/k-t/0-9/;
9160: $txt=~tr/U-Z/0-5/;
9161: $txt=~tr/u-z/0-5/;
9162: $txt=~s/\D//g;
9163: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9164: my $total;
9165: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9166: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9167: return int($total);
9168: }
9169:
1.575 albertel 9170: sub numval3 {
9171: use integer;
9172: my $txt=shift;
9173: $txt=~tr/A-J/0-9/;
9174: $txt=~tr/a-j/0-9/;
9175: $txt=~tr/K-T/0-9/;
9176: $txt=~tr/k-t/0-9/;
9177: $txt=~tr/U-Z/0-5/;
9178: $txt=~tr/u-z/0-5/;
9179: $txt=~s/\D//g;
9180: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9181: my $total;
9182: foreach my $val (@txts) { $total+=$val; }
9183: if ($_64bit) { $total=(($total<<32)>>32); }
9184: return $total;
9185: }
9186:
1.675 albertel 9187: sub digest {
9188: my ($data)=@_;
9189: my $digest=&Digest::MD5::md5($data);
9190: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9191: my ($e,$f);
9192: {
9193: use integer;
9194: $e=($a+$b);
9195: $f=($c+$d);
9196: if ($_64bit) {
9197: $e=(($e<<32)>>32);
9198: $f=(($f<<32)>>32);
9199: }
9200: }
9201: if (wantarray) {
9202: return ($e,$f);
9203: } else {
9204: my $g;
9205: {
9206: use integer;
9207: $g=($e+$f);
9208: if ($_64bit) {
9209: $g=(($g<<32)>>32);
9210: }
9211: }
9212: return $g;
9213: }
9214: }
9215:
1.368 albertel 9216: sub latest_rnd_algorithm_id {
1.675 albertel 9217: return '64bit5';
1.366 albertel 9218: }
1.32 www 9219:
1.503 albertel 9220: sub get_rand_alg {
9221: my ($courseid)=@_;
1.790 albertel 9222: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9223: if ($courseid) {
1.620 albertel 9224: return $env{"course.$courseid.rndseed"};
1.503 albertel 9225: }
9226: return &latest_rnd_algorithm_id();
9227: }
9228:
1.562 albertel 9229: sub validCODE {
9230: my ($CODE)=@_;
9231: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9232: return 0;
9233: }
9234:
1.491 albertel 9235: sub getCODE {
1.620 albertel 9236: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9237: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9238: defined($Apache::lonhomework::parsing_a_task) ) &&
9239: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9240: return $Apache::lonhomework::history{'resource.CODE'};
9241: }
9242: return undef;
9243: }
9244:
1.31 www 9245: sub rndseed {
1.155 albertel 9246: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9247: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9248: if (!defined($symb)) {
1.366 albertel 9249: unless ($symb=$wsymb) { return time; }
9250: }
9251: if (!$courseid) { $courseid=$wcourseid; }
9252: if (!$domain) { $domain=$wdomain; }
9253: if (!$username) { $username=$wusername }
1.503 albertel 9254: my $which=&get_rand_alg();
1.803 albertel 9255:
1.491 albertel 9256: if (defined(&getCODE())) {
1.675 albertel 9257: if ($which eq '64bit5') {
9258: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9259: } elsif ($which eq '64bit4') {
1.575 albertel 9260: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9261: } else {
9262: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9263: }
1.675 albertel 9264: } elsif ($which eq '64bit5') {
9265: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9266: } elsif ($which eq '64bit4') {
9267: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9268: } elsif ($which eq '64bit3') {
9269: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9270: } elsif ($which eq '64bit2') {
9271: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9272: } elsif ($which eq '64bit') {
9273: return &rndseed_64bit($symb,$courseid,$domain,$username);
9274: }
9275: return &rndseed_32bit($symb,$courseid,$domain,$username);
9276: }
9277:
9278: sub rndseed_32bit {
9279: my ($symb,$courseid,$domain,$username)=@_;
9280: {
9281: use integer;
9282: my $symbchck=unpack("%32C*",$symb) << 27;
9283: my $symbseed=numval($symb) << 22;
9284: my $namechck=unpack("%32C*",$username) << 17;
9285: my $nameseed=numval($username) << 12;
9286: my $domainseed=unpack("%32C*",$domain) << 7;
9287: my $courseseed=unpack("%32C*",$courseid);
9288: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9289: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9290: #&logthis("rndseed :$num:$symb");
1.564 albertel 9291: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9292: return $num;
9293: }
9294: }
9295:
9296: sub rndseed_64bit {
9297: my ($symb,$courseid,$domain,$username)=@_;
9298: {
9299: use integer;
9300: my $symbchck=unpack("%32S*",$symb) << 21;
9301: my $symbseed=numval($symb) << 10;
9302: my $namechck=unpack("%32S*",$username);
9303:
9304: my $nameseed=numval($username) << 21;
9305: my $domainseed=unpack("%32S*",$domain) << 10;
9306: my $courseseed=unpack("%32S*",$courseid);
9307:
9308: my $num1=$symbchck+$symbseed+$namechck;
9309: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9310: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9311: #&logthis("rndseed :$num:$symb");
1.564 albertel 9312: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9313: return "$num1,$num2";
1.155 albertel 9314: }
1.366 albertel 9315: }
9316:
1.443 albertel 9317: sub rndseed_64bit2 {
9318: my ($symb,$courseid,$domain,$username)=@_;
9319: {
9320: use integer;
9321: # strings need to be an even # of cahracters long, it it is odd the
9322: # last characters gets thrown away
9323: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9324: my $symbseed=numval($symb) << 10;
9325: my $namechck=unpack("%32S*",$username.' ');
9326:
9327: my $nameseed=numval($username) << 21;
1.501 albertel 9328: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9329: my $courseseed=unpack("%32S*",$courseid.' ');
9330:
9331: my $num1=$symbchck+$symbseed+$namechck;
9332: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9333: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9334: #&logthis("rndseed :$num:$symb");
1.803 albertel 9335: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9336: return "$num1,$num2";
9337: }
9338: }
9339:
9340: sub rndseed_64bit3 {
9341: my ($symb,$courseid,$domain,$username)=@_;
9342: {
9343: use integer;
9344: # strings need to be an even # of cahracters long, it it is odd the
9345: # last characters gets thrown away
9346: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9347: my $symbseed=numval2($symb) << 10;
9348: my $namechck=unpack("%32S*",$username.' ');
9349:
9350: my $nameseed=numval2($username) << 21;
1.443 albertel 9351: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9352: my $courseseed=unpack("%32S*",$courseid.' ');
9353:
9354: my $num1=$symbchck+$symbseed+$namechck;
9355: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9356: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9357: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9358: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9359:
1.503 albertel 9360: return "$num1:$num2";
1.443 albertel 9361: }
9362: }
9363:
1.575 albertel 9364: sub rndseed_64bit4 {
9365: my ($symb,$courseid,$domain,$username)=@_;
9366: {
9367: use integer;
9368: # strings need to be an even # of cahracters long, it it is odd the
9369: # last characters gets thrown away
9370: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9371: my $symbseed=numval3($symb) << 10;
9372: my $namechck=unpack("%32S*",$username.' ');
9373:
9374: my $nameseed=numval3($username) << 21;
9375: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9376: my $courseseed=unpack("%32S*",$courseid.' ');
9377:
9378: my $num1=$symbchck+$symbseed+$namechck;
9379: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9380: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9381: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9382: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9383:
9384: return "$num1:$num2";
9385: }
9386: }
9387:
1.675 albertel 9388: sub rndseed_64bit5 {
9389: my ($symb,$courseid,$domain,$username)=@_;
9390: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9391: return "$num1:$num2";
9392: }
9393:
1.366 albertel 9394: sub rndseed_CODE_64bit {
9395: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9396: {
1.366 albertel 9397: use integer;
1.443 albertel 9398: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9399: my $symbseed=numval2($symb);
1.491 albertel 9400: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9401: my $CODEseed=numval(&getCODE());
1.443 albertel 9402: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9403: my $num1=$symbseed+$CODEchck;
9404: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9405: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9406: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9407: if ($_64bit) { $num1=(($num1<<32)>>32); }
9408: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9409: return "$num1:$num2";
1.366 albertel 9410: }
9411: }
9412:
1.575 albertel 9413: sub rndseed_CODE_64bit4 {
9414: my ($symb,$courseid,$domain,$username)=@_;
9415: {
9416: use integer;
9417: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9418: my $symbseed=numval3($symb);
9419: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9420: my $CODEseed=numval3(&getCODE());
9421: my $courseseed=unpack("%32S*",$courseid.' ');
9422: my $num1=$symbseed+$CODEchck;
9423: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9424: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9425: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9426: if ($_64bit) { $num1=(($num1<<32)>>32); }
9427: if ($_64bit) { $num2=(($num2<<32)>>32); }
9428: return "$num1:$num2";
9429: }
9430: }
9431:
1.675 albertel 9432: sub rndseed_CODE_64bit5 {
9433: my ($symb,$courseid,$domain,$username)=@_;
9434: my $code = &getCODE();
9435: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9436: return "$num1:$num2";
9437: }
9438:
1.366 albertel 9439: sub setup_random_from_rndseed {
9440: my ($rndseed)=@_;
1.503 albertel 9441: if ($rndseed =~/([,:])/) {
9442: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9443: &Math::Random::random_set_seed(abs($num1),abs($num2));
9444: } else {
9445: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9446: }
1.36 albertel 9447: }
9448:
1.474 albertel 9449: sub latest_receipt_algorithm_id {
1.835 albertel 9450: return 'receipt3';
1.474 albertel 9451: }
9452:
1.480 www 9453: sub recunique {
9454: my $fucourseid=shift;
9455: my $unique;
1.835 albertel 9456: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9457: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9458: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9459: } else {
9460: $unique=$perlvar{'lonReceipt'};
9461: }
9462: return unpack("%32C*",$unique);
9463: }
9464:
9465: sub recprefix {
9466: my $fucourseid=shift;
9467: my $prefix;
1.835 albertel 9468: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9469: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9470: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9471: } else {
9472: $prefix=$perlvar{'lonHostID'};
9473: }
9474: return unpack("%32C*",$prefix);
9475: }
9476:
1.76 www 9477: sub ireceipt {
1.474 albertel 9478: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9479:
9480: my $return =&recprefix($fucourseid).'-';
9481:
9482: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9483: $env{'request.state'} eq 'construct') {
9484: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9485: return $return;
9486: }
9487:
1.76 www 9488: my $cuname=unpack("%32C*",$funame);
9489: my $cudom=unpack("%32C*",$fudom);
9490: my $cucourseid=unpack("%32C*",$fucourseid);
9491: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9492: my $cunique=&recunique($fucourseid);
1.474 albertel 9493: my $cpart=unpack("%32S*",$part);
1.835 albertel 9494: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9495:
1.790 albertel 9496: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9497:
9498: $return.= ($cunique%$cuname+
9499: $cunique%$cudom+
9500: $cusymb%$cuname+
9501: $cusymb%$cudom+
9502: $cucourseid%$cuname+
9503: $cucourseid%$cudom+
9504: $cpart%$cuname+
9505: $cpart%$cudom);
9506: } else {
9507: $return.= ($cunique%$cuname+
9508: $cunique%$cudom+
9509: $cusymb%$cuname+
9510: $cusymb%$cudom+
9511: $cucourseid%$cuname+
9512: $cucourseid%$cudom);
9513: }
9514: return $return;
1.76 www 9515: }
9516:
9517: sub receipt {
1.474 albertel 9518: my ($part)=@_;
1.790 albertel 9519: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9520: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9521: }
1.260 ng 9522:
1.790 albertel 9523: sub whichuser {
9524: my ($passedsymb)=@_;
9525: my ($symb,$courseid,$domain,$name,$publicuser);
9526: if (defined($env{'form.grade_symb'})) {
9527: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9528: my $allowed=&allowed('vgr',$tmp_courseid);
9529: if (!$allowed &&
9530: exists($env{'request.course.sec'}) &&
9531: $env{'request.course.sec'} !~ /^\s*$/) {
9532: $allowed=&allowed('vgr',$tmp_courseid.
9533: '/'.$env{'request.course.sec'});
9534: }
9535: if ($allowed) {
9536: ($symb)=&get_env_multiple('form.grade_symb');
9537: $courseid=$tmp_courseid;
9538: ($domain)=&get_env_multiple('form.grade_domain');
9539: ($name)=&get_env_multiple('form.grade_username');
9540: return ($symb,$courseid,$domain,$name,$publicuser);
9541: }
9542: }
9543: if (!$passedsymb) {
9544: $symb=&symbread();
9545: } else {
9546: $symb=$passedsymb;
9547: }
9548: $courseid=$env{'request.course.id'};
9549: $domain=$env{'user.domain'};
9550: $name=$env{'user.name'};
9551: if ($name eq 'public' && $domain eq 'public') {
9552: if (!defined($env{'form.username'})) {
9553: $env{'form.username'}.=time.rand(10000000);
9554: }
9555: $name.=$env{'form.username'};
9556: }
9557: return ($symb,$courseid,$domain,$name,$publicuser);
9558:
9559: }
9560:
1.36 albertel 9561: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9562: # returns either the contents of the file or
9563: # -1 if the file doesn't exist
1.481 raeburn 9564: #
9565: # if the target is a file that was uploaded via DOCS,
9566: # a check will be made to see if a current copy exists on the local server,
9567: # if it does this will be served, otherwise a copy will be retrieved from
9568: # the home server for the course and stored in /home/httpd/html/userfiles on
9569: # the local server.
1.472 albertel 9570:
1.36 albertel 9571: sub getfile {
1.538 albertel 9572: my ($file) = @_;
1.609 banghart 9573: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9574: &repcopy($file);
9575: return &readfile($file);
9576: }
9577:
9578: sub repcopy_userfile {
9579: my ($file)=@_;
1.609 banghart 9580: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9581: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9582: my ($cdom,$cnum,$filename) =
1.811 albertel 9583: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9584: my $uri="/uploaded/$cdom/$cnum/$filename";
9585: if (-e "$file") {
1.828 www 9586: # we already have a local copy, check it out
1.538 albertel 9587: my @fileinfo = stat($file);
1.828 www 9588: my $rtncode;
9589: my $info;
1.538 albertel 9590: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9591: if ($lwpresp ne 'ok') {
1.828 www 9592: # there is no such file anymore, even though we had a local copy
1.482 albertel 9593: if ($rtncode eq '404') {
1.538 albertel 9594: unlink($file);
1.482 albertel 9595: }
9596: return -1;
9597: }
9598: if ($info < $fileinfo[9]) {
1.828 www 9599: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9600: return 'ok';
1.828 www 9601: } else {
9602: # the file is outdated, get rid of it
9603: unlink($file);
1.482 albertel 9604: }
1.828 www 9605: }
9606: # one way or the other, at this point, we don't have the file
9607: # construct the correct path for the file
9608: my @parts = ($cdom,$cnum);
9609: if ($filename =~ m|^(.+)/[^/]+$|) {
9610: push @parts, split(/\//,$1);
9611: }
9612: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9613: foreach my $part (@parts) {
9614: $path .= '/'.$part;
9615: if (!-e $path) {
9616: mkdir($path,0770);
1.482 albertel 9617: }
9618: }
1.828 www 9619: # now the path exists for sure
9620: # get a user agent
9621: my $ua=new LWP::UserAgent;
9622: my $transferfile=$file.'.in.transfer';
9623: # FIXME: this should flock
9624: if (-e $transferfile) { return 'ok'; }
9625: my $request;
9626: $uri=~s/^\///;
1.980 raeburn 9627: my $homeserver = &homeserver($cnum,$cdom);
9628: my $protocol = $protocol{$homeserver};
9629: $protocol = 'http' if ($protocol ne 'https');
9630: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9631: my $response=$ua->request($request,$transferfile);
9632: # did it work?
9633: if ($response->is_error()) {
9634: unlink($transferfile);
9635: &logthis("Userfile repcopy failed for $uri");
9636: return -1;
9637: }
9638: # worked, rename the transfer file
9639: rename($transferfile,$file);
1.607 raeburn 9640: return 'ok';
1.481 raeburn 9641: }
9642:
1.517 albertel 9643: sub tokenwrapper {
9644: my $uri=shift;
1.980 raeburn 9645: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9646: $uri=~s|^/||;
1.620 albertel 9647: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9648: my $token=$1;
1.552 albertel 9649: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9650: if ($udom && $uname && $file) {
9651: $file=~s|(\?\.*)*$||;
1.949 raeburn 9652: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9653: my $homeserver = &homeserver($uname,$udom);
9654: my $protocol = $protocol{$homeserver};
9655: $protocol = 'http' if ($protocol ne 'https');
9656: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9657: (($uri=~/\?/)?'&':'?').'token='.$token.
9658: '&tokenissued='.$perlvar{'lonHostID'};
9659: } else {
9660: return '/adm/notfound.html';
9661: }
9662: }
9663:
1.828 www 9664: # call with reqtype HEAD: get last modification time
9665: # call with reqtype GET: get the file contents
9666: # Do not call this with reqtype GET for large files! It loads everything into memory
9667: #
1.481 raeburn 9668: sub getuploaded {
9669: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9670: $uri=~s/^\///;
1.980 raeburn 9671: my $homeserver = &homeserver($cnum,$cdom);
9672: my $protocol = $protocol{$homeserver};
9673: $protocol = 'http' if ($protocol ne 'https');
9674: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9675: my $ua=new LWP::UserAgent;
9676: my $request=new HTTP::Request($reqtype,$uri);
9677: my $response=$ua->request($request);
9678: $$rtncode = $response->code;
1.482 albertel 9679: if (! $response->is_success()) {
9680: return 'failed';
9681: }
9682: if ($reqtype eq 'HEAD') {
1.486 www 9683: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9684: } elsif ($reqtype eq 'GET') {
9685: $$info = $response->content;
1.472 albertel 9686: }
1.482 albertel 9687: return 'ok';
1.36 albertel 9688: }
9689:
1.481 raeburn 9690: sub readfile {
9691: my $file = shift;
9692: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9693: my $fh;
9694: open($fh,"<$file");
9695: my $a='';
1.800 albertel 9696: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9697: return $a;
9698: }
9699:
1.36 albertel 9700: sub filelocation {
1.590 banghart 9701: my ($dir,$file) = @_;
9702: my $location;
9703: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9704:
9705: if ($file =~ m-^/adm/-) {
9706: $file=~s-^/adm/wrapper/-/-;
9707: $file=~s-^/adm/coursedocs/showdoc/-/-;
9708: }
1.882 albertel 9709:
1.590 banghart 9710: if ($file=~m:^/~:) { # is a contruction space reference
9711: $location = $file;
9712: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9713: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9714: # is a correct contruction space reference
9715: $location = $file;
1.956 raeburn 9716: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9717: $location = $file;
1.609 banghart 9718: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9719: my ($udom,$uname,$filename)=
1.811 albertel 9720: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9721: my $home=&homeserver($uname,$udom);
9722: my $is_me=0;
9723: my @ids=¤t_machine_ids();
9724: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9725: if ($is_me) {
1.955 raeburn 9726: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9727: } else {
9728: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9729: $udom.'/'.$uname.'/'.$filename;
9730: }
1.882 albertel 9731: } elsif ($file =~ m-^/adm/-) {
9732: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9733: } else {
9734: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9735: $file=~s:^/res/:/:;
9736: if ( !( $file =~ m:^/:) ) {
9737: $location = $dir. '/'.$file;
9738: } else {
9739: $location = '/home/httpd/html/res'.$file;
9740: }
1.59 albertel 9741: }
1.590 banghart 9742: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9743: while ($location=~m{/\.\./}) {
9744: if ($location =~ m{/[^/]+/\.\./}) {
9745: $location=~ s{/[^/]+/\.\./}{/}g;
9746: } else {
9747: $location=~ s{/\.\./}{/}g;
9748: }
9749: } #remove dir/..
1.590 banghart 9750: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9751: return $location;
1.46 www 9752: }
1.36 albertel 9753:
1.46 www 9754: sub hreflocation {
9755: my ($dir,$file)=@_;
1.980 raeburn 9756: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9757: $file=filelocation($dir,$file);
1.700 albertel 9758: } elsif ($file=~m-^/adm/-) {
9759: $file=~s-^/adm/wrapper/-/-;
9760: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9761: }
9762: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9763: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9764: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9765: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9766: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9767: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9768: -/uploaded/$1/$2/-x;
1.46 www 9769: }
1.913 albertel 9770: if ($file=~ m{^/userfiles/}) {
9771: $file =~ s{^/userfiles/}{/uploaded/};
9772: }
1.462 albertel 9773: return $file;
1.465 albertel 9774: }
9775:
9776: sub current_machine_domains {
1.853 albertel 9777: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9778: }
9779:
9780: sub machine_domains {
9781: my ($hostname) = @_;
1.465 albertel 9782: my @domains;
1.838 albertel 9783: my %hostname = &all_hostnames();
1.465 albertel 9784: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9785: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9786: if ($hostname eq $name) {
1.844 albertel 9787: push(@domains,&host_domain($id));
1.465 albertel 9788: }
9789: }
9790: return @domains;
9791: }
9792:
9793: sub current_machine_ids {
1.853 albertel 9794: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9795: }
9796:
9797: sub machine_ids {
9798: my ($hostname) = @_;
9799: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9800: my @ids;
1.888 albertel 9801: my %name_to_host = &all_names();
1.889 albertel 9802: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9803: return @{ $name_to_host{$hostname} };
9804: }
9805: return;
1.31 www 9806: }
9807:
1.824 raeburn 9808: sub additional_machine_domains {
9809: my @domains;
9810: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9811: while( my $line = <$fh>) {
9812: $line =~ s/\s//g;
9813: push(@domains,$line);
9814: }
9815: return @domains;
9816: }
9817:
9818: sub default_login_domain {
9819: my $domain = $perlvar{'lonDefDomain'};
9820: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9821: foreach my $posdom (¤t_machine_domains(),
9822: &additional_machine_domains()) {
9823: if (lc($posdom) eq lc($testdomain)) {
9824: $domain=$posdom;
9825: last;
9826: }
9827: }
9828: return $domain;
9829: }
9830:
1.31 www 9831: # ------------------------------------------------------------- Declutters URLs
9832:
9833: sub declutter {
9834: my $thisfn=shift;
1.569 albertel 9835: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9836: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9837: $thisfn=~s/^\///;
1.697 albertel 9838: $thisfn=~s|^adm/wrapper/||;
9839: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9840: $thisfn=~s/^res\///;
1.1032 raeburn 9841: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9842: $thisfn=~s/\?.+$//;
9843: }
1.268 www 9844: return $thisfn;
9845: }
9846:
9847: # ------------------------------------------------------------- Clutter up URLs
9848:
9849: sub clutter {
9850: my $thisfn='/'.&declutter(shift);
1.887 albertel 9851: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9852: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9853: $thisfn='/res'.$thisfn;
9854: }
1.1031 raeburn 9855: if ($thisfn !~m|^/adm|) {
9856: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9857: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9858: } else {
9859: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9860: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9861: if ($embstyle eq 'ssi'
9862: || ($embstyle eq 'hdn')
9863: || ($embstyle eq 'rat')
9864: || ($embstyle eq 'prv')
9865: || ($embstyle eq 'ign')) {
9866: #do nothing with these
9867: } elsif (($embstyle eq 'img')
1.695 albertel 9868: || ($embstyle eq 'emb')
9869: || ($embstyle eq 'wrp')) {
9870: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9871: } elsif ($embstyle eq 'unk'
9872: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9873: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9874: } else {
1.718 www 9875: # &logthis("Got a blank emb style");
1.695 albertel 9876: }
1.694 albertel 9877: }
9878: }
1.31 www 9879: return $thisfn;
1.12 www 9880: }
9881:
1.787 albertel 9882: sub clutter_with_no_wrapper {
9883: my $uri = &clutter(shift);
9884: if ($uri =~ m-^/adm/-) {
9885: $uri =~ s-^/adm/wrapper/-/-;
9886: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9887: }
9888: return $uri;
9889: }
9890:
1.557 albertel 9891: sub freeze_escape {
9892: my ($value)=@_;
9893: if (ref($value)) {
9894: $value=&nfreeze($value);
9895: return '__FROZEN__'.&escape($value);
9896: }
9897: return &escape($value);
9898: }
9899:
1.11 www 9900:
1.557 albertel 9901: sub thaw_unescape {
9902: my ($value)=@_;
9903: if ($value =~ /^__FROZEN__/) {
9904: substr($value,0,10,undef);
9905: $value=&unescape($value);
9906: return &thaw($value);
9907: }
9908: return &unescape($value);
9909: }
9910:
1.436 albertel 9911: sub correct_line_ends {
9912: my ($result)=@_;
9913: $$result =~s/\r\n/\n/mg;
9914: $$result =~s/\r/\n/mg;
1.415 albertel 9915: }
1.1 albertel 9916: # ================================================================ Main Program
9917:
1.184 www 9918: sub goodbye {
1.204 albertel 9919: &logthis("Starting Shut down");
1.443 albertel 9920: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9921: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9922: #converted
1.599 albertel 9923: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9924: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9925: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9926: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9927: #1.1 only
1.870 albertel 9928: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9929: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9930: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9931: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9932: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9933: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9934: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9935: &flushcourselogs();
9936: &logthis("Shutting down");
9937: }
9938:
1.852 albertel 9939: sub get_dns {
1.869 albertel 9940: my ($url,$func,$ignore_cache) = @_;
9941: if (!$ignore_cache) {
9942: my ($content,$cached)=
9943: &Apache::lonnet::is_cached_new('dns',$url);
9944: if ($cached) {
9945: &$func($content);
9946: return;
9947: }
9948: }
9949:
9950: my %alldns;
1.852 albertel 9951: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9952: foreach my $dns (<$config>) {
9953: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9954: my $line = $1;
9955: my ($host,$protocol) = split(/:/,$line);
9956: if ($protocol ne 'https') {
9957: $protocol = 'http';
9958: }
9959: $alldns{$host} = $protocol;
1.869 albertel 9960: }
9961: while (%alldns) {
9962: my ($dns) = keys(%alldns);
1.852 albertel 9963: my $ua=new LWP::UserAgent;
1.979 raeburn 9964: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9965: my $response=$ua->request($request);
1.979 raeburn 9966: delete($alldns{$dns});
1.852 albertel 9967: next if ($response->is_error());
9968: my @content = split("\n",$response->content);
1.869 albertel 9969: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9970: &$func(\@content);
1.869 albertel 9971: return;
1.852 albertel 9972: }
9973: close($config);
1.871 albertel 9974: my $which = (split('/',$url))[3];
9975: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9976: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9977: my @content = <$config>;
9978: &$func(\@content);
9979: return;
1.852 albertel 9980: }
1.327 albertel 9981: # ------------------------------------------------------------ Read domain file
9982: {
1.852 albertel 9983: my $loaded;
1.846 albertel 9984: my %domain;
9985:
1.852 albertel 9986: sub parse_domain_tab {
9987: my ($lines) = @_;
9988: foreach my $line (@$lines) {
9989: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9990:
1.846 albertel 9991: chomp($line);
1.852 albertel 9992: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9993: my %this_domain;
9994: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9995: 'lang_def', 'city', 'longi', 'lati',
9996: 'primary') {
9997: $this_domain{$field} = shift(@elements);
9998: }
9999: $domain{$name} = \%this_domain;
1.852 albertel 10000: }
10001: }
1.864 albertel 10002:
10003: sub reset_domain_info {
10004: undef($loaded);
10005: undef(%domain);
10006: }
10007:
1.852 albertel 10008: sub load_domain_tab {
1.869 albertel 10009: my ($ignore_cache) = @_;
10010: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10011: my $fh;
10012: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10013: my @lines = <$fh>;
10014: &parse_domain_tab(\@lines);
1.448 albertel 10015: }
1.852 albertel 10016: close($fh);
10017: $loaded = 1;
1.327 albertel 10018: }
1.846 albertel 10019:
10020: sub domain {
1.852 albertel 10021: &load_domain_tab() if (!$loaded);
10022:
1.846 albertel 10023: my ($name,$what) = @_;
10024: return if ( !exists($domain{$name}) );
10025:
10026: if (!$what) {
10027: return $domain{$name}{'description'};
10028: }
10029: return $domain{$name}{$what};
10030: }
1.974 raeburn 10031:
10032: sub domain_info {
10033: &load_domain_tab() if (!$loaded);
10034: return %domain;
10035: }
10036:
1.327 albertel 10037: }
10038:
10039:
1.1 albertel 10040: # ------------------------------------------------------------- Read hosts file
10041: {
1.838 albertel 10042: my %hostname;
1.844 albertel 10043: my %hostdom;
1.845 albertel 10044: my %libserv;
1.852 albertel 10045: my $loaded;
1.888 albertel 10046: my %name_to_host;
1.1056.4.6 raeburn 10047: my %internetdom;
1.852 albertel 10048:
10049: sub parse_hosts_tab {
10050: my ($file) = @_;
10051: foreach my $configline (@$file) {
10052: next if ($configline =~ /^(\#|\s*$ )/x);
10053: next if ($configline =~ /^\^/);
10054: chomp($configline);
1.1056.4.6 raeburn 10055: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10056: $name=~s/\s//g;
10057: if ($id && $domain && $role && $name) {
10058: $hostname{$id}=$name;
1.888 albertel 10059: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10060: $hostdom{$id}=$domain;
10061: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10062: if (defined($protocol)) {
10063: if ($protocol eq 'https') {
10064: $protocol{$id} = $protocol;
10065: } else {
10066: $protocol{$id} = 'http';
10067: }
1.968 raeburn 10068: } else {
1.969 raeburn 10069: $protocol{$id} = 'http';
1.968 raeburn 10070: }
1.1056.4.6 raeburn 10071: if (defined($intdom)) {
10072: $internetdom{$id} = $intdom;
10073: }
1.852 albertel 10074: }
10075: }
10076: }
1.864 albertel 10077:
10078: sub reset_hosts_info {
1.897 albertel 10079: &purge_remembered();
1.864 albertel 10080: &reset_domain_info();
10081: &reset_hosts_ip_info();
1.892 albertel 10082: undef(%name_to_host);
1.864 albertel 10083: undef(%hostname);
10084: undef(%hostdom);
10085: undef(%libserv);
10086: undef($loaded);
10087: }
1.1 albertel 10088:
1.852 albertel 10089: sub load_hosts_tab {
1.869 albertel 10090: my ($ignore_cache) = @_;
10091: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10092: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10093: my @config = <$config>;
10094: &parse_hosts_tab(\@config);
10095: close($config);
10096: $loaded=1;
1.1 albertel 10097: }
1.852 albertel 10098:
1.838 albertel 10099: sub hostname {
1.852 albertel 10100: &load_hosts_tab() if (!$loaded);
10101:
1.838 albertel 10102: my ($lonid) = @_;
10103: return $hostname{$lonid};
10104: }
1.845 albertel 10105:
1.838 albertel 10106: sub all_hostnames {
1.852 albertel 10107: &load_hosts_tab() if (!$loaded);
10108:
1.838 albertel 10109: return %hostname;
10110: }
1.845 albertel 10111:
1.888 albertel 10112: sub all_names {
10113: &load_hosts_tab() if (!$loaded);
10114:
10115: return %name_to_host;
10116: }
10117:
1.974 raeburn 10118: sub all_host_domain {
10119: &load_hosts_tab() if (!$loaded);
10120: return %hostdom;
10121: }
10122:
1.845 albertel 10123: sub is_library {
1.852 albertel 10124: &load_hosts_tab() if (!$loaded);
10125:
1.845 albertel 10126: return exists($libserv{$_[0]});
10127: }
10128:
10129: sub all_library {
1.852 albertel 10130: &load_hosts_tab() if (!$loaded);
10131:
1.845 albertel 10132: return %libserv;
10133: }
10134:
1.1056.4.2 raeburn 10135: sub unique_library {
10136: #2x reverse removes all hostnames that appear more than once
10137: my %unique = reverse &all_library();
10138: return reverse %unique;
10139: }
10140:
1.841 albertel 10141: sub get_servers {
1.852 albertel 10142: &load_hosts_tab() if (!$loaded);
10143:
1.841 albertel 10144: my ($domain,$type) = @_;
10145: my %possible_hosts = ($type eq 'library') ? %libserv
10146: : %hostname;
10147: my %result;
1.842 albertel 10148: if (ref($domain) eq 'ARRAY') {
10149: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10150: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10151: $result{$host} = $hostname;
10152: }
10153: }
10154: } else {
10155: while ( my ($host,$hostname) = each(%possible_hosts)) {
10156: if ($hostdom{$host} eq $domain) {
10157: $result{$host} = $hostname;
10158: }
1.841 albertel 10159: }
10160: }
10161: return %result;
10162: }
1.845 albertel 10163:
1.1056.4.2 raeburn 10164: sub get_unique_servers {
10165: my %unique = reverse &get_servers(@_);
10166: return reverse %unique;
10167: }
10168:
1.844 albertel 10169: sub host_domain {
1.852 albertel 10170: &load_hosts_tab() if (!$loaded);
10171:
1.844 albertel 10172: my ($lonid) = @_;
10173: return $hostdom{$lonid};
10174: }
10175:
1.841 albertel 10176: sub all_domains {
1.852 albertel 10177: &load_hosts_tab() if (!$loaded);
10178:
1.841 albertel 10179: my %seen;
10180: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10181: return @uniq;
10182: }
1.1056.4.3 raeburn 10183:
10184: sub internet_dom {
10185: &load_hosts_tab() if (!$loaded);
10186:
10187: my ($lonid) = @_;
10188: return $internetdom{$lonid};
10189: }
1.1 albertel 10190: }
10191:
1.847 albertel 10192: {
10193: my %iphost;
1.856 albertel 10194: my %name_to_ip;
10195: my %lonid_to_ip;
1.869 albertel 10196:
1.847 albertel 10197: sub get_hosts_from_ip {
10198: my ($ip) = @_;
10199: my %iphosts = &get_iphost();
10200: if (ref($iphosts{$ip})) {
10201: return @{$iphosts{$ip}};
10202: }
10203: return;
1.839 albertel 10204: }
1.864 albertel 10205:
10206: sub reset_hosts_ip_info {
10207: undef(%iphost);
10208: undef(%name_to_ip);
10209: undef(%lonid_to_ip);
10210: }
1.856 albertel 10211:
10212: sub get_host_ip {
10213: my ($lonid) = @_;
10214: if (exists($lonid_to_ip{$lonid})) {
10215: return $lonid_to_ip{$lonid};
10216: }
10217: my $name=&hostname($lonid);
10218: my $ip = gethostbyname($name);
10219: return if (!$ip || length($ip) ne 4);
10220: $ip=inet_ntoa($ip);
10221: $name_to_ip{$name} = $ip;
10222: $lonid_to_ip{$lonid} = $ip;
10223: return $ip;
10224: }
1.847 albertel 10225:
10226: sub get_iphost {
1.869 albertel 10227: my ($ignore_cache) = @_;
1.894 albertel 10228:
1.869 albertel 10229: if (!$ignore_cache) {
10230: if (%iphost) {
10231: return %iphost;
10232: }
10233: my ($ip_info,$cached)=
10234: &Apache::lonnet::is_cached_new('iphost','iphost');
10235: if ($cached) {
10236: %iphost = %{$ip_info->[0]};
10237: %name_to_ip = %{$ip_info->[1]};
10238: %lonid_to_ip = %{$ip_info->[2]};
10239: return %iphost;
10240: }
10241: }
1.894 albertel 10242:
10243: # get yesterday's info for fallback
10244: my %old_name_to_ip;
10245: my ($ip_info,$cached)=
10246: &Apache::lonnet::is_cached_new('iphost','iphost');
10247: if ($cached) {
10248: %old_name_to_ip = %{$ip_info->[1]};
10249: }
10250:
1.888 albertel 10251: my %name_to_host = &all_names();
10252: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10253: my $ip;
10254: if (!exists($name_to_ip{$name})) {
10255: $ip = gethostbyname($name);
10256: if (!$ip || length($ip) ne 4) {
1.894 albertel 10257: if (defined($old_name_to_ip{$name})) {
10258: $ip = $old_name_to_ip{$name};
10259: &logthis("Can't find $name defaulting to old $ip");
10260: } else {
10261: &logthis("Name $name no IP found");
10262: next;
10263: }
10264: } else {
10265: $ip=inet_ntoa($ip);
1.847 albertel 10266: }
10267: $name_to_ip{$name} = $ip;
10268: } else {
10269: $ip = $name_to_ip{$name};
1.653 albertel 10270: }
1.888 albertel 10271: foreach my $id (@{ $name_to_host{$name} }) {
10272: $lonid_to_ip{$id} = $ip;
10273: }
10274: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10275: }
1.869 albertel 10276: &Apache::lonnet::do_cache_new('iphost','iphost',
10277: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10278: 48*60*60);
1.869 albertel 10279:
1.847 albertel 10280: return %iphost;
1.598 albertel 10281: }
10282:
1.992 raeburn 10283: #
10284: # Given a DNS returns the loncapa host name for that DNS
10285: #
10286: sub host_from_dns {
10287: my ($dns) = @_;
10288: my @hosts;
10289: my $ip;
10290:
1.993 raeburn 10291: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10292: $ip = $name_to_ip{$dns};
10293: }
10294: if (!$ip) {
10295: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10296: if (length($ip) == 4) {
10297: $ip = &IO::Socket::inet_ntoa($ip);
10298: }
10299: }
10300: if ($ip) {
10301: @hosts = get_hosts_from_ip($ip);
10302: return $hosts[0];
10303: }
10304: return undef;
1.986 foxr 10305: }
1.992 raeburn 10306:
1.1056.4.3 raeburn 10307: sub get_internet_names {
10308: my ($lonid) = @_;
10309: return if ($lonid eq '');
10310: my ($idnref,$cached)=
10311: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10312: if ($cached) {
10313: return $idnref;
10314: }
10315: my $ip = &get_host_ip($lonid);
10316: my @hosts = &get_hosts_from_ip($ip);
10317: my %iphost = &get_iphost();
10318: my (@idns,%seen);
10319: foreach my $id (@hosts) {
10320: my $dom = &host_domain($id);
10321: my $prim_id = &domain($dom,'primary');
10322: my $prim_ip = &get_host_ip($prim_id);
10323: next if ($seen{$prim_ip});
10324: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10325: foreach my $id (@{$iphost{$prim_ip}}) {
10326: my $intdom = &internet_dom($id);
10327: unless (grep(/^\Q$intdom\E$/,@idns)) {
10328: push(@idns,$intdom);
10329: }
10330: }
10331: }
10332: $seen{$prim_ip} = 1;
10333: }
10334: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10335: }
10336:
10337: }
10338:
10339: sub all_loncaparevs {
10340: return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
1.986 foxr 10341: }
10342:
1.862 albertel 10343: BEGIN {
10344:
10345: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10346: unless ($readit) {
10347: {
10348: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10349: %perlvar = (%perlvar,%{$configvars});
10350: }
10351:
10352:
1.1 albertel 10353: # ------------------------------------------------------ Read spare server file
10354: {
1.448 albertel 10355: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10356:
10357: while (my $configline=<$config>) {
10358: chomp($configline);
1.284 matthew 10359: if ($configline) {
1.784 albertel 10360: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10361: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10362: push(@{ $spareid{$type} }, $host);
1.1 albertel 10363: }
10364: }
1.448 albertel 10365: close($config);
1.1 albertel 10366: }
1.11 www 10367: # ------------------------------------------------------------ Read permissions
10368: {
1.448 albertel 10369: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10370:
10371: while (my $configline=<$config>) {
1.448 albertel 10372: chomp($configline);
10373: if ($configline) {
10374: my ($role,$perm)=split(/ /,$configline);
10375: if ($perm ne '') { $pr{$role}=$perm; }
10376: }
1.11 www 10377: }
1.448 albertel 10378: close($config);
1.11 www 10379: }
10380:
10381: # -------------------------------------------- Read plain texts for permissions
10382: {
1.448 albertel 10383: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10384:
10385: while (my $configline=<$config>) {
1.448 albertel 10386: chomp($configline);
10387: if ($configline) {
1.742 raeburn 10388: my ($short,@plain)=split(/:/,$configline);
10389: %{$prp{$short}} = ();
10390: if (@plain > 0) {
10391: $prp{$short}{'std'} = $plain[0];
10392: for (my $i=1; $i<@plain; $i++) {
10393: $prp{$short}{'alt'.$i} = $plain[$i];
10394: }
10395: }
1.448 albertel 10396: }
1.135 www 10397: }
1.448 albertel 10398: close($config);
1.135 www 10399: }
10400:
10401: # ---------------------------------------------------------- Read package table
10402: {
1.448 albertel 10403: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10404:
10405: while (my $configline=<$config>) {
1.483 albertel 10406: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10407: chomp($configline);
10408: my ($short,$plain)=split(/:/,$configline);
10409: my ($pack,$name)=split(/\&/,$short);
10410: if ($plain ne '') {
10411: $packagetab{$pack.'&'.$name.'&name'}=$name;
10412: $packagetab{$short}=$plain;
10413: }
1.11 www 10414: }
1.448 albertel 10415: close($config);
1.329 matthew 10416: }
10417:
1.1056.4.3 raeburn 10418: # ---------------------------------------------------------- Read loncaparev table
10419: {
10420: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10421: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10422: while (my $configline=<$config>) {
10423: chomp($configline);
10424: my ($hostid,$loncaparev)=split(/:/,$configline);
10425: $loncaparevs{$hostid}=$loncaparev;
10426: }
10427: close($config);
10428: }
10429: }
10430: }
10431:
10432: # ---------------------------------------------------------- Read serverhostID table
10433: {
10434: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10435: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10436: while (my $configline=<$config>) {
10437: chomp($configline);
10438: my ($name,$id)=split(/:/,$configline);
10439: $serverhomeIDs{$name}=$id;
10440: }
10441: close($config);
10442: }
10443: }
10444: }
10445:
1.1056.4.5 raeburn 10446: {
10447: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10448: if (-e $file) {
10449: my $parser = HTML::LCParser->new($file);
10450: while (my $token = $parser->get_token()) {
10451: if ($token->[0] eq 'S') {
10452: my $item = $token->[1];
10453: my $name = $token->[2]{'name'};
10454: my $value = $token->[2]{'value'};
10455: if ($item ne '' && $name ne '' && $value ne '') {
10456: my $release = $parser->get_text();
10457: $release =~ s/(^\s*|\s*$ )//gx;
10458: $needsrelease{$item.':'.$name.':'.$value} = $release;
10459: }
10460: }
10461: }
10462: }
10463: }
10464:
1.329 matthew 10465: # ------------- set up temporary directory
10466: {
10467: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10468:
1.11 www 10469: }
10470:
1.794 albertel 10471: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10472: 'compress_threshold'=> 20_000,
10473: });
1.185 www 10474:
1.281 www 10475: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10476: $dumpcount=0;
1.958 www 10477: $locknum=0;
1.22 www 10478:
1.163 harris41 10479: &logtouch();
1.672 albertel 10480: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10481: $readit=1;
1.564 albertel 10482: {
10483: use integer;
10484: my $test=(2**32)+1;
1.568 albertel 10485: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10486: &logthis(" Detected 64bit platform ($_64bit)");
10487: }
1.195 www 10488: }
1.1 albertel 10489: }
1.179 www 10490:
1.1 albertel 10491: 1;
1.191 harris41 10492: __END__
10493:
1.243 albertel 10494: =pod
10495:
1.191 harris41 10496: =head1 NAME
10497:
1.243 albertel 10498: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10499:
10500: =head1 SYNOPSIS
10501:
1.243 albertel 10502: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10503:
10504: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10505:
1.243 albertel 10506: Common parameters:
10507:
10508: =over 4
10509:
10510: =item *
10511:
10512: $uname : an internal username (if $cname expecting a course Id specifically)
10513:
10514: =item *
10515:
10516: $udom : a domain (if $cdom expecting a course's domain specifically)
10517:
10518: =item *
10519:
10520: $symb : a resource instance identifier
10521:
10522: =item *
10523:
10524: $namespace : the name of a .db file that contains the data needed or
10525: being set.
10526:
10527: =back
10528:
1.394 bowersj2 10529: =head1 OVERVIEW
1.191 harris41 10530:
1.394 bowersj2 10531: lonnet provides subroutines which interact with the
10532: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10533: about classes, users, and resources.
1.243 albertel 10534:
10535: For many of these objects you can also use this to store data about
10536: them or modify them in various ways.
1.191 harris41 10537:
1.394 bowersj2 10538: =head2 Symbs
1.191 harris41 10539:
1.394 bowersj2 10540: To identify a specific instance of a resource, LON-CAPA uses symbols
10541: or "symbs"X<symb>. These identifiers are built from the URL of the
10542: map, the resource number of the resource in the map, and the URL of
10543: the resource itself. The latter is somewhat redundant, but might help
10544: if maps change.
10545:
10546: An example is
10547:
10548: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10549:
10550: The respective map entry is
10551:
10552: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10553: title="Problem 2">
10554: </resource>
10555:
10556: Symbs are used by the random number generator, as well as to store and
10557: restore data specific to a certain instance of for example a problem.
10558:
10559: =head2 Storing And Retrieving Data
10560:
10561: X<store()>X<cstore()>X<restore()>Three of the most important functions
10562: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10563: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10564: is is the non-critical message twin of cstore. These functions are for
10565: handlers to store a perl hash to a user's permanent data space in an
10566: easy manner, and to retrieve it again on another call. It is expected
10567: that a handler would use this once at the beginning to retrieve data,
10568: and then again once at the end to send only the new data back.
10569:
10570: The data is stored in the user's data directory on the user's
10571: homeserver under the ID of the course.
10572:
10573: The hash that is returned by restore will have all of the previous
10574: value for all of the elements of the hash.
10575:
10576: Example:
10577:
10578: #creating a hash
10579: my %hash;
10580: $hash{'foo'}='bar';
10581:
10582: #storing it
10583: &Apache::lonnet::cstore(\%hash);
10584:
10585: #changing a value
10586: $hash{'foo'}='notbar';
10587:
10588: #adding a new value
10589: $hash{'bar'}='foo';
10590: &Apache::lonnet::cstore(\%hash);
10591:
10592: #retrieving the hash
10593: my %history=&Apache::lonnet::restore();
10594:
10595: #print the hash
10596: foreach my $key (sort(keys(%history))) {
10597: print("\%history{$key} = $history{$key}");
10598: }
10599:
10600: Will print out:
1.191 harris41 10601:
1.394 bowersj2 10602: %history{1:foo} = bar
10603: %history{1:keys} = foo:timestamp
10604: %history{1:timestamp} = 990455579
10605: %history{2:bar} = foo
10606: %history{2:foo} = notbar
10607: %history{2:keys} = foo:bar:timestamp
10608: %history{2:timestamp} = 990455580
10609: %history{bar} = foo
10610: %history{foo} = notbar
10611: %history{timestamp} = 990455580
10612: %history{version} = 2
10613:
10614: Note that the special hash entries C<keys>, C<version> and
10615: C<timestamp> were added to the hash. C<version> will be equal to the
10616: total number of versions of the data that have been stored. The
10617: C<timestamp> attribute will be the UNIX time the hash was
10618: stored. C<keys> is available in every historical section to list which
10619: keys were added or changed at a specific historical revision of a
10620: hash.
10621:
10622: B<Warning>: do not store the hash that restore returns directly. This
10623: will cause a mess since it will restore the historical keys as if the
10624: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10625:
1.394 bowersj2 10626: Calling convention:
1.191 harris41 10627:
1.394 bowersj2 10628: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10629: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10630:
1.394 bowersj2 10631: For more detailed information, see lonnet specific documentation.
1.191 harris41 10632:
1.394 bowersj2 10633: =head1 RETURN MESSAGES
1.191 harris41 10634:
1.394 bowersj2 10635: =over 4
1.191 harris41 10636:
1.394 bowersj2 10637: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10638:
1.394 bowersj2 10639: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10640: when the connection is brought back up
1.191 harris41 10641:
1.394 bowersj2 10642: =item * B<con_failed>: unable to contact remote host and unable to save message
10643: for later delivery
1.191 harris41 10644:
1.967 bisitz 10645: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10646:
1.394 bowersj2 10647: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10648: that was requested
1.191 harris41 10649:
1.243 albertel 10650: =back
1.191 harris41 10651:
1.243 albertel 10652: =head1 PUBLIC SUBROUTINES
1.191 harris41 10653:
1.243 albertel 10654: =head2 Session Environment Functions
1.191 harris41 10655:
1.243 albertel 10656: =over 4
1.191 harris41 10657:
1.394 bowersj2 10658: =item *
10659: X<appenv()>
1.949 raeburn 10660: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10661: the user envirnoment file, and will be restored for each access this
1.620 albertel 10662: user makes during this session, also modifies the %env for the current
1.949 raeburn 10663: process. Optional rolesarrayref - if defined contains a reference to an array
10664: of roles which are exempt from the restriction on modifying user.role entries
10665: in the user's environment.db and in %env.
1.191 harris41 10666:
10667: =item *
1.394 bowersj2 10668: X<delenv()>
1.987 raeburn 10669: B<delenv($delthis,$regexp)>: removes all items from the session
10670: environment file that begin with $delthis. If the
10671: optional second arg - $regexp - is true, $delthis is treated as a
10672: regular expression, otherwise \Q$delthis\E is used.
10673: The values are also deleted from the current processes %env.
1.191 harris41 10674:
1.795 albertel 10675: =item * get_env_multiple($name)
10676:
10677: gets $name from the %env hash, it seemlessly handles the cases where multiple
10678: values may be defined and end up as an array ref.
10679:
10680: returns an array of values
10681:
1.243 albertel 10682: =back
10683:
10684: =head2 User Information
1.191 harris41 10685:
1.243 albertel 10686: =over 4
1.191 harris41 10687:
10688: =item *
1.394 bowersj2 10689: X<queryauthenticate()>
10690: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10691: authentication scheme
10692:
10693: =item *
1.394 bowersj2 10694: X<authenticate()>
1.1056.4.3 raeburn 10695: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10696: authenticate user from domain's lib servers (first use the current
10697: one). C<$upass> should be the users password.
1.1056.4.3 raeburn 10698: $checkdefauth is optional (value is 1 if a check should be made to
10699: authenticate user using default authentication method, and allow
10700: account creation if username does not have account in the domain).
10701: $clientcancheckhost is optional (value is 1 if checking whether the
10702: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10703:
10704: =item *
1.394 bowersj2 10705: X<homeserver()>
10706: B<homeserver($uname,$udom)>: find the server which has
10707: the user's directory and files (there must be only one), this caches
10708: the answer, and also caches if there is a borken connection.
1.191 harris41 10709:
10710: =item *
1.394 bowersj2 10711: X<idget()>
10712: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10713: (IDs are a unique resource in a domain, there must be only 1 ID per
10714: username, and only 1 username per ID in a specific domain) (returns
10715: hash: id=>name,id=>name)
1.191 harris41 10716:
10717: =item *
1.394 bowersj2 10718: X<idrget()>
10719: B<idrget($udom,@unames)>: find the IDs behind a list of
10720: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10721:
10722: =item *
1.394 bowersj2 10723: X<idput()>
10724: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10725:
10726: =item *
1.394 bowersj2 10727: X<rolesinit()>
10728: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10729:
10730: =item *
1.551 albertel 10731: X<getsection()>
10732: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10733: course $cname, return section name/number or '' for "not in course"
10734: and '-1' for "no section"
10735:
10736: =item *
1.394 bowersj2 10737: X<userenvironment()>
10738: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10739: passed in @what from the requested user's environment, returns a hash
10740:
1.858 raeburn 10741: =item *
10742: X<userlog_query()>
1.859 albertel 10743: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10744: activity.log file. %filters defines filters applied when parsing the
10745: log file. These can be start or end timestamps, or the type of action
10746: - log to look for Login or Logout events, check for Checkin or
10747: Checkout, role for role selection. The response is in the form
10748: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10749: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10750:
1.243 albertel 10751: =back
10752:
10753: =head2 User Roles
10754:
10755: =over 4
10756:
10757: =item *
10758:
1.810 raeburn 10759: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10760: F: full access
10761: U,I,K: authentication modes (cxx only)
10762: '': forbidden
10763: 1: user needs to choose course
10764: 2: browse allowed
1.766 albertel 10765: A: passphrase authentication needed
1.243 albertel 10766:
10767: =item *
10768:
10769: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10770: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10771: and course level
10772:
10773: =item *
10774:
1.988 raeburn 10775: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10776: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10777: $type is Course (default) or Community.
1.988 raeburn 10778: If $forcedefault evaluates to true, text returned will be default
10779: text for $type. Otherwise, if this is a course, the text returned
10780: will be a custom name for the role (if defined in the course's
10781: environment). If no custom name is defined the default is returned.
10782:
1.832 raeburn 10783: =item *
10784:
1.935 raeburn 10785: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10786: All arguments are optional. Returns a hash of a roles, either for
10787: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10788: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10789: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10790: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10791: For each key, value is set to colon-separated start and end times for
10792: the role. If no username and domain are specified, will default to
1.934 raeburn 10793: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10794: of role statuses (active, future or previous), roles
10795: (e.g., cc,in, st etc.) and domains of the roles which can be used
10796: to restrict the list of roles reported. If no array ref is
10797: provided for types, will default to return only active roles.
1.834 albertel 10798:
1.243 albertel 10799: =back
10800:
10801: =head2 User Modification
10802:
10803: =over 4
10804:
10805: =item *
10806:
1.957 raeburn 10807: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10808: user for the level given by URL. Optional start and end dates (leave empty
10809: string or zero for "no date")
1.191 harris41 10810:
10811: =item *
10812:
1.243 albertel 10813: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10814: change a users, password, possible return values are: ok,
10815: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10816: refused
1.191 harris41 10817:
10818: =item *
10819:
1.243 albertel 10820: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10821:
10822: =item *
10823:
1.1056.4.1 raeburn 10824: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10825: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10826:
10827: will update user information (firstname,middlename,lastname,generation,
10828: permanentemail), and if forceid is true, student/employee ID also.
10829: A user's institutional affiliation(s) can also be updated.
10830: User information fields will not be overwritten with empty entries
10831: unless the field is included in the $candelete array reference.
10832: This array is included when a single user is modified via "Manage Users",
10833: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10834:
10835: =item *
10836:
1.286 matthew 10837: modifystudent
10838:
1.957 raeburn 10839: modify a student's enrollment and identification information.
1.286 matthew 10840: The course id is resolved based on the current users environment.
10841: This means the envoking user must be a course coordinator or otherwise
10842: associated with a course.
10843:
1.297 matthew 10844: This call is essentially a wrapper for lonnet::modifyuser and
10845: lonnet::modify_student_enrollment
1.286 matthew 10846:
10847: Inputs:
10848:
10849: =over 4
10850:
1.957 raeburn 10851: =item B<$udom> Student's loncapa domain
1.286 matthew 10852:
1.957 raeburn 10853: =item B<$uname> Student's loncapa login name
1.286 matthew 10854:
1.964 bisitz 10855: =item B<$uid> Student/Employee ID
1.286 matthew 10856:
1.957 raeburn 10857: =item B<$umode> Student's authentication mode
1.286 matthew 10858:
1.957 raeburn 10859: =item B<$upass> Student's password
1.286 matthew 10860:
1.957 raeburn 10861: =item B<$first> Student's first name
1.286 matthew 10862:
1.957 raeburn 10863: =item B<$middle> Student's middle name
1.286 matthew 10864:
1.957 raeburn 10865: =item B<$last> Student's last name
1.286 matthew 10866:
1.957 raeburn 10867: =item B<$gene> Student's generation
1.286 matthew 10868:
1.957 raeburn 10869: =item B<$usec> Student's section in course
1.286 matthew 10870:
10871: =item B<$end> Unix time of the roles expiration
10872:
10873: =item B<$start> Unix time of the roles start date
10874:
10875: =item B<$forceid> If defined, allow $uid to be changed
10876:
10877: =item B<$desiredhome> server to use as home server for student
10878:
1.957 raeburn 10879: =item B<$email> Student's permanent e-mail address
10880:
10881: =item B<$type> Type of enrollment (auto or manual)
10882:
1.963 raeburn 10883: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10884:
10885: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10886:
1.963 raeburn 10887: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10888:
1.963 raeburn 10889: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10890:
1.963 raeburn 10891: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10892:
1.286 matthew 10893: =back
1.297 matthew 10894:
10895: =item *
10896:
10897: modify_student_enrollment
10898:
10899: Change a students enrollment status in a class. The environment variable
10900: 'role.request.course' must be defined for this function to proceed.
10901:
10902: Inputs:
10903:
10904: =over 4
10905:
10906: =item $udom, students domain
10907:
10908: =item $uname, students name
10909:
10910: =item $uid, students user id
10911:
10912: =item $first, students first name
10913:
10914: =item $middle
10915:
10916: =item $last
10917:
10918: =item $gene
10919:
10920: =item $usec
10921:
10922: =item $end
10923:
10924: =item $start
10925:
1.957 raeburn 10926: =item $type
10927:
10928: =item $locktype
10929:
10930: =item $cid
10931:
10932: =item $selfenroll
10933:
10934: =item $context
10935:
1.297 matthew 10936: =back
10937:
1.191 harris41 10938:
10939: =item *
10940:
1.243 albertel 10941: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10942: custom role; give a custom role to a user for the level given by URL. Specify
10943: name and domain of role author, and role name
1.191 harris41 10944:
10945: =item *
10946:
1.243 albertel 10947: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10948:
10949: =item *
10950:
1.243 albertel 10951: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10952:
10953: =back
10954:
10955: =head2 Course Infomation
10956:
10957: =over 4
1.191 harris41 10958:
10959: =item *
10960:
1.631 albertel 10961: coursedescription($courseid) : returns a hash of information about the
10962: specified course id, including all environment settings for the
10963: course, the description of the course will be in the hash under the
10964: key 'description'
1.191 harris41 10965:
10966: =item *
10967:
1.624 albertel 10968: resdata($name,$domain,$type,@which) : request for current parameter
10969: setting for a specific $type, where $type is either 'course' or 'user',
10970: @what should be a list of parameters to ask about. This routine caches
10971: answers for 5 minutes.
1.243 albertel 10972:
1.877 foxr 10973: =item *
10974:
10975: get_courseresdata($courseid, $domain) : dump the entire course resource
10976: data base, returning a hash that is keyed by the resource name and has
10977: values that are the resource value. I believe that the timestamps and
10978: versions are also returned.
10979:
10980:
1.243 albertel 10981: =back
10982:
10983: =head2 Course Modification
10984:
10985: =over 4
1.191 harris41 10986:
10987: =item *
10988:
1.243 albertel 10989: writecoursepref($courseid,%prefs) : write preferences (environment
10990: database) for a course
1.191 harris41 10991:
10992: =item *
10993:
1.1011 raeburn 10994: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10995:
10996: =item *
10997:
1.1038 raeburn 10998: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10999:
11000: =back
11001:
11002: =head2 Resource Subroutines
11003:
11004: =over 4
1.191 harris41 11005:
11006: =item *
11007:
1.243 albertel 11008: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 11009:
11010: =item *
11011:
1.243 albertel 11012: repcopy($filename) : subscribes to the requested file, and attempts to
11013: replicate from the owning library server, Might return
1.607 raeburn 11014: 'unavailable', 'not_found', 'forbidden', 'ok', or
11015: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 11016: resource. Expects the local filesystem pathname
11017: (/home/httpd/html/res/....)
11018:
11019: =back
11020:
11021: =head2 Resource Information
11022:
11023: =over 4
1.191 harris41 11024:
11025: =item *
11026:
1.243 albertel 11027: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11028: a vairety of different possible values, $varname should be a request
11029: string, and the other parameters can be used to specify who and what
11030: one is asking about.
11031:
11032: Possible values for $varname are environment.lastname (or other item
11033: from the envirnment hash), user.name (or someother aspect about the
11034: user), resource.0.maxtries (or some other part and parameter of a
11035: resource)
1.204 albertel 11036:
11037: =item *
11038:
1.243 albertel 11039: directcondval($number) : get current value of a condition; reads from a state
11040: string
1.204 albertel 11041:
11042: =item *
11043:
1.243 albertel 11044: condval($condidx) : value of condition index based on state
1.204 albertel 11045:
11046: =item *
11047:
1.243 albertel 11048: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11049: resource's metadata, $what should be either a specific key, or either
11050: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11051: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11052:
11053: this function automatically caches all requests
1.191 harris41 11054:
11055: =item *
11056:
1.243 albertel 11057: metadata_query($query,$custom,$customshow) : make a metadata query against the
11058: network of library servers; returns file handle of where SQL and regex results
11059: will be stored for query
1.191 harris41 11060:
11061: =item *
11062:
1.243 albertel 11063: symbread($filename) : return symbolic list entry (filename argument optional);
11064: returns the data handle
1.191 harris41 11065:
11066: =item *
11067:
1.243 albertel 11068: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11069: a possible symb for the URL in $thisfn, and if is an encryypted
11070: resource that the user accessed using /enc/ returns a 1 on success, 0
11071: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11072: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11073:
1.191 harris41 11074:
11075: =item *
11076:
1.243 albertel 11077: symbclean($symb) : removes versions numbers from a symb, returns the
11078: cleaned symb
1.191 harris41 11079:
11080: =item *
11081:
1.243 albertel 11082: is_on_map($uri) : checks if the $uri is somewhere on the current
11083: course map, user must be in a course for it to work.
1.191 harris41 11084:
11085: =item *
11086:
1.243 albertel 11087: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11088:
11089: =item *
11090:
1.243 albertel 11091: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11092: a random seed, all arguments are optional, if they aren't sent it uses the
11093: environment to derive them. Note: if symb isn't sent and it can't get one
11094: from &symbread it will use the current time as its return value
1.191 harris41 11095:
11096: =item *
11097:
1.243 albertel 11098: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11099: unfakeable, receipt
1.191 harris41 11100:
11101: =item *
11102:
1.620 albertel 11103: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11104:
11105: =item *
11106:
1.243 albertel 11107: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11108:
11109: =item *
11110:
1.243 albertel 11111: 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 11112:
11113: =item *
11114:
1.243 albertel 11115: 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 11116:
11117: =item *
11118:
1.243 albertel 11119: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11120:
11121: =item *
11122:
1.243 albertel 11123: devalidate($symb) : devalidate temporary spreadsheet calculations,
11124: forcing spreadsheet to reevaluate the resource scores next time.
11125:
11126: =back
11127:
11128: =head2 Storing/Retreiving Data
11129:
11130: =over 4
1.191 harris41 11131:
11132: =item *
11133:
1.243 albertel 11134: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11135: for this url; hashref needs to be given and should be a \%hashname; the
11136: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11137: be derived from the env
1.191 harris41 11138:
11139: =item *
11140:
1.243 albertel 11141: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11142: uses critical subroutine
1.191 harris41 11143:
11144: =item *
11145:
1.243 albertel 11146: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11147: all args are optional
1.191 harris41 11148:
11149: =item *
11150:
1.717 albertel 11151: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11152: dumps the complete (or key matching regexp) namespace into a hash
11153: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11154: normally &store()ed into
11155:
11156: $range should be either an integer '100' (give me the first 100
11157: matching records)
11158: or be two integers sperated by a - with no spaces
11159: '30-50' (give me the 30th through the 50th matching
11160: records)
11161:
11162:
11163: =item *
11164:
11165: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11166: replaces a &store() version of data with a replacement set of data
11167: for a particular resource in a namespace passed in the $storehash hash
11168: reference
11169:
11170: =item *
11171:
1.243 albertel 11172: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11173: works very similar to store/cstore, but all data is stored in a
11174: temporary location and can be reset using tmpreset, $storehash should
11175: be a hash reference, returns nothing on success
1.191 harris41 11176:
11177: =item *
11178:
1.243 albertel 11179: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11180: similar to restore, but all data is stored in a temporary location and
11181: can be reset using tmpreset. Returns a hash of values on success,
11182: error string otherwise.
1.191 harris41 11183:
11184: =item *
11185:
1.243 albertel 11186: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11187: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11188:
11189: =item *
11190:
1.243 albertel 11191: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11192: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11193:
11194: =item *
11195:
1.243 albertel 11196: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11197: namesp ($udom and $uname are optional)
1.191 harris41 11198:
11199: =item *
11200:
1.702 albertel 11201: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11202: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11203: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11204:
1.702 albertel 11205: $range should be either an integer '100' (give me the first 100
11206: matching records)
11207: or be two integers sperated by a - with no spaces
11208: '30-50' (give me the 30th through the 50th matching
11209: records)
1.449 matthew 11210: =item *
11211:
11212: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11213: $store can be a scalar, an array reference, or if the amount to be
11214: incremented is > 1, a hash reference.
11215:
11216: ($udom and $uname are optional)
1.191 harris41 11217:
11218: =item *
11219:
1.243 albertel 11220: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11221: ($udom and $uname are optional)
1.191 harris41 11222:
11223: =item *
11224:
1.243 albertel 11225: cput($namespace,$storehash,$udom,$uname) : critical put
11226: ($udom and $uname are optional)
1.191 harris41 11227:
11228: =item *
11229:
1.748 albertel 11230: newput($namespace,$storehash,$udom,$uname) :
11231:
11232: Attempts to store the items in the $storehash, but only if they don't
11233: currently exist, if this succeeds you can be certain that you have
11234: successfully created a new key value pair in the $namespace db.
11235:
11236:
11237: Args:
11238: $namespace: name of database to store values to
11239: $storehash: hashref to store to the db
11240: $udom: (optional) domain of user containing the db
11241: $uname: (optional) name of user caontaining the db
11242:
11243: Returns:
11244: 'ok' -> succeeded in storing all keys of $storehash
11245: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11246: least <key> already existed in the db (other
11247: requested keys may also already exist)
1.967 bisitz 11248: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11249: 'con_lost' -> unable to contact request server
11250: 'refused' -> action was not allowed by remote machine
11251:
11252:
11253: =item *
11254:
1.243 albertel 11255: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11256: reference filled in from namesp (encrypts the return communication)
11257: ($udom and $uname are optional)
1.191 harris41 11258:
11259: =item *
11260:
1.243 albertel 11261: log($udom,$name,$home,$message) : write to permanent log for user; use
11262: critical subroutine
11263:
1.806 raeburn 11264: =item *
11265:
1.860 raeburn 11266: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11267: array reference filled in from namespace found in domain level on either
11268: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11269:
11270: =item *
11271:
1.860 raeburn 11272: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11273: domain level either on specified domain server ($uhome) or primary domain
11274: server ($udom and $uhome are optional)
1.806 raeburn 11275:
1.943 raeburn 11276: =item *
11277:
11278: get_domain_defaults($target_domain) : returns hash with defaults for
11279: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11280: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11281: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11282: Values are retrieved from cache (if current), or from domain's configuration.db
11283: (if available), or lastly from values in lonTabs/dns_domain,tab,
11284: or lonTabs/domain.tab.
11285:
11286: %domdefaults = &get_auth_defaults($target_domain);
11287:
1.243 albertel 11288: =back
11289:
11290: =head2 Network Status Functions
11291:
11292: =over 4
1.191 harris41 11293:
11294: =item *
11295:
11296: dirlist($uri) : return directory list based on URI
11297:
11298: =item *
11299:
1.243 albertel 11300: spareserver() : find server with least workload from spare.tab
11301:
1.986 foxr 11302:
11303: =item *
11304:
11305: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11306: if there is no corresponding loncapa host.
11307:
1.243 albertel 11308: =back
11309:
1.986 foxr 11310:
1.243 albertel 11311: =head2 Apache Request
11312:
11313: =over 4
1.191 harris41 11314:
11315: =item *
11316:
1.243 albertel 11317: ssi($url,%hash) : server side include, does a complete request cycle on url to
11318: localhost, posts hash
11319:
11320: =back
11321:
11322: =head2 Data to String to Data
11323:
11324: =over 4
1.191 harris41 11325:
11326: =item *
11327:
1.243 albertel 11328: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11329: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11330:
11331: =item *
11332:
1.243 albertel 11333: hashref2str($hashref) : convert a hashref into a string complete with
11334: escaping and '=' and '&' separators, supports elements that are
11335: arrayrefs and hashrefs
1.191 harris41 11336:
11337: =item *
11338:
1.243 albertel 11339: arrayref2str($arrayref) : convert an arrayref into a string complete
11340: with escaping and '&' separators, supports elements that are arrayrefs
11341: and hashrefs
1.191 harris41 11342:
11343: =item *
11344:
1.243 albertel 11345: str2hash($string) : convert string to hash using unescaping and
11346: splitting on '=' and '&', supports elements that are arrayrefs and
11347: hashrefs
1.191 harris41 11348:
11349: =item *
11350:
1.243 albertel 11351: str2array($string) : convert string to hash using unescaping and
11352: splitting on '&', supports elements that are arrayrefs and hashrefs
11353:
11354: =back
11355:
11356: =head2 Logging Routines
11357:
11358: =over 4
11359:
11360: These routines allow one to make log messages in the lonnet.log and
11361: lonnet.perm logfiles.
1.191 harris41 11362:
11363: =item *
11364:
1.243 albertel 11365: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11366:
11367: =item *
11368:
1.243 albertel 11369: logthis() : append message to the normal lonnet.log file, it gets
11370: preiodically rolled over and deleted.
1.191 harris41 11371:
11372: =item *
11373:
1.243 albertel 11374: logperm() : append a permanent message to lonnet.perm.log, this log
11375: file never gets deleted by any automated portion of the system, only
11376: messages of critical importance should go in here.
11377:
11378: =back
11379:
11380: =head2 General File Helper Routines
11381:
11382: =over 4
1.191 harris41 11383:
11384: =item *
11385:
1.481 raeburn 11386: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11387: (a) files in /uploaded
11388: (i) If a local copy of the file exists -
11389: compares modification date of local copy with last-modified date for
11390: definitive version stored on home server for course. If local copy is
11391: stale, requests a new version from the home server and stores it.
11392: If the original has been removed from the home server, then local copy
11393: is unlinked.
11394: (ii) If local copy does not exist -
11395: requests the file from the home server and stores it.
11396:
11397: If $caller is 'uploadrep':
11398: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11399: for request for files originally uploaded via DOCS.
11400: - returns 'ok' if fresh local copy now available, -1 otherwise.
11401:
11402: Otherwise:
11403: This indicates a call from the content generation phase of the request.
11404: - returns the entire contents of the file or -1.
11405:
11406: (b) files in /res
11407: - returns the entire contents of a file or -1;
11408: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11409:
1.712 albertel 11410:
11411: =item *
11412:
11413: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11414: reference
11415:
11416: returns either a stat() list of data about the file or an empty list
11417: if the file doesn't exist or couldn't find out about it (connection
11418: problems or user unknown)
11419:
1.191 harris41 11420: =item *
11421:
1.243 albertel 11422: filelocation($dir,$file) : returns file system location of a file
11423: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11424: directory that relative $file lookups are to looked in ($dir of /a/dir
11425: and a file of ../bob will become /a/bob)
1.191 harris41 11426:
11427: =item *
11428:
11429: hreflocation($dir,$file) : returns file system location or a URL; same as
11430: filelocation except for hrefs
11431:
11432: =item *
11433:
11434: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11435:
1.243 albertel 11436: =back
11437:
1.608 albertel 11438: =head2 Usererfile file routines (/uploaded*)
11439:
11440: =over 4
11441:
11442: =item *
11443:
11444: userfileupload(): main rotine for putting a file in a user or course's
11445: filespace, arguments are,
11446:
1.620 albertel 11447: formname - required - this is the name of the element in $env where the
1.608 albertel 11448: filename, and the contents of the file to create/modifed exist
1.620 albertel 11449: the filename is in $env{'form.'.$formname.'.filename'} and the
11450: contents of the file is located in $env{'form.'.$formname}
1.1056.4.13! raeburn 11451: context - if coursedoc, store the file in the course of the active role
! 11452: of the current user;
! 11453: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
! 11454: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 11455: subdir - required - subdirectory to put the file in under ../userfiles/
11456: if undefined, it will be placed in "unknown"
11457:
11458: (This routine calls clean_filename() to remove any dangerous
11459: characters from the filename, and then calls finuserfileupload() to
11460: complete the transaction)
11461:
11462: returns either the url of the uploaded file (/uploaded/....) if successful
11463: and /adm/notfound.html if unsuccessful
11464:
11465: =item *
11466:
11467: clean_filename(): routine for cleaing a filename up for storage in
11468: userfile space, argument is:
11469:
11470: filename - proposed filename
11471:
11472: returns: the new clean filename
11473:
11474: =item *
11475:
1.1056.4.13! raeburn 11476: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 11477: userspace, probably shouldn't be called directly
11478:
11479: docuname: username or courseid of destination for the file
11480: docudom: domain of user/course of destination for the file
11481: formname: same as for userfileupload()
1.1056.4.13! raeburn 11482: fname: filename (including subdirectories) for the file
! 11483: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
! 11484: allfiles: reference to hash used to store objects found by parser
! 11485: codebase: reference to hash used for codebases of java objects found by parser
! 11486: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
! 11487: thumbheight: height (pixels) of thumbnail to be created for uploaded image
! 11488: resizewidth: width to be used to resize image using resizeImage from ImageMagick
! 11489: resizeheight: height to be used to resize image using resizeImage from ImageMagick
! 11490: context: if 'overwrite', will move the uploaded file from its temporary location to
! 11491: userfiles to facilitate overwriting a previously uploaded file with same name.
1.608 albertel 11492:
11493: returns either the url of the uploaded file (/uploaded/....) if successful
1.1056.4.13! raeburn 11494: and /adm/notfound.html if unsuccessful (or an error message if context
! 11495: was 'overwrite').
! 11496:
1.608 albertel 11497:
11498: =item *
11499:
11500: renameuserfile(): renames an existing userfile to a new name
11501:
11502: Args:
11503: docuname: username or courseid of destination for the file
11504: docudom: domain of user/course of destination for the file
11505: old: current file name (including any subdirs under userfiles)
11506: new: desired file name (including any subdirs under userfiles)
11507:
11508: =item *
11509:
11510: mkdiruserfile(): creates a directory is a userfiles dir
11511:
11512: Args:
11513: docuname: username or courseid of destination for the file
11514: docudom: domain of user/course of destination for the file
11515: dir: dir to create (including any subdirs under userfiles)
11516:
11517: =item *
11518:
11519: removeuserfile(): removes a file that exists in userfiles
11520:
11521: Args:
11522: docuname: username or courseid of destination for the file
11523: docudom: domain of user/course of destination for the file
11524: fname: filname to delete (including any subdirs under userfiles)
11525:
11526: =item *
11527:
11528: removeuploadedurl(): convience function for removeuserfile()
11529:
11530: Args:
11531: url: a full /uploaded/... url to delete
11532:
1.747 albertel 11533: =item *
11534:
11535: get_portfile_permissions():
11536: Args:
11537: domain: domain of user or course contain the portfolio files
11538: user: name of user or num of course contain the portfolio files
11539: Returns:
11540: hashref of a dump of the proper file_permissions.db
11541:
11542:
11543: =item *
11544:
11545: get_access_controls():
11546:
11547: Args:
11548: current_permissions: the hash ref returned from get_portfile_permissions()
11549: group: (optional) the group you want the files associated with
11550: file: (optional) the file you want access info on
11551:
11552: Returns:
1.749 raeburn 11553: a hash (keys are file names) of hashes containing
11554: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11555: values are XML containing access control settings (see below)
1.747 albertel 11556:
11557: Internal notes:
11558:
1.749 raeburn 11559: access controls are stored in file_permissions.db as key=value pairs.
11560: key -> path to file/file_name\0uniqueID:scope_end_start
11561: where scope -> public,guest,course,group,domains or users.
11562: end -> UNIX time for end of access (0 -> no end date)
11563: start -> UNIX time for start of access
11564:
11565: value -> XML description of access control
11566: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11567: <start></start>
11568: <end></end>
11569:
11570: <password></password> for scope type = guest
11571:
11572: <domain></domain> for scope type = course or group
11573: <number></number>
11574: <roles id="">
11575: <role></role>
11576: <access></access>
11577: <section></section>
11578: <group></group>
11579: </roles>
11580:
11581: <dom></dom> for scope type = domains
11582:
11583: <users> for scope type = users
11584: <user>
11585: <uname></uname>
11586: <udom></udom>
11587: </user>
11588: </users>
11589: </scope>
11590:
11591: Access data is also aggregated for each file in an additional key=value pair:
11592: key -> path to file/file_name\0accesscontrol
11593: value -> reference to hash
11594: hash contains key = value pairs
11595: where key = uniqueID:scope_end_start
11596: value = UNIX time record was last updated
11597:
11598: Used to improve speed of look-ups of access controls for each file.
11599:
11600: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11601:
11602: modify_access_controls():
11603:
11604: Modifies access controls for a portfolio file
11605: Args
11606: 1. file name
11607: 2. reference to hash of required changes,
11608: 3. domain
11609: 4. username
11610: where domain,username are the domain of the portfolio owner
11611: (either a user or a course)
11612:
11613: Returns:
11614: 1. result of additions or updates ('ok' or 'error', with error message).
11615: 2. result of deletions ('ok' or 'error', with error message).
11616: 3. reference to hash of any new or updated access controls.
11617: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11618: key = integer (inbound ID)
11619: value = uniqueID
1.747 albertel 11620:
1.608 albertel 11621: =back
11622:
1.243 albertel 11623: =head2 HTTP Helper Routines
11624:
11625: =over 4
11626:
1.191 harris41 11627: =item *
11628:
11629: escape() : unpack non-word characters into CGI-compatible hex codes
11630:
11631: =item *
11632:
11633: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11634:
1.243 albertel 11635: =back
11636:
11637: =head1 PRIVATE SUBROUTINES
11638:
11639: =head2 Underlying communication routines (Shouldn't call)
11640:
11641: =over 4
11642:
11643: =item *
11644:
11645: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11646:
11647: =item *
11648:
11649: reply() : uses subreply to send a message to remote machine, logs all failures
11650:
11651: =item *
11652:
11653: critical() : passes a critical message to another server; if cannot
11654: get through then place message in connection buffer directory and
11655: returns con_delayed, if incapable of saving message, returns
11656: con_failed
11657:
11658: =item *
11659:
11660: reconlonc() : tries to reconnect lonc client processes.
11661:
11662: =back
11663:
11664: =head2 Resource Access Logging
11665:
11666: =over 4
11667:
11668: =item *
11669:
11670: flushcourselogs() : flush (save) buffer logs and access logs
11671:
11672: =item *
11673:
11674: courselog($what) : save message for course in hash
11675:
11676: =item *
11677:
11678: courseacclog($what) : save message for course using &courselog(). Perform
11679: special processing for specific resource types (problems, exams, quizzes, etc).
11680:
1.191 harris41 11681: =item *
11682:
11683: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11684: as a PerlChildExitHandler
1.243 albertel 11685:
11686: =back
11687:
11688: =head2 Other
11689:
11690: =over 4
11691:
11692: =item *
11693:
11694: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11695:
11696: =back
11697:
11698: =cut
1.877 foxr 11699:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>