Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1095
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1095 ! raeburn 4: # $Id: lonnet.pm,v 1.1094 2010/11/27 16:55:57 raeburn Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
1.971 jms 51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1079 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.1024 raeburn 95: use File::MMagic;
1.807 albertel 96: use LONCAPA qw(:DEFAULT :match);
1.740 www 97: use LONCAPA::Configuration;
1.1090 raeburn 98: use File::Copy;
1.676 albertel 99:
1.195 www 100: my $readit;
1.550 foxr 101: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 102:
1.619 albertel 103: require Exporter;
104:
105: our @ISA = qw (Exporter);
106: our @EXPORT = qw(%env);
107:
1.449 matthew 108:
1.1 albertel 109: # --------------------------------------------------------------------- Logging
1.729 www 110: {
111: my $logid;
112: sub instructor_log {
1.957 raeburn 113: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
114: if (($cnum eq '') || ($cdom eq '')) {
115: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
116: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
117: }
1.729 www 118: $logid++;
1.957 raeburn 119: my $now = time();
120: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 121: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 122: { $id => {
123: 'exe_uname' => $env{'user.name'},
124: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 125: 'exe_time' => $now,
1.730 www 126: 'exe_ip' => $ENV{'REMOTE_ADDR'},
127: 'delflag' => $delflag,
128: 'logentry' => $storehash,
129: 'uname' => $uname,
130: 'udom' => $udom,
131: }
1.957 raeburn 132: },$cdom,$cnum);
1.729 www 133: }
134: }
1.1 albertel 135:
1.163 harris41 136: sub logtouch {
137: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 138: unless (-e "$execdir/logs/lonnet.log") {
139: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 140: close $fh;
141: }
142: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
143: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
144: }
145:
1.1 albertel 146: sub logthis {
147: my $message=shift;
148: my $execdir=$perlvar{'lonDaemons'};
149: my $now=time;
150: my $local=localtime($now);
1.448 albertel 151: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 152: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
153: print $fh $logstring;
1.448 albertel 154: close($fh);
155: }
1.1 albertel 156: return 1;
157: }
158:
159: sub logperm {
160: my $message=shift;
161: my $execdir=$perlvar{'lonDaemons'};
162: my $now=time;
163: my $local=localtime($now);
1.448 albertel 164: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
165: print $fh "$now:$message:$local\n";
166: close($fh);
167: }
1.1 albertel 168: return 1;
169: }
170:
1.850 albertel 171: sub create_connection {
1.853 albertel 172: my ($hostname,$lonid) = @_;
1.851 albertel 173: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 174: Type => SOCK_STREAM,
175: Timeout => 10);
176: return 0 if (!$client);
1.890 albertel 177: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 178: my $result = <$client>;
179: chomp($result);
180: return 1 if ($result eq 'done');
181: return 0;
182: }
183:
1.983 raeburn 184: sub get_server_timezone {
185: my ($cnum,$cdom) = @_;
186: my $home=&homeserver($cnum,$cdom);
187: if ($home ne 'no_host') {
188: my $cachetime = 24*3600;
189: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
190: if (defined($cached)) {
191: return $timezone;
192: } else {
193: my $timezone = &reply('servertimezone',$home);
194: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
195: }
196: }
197: }
1.850 albertel 198:
1.993 raeburn 199: sub get_server_loncaparev {
1.1073 raeburn 200: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 201: if (defined($lonhost)) {
202: if (!defined(&hostname($lonhost))) {
203: undef($lonhost);
204: }
205: }
206: if (!defined($lonhost)) {
207: if (defined(&domain($dom,'primary'))) {
208: $lonhost=&domain($dom,'primary');
209: if ($lonhost eq 'no_host') {
210: undef($lonhost);
211: }
212: }
213: }
214: if (defined($lonhost)) {
1.1073 raeburn 215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
218: if (defined($cached)) {
219: return $loncaparev;
220: }
221: }
222: my ($answer,$loncaparev);
223: my @ids=¤t_machine_ids();
224: if (grep(/^\Q$lonhost\E$/,@ids)) {
225: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 226: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 227: $loncaparev = $1;
228: }
229: } else {
230: $answer = &reply('serverloncaparev',$lonhost);
231: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
232: if ($caller eq 'loncron') {
233: my $ua=new LWP::UserAgent;
1.1082 raeburn 234: $ua->timeout(4);
1.1073 raeburn 235: my $protocol = $protocol{$lonhost};
236: $protocol = 'http' if ($protocol ne 'https');
237: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
238: my $request=new HTTP::Request('GET',$url);
239: my $response=$ua->request($request);
240: unless ($response->is_error()) {
241: my $content = $response->content;
1.1081 raeburn 242: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 243: $loncaparev = $1;
244: }
245: }
246: } else {
247: $loncaparev = $loncaparevs{$lonhost};
248: }
1.1081 raeburn 249: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 250: $loncaparev = $1;
251: }
1.993 raeburn 252: }
1.1073 raeburn 253: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 254: }
255: }
256:
1.1074 raeburn 257: sub get_server_homeID {
258: my ($hostname,$ignore_cache,$caller) = @_;
259: unless ($ignore_cache) {
260: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
261: if (defined($cached)) {
262: return $serverhomeID;
263: }
264: }
265: my $cachetime = 12*3600;
266: my $serverhomeID;
267: if ($caller eq 'loncron') {
268: my @machine_ids = &machine_ids($hostname);
269: foreach my $id (@machine_ids) {
270: my $response = &reply('serverhomeID',$id);
271: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
272: $serverhomeID = $response;
273: last;
274: }
275: }
276: if ($serverhomeID eq '') {
277: $serverhomeID = $machine_ids[-1];
278: }
279: } else {
280: $serverhomeID = $serverhomeIDs{$hostname};
281: }
282: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
283: }
284:
1.1 albertel 285: # -------------------------------------------------- Non-critical communication
286: sub subreply {
287: my ($cmd,$server)=@_;
1.838 albertel 288: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 289: #
290: # With loncnew process trimming, there's a timing hole between lonc server
291: # process exit and the master server picking up the listen on the AF_UNIX
292: # socket. In that time interval, a lock file will exist:
293:
294: my $lockfile=$peerfile.".lock";
295: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
296: sleep(1);
297: }
298: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 299: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 300: #
1.550 foxr 301: # We'll give the connection a few tries before abandoning it. If
302: # connection is not possible, we'll con_lost back to the client.
303: #
304: my $client;
305: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
306: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
307: Type => SOCK_STREAM,
308: Timeout => 10);
1.869 albertel 309: if ($client) {
1.550 foxr 310: last; # Connected!
1.850 albertel 311: } else {
1.853 albertel 312: &create_connection(&hostname($server),$server);
1.550 foxr 313: }
1.850 albertel 314: sleep(1); # Try again later if failed connection.
1.550 foxr 315: }
316: my $answer;
317: if ($client) {
1.704 albertel 318: print $client "sethost:$server:$cmd\n";
1.550 foxr 319: $answer=<$client>;
320: if (!$answer) { $answer="con_lost"; }
321: chomp($answer);
322: } else {
323: $answer = 'con_lost'; # Failed connection.
324: }
1.1 albertel 325: return $answer;
326: }
327:
328: sub reply {
329: my ($cmd,$server)=@_;
1.838 albertel 330: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 331: my $answer=subreply($cmd,$server);
1.65 www 332: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 333: &logthis("<font color=\"blue\">WARNING:".
1.12 www 334: " $cmd to $server returned $answer</font>");
335: }
1.1 albertel 336: return $answer;
337: }
338:
339: # ----------------------------------------------------------- Send USR1 to lonc
340:
341: sub reconlonc {
1.891 albertel 342: my ($lonid) = @_;
343: my $hostname = &hostname($lonid);
344: if ($lonid) {
345: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
346: if ($hostname && -e $peerfile) {
347: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
348: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
349: Type => SOCK_STREAM,
350: Timeout => 10);
351: if ($client) {
352: print $client ("reset_retries\n");
353: my $answer=<$client>;
354: #reset just this one.
355: }
356: }
357: return;
358: }
359:
1.836 www 360: &logthis("Trying to reconnect lonc");
1.1 albertel 361: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 362: if (open(my $fh,"<$loncfile")) {
1.1 albertel 363: my $loncpid=<$fh>;
364: chomp($loncpid);
365: if (kill 0 => $loncpid) {
366: &logthis("lonc at pid $loncpid responding, sending USR1");
367: kill USR1 => $loncpid;
368: sleep 1;
1.836 www 369: } else {
1.12 www 370: &logthis(
1.672 albertel 371: "<font color=\"blue\">WARNING:".
1.12 www 372: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 373: }
374: } else {
1.836 www 375: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 376: }
377: }
378:
379: # ------------------------------------------------------ Critical communication
1.12 www 380:
1.1 albertel 381: sub critical {
382: my ($cmd,$server)=@_;
1.838 albertel 383: unless (&hostname($server)) {
1.672 albertel 384: &logthis("<font color=\"blue\">WARNING:".
1.89 www 385: " Critical message to unknown server ($server)</font>");
386: return 'no_such_host';
387: }
1.1 albertel 388: my $answer=reply($cmd,$server);
389: if ($answer eq 'con_lost') {
390: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 391: my $answer=reply($cmd,$server);
1.1 albertel 392: if ($answer eq 'con_lost') {
393: my $now=time;
394: my $middlename=$cmd;
1.5 www 395: $middlename=substr($middlename,0,16);
1.1 albertel 396: $middlename=~s/\W//g;
397: my $dfilename=
1.305 www 398: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
399: $dumpcount++;
1.1 albertel 400: {
1.448 albertel 401: my $dfh;
402: if (open($dfh,">$dfilename")) {
403: print $dfh "$cmd\n";
404: close($dfh);
405: }
1.1 albertel 406: }
407: sleep 2;
408: my $wcmd='';
409: {
1.448 albertel 410: my $dfh;
411: if (open($dfh,"<$dfilename")) {
412: $wcmd=<$dfh>;
413: close($dfh);
414: }
1.1 albertel 415: }
416: chomp($wcmd);
1.7 www 417: if ($wcmd eq $cmd) {
1.672 albertel 418: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 419: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 420: &logperm("D:$server:$cmd");
421: return 'con_delayed';
422: } else {
1.672 albertel 423: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 424: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 425: &logperm("F:$server:$cmd");
426: return 'con_failed';
427: }
428: }
429: }
430: return $answer;
1.405 albertel 431: }
432:
1.755 albertel 433: # ------------------------------------------- check if return value is an error
434:
435: sub error {
436: my ($result) = @_;
1.756 albertel 437: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 438: if ($2 == 2) { return undef; }
439: return $1;
440: }
441: return undef;
442: }
443:
1.783 albertel 444: sub convert_and_load_session_env {
445: my ($lonidsdir,$handle)=@_;
446: my @profile;
447: {
1.917 albertel 448: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
449: if (!$opened) {
1.915 albertel 450: return 0;
451: }
1.783 albertel 452: flock($idf,LOCK_SH);
453: @profile=<$idf>;
454: close($idf);
455: }
456: my %temp_env;
457: foreach my $line (@profile) {
1.786 albertel 458: if ($line !~ m/=/) {
459: return 0;
460: }
1.783 albertel 461: chomp($line);
462: my ($envname,$envvalue)=split(/=/,$line,2);
463: $temp_env{&unescape($envname)} = &unescape($envvalue);
464: }
465: unlink("$lonidsdir/$handle.id");
466: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
467: 0640)) {
468: %disk_env = %temp_env;
469: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
470: untie(%disk_env);
471: }
1.786 albertel 472: return 1;
1.783 albertel 473: }
474:
1.374 www 475: # ------------------------------------------- Transfer profile into environment
1.780 albertel 476: my $env_loaded;
477: sub transfer_profile_to_env {
1.788 albertel 478: my ($lonidsdir,$handle,$force_transfer) = @_;
479: if (!$force_transfer && $env_loaded) { return; }
1.374 www 480:
1.720 albertel 481: if (!defined($lonidsdir)) {
482: $lonidsdir = $perlvar{'lonIDsDir'};
483: }
484: if (!defined($handle)) {
485: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
486: }
487:
1.786 albertel 488: my $convert;
489: {
1.917 albertel 490: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
491: if (!$opened) {
1.915 albertel 492: return;
493: }
1.786 albertel 494: flock($idf,LOCK_SH);
495: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
496: &GDBM_READER(),0640)) {
497: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
498: untie(%disk_env);
499: } else {
500: $convert = 1;
501: }
502: }
503: if ($convert) {
504: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
505: &logthis("Failed to load session, or convert session.");
506: }
1.374 www 507: }
1.783 albertel 508:
1.786 albertel 509: my %remove;
1.783 albertel 510: while ( my $envname = each(%env) ) {
1.433 matthew 511: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
512: if ($time < time-300) {
1.783 albertel 513: $remove{$key}++;
1.433 matthew 514: }
515: }
516: }
1.783 albertel 517:
1.619 albertel 518: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 519: $env_loaded=1;
1.783 albertel 520: foreach my $expired_key (keys(%remove)) {
1.433 matthew 521: &delenv($expired_key);
1.374 www 522: }
1.1 albertel 523: }
524:
1.916 albertel 525: # ---------------------------------------------------- Check for valid session
526: sub check_for_valid_session {
527: my ($r) = @_;
528: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
529: my $lonid=$cookies{'lonID'};
530: return undef if (!$lonid);
531:
532: my $handle=&LONCAPA::clean_handle($lonid->value);
533: my $lonidsdir=$r->dir_config('lonIDsDir');
534: return undef if (!-e "$lonidsdir/$handle.id");
535:
1.917 albertel 536: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
537: return undef if (!$opened);
1.916 albertel 538:
539: flock($idf,LOCK_SH);
540: my %disk_env;
541: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
542: &GDBM_READER(),0640)) {
543: return undef;
544: }
545:
546: if (!defined($disk_env{'user.name'})
547: || !defined($disk_env{'user.domain'})) {
548: return undef;
549: }
550: return $handle;
551: }
552:
1.830 albertel 553: sub timed_flock {
554: my ($file,$lock_type) = @_;
555: my $failed=0;
556: eval {
557: local $SIG{__DIE__}='DEFAULT';
558: local $SIG{ALRM}=sub {
559: $failed=1;
560: die("failed lock");
561: };
562: alarm(13);
563: flock($file,$lock_type);
564: alarm(0);
565: };
566: if ($failed) {
567: return undef;
568: } else {
569: return 1;
570: }
571: }
572:
1.5 www 573: # ---------------------------------------------------------- Append Environment
574:
575: sub appenv {
1.949 raeburn 576: my ($newenv,$roles) = @_;
577: if (ref($newenv) eq 'HASH') {
578: foreach my $key (keys(%{$newenv})) {
579: my $refused = 0;
580: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
581: $refused = 1;
582: if (ref($roles) eq 'ARRAY') {
583: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
584: if (grep(/^\Q$role\E$/,@{$roles})) {
585: $refused = 0;
586: }
587: }
588: }
589: if ($refused) {
590: &logthis("<font color=\"blue\">WARNING: ".
591: "Attempt to modify environment ".$key." to ".$newenv->{$key}
592: .'</font>');
593: delete($newenv->{$key});
594: } else {
595: $env{$key}=$newenv->{$key};
596: }
597: }
598: my $opened = open(my $env_file,'+<',$env{'user.environment'});
599: if ($opened
600: && &timed_flock($env_file,LOCK_EX)
601: &&
602: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
603: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
604: while (my ($key,$value) = each(%{$newenv})) {
605: $disk_env{$key} = $value;
606: }
607: untie(%disk_env);
1.35 www 608: }
1.191 harris41 609: }
1.56 www 610: return 'ok';
611: }
612: # ----------------------------------------------------- Delete from Environment
613:
614: sub delenv {
1.987 raeburn 615: my ($delthis,$regexp) = @_;
1.56 www 616: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 617: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 618: "Attempt to delete from environment ".$delthis);
619: return 'error';
620: }
1.917 albertel 621: my $opened = open(my $env_file,'+<',$env{'user.environment'});
622: if ($opened
1.915 albertel 623: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 624: &&
625: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
626: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 627: foreach my $key (keys(%disk_env)) {
1.987 raeburn 628: if ($regexp) {
629: if ($key=~/^$delthis/) {
630: delete($env{$key});
631: delete($disk_env{$key});
632: }
633: } else {
634: if ($key=~/^\Q$delthis\E/) {
635: delete($env{$key});
636: delete($disk_env{$key});
637: }
638: }
1.448 albertel 639: }
1.783 albertel 640: untie(%disk_env);
1.5 www 641: }
642: return 'ok';
1.369 albertel 643: }
644:
1.790 albertel 645: sub get_env_multiple {
646: my ($name) = @_;
647: my @values;
648: if (defined($env{$name})) {
649: # exists is it an array
650: if (ref($env{$name})) {
651: @values=@{ $env{$name} };
652: } else {
653: $values[0]=$env{$name};
654: }
655: }
656: return(@values);
657: }
658:
1.958 www 659: # ------------------------------------------------------------------- Locking
660:
661: sub set_lock {
662: my ($text)=@_;
663: $locknum++;
664: my $id=$$.'-'.$locknum;
665: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
666: 'session.lock.'.$id => $text});
667: return $id;
668: }
669:
670: sub get_locks {
671: my $num=0;
672: my %texts=();
673: foreach my $lock (split(/\,/,$env{'session.locks'})) {
674: if ($lock=~/\w/) {
675: $num++;
676: $texts{$lock}=$env{'session.lock.'.$lock};
677: }
678: }
679: return ($num,%texts);
680: }
681:
682: sub remove_lock {
683: my ($id)=@_;
684: my $newlocks='';
685: foreach my $lock (split(/\,/,$env{'session.locks'})) {
686: if (($lock=~/\w/) && ($lock ne $id)) {
687: $newlocks.=','.$lock;
688: }
689: }
690: &appenv({'session.locks' => $newlocks});
691: &delenv('session.lock.'.$id);
692: }
693:
694: sub remove_all_locks {
695: my $activelocks=$env{'session.locks'};
696: foreach my $lock (split(/\,/,$env{'session.locks'})) {
697: if ($lock=~/\w/) {
698: &remove_lock($lock);
699: }
700: }
701: }
702:
703:
1.369 albertel 704: # ------------------------------------------ Find out current server userload
705: sub userload {
706: my $numusers=0;
707: {
708: opendir(LONIDS,$perlvar{'lonIDsDir'});
709: my $filename;
710: my $curtime=time;
711: while ($filename=readdir(LONIDS)) {
1.925 albertel 712: next if ($filename eq '.' || $filename eq '..');
713: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 714: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 715: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 716: }
717: closedir(LONIDS);
718: }
719: my $userloadpercent=0;
720: my $maxuserload=$perlvar{'lonUserLoadLim'};
721: if ($maxuserload) {
1.371 albertel 722: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 723: }
1.372 albertel 724: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 725: return $userloadpercent;
1.283 www 726: }
727:
1.1 albertel 728: # ------------------------------ Find server with least workload from spare.tab
1.11 www 729:
1.1 albertel 730: sub spareserver {
1.1083 raeburn 731: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 732: my $spare_server;
1.370 albertel 733: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 734: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
735: : $userloadpercent;
1.1083 raeburn 736: my ($uint_dom,$remotesessions);
737: if (($udom ne '') && (&domain($udom) ne '')) {
738: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
739: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
740: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
741: $remotesessions = $udomdefaults{'remotesessions'};
742: }
1.784 albertel 743: foreach my $try_server (@{ $spareid{'primary'} }) {
1.1083 raeburn 744: if ($uint_dom) {
745: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
746: $try_server));
747: }
1.784 albertel 748: ($spare_server, $lowest_load) =
749: &compare_server_load($try_server, $spare_server, $lowest_load);
750: }
751:
752: my $found_server = ($spare_server ne '' && $lowest_load < 100);
753:
754: if (!$found_server) {
755: foreach my $try_server (@{ $spareid{'default'} }) {
1.1083 raeburn 756: if ($uint_dom) {
757: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
758: $try_server));
759: }
1.784 albertel 760: ($spare_server, $lowest_load) =
761: &compare_server_load($try_server, $spare_server, $lowest_load);
762: }
763: }
764:
765: if (!$want_server_name) {
1.968 raeburn 766: my $protocol = 'http';
767: if ($protocol{$spare_server} eq 'https') {
768: $protocol = $protocol{$spare_server};
769: }
1.1001 raeburn 770: if (defined($spare_server)) {
771: my $hostname = &hostname($spare_server);
1.1083 raeburn 772: if (defined($hostname)) {
1.1001 raeburn 773: $spare_server = $protocol.'://'.$hostname;
774: }
775: }
1.784 albertel 776: }
777: return $spare_server;
778: }
779:
780: sub compare_server_load {
781: my ($try_server, $spare_server, $lowest_load) = @_;
782:
783: my $loadans = &reply('load', $try_server);
784: my $userloadans = &reply('userload',$try_server);
785:
786: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1072 www 787: return; #didn't get a number from the server
1.784 albertel 788: }
789:
790: my $load;
791: if ($loadans =~ /\d/) {
792: if ($userloadans =~ /\d/) {
793: #both are numbers, pick the bigger one
794: $load = ($loadans > $userloadans) ? $loadans
795: : $userloadans;
1.411 albertel 796: } else {
1.784 albertel 797: $load = $loadans;
1.411 albertel 798: }
1.784 albertel 799: } else {
800: $load = $userloadans;
801: }
802:
803: if (($load =~ /\d/) && ($load < $lowest_load)) {
804: $spare_server = $try_server;
805: $lowest_load = $load;
1.370 albertel 806: }
1.784 albertel 807: return ($spare_server,$lowest_load);
1.202 matthew 808: }
1.914 albertel 809:
810: # --------------------------- ask offload servers if user already has a session
811: sub find_existing_session {
812: my ($udom,$uname) = @_;
813: foreach my $try_server (@{ $spareid{'primary'} },
814: @{ $spareid{'default'} }) {
815: return $try_server if (&has_user_session($try_server, $udom, $uname));
816: }
817: return;
818: }
819:
820: # -------------------------------- ask if server already has a session for user
821: sub has_user_session {
822: my ($lonid,$udom,$uname) = @_;
823: my $result = &reply(join(':','userhassession',
824: map {&escape($_)} ($udom,$uname)),$lonid);
825: return 1 if ($result eq 'ok');
826:
827: return 0;
828: }
829:
1.1076 raeburn 830: # --------- determine least loaded server in a user's domain which allows login
831:
832: sub choose_server {
833: my ($udom) = @_;
834: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 835: my %servers = &get_servers($udom);
1.1076 raeburn 836: my $lowest_load = 30000;
837: my ($login_host,$hostname);
838: foreach my $lonhost (keys(%servers)) {
839: my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
840: if ($loginvia eq '') {
841: ($login_host, $lowest_load) =
842: &compare_server_load($lonhost, $login_host, $lowest_load);
843: }
844: }
845: if ($login_host ne '') {
846: $hostname = $servers{$login_host};
847: }
848: return ($login_host,$hostname);
849: }
850:
1.202 matthew 851: # --------------------------------------------- Try to change a user's password
852:
853: sub changepass {
1.799 raeburn 854: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 855: $currentpass = &escape($currentpass);
856: $newpass = &escape($newpass);
1.1030 raeburn 857: my $lonhost = $perlvar{'lonHostID'};
858: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 859: $server);
860: if (! $answer) {
861: &logthis("No reply on password change request to $server ".
862: "by $uname in domain $udom.");
863: } elsif ($answer =~ "^ok") {
864: &logthis("$uname in $udom successfully changed their password ".
865: "on $server.");
866: } elsif ($answer =~ "^pwchange_failure") {
867: &logthis("$uname in $udom was unable to change their password ".
868: "on $server. The action was blocked by either lcpasswd ".
869: "or pwchange");
870: } elsif ($answer =~ "^non_authorized") {
871: &logthis("$uname in $udom did not get their password correct when ".
872: "attempting to change it on $server.");
873: } elsif ($answer =~ "^auth_mode_error") {
874: &logthis("$uname in $udom attempted to change their password despite ".
875: "not being locally or internally authenticated on $server.");
876: } elsif ($answer =~ "^unknown_user") {
877: &logthis("$uname in $udom attempted to change their password ".
878: "on $server but were unable to because $server is not ".
879: "their home server.");
880: } elsif ($answer =~ "^refused") {
881: &logthis("$server refused to change $uname in $udom password because ".
882: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 883: } elsif ($answer =~ "invalid_client") {
884: &logthis("$server refused to change $uname in $udom password because ".
885: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 886: }
887: return $answer;
1.1 albertel 888: }
889:
1.169 harris41 890: # ----------------------- Try to determine user's current authentication scheme
891:
892: sub queryauthenticate {
893: my ($uname,$udom)=@_;
1.456 albertel 894: my $uhome=&homeserver($uname,$udom);
895: if (!$uhome) {
896: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
897: return 'no_host';
898: }
899: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
900: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
901: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 902: }
1.456 albertel 903: return $answer;
1.169 harris41 904: }
905:
1.1 albertel 906: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 907:
1.1 albertel 908: sub authenticate {
1.1073 raeburn 909: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 910: $upass=&escape($upass);
911: $uname= &LONCAPA::clean_username($uname);
1.836 www 912: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 913: my $newhome;
1.836 www 914: if ((!$uhome) || ($uhome eq 'no_host')) {
915: # Maybe the machine was offline and only re-appeared again recently?
916: &reconlonc();
917: # One more
1.952 raeburn 918: $uhome=&homeserver($uname,$udom,1);
919: if (($uhome eq 'no_host') && $checkdefauth) {
920: if (defined(&domain($udom,'primary'))) {
921: $newhome=&domain($udom,'primary');
922: }
923: if ($newhome ne '') {
924: $uhome = $newhome;
925: }
926: }
1.836 www 927: if ((!$uhome) || ($uhome eq 'no_host')) {
928: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 929: return 'no_host';
930: }
1.1 albertel 931: }
1.1073 raeburn 932: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 933: if ($answer eq 'authorized') {
1.952 raeburn 934: if ($newhome) {
935: &logthis("User $uname at $udom authorized by $uhome, but needs account");
936: return 'no_account_on_host';
937: } else {
938: &logthis("User $uname at $udom authorized by $uhome");
939: return $uhome;
940: }
1.471 albertel 941: }
942: if ($answer eq 'non_authorized') {
943: &logthis("User $uname at $udom rejected by $uhome");
944: return 'no_host';
1.9 www 945: }
1.471 albertel 946: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 947: return 'no_host';
948: }
949:
1.1073 raeburn 950: sub can_host_session {
1.1074 raeburn 951: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 952: my $canhost = 1;
1.1074 raeburn 953: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 954: if (ref($remotesessions) eq 'HASH') {
955: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 956: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 957: $canhost = 0;
958: } else {
959: $canhost = 1;
960: }
961: }
962: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 963: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 964: $canhost = 1;
965: } else {
966: $canhost = 0;
967: }
968: }
969: if ($canhost) {
970: if ($remotesessions->{'version'} ne '') {
971: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
972: if ($reqmajor ne '' && $reqminor ne '') {
973: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
974: my $major = $1;
975: my $minor = $2;
976: if (($major < $reqmajor ) ||
977: (($major == $reqmajor) && ($minor < $reqminor))) {
978: $canhost = 0;
979: }
980: } else {
981: $canhost = 0;
982: }
983: }
984: }
985: }
986: }
987: if ($canhost) {
988: if (ref($hostedsessions) eq 'HASH') {
989: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
990: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
991: $canhost = 0;
992: } else {
993: $canhost = 1;
994: }
995: }
996: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
997: if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
998: $canhost = 1;
999: } else {
1000: $canhost = 0;
1001: }
1002: }
1003: }
1004: }
1005: return $canhost;
1006: }
1007:
1.1083 raeburn 1008: sub spare_can_host {
1009: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1010: my $canhost=1;
1011: my @intdoms;
1012: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1013: if (ref($internet_names) eq 'ARRAY') {
1014: @intdoms = @{$internet_names};
1015: }
1016: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1017: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1018: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1019: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1020: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1021: $canhost = &can_host_session($udom,$try_server,$remoterev,
1022: $remotesessions,
1023: $defdomdefaults{'hostedsessions'});
1024: }
1025: return $canhost;
1026: }
1027:
1.1 albertel 1028: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1029:
1.599 albertel 1030: my %homecache;
1.1 albertel 1031: sub homeserver {
1.230 stredwic 1032: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1033: my $index="$uname:$udom";
1.426 albertel 1034:
1.599 albertel 1035: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1036:
1037: my %servers = &get_servers($udom,'library');
1038: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1039: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1040: exists($badServerCache{$tryserver}));
1.841 albertel 1041:
1042: my $answer=reply("home:$udom:$uname",$tryserver);
1043: if ($answer eq 'found') {
1044: delete($badServerCache{$tryserver});
1045: return $homecache{$index}=$tryserver;
1046: } elsif ($answer eq 'no_host') {
1047: $badServerCache{$tryserver}=1;
1048: }
1.1 albertel 1049: }
1050: return 'no_host';
1.70 www 1051: }
1052:
1053: # ------------------------------------- Find the usernames behind a list of IDs
1054:
1055: sub idget {
1056: my ($udom,@ids)=@_;
1057: my %returnhash=();
1058:
1.841 albertel 1059: my %servers = &get_servers($udom,'library');
1060: foreach my $tryserver (keys(%servers)) {
1061: my $idlist=join('&',@ids);
1062: $idlist=~tr/A-Z/a-z/;
1063: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1064: my @answer=();
1065: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1066: @answer=split(/\&/,$reply);
1067: } ;
1068: my $i;
1069: for ($i=0;$i<=$#ids;$i++) {
1070: if ($answer[$i]) {
1071: $returnhash{$ids[$i]}=$answer[$i];
1072: }
1073: }
1074: }
1.70 www 1075: return %returnhash;
1076: }
1077:
1078: # ------------------------------------- Find the IDs behind a list of usernames
1079:
1080: sub idrget {
1081: my ($udom,@unames)=@_;
1082: my %returnhash=();
1.800 albertel 1083: foreach my $uname (@unames) {
1084: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1085: }
1.70 www 1086: return %returnhash;
1087: }
1088:
1089: # ------------------------------- Store away a list of names and associated IDs
1090:
1091: sub idput {
1092: my ($udom,%ids)=@_;
1093: my %servers=();
1.800 albertel 1094: foreach my $uname (keys(%ids)) {
1095: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1096: my $uhom=&homeserver($uname,$udom);
1.70 www 1097: if ($uhom ne 'no_host') {
1.800 albertel 1098: my $id=&escape($ids{$uname});
1.70 www 1099: $id=~tr/A-Z/a-z/;
1.800 albertel 1100: my $esc_unam=&escape($uname);
1.70 www 1101: if ($servers{$uhom}) {
1.800 albertel 1102: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1103: } else {
1.800 albertel 1104: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1105: }
1106: }
1.191 harris41 1107: }
1.800 albertel 1108: foreach my $server (keys(%servers)) {
1109: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1110: }
1.344 www 1111: }
1112:
1.1023 raeburn 1113: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1114: sub dump_dom {
1.1023 raeburn 1115: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1116: if (!$udom) {
1117: $udom=$env{'user.domain'};
1118: }
1119: my %returnhash;
1.1023 raeburn 1120: if ($udom) {
1121: my $uname = &get_domainconfiguser($udom);
1122: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1123: }
1124: return %returnhash;
1125: }
1126:
1.1023 raeburn 1127: # ------------------------------------------ get items from domain db files
1.806 raeburn 1128:
1129: sub get_dom {
1.860 raeburn 1130: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1131: my $items='';
1132: foreach my $item (@$storearr) {
1133: $items.=&escape($item).'&';
1134: }
1135: $items=~s/\&$//;
1.860 raeburn 1136: if (!$udom) {
1137: $udom=$env{'user.domain'};
1138: if (defined(&domain($udom,'primary'))) {
1139: $uhome=&domain($udom,'primary');
1140: } else {
1.874 albertel 1141: undef($uhome);
1.860 raeburn 1142: }
1143: } else {
1144: if (!$uhome) {
1145: if (defined(&domain($udom,'primary'))) {
1146: $uhome=&domain($udom,'primary');
1147: }
1148: }
1149: }
1150: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1151: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1152: my %returnhash;
1.875 albertel 1153: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1154: return %returnhash;
1155: }
1.806 raeburn 1156: my @pairs=split(/\&/,$rep);
1157: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1158: return @pairs;
1159: }
1160: my $i=0;
1161: foreach my $item (@$storearr) {
1162: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1163: $i++;
1164: }
1165: return %returnhash;
1166: } else {
1.880 banghart 1167: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1168: }
1169: }
1170:
1171: # -------------------------------------------- put items in domain db files
1172:
1173: sub put_dom {
1.860 raeburn 1174: my ($namespace,$storehash,$udom,$uhome)=@_;
1175: if (!$udom) {
1176: $udom=$env{'user.domain'};
1177: if (defined(&domain($udom,'primary'))) {
1178: $uhome=&domain($udom,'primary');
1179: } else {
1.874 albertel 1180: undef($uhome);
1.860 raeburn 1181: }
1182: } else {
1183: if (!$uhome) {
1184: if (defined(&domain($udom,'primary'))) {
1185: $uhome=&domain($udom,'primary');
1186: }
1187: }
1188: }
1189: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1190: my $items='';
1191: foreach my $item (keys(%$storehash)) {
1192: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1193: }
1194: $items=~s/\&$//;
1195: return &reply("putdom:$udom:$namespace:$items",$uhome);
1196: } else {
1.860 raeburn 1197: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1198: }
1199: }
1200:
1.1023 raeburn 1201: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1202: sub newput_dom {
1.1023 raeburn 1203: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1204: my $result;
1205: if (!$udom) {
1206: $udom=$env{'user.domain'};
1207: }
1.1023 raeburn 1208: if ($udom) {
1209: my $uname = &get_domainconfiguser($udom);
1210: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1211: }
1212: return $result;
1213: }
1214:
1.1023 raeburn 1215: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1216: sub del_dom {
1.1023 raeburn 1217: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1218: if (ref($storearr) eq 'ARRAY') {
1219: if (!$udom) {
1220: $udom=$env{'user.domain'};
1221: }
1.1023 raeburn 1222: if ($udom) {
1223: my $uname = &get_domainconfiguser($udom);
1224: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1225: }
1226: }
1227: }
1228:
1.1023 raeburn 1229: # ----------------------------------construct domainconfig user for a domain
1230: sub get_domainconfiguser {
1231: my ($udom) = @_;
1232: return $udom.'-domainconfig';
1233: }
1234:
1.837 raeburn 1235: sub retrieve_inst_usertypes {
1236: my ($udom) = @_;
1237: my (%returnhash,@order);
1.989 raeburn 1238: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1239: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1240: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1241: %returnhash = %{$domdefs{'inststatustypes'}};
1242: @order = @{$domdefs{'inststatusorder'}};
1243: } else {
1244: if (defined(&domain($udom,'primary'))) {
1245: my $uhome=&domain($udom,'primary');
1246: my $rep=&reply("inst_usertypes:$udom",$uhome);
1247: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1248: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1249: return (\%returnhash,\@order);
1250: }
1251: my ($hashitems,$orderitems) = split(/:/,$rep);
1252: my @pairs=split(/\&/,$hashitems);
1253: foreach my $item (@pairs) {
1254: my ($key,$value)=split(/=/,$item,2);
1255: $key = &unescape($key);
1256: next if ($key =~ /^error: 2 /);
1257: $returnhash{$key}=&thaw_unescape($value);
1258: }
1259: my @esc_order = split(/\&/,$orderitems);
1260: foreach my $item (@esc_order) {
1261: push(@order,&unescape($item));
1262: }
1263: } else {
1264: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1265: }
1266: }
1267: return (\%returnhash,\@order);
1268: }
1269:
1.868 raeburn 1270: sub is_domainimage {
1271: my ($url) = @_;
1272: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1273: if (&domain($1) ne '') {
1274: return '1';
1275: }
1276: }
1277: return;
1278: }
1279:
1.899 raeburn 1280: sub inst_directory_query {
1281: my ($srch) = @_;
1282: my $udom = $srch->{'srchdomain'};
1283: my %results;
1284: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1285: my $outcome;
1.899 raeburn 1286: if ($homeserver ne '') {
1.904 albertel 1287: my $queryid=&reply("querysend:instdirsearch:".
1288: &escape($srch->{'srchby'}).':'.
1289: &escape($srch->{'srchterm'}).':'.
1290: &escape($srch->{'srchtype'}),$homeserver);
1291: my $host=&hostname($homeserver);
1292: if ($queryid !~/^\Q$host\E\_/) {
1293: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1294: return;
1295: }
1296: my $response = &get_query_reply($queryid);
1297: my $maxtries = 5;
1298: my $tries = 1;
1299: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1300: $response = &get_query_reply($queryid);
1301: $tries ++;
1302: }
1303:
1304: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1305: if ($response eq 'unavailable') {
1306: $outcome = $response;
1307: } else {
1308: $outcome = 'ok';
1309: my @matches = split(/\n/,$response);
1310: foreach my $match (@matches) {
1311: my ($key,$value) = split(/=/,$match);
1312: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1313: }
1.899 raeburn 1314: }
1315: }
1316: }
1.909 raeburn 1317: return ($outcome,%results);
1.899 raeburn 1318: }
1319:
1320: sub usersearch {
1321: my ($srch) = @_;
1322: my $dom = $srch->{'srchdomain'};
1323: my %results;
1324: my %libserv = &all_library();
1325: my $query = 'usersearch';
1326: foreach my $tryserver (keys(%libserv)) {
1327: if (&host_domain($tryserver) eq $dom) {
1328: my $host=&hostname($tryserver);
1329: my $queryid=
1.911 raeburn 1330: &reply("querysend:".&escape($query).':'.
1331: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1332: &escape($srch->{'srchtype'}).':'.
1333: &escape($srch->{'srchterm'}),$tryserver);
1334: if ($queryid !~/^\Q$host\E\_/) {
1335: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1336: next;
1.899 raeburn 1337: }
1338: my $reply = &get_query_reply($queryid);
1339: my $maxtries = 1;
1340: my $tries = 1;
1341: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1342: $reply = &get_query_reply($queryid);
1343: $tries ++;
1344: }
1345: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1346: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1347: } else {
1.911 raeburn 1348: my @matches;
1349: if ($reply =~ /\n/) {
1350: @matches = split(/\n/,$reply);
1351: } else {
1352: @matches = split(/\&/,$reply);
1353: }
1.899 raeburn 1354: foreach my $match (@matches) {
1355: my ($uname,$udom,%userhash);
1.911 raeburn 1356: foreach my $entry (split(/:/,$match)) {
1357: my ($key,$value) =
1358: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1359: $userhash{$key} = $value;
1360: if ($key eq 'username') {
1361: $uname = $value;
1362: } elsif ($key eq 'domain') {
1363: $udom = $value;
1.911 raeburn 1364: }
1.899 raeburn 1365: }
1366: $results{$uname.':'.$udom} = \%userhash;
1367: }
1368: }
1369: }
1370: }
1371: return %results;
1372: }
1373:
1.912 raeburn 1374: sub get_instuser {
1375: my ($udom,$uname,$id) = @_;
1376: my $homeserver = &domain($udom,'primary');
1377: my ($outcome,%results);
1378: if ($homeserver ne '') {
1379: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1380: &escape($id).':'.&escape($udom),$homeserver);
1381: my $host=&hostname($homeserver);
1382: if ($queryid !~/^\Q$host\E\_/) {
1383: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1384: return;
1385: }
1386: my $response = &get_query_reply($queryid);
1387: my $maxtries = 5;
1388: my $tries = 1;
1389: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1390: $response = &get_query_reply($queryid);
1391: $tries ++;
1392: }
1393: if (!&error($response) && $response ne 'refused') {
1394: if ($response eq 'unavailable') {
1395: $outcome = $response;
1396: } else {
1397: $outcome = 'ok';
1398: my @matches = split(/\n/,$response);
1399: foreach my $match (@matches) {
1400: my ($key,$value) = split(/=/,$match);
1401: $results{&unescape($key)} = &thaw_unescape($value);
1402: }
1403: }
1404: }
1405: }
1406: my %userinfo;
1407: if (ref($results{$uname}) eq 'HASH') {
1408: %userinfo = %{$results{$uname}};
1409: }
1410: return ($outcome,%userinfo);
1411: }
1412:
1413: sub inst_rulecheck {
1.923 raeburn 1414: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1415: my %returnhash;
1416: if ($udom ne '') {
1417: if (ref($rules) eq 'ARRAY') {
1418: @{$rules} = map {&escape($_);} (@{$rules});
1419: my $rulestr = join(':',@{$rules});
1420: my $homeserver=&domain($udom,'primary');
1421: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1422: my $response;
1423: if ($item eq 'username') {
1424: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1425: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1426: $homeserver));
1.923 raeburn 1427: } elsif ($item eq 'id') {
1428: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1429: ':'.&escape($id).':'.$rulestr,
1430: $homeserver));
1.945 raeburn 1431: } elsif ($item eq 'selfcreate') {
1432: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1433: &escape($udom).':'.&escape($uname).
1434: ':'.$rulestr,$homeserver));
1.923 raeburn 1435: }
1.912 raeburn 1436: if ($response ne 'refused') {
1437: my @pairs=split(/\&/,$response);
1438: foreach my $item (@pairs) {
1439: my ($key,$value)=split(/=/,$item,2);
1440: $key = &unescape($key);
1441: next if ($key =~ /^error: 2 /);
1442: $returnhash{$key}=&thaw_unescape($value);
1443: }
1444: }
1445: }
1446: }
1447: }
1448: return %returnhash;
1449: }
1450:
1451: sub inst_userrules {
1.923 raeburn 1452: my ($udom,$check) = @_;
1.912 raeburn 1453: my (%ruleshash,@ruleorder);
1454: if ($udom ne '') {
1455: my $homeserver=&domain($udom,'primary');
1456: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1457: my $response;
1458: if ($check eq 'id') {
1459: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1460: $homeserver);
1.943 raeburn 1461: } elsif ($check eq 'email') {
1462: $response=&reply('instemailrules:'.&escape($udom),
1463: $homeserver);
1.923 raeburn 1464: } else {
1465: $response=&reply('instuserrules:'.&escape($udom),
1466: $homeserver);
1467: }
1.912 raeburn 1468: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1469: ($response ne 'unknown_cmd') &&
1.912 raeburn 1470: ($response ne 'no_such_host')) {
1471: my ($hashitems,$orderitems) = split(/:/,$response);
1472: my @pairs=split(/\&/,$hashitems);
1473: foreach my $item (@pairs) {
1474: my ($key,$value)=split(/=/,$item,2);
1475: $key = &unescape($key);
1476: next if ($key =~ /^error: 2 /);
1477: $ruleshash{$key}=&thaw_unescape($value);
1478: }
1479: my @esc_order = split(/\&/,$orderitems);
1480: foreach my $item (@esc_order) {
1481: push(@ruleorder,&unescape($item));
1482: }
1483: }
1484: }
1485: }
1486: return (\%ruleshash,\@ruleorder);
1487: }
1488:
1.976 raeburn 1489: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1490:
1491: sub get_domain_defaults {
1492: my ($domain) = @_;
1493: my $cachetime = 60*60*24;
1494: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1495: if (defined($cached)) {
1496: if (ref($result) eq 'HASH') {
1497: return %{$result};
1498: }
1499: }
1500: my %domdefaults;
1501: my %domconfig =
1.989 raeburn 1502: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1503: 'requestcourses','inststatus',
1.1073 raeburn 1504: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1505: if (ref($domconfig{'defaults'}) eq 'HASH') {
1506: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1507: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1508: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1509: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1510: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1511: } else {
1512: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1513: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1514: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1515: }
1.976 raeburn 1516: if (ref($domconfig{'quotas'}) eq 'HASH') {
1517: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1518: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1519: } else {
1520: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1521: }
1522: my @usertools = ('aboutme','blog','portfolio');
1523: foreach my $item (@usertools) {
1524: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1525: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1526: }
1527: }
1528: }
1.985 raeburn 1529: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1530: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1531: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1532: }
1533: }
1.989 raeburn 1534: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1535: foreach my $item ('inststatustypes','inststatusorder') {
1536: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1537: }
1538: }
1.1047 raeburn 1539: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1540: foreach my $item ('canuse_pdfforms') {
1541: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1542: }
1543: }
1.1073 raeburn 1544: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1545: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1546: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1547: }
1548: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1549: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1550: }
1551: }
1.943 raeburn 1552: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1553: $cachetime);
1554: return %domdefaults;
1555: }
1556:
1.344 www 1557: # --------------------------------------------------- Assign a key to a student
1558:
1559: sub assign_access_key {
1.364 www 1560: #
1561: # a valid key looks like uname:udom#comments
1562: # comments are being appended
1563: #
1.498 www 1564: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1565: $kdom=
1.620 albertel 1566: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1567: $knum=
1.620 albertel 1568: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1569: $cdom=
1.620 albertel 1570: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1571: $cnum=
1.620 albertel 1572: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1573: $udom=$env{'user.name'} unless (defined($udom));
1574: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1575: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1576: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1577: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1578: # assigned to this person
1579: # - this should not happen,
1.345 www 1580: # unless something went wrong
1581: # the first time around
1582: # ready to assign
1.364 www 1583: $logentry=$1.'; '.$logentry;
1.496 www 1584: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1585: $kdom,$knum) eq 'ok') {
1.345 www 1586: # key now belongs to user
1.346 www 1587: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1588: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 1589: &appenv({'environment.'.$envkey => $ckey});
1.345 www 1590: return 'ok';
1591: } else {
1592: return
1593: 'error: Count not permanently assign key, will need to be re-entered later.';
1594: }
1595: } else {
1596: return 'error: Could not assign key, try again later.';
1597: }
1.364 www 1598: } elsif (!$existing{$ckey}) {
1.345 www 1599: # the key does not exist
1600: return 'error: The key does not exist';
1601: } else {
1602: # the key is somebody else's
1603: return 'error: The key is already in use';
1604: }
1.344 www 1605: }
1606:
1.364 www 1607: # ------------------------------------------ put an additional comment on a key
1608:
1609: sub comment_access_key {
1610: #
1611: # a valid key looks like uname:udom#comments
1612: # comments are being appended
1613: #
1614: my ($ckey,$cdom,$cnum,$logentry)=@_;
1615: $cdom=
1.620 albertel 1616: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 1617: $cnum=
1.620 albertel 1618: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 1619: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1620: if ($existing{$ckey}) {
1621: $existing{$ckey}.='; '.$logentry;
1622: # ready to assign
1.367 www 1623: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 1624: $cdom,$cnum) eq 'ok') {
1625: return 'ok';
1626: } else {
1627: return 'error: Count not store comment.';
1628: }
1629: } else {
1630: # the key does not exist
1631: return 'error: The key does not exist';
1632: }
1633: }
1634:
1.344 www 1635: # ------------------------------------------------------ Generate a set of keys
1636:
1637: sub generate_access_keys {
1.364 www 1638: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 1639: $cdom=
1.620 albertel 1640: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1641: $cnum=
1.620 albertel 1642: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 1643: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 1644: unless (($cdom) && ($cnum)) { return 0; }
1645: if ($number>10000) { return 0; }
1646: sleep(2); # make sure don't get same seed twice
1647: srand(time()^($$+($$<<15))); # from "Programming Perl"
1648: my $total=0;
1649: for (my $i=1;$i<=$number;$i++) {
1650: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1651: sprintf("%lx",int(100000*rand)).'-'.
1652: sprintf("%lx",int(100000*rand));
1653: $newkey=~s/1/g/g; # folks mix up 1 and l
1654: $newkey=~s/0/h/g; # and also 0 and O
1655: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1656: if ($existing{$newkey}) {
1657: $i--;
1658: } else {
1.364 www 1659: if (&put('accesskeys',
1660: { $newkey => '# generated '.localtime().
1.620 albertel 1661: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 1662: '; '.$logentry },
1663: $cdom,$cnum) eq 'ok') {
1.344 www 1664: $total++;
1665: }
1666: }
1667: }
1.620 albertel 1668: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 1669: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1670: return $total;
1671: }
1672:
1673: # ------------------------------------------------------- Validate an accesskey
1674:
1675: sub validate_access_key {
1676: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1677: $cdom=
1.620 albertel 1678: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1679: $cnum=
1.620 albertel 1680: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1681: $udom=$env{'user.domain'} unless (defined($udom));
1682: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 1683: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 1684: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 1685: }
1686:
1687: # ------------------------------------- Find the section of student in a course
1.652 albertel 1688: sub devalidate_getsection_cache {
1689: my ($udom,$unam,$courseid)=@_;
1690: my $hashid="$udom:$unam:$courseid";
1691: &devalidate_cache_new('getsection',$hashid);
1692: }
1.298 matthew 1693:
1.815 albertel 1694: sub courseid_to_courseurl {
1695: my ($courseid) = @_;
1696: #already url style courseid
1697: return $courseid if ($courseid =~ m{^/});
1698:
1699: if (exists($env{'course.'.$courseid.'.num'})) {
1700: my $cnum = $env{'course.'.$courseid.'.num'};
1701: my $cdom = $env{'course.'.$courseid.'.domain'};
1702: return "/$cdom/$cnum";
1703: }
1704:
1705: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1706: if (exists($courseinfo{'num'})) {
1707: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1708: }
1709:
1710: return undef;
1711: }
1712:
1.298 matthew 1713: sub getsection {
1714: my ($udom,$unam,$courseid)=@_;
1.599 albertel 1715: my $cachetime=1800;
1.551 albertel 1716:
1717: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1718: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1719: if (defined($cached)) { return $result; }
1720:
1.298 matthew 1721: my %Pending;
1722: my %Expired;
1723: #
1724: # Each role can either have not started yet (pending), be active,
1725: # or have expired.
1726: #
1727: # If there is an active role, we are done.
1728: #
1729: # If there is more than one role which has not started yet,
1730: # choose the one which will start sooner
1731: # If there is one role which has not started yet, return it.
1732: #
1733: # If there is more than one expired role, choose the one which ended last.
1734: # If there is a role which has expired, return it.
1735: #
1.815 albertel 1736: $courseid = &courseid_to_courseurl($courseid);
1.1086 raeburn 1737: my $extra = &freeze_escape({'skipcheck' => 1});
1738: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 1739: foreach my $key (keys(%roleshash)) {
1.479 albertel 1740: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1741: my $section=$1;
1742: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1743: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1744: my $now=time;
1.548 albertel 1745: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1746: $Expired{$end}=$section;
1747: next;
1748: }
1.548 albertel 1749: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1750: $Pending{$start}=$section;
1751: next;
1752: }
1.599 albertel 1753: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1754: }
1755: #
1756: # Presumedly there will be few matching roles from the above
1757: # loop and the sorting time will be negligible.
1758: if (scalar(keys(%Pending))) {
1759: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1760: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1761: }
1762: if (scalar(keys(%Expired))) {
1763: my @sorted = sort {$a <=> $b} keys(%Expired);
1764: my $time = pop(@sorted);
1.599 albertel 1765: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1766: }
1.599 albertel 1767: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1768: }
1.70 www 1769:
1.599 albertel 1770: sub save_cache {
1771: &purge_remembered();
1.722 albertel 1772: #&Apache::loncommon::validate_page();
1.620 albertel 1773: undef(%env);
1.780 albertel 1774: undef($env_loaded);
1.599 albertel 1775: }
1.452 albertel 1776:
1.599 albertel 1777: my $to_remember=-1;
1778: my %remembered;
1779: my %accessed;
1780: my $kicks=0;
1781: my $hits=0;
1.849 albertel 1782: sub make_key {
1783: my ($name,$id) = @_;
1.872 albertel 1784: if (length($id) > 65
1785: && length(&escape($id)) > 200) {
1786: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1787: }
1.849 albertel 1788: return &escape($name.':'.$id);
1789: }
1790:
1.599 albertel 1791: sub devalidate_cache_new {
1792: my ($name,$id,$debug) = @_;
1793: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1794: $id=&make_key($name,$id);
1.599 albertel 1795: $memcache->delete($id);
1796: delete($remembered{$id});
1797: delete($accessed{$id});
1798: }
1799:
1800: sub is_cached_new {
1801: my ($name,$id,$debug) = @_;
1.849 albertel 1802: $id=&make_key($name,$id);
1.599 albertel 1803: if (exists($remembered{$id})) {
1804: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1805: $accessed{$id}=[&gettimeofday()];
1806: $hits++;
1807: return ($remembered{$id},1);
1808: }
1809: my $value = $memcache->get($id);
1810: if (!(defined($value))) {
1811: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1812: return (undef,undef);
1.416 albertel 1813: }
1.599 albertel 1814: if ($value eq '__undef__') {
1815: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1816: $value=undef;
1817: }
1818: &make_room($id,$value,$debug);
1819: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1820: return ($value,1);
1821: }
1822:
1823: sub do_cache_new {
1824: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1825: $id=&make_key($name,$id);
1.599 albertel 1826: my $setvalue=$value;
1827: if (!defined($setvalue)) {
1828: $setvalue='__undef__';
1829: }
1.623 albertel 1830: if (!defined($time) ) {
1831: $time=600;
1832: }
1.599 albertel 1833: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 1834: my $result = $memcache->set($id,$setvalue,$time);
1835: if (! $result) {
1.872 albertel 1836: &logthis("caching of id -> $id failed");
1.910 albertel 1837: $memcache->disconnect_all();
1.872 albertel 1838: }
1.600 albertel 1839: # need to make a copy of $value
1.919 albertel 1840: &make_room($id,$value,$debug);
1.599 albertel 1841: return $value;
1842: }
1843:
1844: sub make_room {
1845: my ($id,$value,$debug)=@_;
1.919 albertel 1846:
1847: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1848: : $value;
1.599 albertel 1849: if ($to_remember<0) { return; }
1850: $accessed{$id}=[&gettimeofday()];
1851: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1852: my $to_kick;
1853: my $max_time=0;
1854: foreach my $other (keys(%accessed)) {
1855: if (&tv_interval($accessed{$other}) > $max_time) {
1856: $to_kick=$other;
1857: $max_time=&tv_interval($accessed{$other});
1858: }
1859: }
1860: delete($remembered{$to_kick});
1861: delete($accessed{$to_kick});
1862: $kicks++;
1863: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1864: return;
1865: }
1866:
1.599 albertel 1867: sub purge_remembered {
1.604 albertel 1868: #&logthis("Tossing ".scalar(keys(%remembered)));
1869: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1870: undef(%remembered);
1871: undef(%accessed);
1.428 albertel 1872: }
1.70 www 1873: # ------------------------------------- Read an entry from a user's environment
1874:
1875: sub userenvironment {
1876: my ($udom,$unam,@what)=@_;
1.976 raeburn 1877: my $items;
1878: foreach my $item (@what) {
1879: $items.=&escape($item).'&';
1880: }
1881: $items=~s/\&$//;
1.70 www 1882: my %returnhash=();
1.1009 raeburn 1883: my $uhome = &homeserver($unam,$udom);
1884: unless ($uhome eq 'no_host') {
1885: my @answer=split(/\&/,
1886: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 1887: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
1888: return %returnhash;
1889: }
1.1009 raeburn 1890: my $i;
1891: for ($i=0;$i<=$#what;$i++) {
1892: $returnhash{$what[$i]}=&unescape($answer[$i]);
1893: }
1.70 www 1894: }
1895: return %returnhash;
1.1 albertel 1896: }
1897:
1.617 albertel 1898: # ---------------------------------------------------------- Get a studentphoto
1899: sub studentphoto {
1900: my ($udom,$unam,$ext) = @_;
1901: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1902: if (defined($env{'request.course.id'})) {
1.708 raeburn 1903: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1904: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1905: return(&retrievestudentphoto($udom,$unam,$ext));
1906: } else {
1907: my ($result,$perm_reqd)=
1.707 albertel 1908: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1909: if ($result eq 'ok') {
1910: if (!($perm_reqd eq 'yes')) {
1911: return(&retrievestudentphoto($udom,$unam,$ext));
1912: }
1913: }
1914: }
1915: }
1916: } else {
1917: my ($result,$perm_reqd) =
1.707 albertel 1918: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1919: if ($result eq 'ok') {
1920: if (!($perm_reqd eq 'yes')) {
1921: return(&retrievestudentphoto($udom,$unam,$ext));
1922: }
1923: }
1924: }
1925: return '/adm/lonKaputt/lonlogo_broken.gif';
1926: }
1927:
1928: sub retrievestudentphoto {
1929: my ($udom,$unam,$ext,$type) = @_;
1930: my $home=&Apache::lonnet::homeserver($unam,$udom);
1931: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1932: if ($ret eq 'ok') {
1933: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1934: if ($type eq 'thumbnail') {
1935: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1936: }
1937: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1938: return $tokenurl;
1939: } else {
1940: if ($type eq 'thumbnail') {
1941: return '/adm/lonKaputt/genericstudent_tn.gif';
1942: } else {
1943: return '/adm/lonKaputt/lonlogo_broken.gif';
1944: }
1.617 albertel 1945: }
1946: }
1947:
1.263 www 1948: # -------------------------------------------------------------------- New chat
1949:
1950: sub chatsend {
1.724 raeburn 1951: my ($newentry,$anon,$group)=@_;
1.620 albertel 1952: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1953: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1954: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1955: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1956: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1957: &escape($newentry)).':'.$group,$chome);
1.292 www 1958: }
1959:
1960: # ------------------------------------------ Find current version of a resource
1961:
1962: sub getversion {
1963: my $fname=&clutter(shift);
1964: unless ($fname=~/^\/res\//) { return -1; }
1965: return ¤tversion(&filelocation('',$fname));
1966: }
1967:
1968: sub currentversion {
1969: my $fname=shift;
1.599 albertel 1970: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1971: if (defined($cached)) { return $result; }
1.292 www 1972: my $author=$fname;
1973: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1974: my ($udom,$uname)=split(/\//,$author);
1975: my $home=homeserver($uname,$udom);
1976: if ($home eq 'no_host') {
1977: return -1;
1978: }
1979: my $answer=reply("currentversion:$fname",$home);
1980: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1981: return -1;
1982: }
1.599 albertel 1983: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1984: }
1985:
1.1 albertel 1986: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1987:
1.1 albertel 1988: sub subscribe {
1989: my $fname=shift;
1.761 raeburn 1990: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1991: $fname=~s/[\n\r]//g;
1.1 albertel 1992: my $author=$fname;
1993: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1994: my ($udom,$uname)=split(/\//,$author);
1995: my $home=homeserver($uname,$udom);
1.335 albertel 1996: if ($home eq 'no_host') {
1997: return 'not_found';
1.1 albertel 1998: }
1999: my $answer=reply("sub:$fname",$home);
1.64 www 2000: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2001: $answer.=' by '.$home;
2002: }
1.1 albertel 2003: return $answer;
2004: }
2005:
1.8 www 2006: # -------------------------------------------------------------- Replicate file
2007:
2008: sub repcopy {
2009: my $filename=shift;
1.23 www 2010: $filename=~s/\/+/\//g;
1.607 raeburn 2011: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2012: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2013: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2014: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2015: return &repcopy_userfile($filename);
2016: }
1.532 albertel 2017: $filename=~s/[\n\r]//g;
1.8 www 2018: my $transname="$filename.in.transfer";
1.828 www 2019: # FIXME: this should flock
1.607 raeburn 2020: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2021: my $remoteurl=subscribe($filename);
1.64 www 2022: if ($remoteurl =~ /^con_lost by/) {
2023: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2024: return 'unavailable';
1.8 www 2025: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2026: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2027: return 'not_found';
1.64 www 2028: } elsif ($remoteurl =~ /^rejected by/) {
2029: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2030: return 'forbidden';
1.20 www 2031: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2032: return 'ok';
1.8 www 2033: } else {
1.290 www 2034: my $author=$filename;
2035: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2036: my ($udom,$uname)=split(/\//,$author);
2037: my $home=homeserver($uname,$udom);
2038: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2039: my @parts=split(/\//,$filename);
2040: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2041: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2042: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2043: return 'bad_request';
1.8 www 2044: }
2045: my $count;
2046: for ($count=5;$count<$#parts;$count++) {
2047: $path.="/$parts[$count]";
2048: if ((-e $path)!=1) {
2049: mkdir($path,0777);
2050: }
2051: }
2052: my $ua=new LWP::UserAgent;
2053: my $request=new HTTP::Request('GET',"$remoteurl");
2054: my $response=$ua->request($request,$transname);
2055: if ($response->is_error()) {
2056: unlink($transname);
2057: my $message=$response->status_line;
1.672 albertel 2058: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2059: ." LWP get: $message: $filename</font>");
1.607 raeburn 2060: return 'unavailable';
1.8 www 2061: } else {
1.16 www 2062: if ($remoteurl!~/\.meta$/) {
2063: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2064: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2065: if ($mresponse->is_error()) {
2066: unlink($filename.'.meta');
2067: &logthis(
1.672 albertel 2068: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2069: }
2070: }
1.8 www 2071: rename($transname,$filename);
1.607 raeburn 2072: return 'ok';
1.8 www 2073: }
1.290 www 2074: }
1.8 www 2075: }
1.330 www 2076: }
2077:
2078: # ------------------------------------------------ Get server side include body
2079: sub ssi_body {
1.381 albertel 2080: my ($filelink,%form)=@_;
1.606 matthew 2081: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2082: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2083: }
1.953 www 2084: my $output='';
2085: my $response;
1.980 raeburn 2086: if ($filelink=~/^https?\:/) {
1.954 raeburn 2087: ($output,$response)=&externalssi($filelink);
1.953 www 2088: } else {
1.1004 droeschl 2089: $filelink .= $filelink=~/\?/ ? '&' : '?';
2090: $filelink .= 'inhibitmenu=yes';
1.953 www 2091: ($output,$response)=&ssi($filelink,%form);
2092: }
1.778 albertel 2093: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2094: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2095: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2096: if (wantarray) {
2097: return ($output, $response);
2098: } else {
2099: return $output;
2100: }
1.8 www 2101: }
2102:
1.15 www 2103: # --------------------------------------------------------- Server Side Include
2104:
1.782 albertel 2105: sub absolute_url {
2106: my ($host_name) = @_;
2107: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2108: if ($host_name eq '') {
2109: $host_name = $ENV{'SERVER_NAME'};
2110: }
2111: return $protocol.$host_name;
2112: }
2113:
1.942 foxr 2114: #
2115: # Server side include.
2116: # Parameters:
2117: # fn Possibly encrypted resource name/id.
2118: # form Hash that describes how the rendering should be done
2119: # and other things.
1.944 foxr 2120: # Returns:
1.950 raeburn 2121: # Scalar context: The content of the response.
2122: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2123: #
1.15 www 2124: sub ssi {
2125:
1.944 foxr 2126: my ($fn,%form)=@_;
1.15 www 2127: my $ua=new LWP::UserAgent;
1.23 www 2128: my $request;
1.711 albertel 2129:
2130: $form{'no_update_last_known'}=1;
1.895 albertel 2131: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2132: if (%form) {
1.782 albertel 2133: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2134: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2135: } else {
1.782 albertel 2136: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2137: }
2138:
1.15 www 2139: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2140: my $response=$ua->request($request);
2141:
1.944 foxr 2142: if (wantarray) {
2143: return ($response->content, $response);
2144: } else {
2145: return $response->content;
1.942 foxr 2146: }
1.324 www 2147: }
2148:
2149: sub externalssi {
2150: my ($url)=@_;
2151: my $ua=new LWP::UserAgent;
2152: my $request=new HTTP::Request('GET',$url);
2153: my $response=$ua->request($request);
1.954 raeburn 2154: if (wantarray) {
2155: return ($response->content, $response);
2156: } else {
2157: return $response->content;
2158: }
1.15 www 2159: }
1.254 www 2160:
1.492 albertel 2161: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2162:
2163: sub allowuploaded {
2164: my ($srcurl,$url)=@_;
2165: $url=&clutter(&declutter($url));
2166: my $dir=$url;
2167: $dir=~s/\/[^\/]+$//;
2168: my %httpref=();
2169: my $httpurl=&hreflocation('',$url);
2170: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2171: &Apache::lonnet::appenv(\%httpref);
1.254 www 2172: }
1.477 raeburn 2173:
1.478 albertel 2174: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2175: # input: action, courseID, current domain, intended
1.637 raeburn 2176: # path to file, source of file, instruction to parse file for objects,
2177: # ref to hash for embedded objects,
2178: # ref to hash for codebase of java objects.
1.1095 ! raeburn 2179: # reference to scalar to accommodate mime type determined
! 2180: # from File::MMagic if $parser = parse.
1.637 raeburn 2181: #
1.485 raeburn 2182: # output: url to file (if action was uploaddoc),
2183: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2184: #
1.478 albertel 2185: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2186: # course.
1.477 raeburn 2187: #
1.478 albertel 2188: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2189: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2190: # course's home server.
1.477 raeburn 2191: #
1.478 albertel 2192: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2193: # be copied from $source (current location) to
2194: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2195: # and will then be copied to
2196: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2197: # course's home server.
1.485 raeburn 2198: #
1.481 raeburn 2199: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2200: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2201: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2202: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2203: # in course's home server.
1.637 raeburn 2204: #
1.477 raeburn 2205:
2206: sub process_coursefile {
1.1095 ! raeburn 2207: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
! 2208: $mimetype)=@_;
1.477 raeburn 2209: my $fetchresult;
1.638 albertel 2210: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2211: if ($action eq 'propagate') {
1.638 albertel 2212: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2213: $home);
1.481 raeburn 2214: } else {
1.477 raeburn 2215: my $fpath = '';
2216: my $fname = $file;
1.478 albertel 2217: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2218: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2219: my $filepath = &build_filepath($fpath);
1.481 raeburn 2220: if ($action eq 'copy') {
2221: if ($source eq '') {
2222: $fetchresult = 'no source file';
2223: return $fetchresult;
2224: } else {
2225: my $destination = $filepath.'/'.$fname;
2226: rename($source,$destination);
2227: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2228: $home);
1.481 raeburn 2229: }
2230: } elsif ($action eq 'uploaddoc') {
2231: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2232: print $fh $env{'form.'.$source};
1.481 raeburn 2233: close($fh);
1.637 raeburn 2234: if ($parser eq 'parse') {
1.1024 raeburn 2235: my $mm = new File::MMagic;
1.1095 ! raeburn 2236: my $type = $mm->checktype_filename($filepath.'/'.$fname);
! 2237: if ($type eq 'text/html') {
1.1024 raeburn 2238: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2239: unless ($parse_result eq 'ok') {
2240: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2241: }
1.637 raeburn 2242: }
1.1095 ! raeburn 2243: if (ref($mimetype)) {
! 2244: $$mimetype = $type;
! 2245: }
1.637 raeburn 2246: }
1.477 raeburn 2247: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2248: $home);
1.481 raeburn 2249: if ($fetchresult eq 'ok') {
2250: return '/uploaded/'.$fpath.'/'.$fname;
2251: } else {
2252: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2253: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2254: return '/adm/notfound.html';
2255: }
1.477 raeburn 2256: }
2257: }
1.485 raeburn 2258: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2259: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2260: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2261: }
2262: return $fetchresult;
2263: }
2264:
1.637 raeburn 2265: sub build_filepath {
2266: my ($fpath) = @_;
2267: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2268: unless ($fpath eq '') {
2269: my @parts=split('/',$fpath);
2270: foreach my $part (@parts) {
2271: $filepath.= '/'.$part;
2272: if ((-e $filepath)!=1) {
2273: mkdir($filepath,0777);
2274: }
2275: }
2276: }
2277: return $filepath;
2278: }
2279:
2280: sub store_edited_file {
1.638 albertel 2281: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2282: my $file = $primary_url;
2283: $file =~ s#^/uploaded/$docudom/$docuname/##;
2284: my $fpath = '';
2285: my $fname = $file;
2286: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2287: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2288: my $filepath = &build_filepath($fpath);
2289: open(my $fh,'>'.$filepath.'/'.$fname);
2290: print $fh $content;
2291: close($fh);
1.638 albertel 2292: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2293: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2294: $home);
1.637 raeburn 2295: if ($$fetchresult eq 'ok') {
2296: return '/uploaded/'.$fpath.'/'.$fname;
2297: } else {
1.638 albertel 2298: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2299: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2300: return '/adm/notfound.html';
2301: }
2302: }
2303:
1.531 albertel 2304: sub clean_filename {
1.831 albertel 2305: my ($fname,$args)=@_;
1.315 www 2306: # Replace Windows backslashes by forward slashes
1.257 www 2307: $fname=~s/\\/\//g;
1.831 albertel 2308: if (!$args->{'keep_path'}) {
2309: # Get rid of everything but the actual filename
2310: $fname=~s/^.*\/([^\/]+)$/$1/;
2311: }
1.315 www 2312: # Replace spaces by underscores
2313: $fname=~s/\s+/\_/g;
2314: # Replace all other weird characters by nothing
1.831 albertel 2315: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2316: # Replace all .\d. sequences with _\d. so they no longer look like version
2317: # numbers
2318: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2319: return $fname;
2320: }
1.1051 raeburn 2321: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2322: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2323: # image with the same aspect ratio as the original, but with dimensions which do
2324: # not exceed $resizewidth and $resizeheight.
2325:
1.984 neumanie 2326: sub resizeImage {
1.1051 raeburn 2327: my ($img_path,$resizewidth,$resizeheight) = @_;
2328: my $ima = Image::Magick->new;
2329: my $resized;
2330: if (-e $img_path) {
2331: $ima->Read($img_path);
2332: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2333: my $width = $ima->Get('width');
2334: my $height = $ima->Get('height');
2335: if ($width > $resizewidth) {
2336: my $factor = $width/$resizewidth;
2337: my $newheight = $height/$factor;
2338: $ima->Scale(width=>$resizewidth,height=>$newheight);
2339: $resized = 1;
2340: }
2341: }
2342: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2343: my $width = $ima->Get('width');
2344: my $height = $ima->Get('height');
2345: if ($height > $resizeheight) {
2346: my $factor = $height/$resizeheight;
2347: my $newwidth = $width/$factor;
2348: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2349: $resized = 1;
2350: }
2351: }
2352: if ($resized) {
2353: $ima->Write($img_path);
2354: }
2355: }
2356: return;
1.977 amueller 2357: }
2358:
1.608 albertel 2359: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2360: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2361: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2362: # $context - possible values: coursedoc, existingfile, overwrite,
2363: # canceloverwrite, or ''.
2364: # if 'coursedoc': upload to the current course
2365: # if 'existingfile': write file to tmp/overwrites directory
2366: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2367: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2368: # $subdir - directory in userfile to store the file into
1.858 raeburn 2369: # $parser - instruction to parse file for objects ($parser = parse)
2370: # $allfiles - reference to hash for embedded objects
2371: # $codebase - reference to hash for codebase of java objects
2372: # $desuname - username for permanent storage of uploaded file
2373: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2374: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2375: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2376: # $resizewidth - width (pixels) to which to resize uploaded image
2377: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 ! raeburn 2378: # $mimetype - reference to scalar to accommodate mime type determined
! 2379: # from File::MMagic if $parser = parse.
1.858 raeburn 2380: #
1.686 albertel 2381: # output: url of file in userspace, or error: <message>
2382: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2383:
1.531 albertel 2384: sub userfileupload {
1.1090 raeburn 2385: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 ! raeburn 2386: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2387: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2388: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2389: $fname=&clean_filename($fname);
1.1090 raeburn 2390: # See if there is anything left
1.257 www 2391: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2392: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2393: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2394: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2395: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2396: my $now = time;
1.1090 raeburn 2397: my $filepath;
1.1095 ! raeburn 2398: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2399: $filepath = 'tmp/helprequests/'.$now;
2400: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2401: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2402: '_'.$env{'user.domain'}.'/pending';
2403: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2404: my ($docuname,$docudom);
2405: if ($destudom) {
2406: $docudom = $destudom;
2407: } else {
2408: $docudom = $env{'user.domain'};
2409: }
2410: if ($destuname) {
2411: $docuname = $destuname;
2412: } else {
2413: $docuname = $env{'user.name'};
2414: }
2415: if (exists($env{'form.group'})) {
2416: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2417: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2418: }
2419: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2420: if ($context eq 'canceloverwrite') {
2421: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2422: if (-e $tempfile) {
2423: my @info = stat($tempfile);
2424: if ($info[9] eq $env{'form.timestamp'}) {
2425: unlink($tempfile);
2426: }
2427: }
2428: return;
1.523 raeburn 2429: }
2430: }
1.1090 raeburn 2431: # Create the directory if not present
1.741 raeburn 2432: my @parts=split(/\//,$filepath);
2433: my $fullpath = $perlvar{'lonDaemons'};
2434: for (my $i=0;$i<@parts;$i++) {
2435: $fullpath .= '/'.$parts[$i];
2436: if ((-e $fullpath)!=1) {
2437: mkdir($fullpath,0777);
2438: }
2439: }
2440: open(my $fh,'>'.$fullpath.'/'.$fname);
2441: print $fh $env{'form.'.$formname};
2442: close($fh);
1.1090 raeburn 2443: if ($context eq 'existingfile') {
2444: my @info = stat($fullpath.'/'.$fname);
2445: return ($fullpath.'/'.$fname,$info[9]);
2446: } else {
2447: return $fullpath.'/'.$fname;
2448: }
1.523 raeburn 2449: }
1.995 raeburn 2450: if ($subdir eq 'scantron') {
2451: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2452: } else {
1.995 raeburn 2453: $fname="$subdir/$fname";
2454: }
1.1090 raeburn 2455: if ($context eq 'coursedoc') {
1.638 albertel 2456: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2457: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2458: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2459: return &finishuserfileupload($docuname,$docudom,
2460: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2461: $codebase,$thumbwidth,$thumbheight,
1.1095 ! raeburn 2462: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2463: } else {
1.620 albertel 2464: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2465: return &process_coursefile('uploaddoc',$docuname,$docudom,
2466: $fname,$formname,$parser,
1.1095 ! raeburn 2467: $allfiles,$codebase,$mimetype);
1.481 raeburn 2468: }
1.719 banghart 2469: } elsif (defined($destuname)) {
2470: my $docuname=$destuname;
2471: my $docudom=$destudom;
1.860 raeburn 2472: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2473: $parser,$allfiles,$codebase,
1.1051 raeburn 2474: $thumbwidth,$thumbheight,
1.1095 ! raeburn 2475: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2476: } else {
1.638 albertel 2477: my $docuname=$env{'user.name'};
2478: my $docudom=$env{'user.domain'};
1.714 raeburn 2479: if (exists($env{'form.group'})) {
2480: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2481: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2482: }
1.860 raeburn 2483: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2484: $parser,$allfiles,$codebase,
1.1051 raeburn 2485: $thumbwidth,$thumbheight,
1.1095 ! raeburn 2486: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2487: }
1.271 www 2488: }
2489:
2490: sub finishuserfileupload {
1.860 raeburn 2491: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 ! raeburn 2492: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2493: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2494: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2495:
1.860 raeburn 2496: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2497: $file=$fname;
2498: if ($fname=~m|/|) {
2499: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2500: $path.=$fnamepath.'/';
2501: }
1.259 www 2502: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2503: my $count;
2504: for ($count=4;$count<=$#parts;$count++) {
2505: $filepath.="/$parts[$count]";
2506: if ((-e $filepath)!=1) {
2507: mkdir($filepath,0777);
2508: }
2509: }
1.984 neumanie 2510:
1.258 www 2511: # Save the file
2512: {
1.701 albertel 2513: if (!open(FH,'>'.$filepath.'/'.$file)) {
2514: &logthis('Failed to create '.$filepath.'/'.$file);
2515: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2516: return '/adm/notfound.html';
2517: }
1.1090 raeburn 2518: if ($context eq 'overwrite') {
2519: my $source = $perlvar{'lonDaemons'}.'/tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2520: my $target = $filepath.'/'.$file;
2521: if (-e $source) {
2522: my @info = stat($source);
2523: if ($info[9] eq $env{'form.timestamp'}) {
2524: unless (&File::Copy::move($source,$target)) {
2525: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2526: return "Moving from $source failed";
2527: }
2528: } else {
2529: return "Temporary file: $source had unexpected date/time for last modification";
2530: }
2531: } else {
2532: return "Temporary file: $source missing";
2533: }
2534: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2535: &logthis('Failed to write to '.$filepath.'/'.$file);
2536: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2537: return '/adm/notfound.html';
2538: }
1.570 albertel 2539: close(FH);
1.1051 raeburn 2540: if ($resizewidth && $resizeheight) {
2541: my $mm = new File::MMagic;
2542: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2543: if ($mime_type =~ m{^image/}) {
2544: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2545: }
1.977 amueller 2546: }
1.258 www 2547: }
1.637 raeburn 2548: if ($parser eq 'parse') {
1.1024 raeburn 2549: my $mm = new File::MMagic;
1.1095 ! raeburn 2550: my $type = $mm->checktype_filename($filepath.'/'.$file);
! 2551: if ($type eq 'text/html') {
1.1024 raeburn 2552: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2553: $allfiles,$codebase);
2554: unless ($parse_result eq 'ok') {
2555: &logthis('Failed to parse '.$filepath.$file.
2556: ' for embedded media: '.$parse_result);
2557: }
1.637 raeburn 2558: }
1.1095 ! raeburn 2559: if (ref($mimetype)) {
! 2560: $$mimetype = $type;
! 2561: }
1.637 raeburn 2562: }
1.860 raeburn 2563: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2564: my $input = $filepath.'/'.$file;
2565: my $output = $filepath.'/'.'tn-'.$file;
2566: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2567: system("convert -sample $thumbsize $input $output");
2568: if (-e $filepath.'/'.'tn-'.$file) {
2569: $fetchthumb = 1;
2570: }
2571: }
1.858 raeburn 2572:
1.259 www 2573: # Notify homeserver to grep it
2574: #
1.984 neumanie 2575: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2576: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2577: if ($fetchresult eq 'ok') {
1.860 raeburn 2578: if ($fetchthumb) {
2579: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2580: if ($thumbresult ne 'ok') {
2581: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2582: $docuhome.': '.$thumbresult);
2583: }
2584: }
1.259 www 2585: #
1.258 www 2586: # Return the URL to it
1.494 albertel 2587: return '/uploaded/'.$path.$file;
1.263 www 2588: } else {
1.494 albertel 2589: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2590: ': '.$fetchresult);
1.263 www 2591: return '/adm/notfound.html';
1.858 raeburn 2592: }
1.493 albertel 2593: }
2594:
1.637 raeburn 2595: sub extract_embedded_items {
1.961 raeburn 2596: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 2597: my @state = ();
2598: my %javafiles = (
2599: codebase => '',
2600: code => '',
2601: archive => ''
2602: );
2603: my %mediafiles = (
2604: src => '',
2605: movie => '',
2606: );
1.648 raeburn 2607: my $p;
2608: if ($content) {
2609: $p = HTML::LCParser->new($content);
2610: } else {
1.961 raeburn 2611: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 2612: }
1.641 albertel 2613: while (my $t=$p->get_token()) {
1.640 albertel 2614: if ($t->[0] eq 'S') {
2615: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 2616: push(@state, $tagname);
1.648 raeburn 2617: if (lc($tagname) eq 'allow') {
2618: &add_filetype($allfiles,$attr->{'src'},'src');
2619: }
1.640 albertel 2620: if (lc($tagname) eq 'img') {
2621: &add_filetype($allfiles,$attr->{'src'},'src');
2622: }
1.886 albertel 2623: if (lc($tagname) eq 'a') {
2624: &add_filetype($allfiles,$attr->{'href'},'href');
2625: }
1.645 raeburn 2626: if (lc($tagname) eq 'script') {
2627: if ($attr->{'archive'} =~ /\.jar$/i) {
2628: &add_filetype($allfiles,$attr->{'archive'},'archive');
2629: } else {
2630: &add_filetype($allfiles,$attr->{'src'},'src');
2631: }
2632: }
2633: if (lc($tagname) eq 'link') {
2634: if (lc($attr->{'rel'}) eq 'stylesheet') {
2635: &add_filetype($allfiles,$attr->{'href'},'href');
2636: }
2637: }
1.640 albertel 2638: if (lc($tagname) eq 'object' ||
2639: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2640: foreach my $item (keys(%javafiles)) {
2641: $javafiles{$item} = '';
2642: }
2643: }
2644: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2645: my $name = lc($attr->{'name'});
2646: foreach my $item (keys(%javafiles)) {
2647: if ($name eq $item) {
2648: $javafiles{$item} = $attr->{'value'};
2649: last;
2650: }
2651: }
2652: foreach my $item (keys(%mediafiles)) {
2653: if ($name eq $item) {
2654: &add_filetype($allfiles, $attr->{'value'}, 'value');
2655: last;
2656: }
2657: }
2658: }
2659: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2660: foreach my $item (keys(%javafiles)) {
2661: if ($attr->{$item}) {
2662: $javafiles{$item} = $attr->{$item};
2663: last;
2664: }
2665: }
2666: foreach my $item (keys(%mediafiles)) {
2667: if ($attr->{$item}) {
2668: &add_filetype($allfiles,$attr->{$item},$item);
2669: last;
2670: }
2671: }
2672: }
2673: } elsif ($t->[0] eq 'E') {
2674: my ($tagname) = ($t->[1]);
2675: if ($javafiles{'codebase'} ne '') {
2676: $javafiles{'codebase'} .= '/';
2677: }
2678: if (lc($tagname) eq 'applet' ||
2679: lc($tagname) eq 'object' ||
2680: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2681: ) {
2682: foreach my $item (keys(%javafiles)) {
2683: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2684: my $file=$javafiles{'codebase'}.$javafiles{$item};
2685: &add_filetype($allfiles,$file,$item);
2686: }
2687: }
2688: }
2689: pop @state;
2690: }
2691: }
1.637 raeburn 2692: return 'ok';
2693: }
2694:
1.639 albertel 2695: sub add_filetype {
2696: my ($allfiles,$file,$type)=@_;
2697: if (exists($allfiles->{$file})) {
2698: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2699: push(@{$allfiles->{$file}}, &escape($type));
2700: }
2701: } else {
2702: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 2703: }
2704: }
2705:
1.493 albertel 2706: sub removeuploadedurl {
1.984 neumanie 2707: my ($url)=@_;
2708: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 2709: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 2710: }
2711:
2712: sub removeuserfile {
2713: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 2714: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2715: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 2716: if ($result eq 'ok') {
1.798 raeburn 2717: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2718: my $metafile = $fname.'.meta';
2719: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 2720: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 2721: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2722: my $sqlresult =
1.823 albertel 2723: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2724: 'portfolio_metadata',$group,
2725: 'delete');
1.798 raeburn 2726: }
2727: }
2728: return $result;
1.257 www 2729: }
1.15 www 2730:
1.530 albertel 2731: sub mkdiruserfile {
2732: my ($docuname,$docudom,$dir)=@_;
2733: my $home=&homeserver($docuname,$docudom);
2734: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2735: }
2736:
1.531 albertel 2737: sub renameuserfile {
2738: my ($docuname,$docudom,$old,$new)=@_;
2739: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 2740: my $result = &reply("renameuserfile:$docudom:$docuname:".
2741: &escape("$old").':'.&escape("$new"),$home);
2742: if ($result eq 'ok') {
2743: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2744: my $oldmeta = $old.'.meta';
2745: my $newmeta = $new.'.meta';
2746: my $metaresult =
2747: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 2748: my $url = "/uploaded/$docudom/$docuname/$old";
2749: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 2750: my $sqlresult =
1.823 albertel 2751: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 2752: 'portfolio_metadata',$group,
2753: 'delete');
1.798 raeburn 2754: }
2755: }
2756: return $result;
1.531 albertel 2757: }
2758:
1.14 www 2759: # ------------------------------------------------------------------------- Log
2760:
2761: sub log {
2762: my ($dom,$nam,$hom,$what)=@_;
1.47 www 2763: return critical("log:$dom:$nam:$what",$hom);
1.157 www 2764: }
2765:
2766: # ------------------------------------------------------------------ Course Log
1.352 www 2767: #
2768: # This routine flushes several buffers of non-mission-critical nature
2769: #
1.157 www 2770:
2771: sub flushcourselogs {
1.352 www 2772: &logthis('Flushing log buffers');
2773: #
2774: # course logs
2775: # This is a log of all transactions in a course, which can be used
2776: # for data mining purposes
2777: #
2778: # It also collects the courseid database, which lists last transaction
2779: # times and course titles for all courseids
2780: #
2781: my %courseidbuffer=();
1.921 raeburn 2782: foreach my $crsid (keys(%courselogs)) {
1.352 www 2783: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 2784: &escape($courselogs{$crsid}),
2785: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 2786: delete $courselogs{$crsid};
2787: } else {
2788: &logthis('Failed to flush log buffer for '.$crsid);
2789: if (length($courselogs{$crsid})>40000) {
1.672 albertel 2790: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 2791: " exceeded maximum size, deleting.</font>");
2792: delete $courselogs{$crsid};
2793: }
1.352 www 2794: }
1.920 raeburn 2795: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 2796: 'description' => $coursedescrbuf{$crsid},
2797: 'inst_code' => $courseinstcodebuf{$crsid},
2798: 'type' => $coursetypebuf{$crsid},
2799: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 2800: };
1.191 harris41 2801: }
1.352 www 2802: #
2803: # Write course id database (reverse lookup) to homeserver of courses
2804: # Is used in pickcourse
2805: #
1.840 albertel 2806: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 2807: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 2808: $courseidbuffer{$crs_home},
2809: $crs_home,'timeonly');
1.352 www 2810: }
2811: #
2812: # File accesses
2813: # Writes to the dynamic metadata of resources to get hit counts, etc.
2814: #
1.449 matthew 2815: foreach my $entry (keys(%accesshash)) {
1.458 matthew 2816: if ($entry =~ /___count$/) {
2817: my ($dom,$name);
1.807 albertel 2818: ($dom,$name,undef)=
1.811 albertel 2819: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 2820: if (! defined($dom) || $dom eq '' ||
2821: ! defined($name) || $name eq '') {
1.620 albertel 2822: my $cid = $env{'request.course.id'};
2823: $dom = $env{'request.'.$cid.'.domain'};
2824: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 2825: }
1.450 matthew 2826: my $value = $accesshash{$entry};
2827: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2828: my %temphash=($url => $value);
1.449 matthew 2829: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2830: if ($result eq 'ok') {
2831: delete $accesshash{$entry};
2832: } elsif ($result eq 'unknown_cmd') {
2833: # Target server has old code running on it.
1.450 matthew 2834: my %temphash=($entry => $value);
1.449 matthew 2835: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2836: delete $accesshash{$entry};
2837: }
2838: }
2839: } else {
1.811 albertel 2840: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 2841: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 2842: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2843: delete $accesshash{$entry};
2844: }
1.185 www 2845: }
1.191 harris41 2846: }
1.352 www 2847: #
2848: # Roles
2849: # Reverse lookup of user roles for course faculty/staff and co-authorship
2850: #
1.800 albertel 2851: foreach my $entry (keys(%userrolehash)) {
1.351 www 2852: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 2853: split(/\:/,$entry);
2854: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 2855: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 2856: $rudom,$runame) eq 'ok') {
2857: delete $userrolehash{$entry};
2858: }
2859: }
1.662 raeburn 2860: #
2861: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2862: #
2863: my %domrolebuffer = ();
1.1000 raeburn 2864: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 2865: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 2866: if ($domrolebuffer{$rudom}) {
2867: $domrolebuffer{$rudom}.='&'.&escape($entry).
2868: '='.&escape($domainrolehash{$entry});
2869: } else {
2870: $domrolebuffer{$rudom}.=&escape($entry).
2871: '='.&escape($domainrolehash{$entry});
2872: }
2873: delete $domainrolehash{$entry};
2874: }
2875: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 2876: my %servers = &get_servers($dom,'library');
2877: foreach my $tryserver (keys(%servers)) {
2878: unless (&reply('domroleput:'.$dom.':'.
2879: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2880: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2881: }
1.662 raeburn 2882: }
2883: }
1.186 www 2884: $dumpcount++;
1.157 www 2885: }
2886:
2887: sub courselog {
2888: my $what=shift;
1.158 www 2889: $what=time.':'.$what;
1.620 albertel 2890: unless ($env{'request.course.id'}) { return ''; }
2891: $coursedombuf{$env{'request.course.id'}}=
2892: $env{'course.'.$env{'request.course.id'}.'.domain'};
2893: $coursenumbuf{$env{'request.course.id'}}=
2894: $env{'course.'.$env{'request.course.id'}.'.num'};
2895: $coursehombuf{$env{'request.course.id'}}=
2896: $env{'course.'.$env{'request.course.id'}.'.home'};
2897: $coursedescrbuf{$env{'request.course.id'}}=
2898: $env{'course.'.$env{'request.course.id'}.'.description'};
2899: $courseinstcodebuf{$env{'request.course.id'}}=
2900: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2901: $courseownerbuf{$env{'request.course.id'}}=
2902: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2903: $coursetypebuf{$env{'request.course.id'}}=
2904: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2905: if (defined $courselogs{$env{'request.course.id'}}) {
2906: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2907: } else {
1.620 albertel 2908: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2909: }
1.620 albertel 2910: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2911: &flushcourselogs();
2912: }
1.158 www 2913: }
2914:
2915: sub courseacclog {
2916: my $fnsymb=shift;
1.620 albertel 2917: unless ($env{'request.course.id'}) { return ''; }
2918: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2919: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2920: $what.=':POST';
1.583 matthew 2921: # FIXME: Probably ought to escape things....
1.800 albertel 2922: foreach my $key (keys(%env)) {
2923: if ($key=~/^form\.(.*)/) {
1.975 raeburn 2924: my $formitem = $1;
2925: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2926: $what.=':'.$formitem.'='.$env{$key};
2927: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2928: $what.=':'.$formitem.'='.$env{$key};
2929: }
1.158 www 2930: }
1.191 harris41 2931: }
1.583 matthew 2932: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2933: # FIXME: We should not be depending on a form parameter that someone
2934: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2935: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2936: $what.= ':POST';
2937: # FIXME: Probably ought to escape things....
2938: foreach my $element ('courseexp','crsfulltext','crsrelated',
2939: 'crsdiscuss') {
1.620 albertel 2940: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2941: }
2942: }
1.158 www 2943: }
2944: &courselog($what);
1.149 www 2945: }
2946:
1.185 www 2947: sub countacc {
2948: my $url=&declutter(shift);
1.458 matthew 2949: return if (! defined($url) || $url eq '');
1.620 albertel 2950: unless ($env{'request.course.id'}) { return ''; }
2951: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2952: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2953: $accesshash{$key}++;
1.185 www 2954: }
1.349 www 2955:
1.361 www 2956: sub linklog {
2957: my ($from,$to)=@_;
2958: $from=&declutter($from);
2959: $to=&declutter($to);
2960: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2961: $accesshash{$to.'___'.$from.'___goto'}=1;
2962: }
2963:
1.349 www 2964: sub userrolelog {
2965: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2966: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2967: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2968: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 2969: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 2970: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2971: $userrolehash
2972: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2973: =$tend.':'.$tstart;
1.662 raeburn 2974: }
1.898 albertel 2975: if (($env{'request.role'} =~ /dc\./) &&
2976: (($trole=~/^au/) || ($trole=~/^in/) ||
2977: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 2978: ($trole=~/^cr/) || ($trole=~/^ta/) ||
2979: ($trole=~/^co/))) {
1.898 albertel 2980: $userrolehash
2981: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2982: =$tend.':'.$tstart;
2983: }
1.662 raeburn 2984: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2985: ($trole=~/^li/) || ($trole=~/^li/) ||
2986: ($trole=~/^au/) || ($trole=~/^dg/) ||
2987: ($trole=~/^sc/)) {
2988: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2989: $domainrolehash
2990: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2991: = $tend.':'.$tstart;
2992: }
1.351 www 2993: }
2994:
1.957 raeburn 2995: sub courserolelog {
2996: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2997: if (($trole eq 'cc') || ($trole eq 'in') ||
2998: ($trole eq 'ep') || ($trole eq 'ad') ||
2999: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3000: ($trole=~/^cr/) || ($trole eq 'gr') ||
3001: ($trole eq 'co')) {
1.957 raeburn 3002: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3003: my $cdom = $1;
3004: my $cnum = $2;
3005: my $sec = $3;
3006: my $namespace = 'rolelog';
3007: my %storehash = (
3008: role => $trole,
3009: start => $tstart,
3010: end => $tend,
3011: selfenroll => $selfenroll,
3012: context => $context,
3013: );
3014: if ($trole eq 'gr') {
3015: $namespace = 'groupslog';
3016: $storehash{'group'} = $sec;
3017: } else {
3018: $storehash{'section'} = $sec;
3019: }
3020: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3021: if (($trole ne 'st') || ($sec ne '')) {
3022: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3023: }
1.957 raeburn 3024: }
3025: }
3026: return;
3027: }
3028:
1.351 www 3029: sub get_course_adv_roles {
1.948 raeburn 3030: my ($cid,$codes) = @_;
1.620 albertel 3031: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3032: my %coursehash=&coursedescription($cid);
1.988 raeburn 3033: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3034: my %nothide=();
1.800 albertel 3035: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3036: if ($user !~ /:/) {
3037: $nothide{join(':',split(/[\@]/,$user))}=1;
3038: } else {
3039: $nothide{$user}=1;
3040: }
1.470 www 3041: }
1.351 www 3042: my %returnhash=();
3043: my %dumphash=
3044: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3045: my $now=time;
1.997 raeburn 3046: my %privileged;
1.1000 raeburn 3047: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3048: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3049: if (($tstart) && ($tstart<0)) { next; }
3050: if (($tend) && ($tend<$now)) { next; }
3051: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3052: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3053: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3054: unless (ref($privileged{$domain}) eq 'HASH') {
3055: my %dompersonnel =
1.998 raeburn 3056: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3057: $privileged{$domain} = {};
3058: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3059: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3060: foreach my $user (keys(%{$dompersonnel{$server}})) {
3061: my ($trole,$uname,$udom) = split(/:/,$user);
3062: $privileged{$udom}{$uname} = 1;
3063: }
3064: }
3065: }
3066: }
3067: if ((exists($privileged{$domain}{$username})) &&
3068: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3069: if ($role eq 'cr') { next; }
1.948 raeburn 3070: if ($codes) {
3071: if ($section) { $role .= ':'.$section; }
3072: if ($returnhash{$role}) {
3073: $returnhash{$role}.=','.$username.':'.$domain;
3074: } else {
3075: $returnhash{$role}=$username.':'.$domain;
3076: }
1.351 www 3077: } else {
1.988 raeburn 3078: my $key=&plaintext($role,$crstype);
1.973 bisitz 3079: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3080: if ($returnhash{$key}) {
3081: $returnhash{$key}.=','.$username.':'.$domain;
3082: } else {
3083: $returnhash{$key}=$username.':'.$domain;
3084: }
1.351 www 3085: }
1.948 raeburn 3086: }
1.400 www 3087: return %returnhash;
3088: }
3089:
3090: sub get_my_roles {
1.937 raeburn 3091: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3092: unless (defined($uname)) { $uname=$env{'user.name'}; }
3093: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3094: my (%dumphash,%nothide);
1.1086 raeburn 3095: if ($context eq 'userroles') {
3096: my $extra = &freeze_escape({'skipcheck' => 1});
3097: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3098: } else {
3099: %dumphash=
1.400 www 3100: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3101: if ($hidepriv) {
3102: my %coursehash=&coursedescription($udom.'_'.$uname);
3103: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3104: if ($user !~ /:/) {
3105: $nothide{join(':',split(/[\@]/,$user))} = 1;
3106: } else {
3107: $nothide{$user} = 1;
3108: }
3109: }
3110: }
1.858 raeburn 3111: }
1.400 www 3112: my %returnhash=();
3113: my $now=time;
1.999 raeburn 3114: my %privileged;
1.800 albertel 3115: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3116: my ($role,$tend,$tstart);
3117: if ($context eq 'userroles') {
3118: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3119: } else {
3120: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3121: }
1.400 www 3122: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3123: my $status = 'active';
1.939 raeburn 3124: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3125: $status = 'previous';
3126: }
3127: if (($tstart) && ($now<$tstart)) {
3128: $status = 'future';
3129: }
3130: if (ref($types) eq 'ARRAY') {
3131: if (!grep(/^\Q$status\E$/,@{$types})) {
3132: next;
3133: }
3134: } else {
3135: if ($status ne 'active') {
3136: next;
3137: }
3138: }
1.867 raeburn 3139: my ($rolecode,$username,$domain,$section,$area);
3140: if ($context eq 'userroles') {
3141: ($area,$rolecode) = split(/_/,$entry);
3142: (undef,$domain,$username,$section) = split(/\//,$area);
3143: } else {
3144: ($role,$username,$domain,$section) = split(/\:/,$entry);
3145: }
1.832 raeburn 3146: if (ref($roledoms) eq 'ARRAY') {
3147: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3148: next;
3149: }
3150: }
3151: if (ref($roles) eq 'ARRAY') {
3152: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3153: if ($role =~ /^cr\//) {
3154: if (!grep(/^cr$/,@{$roles})) {
3155: next;
3156: }
3157: } else {
3158: next;
3159: }
1.832 raeburn 3160: }
1.867 raeburn 3161: }
1.937 raeburn 3162: if ($hidepriv) {
1.999 raeburn 3163: if ($context eq 'userroles') {
3164: if ((&privileged($username,$domain)) &&
3165: (!$nothide{$username.':'.$domain})) {
3166: next;
3167: }
3168: } else {
3169: unless (ref($privileged{$domain}) eq 'HASH') {
3170: my %dompersonnel =
3171: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3172: $privileged{$domain} = {};
3173: if (keys(%dompersonnel)) {
3174: foreach my $server (keys(%dompersonnel)) {
3175: if (ref($dompersonnel{$server}) eq 'HASH') {
3176: foreach my $user (keys(%{$dompersonnel{$server}})) {
3177: my ($trole,$uname,$udom) = split(/:/,$user);
3178: $privileged{$udom}{$uname} = $trole;
3179: }
3180: }
3181: }
3182: }
3183: }
3184: if (exists($privileged{$domain}{$username})) {
3185: if (!$nothide{$username.':'.$domain}) {
3186: next;
3187: }
3188: }
1.937 raeburn 3189: }
3190: }
1.933 raeburn 3191: if ($withsec) {
3192: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3193: $tstart.':'.$tend;
3194: } else {
3195: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3196: }
1.832 raeburn 3197: }
1.373 www 3198: return %returnhash;
1.399 www 3199: }
3200:
3201: # ----------------------------------------------------- Frontpage Announcements
3202: #
3203: #
3204:
3205: sub postannounce {
3206: my ($server,$text)=@_;
1.844 albertel 3207: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3208: unless ($text=~/\w/) { $text=''; }
3209: return &reply('setannounce:'.&escape($text),$server);
3210: }
3211:
3212: sub getannounce {
1.448 albertel 3213:
3214: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3215: my $announcement='';
1.800 albertel 3216: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3217: close($fh);
1.399 www 3218: if ($announcement=~/\w/) {
3219: return
3220: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3221: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3222: } else {
3223: return '';
3224: }
3225: } else {
3226: return '';
3227: }
1.351 www 3228: }
1.353 www 3229:
3230: # ---------------------------------------------------------- Course ID routines
3231: # Deal with domain's nohist_courseid.db files
3232: #
3233:
3234: sub courseidput {
1.921 raeburn 3235: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3236: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3237: my $outcome;
3238: if ($caller eq 'timeonly') {
3239: my $cids = '';
3240: foreach my $item (keys(%$storehash)) {
3241: $cids.=&escape($item).'&';
3242: }
3243: $cids=~s/\&$//;
3244: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3245: $coursehome);
3246: } else {
3247: my $items = '';
3248: foreach my $item (keys(%$storehash)) {
3249: $items.= &escape($item).'='.
3250: &freeze_escape($$storehash{$item}).'&';
3251: }
3252: $items=~s/\&$//;
3253: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3254: $coursehome);
1.918 raeburn 3255: }
3256: if ($outcome eq 'unknown_cmd') {
3257: my $what;
3258: foreach my $cid (keys(%$storehash)) {
3259: $what .= &escape($cid).'=';
1.921 raeburn 3260: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3261: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3262: }
3263: $what =~ s/\:$/&/;
3264: }
3265: $what =~ s/\&$//;
3266: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3267: } else {
3268: return $outcome;
3269: }
1.353 www 3270: }
3271:
3272: sub courseiddump {
1.921 raeburn 3273: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3274: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3275: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3276: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3277: my $as_hash = 1;
3278: my %returnhash;
3279: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3280: my %libserv = &all_library();
3281: foreach my $tryserver (keys(%libserv)) {
3282: if ( ( $hostidflag == 1
3283: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3284: || (!defined($hostidflag)) ) {
3285:
1.918 raeburn 3286: if (($domfilter eq '') ||
3287: (&host_domain($tryserver) eq $domfilter)) {
3288: my $rep =
3289: &reply('courseiddump:'.&host_domain($tryserver).':'.
3290: $sincefilter.':'.&escape($descfilter).':'.
3291: &escape($instcodefilter).':'.&escape($ownerfilter).
3292: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3293: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3294: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3295: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3296: &escape($cc_clone).':'.$cloneonly.':'.
3297: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3298: &escape($creationcontext).':'.$domcloner,
3299: $tryserver);
1.918 raeburn 3300: my @pairs=split(/\&/,$rep);
3301: foreach my $item (@pairs) {
3302: my ($key,$value)=split(/\=/,$item,2);
3303: $key = &unescape($key);
3304: next if ($key =~ /^error: 2 /);
3305: my $result = &thaw_unescape($value);
3306: if (ref($result) eq 'HASH') {
3307: $returnhash{$key}=$result;
3308: } else {
1.921 raeburn 3309: my @responses = split(/:/,$value);
3310: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3311: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3312: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3313: }
1.1008 raeburn 3314: }
1.353 www 3315: }
3316: }
3317: }
3318: }
3319: return %returnhash;
3320: }
3321:
1.1055 raeburn 3322: sub courselastaccess {
3323: my ($cdom,$cnum,$hostidref) = @_;
3324: my %returnhash;
3325: if ($cdom && $cnum) {
3326: my $chome = &homeserver($cnum,$cdom);
3327: if ($chome ne 'no_host') {
3328: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3329: &extract_lastaccess(\%returnhash,$rep);
3330: }
3331: } else {
3332: if (!$cdom) { $cdom=''; }
3333: my %libserv = &all_library();
3334: foreach my $tryserver (keys(%libserv)) {
3335: if (ref($hostidref) eq 'ARRAY') {
3336: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3337: }
3338: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3339: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3340: &extract_lastaccess(\%returnhash,$rep);
3341: }
3342: }
3343: }
3344: return %returnhash;
3345: }
3346:
3347: sub extract_lastaccess {
3348: my ($returnhash,$rep) = @_;
3349: if (ref($returnhash) eq 'HASH') {
3350: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3351: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3352: $rep eq '') {
3353: my @pairs=split(/\&/,$rep);
3354: foreach my $item (@pairs) {
3355: my ($key,$value)=split(/\=/,$item,2);
3356: $key = &unescape($key);
3357: next if ($key =~ /^error: 2 /);
3358: $returnhash->{$key} = &thaw_unescape($value);
3359: }
3360: }
3361: }
3362: return;
3363: }
3364:
1.658 raeburn 3365: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3366:
3367: sub dcmailput {
1.685 raeburn 3368: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3369: my $status = &Apache::lonnet::critical(
1.740 www 3370: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3371: &escape($message),$server);
1.662 raeburn 3372: return $status;
3373: }
3374:
1.658 raeburn 3375: sub dcmaildump {
3376: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3377: my %returnhash=();
1.846 albertel 3378:
3379: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3380: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3381: &escape($enddate).':';
3382: my @esc_senders=map { &escape($_)} @$senders;
3383: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3384: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3385: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3386: if (($key) && ($value)) {
3387: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3388: }
3389: }
3390: }
3391: return %returnhash;
3392: }
1.662 raeburn 3393: # ---------------------------------------------------------- Domain roles
3394:
3395: sub get_domain_roles {
3396: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3397: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3398: $startdate = '.';
3399: }
1.1018 raeburn 3400: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3401: $enddate = '.';
3402: }
1.922 raeburn 3403: my $rolelist;
3404: if (ref($roles) eq 'ARRAY') {
3405: $rolelist = join(':',@{$roles});
3406: }
1.662 raeburn 3407: my %personnel = ();
1.841 albertel 3408:
3409: my %servers = &get_servers($dom,'library');
3410: foreach my $tryserver (keys(%servers)) {
3411: %{$personnel{$tryserver}}=();
3412: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3413: &escape($startdate).':'.
3414: &escape($enddate).':'.
3415: &escape($rolelist), $tryserver))) {
3416: my ($key,$value) = split(/\=/,$line,2);
3417: if (($key) && ($value)) {
3418: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3419: }
3420: }
1.662 raeburn 3421: }
3422: return %personnel;
3423: }
1.658 raeburn 3424:
1.1057 www 3425: # ----------------------------------------------------------- Interval timing
1.149 www 3426:
1.504 albertel 3427: sub get_first_access {
3428: my ($type,$argsymb)=@_;
1.790 albertel 3429: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3430: if ($argsymb) { $symb=$argsymb; }
3431: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3432: if ($type eq 'course') {
3433: $res='course';
3434: } elsif ($type eq 'map') {
1.588 albertel 3435: $res=&symbread($map);
3436: } else {
3437: $res=$symb;
3438: }
3439: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3440: return $times{"$courseid\0$res"};
1.504 albertel 3441: }
3442:
3443: sub set_first_access {
3444: my ($type)=@_;
1.790 albertel 3445: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3446: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3447: if ($type eq 'course') {
3448: $res='course';
3449: } elsif ($type eq 'map') {
1.588 albertel 3450: $res=&symbread($map);
3451: } else {
3452: $res=$symb;
3453: }
3454: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3455: if (!$firstaccess) {
1.588 albertel 3456: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3457: }
3458: return 'already_set';
1.504 albertel 3459: }
3460:
1.110 www 3461: # --------------------------------------------- Set Expire Date for Spreadsheet
3462:
3463: sub expirespread {
3464: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3465: my $cid=$env{'request.course.id'};
1.110 www 3466: if ($cid) {
3467: my $now=time;
3468: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3469: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3470: $env{'course.'.$cid.'.num'}.
1.110 www 3471: ':nohist_expirationdates:'.
3472: &escape($key).'='.$now,
1.620 albertel 3473: $env{'course.'.$cid.'.home'})
1.110 www 3474: }
3475: return 'ok';
1.14 www 3476: }
3477:
1.109 www 3478: # ----------------------------------------------------- Devalidate Spreadsheets
3479:
3480: sub devalidate {
1.325 www 3481: my ($symb,$uname,$udom)=@_;
1.620 albertel 3482: my $cid=$env{'request.course.id'};
1.109 www 3483: if ($cid) {
1.391 matthew 3484: # delete the stored spreadsheets for
3485: # - the student level sheet of this user in course's homespace
3486: # - the assessment level sheet for this resource
3487: # for this user in user's homespace
1.553 albertel 3488: # - current conditional state info
1.325 www 3489: my $key=$uname.':'.$udom.':';
1.109 www 3490: my $status=
1.299 matthew 3491: &del('nohist_calculatedsheets',
1.391 matthew 3492: [$key.'studentcalc:'],
1.620 albertel 3493: $env{'course.'.$cid.'.domain'},
3494: $env{'course.'.$cid.'.num'})
1.133 albertel 3495: .' '.
3496: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3497: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3498: unless ($status eq 'ok ok') {
3499: &logthis('Could not devalidate spreadsheet '.
1.325 www 3500: $uname.' at '.$udom.' for '.
1.109 www 3501: $symb.': '.$status);
1.133 albertel 3502: }
1.553 albertel 3503: &delenv('user.state.'.$cid);
1.109 www 3504: }
3505: }
3506:
1.265 albertel 3507: sub get_scalar {
3508: my ($string,$end) = @_;
3509: my $value;
3510: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3511: $value = $1;
3512: } elsif ($$string =~ s/^([^&]*?)&//) {
3513: $value = $1;
3514: }
3515: return &unescape($value);
3516: }
3517:
3518: sub array2str {
3519: my (@array) = @_;
3520: my $result=&arrayref2str(\@array);
3521: $result=~s/^__ARRAY_REF__//;
3522: $result=~s/__END_ARRAY_REF__$//;
3523: return $result;
3524: }
3525:
1.204 albertel 3526: sub arrayref2str {
3527: my ($arrayref) = @_;
1.265 albertel 3528: my $result='__ARRAY_REF__';
1.204 albertel 3529: foreach my $elem (@$arrayref) {
1.265 albertel 3530: if(ref($elem) eq 'ARRAY') {
3531: $result.=&arrayref2str($elem).'&';
3532: } elsif(ref($elem) eq 'HASH') {
3533: $result.=&hashref2str($elem).'&';
3534: } elsif(ref($elem)) {
3535: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3536: } else {
3537: $result.=&escape($elem).'&';
3538: }
3539: }
3540: $result=~s/\&$//;
1.265 albertel 3541: $result .= '__END_ARRAY_REF__';
1.204 albertel 3542: return $result;
3543: }
3544:
1.168 albertel 3545: sub hash2str {
1.204 albertel 3546: my (%hash) = @_;
3547: my $result=&hashref2str(\%hash);
1.265 albertel 3548: $result=~s/^__HASH_REF__//;
3549: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3550: return $result;
3551: }
3552:
3553: sub hashref2str {
3554: my ($hashref)=@_;
1.265 albertel 3555: my $result='__HASH_REF__';
1.800 albertel 3556: foreach my $key (sort(keys(%$hashref))) {
3557: if (ref($key) eq 'ARRAY') {
3558: $result.=&arrayref2str($key).'=';
3559: } elsif (ref($key) eq 'HASH') {
3560: $result.=&hashref2str($key).'=';
3561: } elsif (ref($key)) {
1.265 albertel 3562: $result.='=';
1.800 albertel 3563: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3564: } else {
1.800 albertel 3565: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3566: }
3567:
1.800 albertel 3568: if(ref($hashref->{$key}) eq 'ARRAY') {
3569: $result.=&arrayref2str($hashref->{$key}).'&';
3570: } elsif(ref($hashref->{$key}) eq 'HASH') {
3571: $result.=&hashref2str($hashref->{$key}).'&';
3572: } elsif(ref($hashref->{$key})) {
1.265 albertel 3573: $result.='&';
1.800 albertel 3574: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3575: } else {
1.800 albertel 3576: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 3577: }
3578: }
1.168 albertel 3579: $result=~s/\&$//;
1.265 albertel 3580: $result .= '__END_HASH_REF__';
1.168 albertel 3581: return $result;
3582: }
3583:
3584: sub str2hash {
1.265 albertel 3585: my ($string)=@_;
3586: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3587: return %$hash;
3588: }
3589:
3590: sub str2hashref {
1.168 albertel 3591: my ($string) = @_;
1.265 albertel 3592:
3593: my %hash;
3594:
3595: if($string !~ /^__HASH_REF__/) {
3596: if (! ($string eq '' || !defined($string))) {
3597: $hash{'error'}='Not hash reference';
3598: }
3599: return (\%hash, $string);
3600: }
3601:
3602: $string =~ s/^__HASH_REF__//;
3603:
3604: while($string !~ /^__END_HASH_REF__/) {
3605: #key
3606: my $key='';
3607: if($string =~ /^__HASH_REF__/) {
3608: ($key, $string)=&str2hashref($string);
3609: if(defined($key->{'error'})) {
3610: $hash{'error'}='Bad data';
3611: return (\%hash, $string);
3612: }
3613: } elsif($string =~ /^__ARRAY_REF__/) {
3614: ($key, $string)=&str2arrayref($string);
3615: if($key->[0] eq 'Array reference error') {
3616: $hash{'error'}='Bad data';
3617: return (\%hash, $string);
3618: }
3619: } else {
3620: $string =~ s/^(.*?)=//;
1.267 albertel 3621: $key=&unescape($1);
1.265 albertel 3622: }
3623: $string =~ s/^=//;
3624:
3625: #value
3626: my $value='';
3627: if($string =~ /^__HASH_REF__/) {
3628: ($value, $string)=&str2hashref($string);
3629: if(defined($value->{'error'})) {
3630: $hash{'error'}='Bad data';
3631: return (\%hash, $string);
3632: }
3633: } elsif($string =~ /^__ARRAY_REF__/) {
3634: ($value, $string)=&str2arrayref($string);
3635: if($value->[0] eq 'Array reference error') {
3636: $hash{'error'}='Bad data';
3637: return (\%hash, $string);
3638: }
3639: } else {
3640: $value=&get_scalar(\$string,'__END_HASH_REF__');
3641: }
3642: $string =~ s/^&//;
3643:
3644: $hash{$key}=$value;
1.204 albertel 3645: }
1.265 albertel 3646:
3647: $string =~ s/^__END_HASH_REF__//;
3648:
3649: return (\%hash, $string);
1.204 albertel 3650: }
3651:
3652: sub str2array {
1.265 albertel 3653: my ($string)=@_;
3654: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3655: return @$array;
3656: }
3657:
3658: sub str2arrayref {
1.204 albertel 3659: my ($string) = @_;
1.265 albertel 3660: my @array;
3661:
3662: if($string !~ /^__ARRAY_REF__/) {
3663: if (! ($string eq '' || !defined($string))) {
3664: $array[0]='Array reference error';
3665: }
3666: return (\@array, $string);
3667: }
3668:
3669: $string =~ s/^__ARRAY_REF__//;
3670:
3671: while($string !~ /^__END_ARRAY_REF__/) {
3672: my $value='';
3673: if($string =~ /^__HASH_REF__/) {
3674: ($value, $string)=&str2hashref($string);
3675: if(defined($value->{'error'})) {
3676: $array[0] ='Array reference error';
3677: return (\@array, $string);
3678: }
3679: } elsif($string =~ /^__ARRAY_REF__/) {
3680: ($value, $string)=&str2arrayref($string);
3681: if($value->[0] eq 'Array reference error') {
3682: $array[0] ='Array reference error';
3683: return (\@array, $string);
3684: }
3685: } else {
3686: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3687: }
3688: $string =~ s/^&//;
3689:
3690: push(@array, $value);
1.191 harris41 3691: }
1.265 albertel 3692:
3693: $string =~ s/^__END_ARRAY_REF__//;
3694:
3695: return (\@array, $string);
1.168 albertel 3696: }
3697:
1.167 albertel 3698: # -------------------------------------------------------------------Temp Store
3699:
1.168 albertel 3700: sub tmpreset {
3701: my ($symb,$namespace,$domain,$stuname) = @_;
3702: if (!$symb) {
3703: $symb=&symbread();
1.620 albertel 3704: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3705: }
3706: $symb=escape($symb);
3707:
1.620 albertel 3708: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 3709: $namespace=~s/\//\_/g;
3710: $namespace=~s/\W//g;
3711:
1.620 albertel 3712: if (!$domain) { $domain=$env{'user.domain'}; }
3713: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3714: if ($domain eq 'public' && $stuname eq 'public') {
3715: $stuname=$ENV{'REMOTE_ADDR'};
3716: }
1.168 albertel 3717: my $path=$perlvar{'lonDaemons'}.'/tmp';
3718: my %hash;
3719: if (tie(%hash,'GDBM_File',
3720: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3721: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 3722: foreach my $key (keys(%hash)) {
1.180 albertel 3723: if ($key=~ /:$symb/) {
1.168 albertel 3724: delete($hash{$key});
3725: }
3726: }
3727: }
3728: }
3729:
1.167 albertel 3730: sub tmpstore {
1.168 albertel 3731: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3732:
3733: if (!$symb) {
3734: $symb=&symbread();
1.620 albertel 3735: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3736: }
3737: $symb=escape($symb);
3738:
3739: if (!$namespace) {
3740: # I don't think we would ever want to store this for a course.
3741: # it seems this will only be used if we don't have a course.
1.620 albertel 3742: #$namespace=$env{'request.course.id'};
1.168 albertel 3743: #if (!$namespace) {
1.620 albertel 3744: $namespace=$env{'request.state'};
1.168 albertel 3745: #}
3746: }
3747: $namespace=~s/\//\_/g;
3748: $namespace=~s/\W//g;
1.620 albertel 3749: if (!$domain) { $domain=$env{'user.domain'}; }
3750: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3751: if ($domain eq 'public' && $stuname eq 'public') {
3752: $stuname=$ENV{'REMOTE_ADDR'};
3753: }
1.168 albertel 3754: my $now=time;
3755: my %hash;
3756: my $path=$perlvar{'lonDaemons'}.'/tmp';
3757: if (tie(%hash,'GDBM_File',
3758: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3759: &GDBM_WRCREAT(),0640)) {
1.168 albertel 3760: $hash{"version:$symb"}++;
3761: my $version=$hash{"version:$symb"};
3762: my $allkeys='';
3763: foreach my $key (keys(%$storehash)) {
3764: $allkeys.=$key.':';
1.591 albertel 3765: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 3766: }
3767: $hash{"$version:$symb:timestamp"}=$now;
3768: $allkeys.='timestamp';
3769: $hash{"$version:keys:$symb"}=$allkeys;
3770: if (untie(%hash)) {
3771: return 'ok';
3772: } else {
3773: return "error:$!";
3774: }
3775: } else {
3776: return "error:$!";
3777: }
3778: }
1.167 albertel 3779:
1.168 albertel 3780: # -----------------------------------------------------------------Temp Restore
1.167 albertel 3781:
1.168 albertel 3782: sub tmprestore {
3783: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 3784:
1.168 albertel 3785: if (!$symb) {
3786: $symb=&symbread();
1.620 albertel 3787: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 3788: }
3789: $symb=escape($symb);
3790:
1.620 albertel 3791: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 3792:
1.620 albertel 3793: if (!$domain) { $domain=$env{'user.domain'}; }
3794: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 3795: if ($domain eq 'public' && $stuname eq 'public') {
3796: $stuname=$ENV{'REMOTE_ADDR'};
3797: }
1.168 albertel 3798: my %returnhash;
3799: $namespace=~s/\//\_/g;
3800: $namespace=~s/\W//g;
3801: my %hash;
3802: my $path=$perlvar{'lonDaemons'}.'/tmp';
3803: if (tie(%hash,'GDBM_File',
3804: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 3805: &GDBM_READER(),0640)) {
1.168 albertel 3806: my $version=$hash{"version:$symb"};
3807: $returnhash{'version'}=$version;
3808: my $scope;
3809: for ($scope=1;$scope<=$version;$scope++) {
3810: my $vkeys=$hash{"$scope:keys:$symb"};
3811: my @keys=split(/:/,$vkeys);
3812: my $key;
3813: $returnhash{"$scope:keys"}=$vkeys;
3814: foreach $key (@keys) {
1.591 albertel 3815: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3816: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 3817: }
3818: }
1.168 albertel 3819: if (!(untie(%hash))) {
3820: return "error:$!";
3821: }
3822: } else {
3823: return "error:$!";
3824: }
3825: return %returnhash;
1.167 albertel 3826: }
3827:
1.9 www 3828: # ----------------------------------------------------------------------- Store
3829:
3830: sub store {
1.124 www 3831: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3832: my $home='';
3833:
1.168 albertel 3834: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3835:
1.213 www 3836: $symb=&symbclean($symb);
1.122 albertel 3837: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3838:
1.620 albertel 3839: if (!$domain) { $domain=$env{'user.domain'}; }
3840: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3841:
3842: &devalidate($symb,$stuname,$domain);
1.109 www 3843:
3844: $symb=escape($symb);
1.187 www 3845: if (!$namespace) {
1.620 albertel 3846: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3847: return '';
3848: }
3849: }
1.620 albertel 3850: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3851:
3852: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3853: $$storehash{'host'}=$perlvar{'lonHostID'};
3854:
1.12 www 3855: my $namevalue='';
1.800 albertel 3856: foreach my $key (keys(%$storehash)) {
3857: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3858: }
1.12 www 3859: $namevalue=~s/\&$//;
1.187 www 3860: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 3861: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 3862: }
3863:
1.47 www 3864: # -------------------------------------------------------------- Critical Store
3865:
3866: sub cstore {
1.124 www 3867: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3868: my $home='';
3869:
1.168 albertel 3870: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3871:
1.213 www 3872: $symb=&symbclean($symb);
1.122 albertel 3873: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 3874:
1.620 albertel 3875: if (!$domain) { $domain=$env{'user.domain'}; }
3876: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 3877:
3878: &devalidate($symb,$stuname,$domain);
1.109 www 3879:
3880: $symb=escape($symb);
1.187 www 3881: if (!$namespace) {
1.620 albertel 3882: unless ($namespace=$env{'request.course.id'}) {
1.187 www 3883: return '';
3884: }
3885: }
1.620 albertel 3886: if (!$home) { $home=$env{'user.home'}; }
1.447 www 3887:
3888: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3889: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 3890:
1.47 www 3891: my $namevalue='';
1.800 albertel 3892: foreach my $key (keys(%$storehash)) {
3893: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 3894: }
1.47 www 3895: $namevalue=~s/\&$//;
1.187 www 3896: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 3897: return critical
3898: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 3899: }
3900:
1.9 www 3901: # --------------------------------------------------------------------- Restore
3902:
3903: sub restore {
1.124 www 3904: my ($symb,$namespace,$domain,$stuname) = @_;
3905: my $home='';
3906:
1.168 albertel 3907: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 3908:
1.122 albertel 3909: if (!$symb) {
3910: unless ($symb=escape(&symbread())) { return ''; }
3911: } else {
1.213 www 3912: $symb=&escape(&symbclean($symb));
1.122 albertel 3913: }
1.188 www 3914: if (!$namespace) {
1.620 albertel 3915: unless ($namespace=$env{'request.course.id'}) {
1.188 www 3916: return '';
3917: }
3918: }
1.620 albertel 3919: if (!$domain) { $domain=$env{'user.domain'}; }
3920: if (!$stuname) { $stuname=$env{'user.name'}; }
3921: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 3922: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3923:
1.12 www 3924: my %returnhash=();
1.800 albertel 3925: foreach my $line (split(/\&/,$answer)) {
3926: my ($name,$value)=split(/\=/,$line);
1.591 albertel 3927: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 3928: }
1.75 www 3929: my $version;
3930: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 3931: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3932: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 3933: }
1.75 www 3934: }
1.13 www 3935: return %returnhash;
1.34 www 3936: }
3937:
3938: # ---------------------------------------------------------- Course Description
3939:
3940: sub coursedescription {
1.731 albertel 3941: my ($courseid,$args)=@_;
1.34 www 3942: $courseid=~s/^\///;
1.49 www 3943: $courseid=~s/\_/\//g;
1.34 www 3944: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 3945: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 3946: my $normalid=$cdomain.'_'.$cnum;
3947: # need to always cache even if we get errors otherwise we keep
3948: # trying and trying and trying to get the course description.
3949: my %envhash=();
3950: my %returnhash=();
1.731 albertel 3951:
3952: my $expiretime=600;
3953: if ($env{'request.course.id'} eq $normalid) {
3954: $expiretime=120;
3955: }
3956:
3957: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3958: if (!$args->{'freshen_cache'}
3959: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3960: foreach my $key (keys(%env)) {
3961: next if ($key !~ /^\Q$prefix\E(.*)/);
3962: my ($setting) = $1;
3963: $returnhash{$setting} = $env{$key};
3964: }
3965: return %returnhash;
3966: }
3967:
3968: # get the data agin
3969: if (!$args->{'one_time'}) {
3970: $envhash{'course.'.$normalid.'.last_cache'}=time;
3971: }
1.811 albertel 3972:
1.34 www 3973: if ($chome ne 'no_host') {
1.302 albertel 3974: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 3975: if (!exists($returnhash{'con_lost'})) {
3976: $returnhash{'home'}= $chome;
3977: $returnhash{'domain'} = $cdomain;
3978: $returnhash{'num'} = $cnum;
1.741 raeburn 3979: if (!defined($returnhash{'type'})) {
3980: $returnhash{'type'} = 'Course';
3981: }
1.130 albertel 3982: while (my ($name,$value) = each %returnhash) {
1.53 www 3983: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 3984: }
1.270 www 3985: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 3986: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 3987: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 3988: $envhash{'course.'.$normalid.'.home'}=$chome;
3989: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3990: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 3991: }
3992: }
1.731 albertel 3993: if (!$args->{'one_time'}) {
1.949 raeburn 3994: &appenv(\%envhash);
1.731 albertel 3995: }
1.302 albertel 3996: return %returnhash;
1.461 www 3997: }
3998:
1.1080 raeburn 3999: sub update_released_required {
4000: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4001: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4002: $cid = $env{'request.course.id'};
4003: $cdom = $env{'course.'.$cid.'.domain'};
4004: $cnum = $env{'course.'.$cid.'.num'};
4005: $chome = $env{'course.'.$cid.'.home'};
4006: }
4007: if ($needsrelease) {
4008: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4009: my $needsupdate;
4010: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4011: $needsupdate = 1;
4012: } else {
4013: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4014: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4015: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4016: $needsupdate = 1;
4017: }
4018: }
4019: if ($needsupdate) {
4020: my %needshash = (
4021: 'internal.releaserequired' => $needsrelease,
4022: );
4023: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4024: if ($putresult eq 'ok') {
4025: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4026: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4027: if (ref($crsinfo{$cid}) eq 'HASH') {
4028: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4029: &courseidput($cdom,\%crsinfo,$chome,'notime');
4030: }
4031: }
4032: }
4033: }
4034: return;
4035: }
4036:
1.461 www 4037: # -------------------------------------------------See if a user is privileged
4038:
4039: sub privileged {
4040: my ($username,$domain)=@_;
4041: my $rolesdump=&reply("dump:$domain:$username:roles",
4042: &homeserver($username,$domain));
1.1033 raeburn 4043: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4044: ($rolesdump =~ /^error:/)) {
4045: return 0;
4046: }
1.461 www 4047: my $now=time;
4048: if ($rolesdump ne '') {
1.800 albertel 4049: foreach my $entry (split(/&/,$rolesdump)) {
4050: if ($entry!~/^rolesdef_/) {
4051: my ($area,$role)=split(/=/,$entry);
1.461 www 4052: $area=~s/\_\w\w$//;
4053: my ($trole,$tend,$tstart)=split(/_/,$role);
4054: if (($trole eq 'dc') || ($trole eq 'su')) {
4055: my $active=1;
4056: if ($tend) {
4057: if ($tend<$now) { $active=0; }
4058: }
4059: if ($tstart) {
4060: if ($tstart>$now) { $active=0; }
4061: }
4062: if ($active) { return 1; }
4063: }
4064: }
4065: }
4066: }
4067: return 0;
1.9 www 4068: }
1.1 albertel 4069:
1.103 harris41 4070: # -------------------------------------------------------- Get user privileges
1.11 www 4071:
4072: sub rolesinit {
4073: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4074: my $now=time;
4075: my %userroles = ('user.login.time' => $now);
1.1086 raeburn 4076: my $extra = &freeze_escape({'skipcheck' => 1});
1.1078 raeburn 4077: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4078: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1078 raeburn 4079: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4080: return \%userroles;
4081: }
1.11 www 4082: my %allroles=();
1.678 raeburn 4083: my %allgroups=();
4084: my $group_privs;
1.11 www 4085:
4086: if ($rolesdump ne '') {
1.800 albertel 4087: foreach my $entry (split(/&/,$rolesdump)) {
4088: if ($entry!~/^rolesdef_/) {
4089: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4090: $area=~s/\_\w\w$//;
1.678 raeburn 4091: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4092: if ($role=~/^cr/) {
1.807 albertel 4093: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4094: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4095: ($tend,$tstart)=split('_',$trest);
4096: } else {
4097: $trole=$role;
4098: }
1.678 raeburn 4099: } elsif ($role =~ m|^gr/|) {
4100: ($trole,$tend,$tstart) = split(/_/,$role);
4101: ($trole,$group_privs) = split(/\//,$trole);
4102: $group_privs = &unescape($group_privs);
1.587 albertel 4103: } else {
4104: ($trole,$tend,$tstart)=split(/_/,$role);
4105: }
1.743 albertel 4106: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4107: $username);
4108: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4109: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4110: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4111: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4112: my $spec=$trole.'.'.$area;
4113: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4114: if ($trole =~ /^cr\//) {
1.567 raeburn 4115: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4116: } elsif ($trole eq 'gr') {
4117: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4118: } else {
1.567 raeburn 4119: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4120: }
1.12 www 4121: }
1.662 raeburn 4122: }
1.191 harris41 4123: }
1.743 albertel 4124: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4125: $userroles{'user.adv'} = $adv;
4126: $userroles{'user.author'} = $author;
1.620 albertel 4127: $env{'user.adv'}=$adv;
1.11 www 4128: }
1.743 albertel 4129: return \%userroles;
1.11 www 4130: }
4131:
1.567 raeburn 4132: sub set_arearole {
4133: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4134: # log the associated role with the area
4135: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4136: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4137: }
4138:
4139: sub custom_roleprivs {
4140: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4141: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4142: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4143: if (&hostname($homsvr) ne '') {
1.567 raeburn 4144: my ($rdummy,$roledef)=
4145: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4146: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4147: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4148: if (defined($syspriv)) {
1.1043 raeburn 4149: if ($trest =~ /^$match_community$/) {
4150: $syspriv =~ s/bre\&S//;
4151: }
1.567 raeburn 4152: $$allroles{'cm./'}.=':'.$syspriv;
4153: $$allroles{$spec.'./'}.=':'.$syspriv;
4154: }
4155: if ($tdomain ne '') {
4156: if (defined($dompriv)) {
4157: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4158: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4159: }
4160: if (($trest ne '') && (defined($coursepriv))) {
4161: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4162: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4163: }
4164: }
4165: }
4166: }
4167: }
4168:
1.678 raeburn 4169: sub group_roleprivs {
4170: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4171: my $access = 1;
4172: my $now = time;
4173: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4174: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4175: if ($access) {
1.811 albertel 4176: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4177: $$allgroups{$course}{$group} .=':'.$group_privs;
4178: }
4179: }
1.567 raeburn 4180:
4181: sub standard_roleprivs {
4182: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4183: if (defined($pr{$trole.':s'})) {
4184: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4185: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4186: }
4187: if ($tdomain ne '') {
4188: if (defined($pr{$trole.':d'})) {
4189: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4190: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4191: }
4192: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4193: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4194: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4195: }
4196: }
4197: }
4198:
4199: sub set_userprivs {
1.1064 raeburn 4200: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4201: my $author=0;
4202: my $adv=0;
1.678 raeburn 4203: my %grouproles = ();
4204: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4205: my @groupkeys;
1.1000 raeburn 4206: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4207: push(@groupkeys,$role);
4208: }
4209: if (ref($groups_roles) eq 'HASH') {
4210: foreach my $key (keys(%{$groups_roles})) {
4211: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4212: push(@groupkeys,$key);
4213: }
4214: }
4215: }
4216: if (@groupkeys > 0) {
4217: foreach my $role (@groupkeys) {
4218: my ($trole,$area,$sec,$extendedarea);
4219: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4220: $trole = $1;
4221: $area = $2;
4222: $sec = $3;
4223: $extendedarea = $area.$sec;
4224: if (exists($$allgroups{$area})) {
4225: foreach my $group (keys(%{$$allgroups{$area}})) {
4226: my $spec = $trole.'.'.$extendedarea;
4227: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4228: $$allgroups{$area}{$group};
1.1064 raeburn 4229: }
1.678 raeburn 4230: }
4231: }
4232: }
4233: }
4234: }
1.800 albertel 4235: foreach my $group (keys(%grouproles)) {
4236: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4237: }
1.800 albertel 4238: foreach my $role (keys(%{$allroles})) {
4239: my %thesepriv;
1.941 raeburn 4240: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4241: foreach my $item (split(/:/,$$allroles{$role})) {
4242: if ($item ne '') {
4243: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4244: if ($restrictions eq '') {
4245: $thesepriv{$privilege}='F';
4246: } elsif ($thesepriv{$privilege} ne 'F') {
4247: $thesepriv{$privilege}.=$restrictions;
4248: }
4249: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4250: }
4251: }
4252: my $thesestr='';
1.800 albertel 4253: foreach my $priv (keys(%thesepriv)) {
4254: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4255: }
4256: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4257: }
4258: return ($author,$adv);
4259: }
4260:
1.994 raeburn 4261: sub role_status {
1.1002 raeburn 4262: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4263: my @pwhere = ();
4264: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4265: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4266: unless (!defined($$role) || $$role eq '') {
4267: $$where=join('.',@pwhere);
4268: $$trolecode=$$role.'.'.$$where;
4269: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4270: $$tstatus='is';
4271: if ($$tstart && $$tstart>$then) {
4272: $$tstatus='future';
1.1034 raeburn 4273: if ($$tstart<$now) {
4274: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4275: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4276: my (%allroles,%allgroups,$group_privs,
4277: %groups_roles,@rolecodes);
1.1002 raeburn 4278: my %userroles = (
4279: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4280: );
1.1064 raeburn 4281: @rolecodes = ('cm');
1.1002 raeburn 4282: my $spec=$$role.'.'.$$where;
4283: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4284: if ($$role =~ /^cr\//) {
4285: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4286: push(@rolecodes,'cr');
1.1002 raeburn 4287: } elsif ($$role eq 'gr') {
1.1064 raeburn 4288: push(@rolecodes,$$role);
1.1002 raeburn 4289: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4290: $env{'user.name'});
1.1064 raeburn 4291: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4292: (undef,my $group_privs) = split(/\//,$trole);
4293: $group_privs = &unescape($group_privs);
4294: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4295: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4296: if (keys(%course_roles) > 0) {
4297: my ($tnum) = ($trest =~ /^($match_courseid)/);
4298: if ($tdomain ne '' && $tnum ne '') {
4299: foreach my $key (keys(%course_roles)) {
4300: if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
4301: my $crsrole = $1;
4302: my $crssec = $2;
4303: if ($crsrole =~ /^cr/) {
4304: unless (grep(/^cr$/,@rolecodes)) {
4305: push(@rolecodes,'cr');
4306: }
4307: } else {
4308: unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
4309: push(@rolecodes,$crsrole);
4310: }
4311: }
4312: my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
4313: if ($crssec ne '') {
4314: $rolekey .= '/'.$crssec;
4315: }
4316: $rolekey .= './';
4317: $groups_roles{$rolekey} = \@rolecodes;
4318: }
4319: }
4320: }
4321: }
1.1002 raeburn 4322: } else {
1.1064 raeburn 4323: push(@rolecodes,$$role);
1.1002 raeburn 4324: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4325: }
1.1064 raeburn 4326: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4327: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4328: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4329: }
4330: }
1.1034 raeburn 4331: $$tstatus = 'is';
1.1002 raeburn 4332: }
1.994 raeburn 4333: }
4334: if ($$tend) {
4335: if ($$tend<$then) {
4336: $$tstatus='expired';
4337: } elsif ($$tend<$now) {
4338: $$tstatus='will_not';
4339: }
4340: }
4341: }
4342: }
4343: }
4344:
4345: sub check_adhoc_privs {
1.1088 raeburn 4346: my ($cdom,$cnum,$then,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4347: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4348: if ($env{$cckey}) {
4349: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1002 raeburn 4350: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4351: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 4352: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4353: }
4354: } else {
1.1088 raeburn 4355: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4356: }
4357: }
4358:
4359: sub set_adhoc_privileges {
4360: # role can be cc or ca
1.1088 raeburn 4361: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4362: my $area = '/'.$dcdom.'/'.$pickedcourse;
4363: my $spec = $role.'.'.$area;
4364: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4365: $env{'user.name'});
4366: my %ccrole = ();
4367: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4368: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4369: &appenv(\%userroles,[$role,'cm']);
4370: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 4371: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4372: &appenv( {'request.role' => $spec,
4373: 'request.role.domain' => $dcdom,
4374: 'request.course.sec' => ''
4375: }
4376: );
4377: my $tadv=0;
4378: if (&allowed('adv') eq 'F') { $tadv=1; }
4379: &appenv({'request.role.adv' => $tadv});
4380: }
1.994 raeburn 4381: }
4382:
1.12 www 4383: # --------------------------------------------------------------- get interface
4384:
4385: sub get {
1.131 albertel 4386: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4387: my $items='';
1.800 albertel 4388: foreach my $item (@$storearr) {
4389: $items.=&escape($item).'&';
1.191 harris41 4390: }
1.12 www 4391: $items=~s/\&$//;
1.620 albertel 4392: if (!$udomain) { $udomain=$env{'user.domain'}; }
4393: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4394: my $uhome=&homeserver($uname,$udomain);
4395:
1.133 albertel 4396: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4397: my @pairs=split(/\&/,$rep);
1.273 albertel 4398: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4399: return @pairs;
4400: }
1.15 www 4401: my %returnhash=();
1.42 www 4402: my $i=0;
1.800 albertel 4403: foreach my $item (@$storearr) {
4404: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4405: $i++;
1.191 harris41 4406: }
1.15 www 4407: return %returnhash;
1.27 www 4408: }
4409:
4410: # --------------------------------------------------------------- del interface
4411:
4412: sub del {
1.133 albertel 4413: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4414: my $items='';
1.800 albertel 4415: foreach my $item (@$storearr) {
4416: $items.=&escape($item).'&';
1.191 harris41 4417: }
1.984 neumanie 4418:
1.27 www 4419: $items=~s/\&$//;
1.620 albertel 4420: if (!$udomain) { $udomain=$env{'user.domain'}; }
4421: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4422: my $uhome=&homeserver($uname,$udomain);
4423: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4424: }
4425:
4426: # -------------------------------------------------------------- dump interface
4427:
4428: sub dump {
1.1086 raeburn 4429: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4430: if (!$udomain) { $udomain=$env{'user.domain'}; }
4431: if (!$uname) { $uname=$env{'user.name'}; }
4432: my $uhome=&homeserver($uname,$udomain);
4433: if ($regexp) {
4434: $regexp=&escape($regexp);
4435: } else {
4436: $regexp='.';
4437: }
1.1086 raeburn 4438: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4439: my @pairs=split(/\&/,$rep);
4440: my %returnhash=();
4441: foreach my $item (@pairs) {
4442: my ($key,$value)=split(/=/,$item,2);
4443: $key = &unescape($key);
4444: next if ($key =~ /^error: 2 /);
4445: $returnhash{$key}=&thaw_unescape($value);
4446: }
4447: return %returnhash;
1.407 www 4448: }
4449:
1.717 albertel 4450: # --------------------------------------------------------- dumpstore interface
4451:
4452: sub dumpstore {
4453: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4454: if (!$udomain) { $udomain=$env{'user.domain'}; }
4455: if (!$uname) { $uname=$env{'user.name'}; }
4456: my $uhome=&homeserver($uname,$udomain);
4457: if ($regexp) {
4458: $regexp=&escape($regexp);
4459: } else {
4460: $regexp='.';
4461: }
4462: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4463: my @pairs=split(/\&/,$rep);
4464: my %returnhash=();
4465: foreach my $item (@pairs) {
4466: my ($key,$value)=split(/=/,$item,2);
4467: next if ($key =~ /^error: 2 /);
4468: $returnhash{$key}=&thaw_unescape($value);
4469: }
4470: return %returnhash;
1.717 albertel 4471: }
4472:
1.407 www 4473: # -------------------------------------------------------------- keys interface
4474:
4475: sub getkeys {
4476: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4477: if (!$udomain) { $udomain=$env{'user.domain'}; }
4478: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4479: my $uhome=&homeserver($uname,$udomain);
4480: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4481: my @keyarray=();
1.800 albertel 4482: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4483: next if ($key =~ /^error: 2 /);
1.800 albertel 4484: push(@keyarray,&unescape($key));
1.407 www 4485: }
4486: return @keyarray;
1.318 matthew 4487: }
4488:
1.319 matthew 4489: # --------------------------------------------------------------- currentdump
4490: sub currentdump {
1.328 matthew 4491: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4492: $courseid = $env{'request.course.id'} if (! defined($courseid));
4493: $sdom = $env{'user.domain'} if (! defined($sdom));
4494: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4495: my $uhome = &homeserver($sname,$sdom);
4496: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4497: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4498: #
1.318 matthew 4499: my %returnhash=();
1.319 matthew 4500: #
4501: if ($rep eq "unknown_cmd") {
4502: # an old lond will not know currentdump
4503: # Do a dump and make it look like a currentdump
1.822 albertel 4504: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4505: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4506: my %hash = @tmp;
4507: @tmp=();
1.424 matthew 4508: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4509: } else {
4510: my @pairs=split(/\&/,$rep);
1.800 albertel 4511: foreach my $pair (@pairs) {
4512: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4513: my ($symb,$param) = split(/:/,$key);
4514: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4515: &thaw_unescape($value);
1.319 matthew 4516: }
1.191 harris41 4517: }
1.12 www 4518: return %returnhash;
1.424 matthew 4519: }
4520:
4521: sub convert_dump_to_currentdump{
4522: my %hash = %{shift()};
4523: my %returnhash;
4524: # Code ripped from lond, essentially. The only difference
4525: # here is the unescaping done by lonnet::dump(). Conceivably
4526: # we might run in to problems with parameter names =~ /^v\./
4527: while (my ($key,$value) = each(%hash)) {
4528: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4529: $symb = &unescape($symb);
4530: $param = &unescape($param);
1.424 matthew 4531: next if ($v eq 'version' || $symb eq 'keys');
4532: next if (exists($returnhash{$symb}) &&
4533: exists($returnhash{$symb}->{$param}) &&
4534: $returnhash{$symb}->{'v.'.$param} > $v);
4535: $returnhash{$symb}->{$param}=$value;
4536: $returnhash{$symb}->{'v.'.$param}=$v;
4537: }
4538: #
4539: # Remove all of the keys in the hashes which keep track of
4540: # the version of the parameter.
4541: while (my ($symb,$param_hash) = each(%returnhash)) {
4542: # use a foreach because we are going to delete from the hash.
4543: foreach my $key (keys(%$param_hash)) {
4544: delete($param_hash->{$key}) if ($key =~ /^v\./);
4545: }
4546: }
4547: return \%returnhash;
1.12 www 4548: }
4549:
1.627 albertel 4550: # ------------------------------------------------------ critical inc interface
4551:
4552: sub cinc {
4553: return &inc(@_,'critical');
4554: }
4555:
1.449 matthew 4556: # --------------------------------------------------------------- inc interface
4557:
4558: sub inc {
1.627 albertel 4559: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 4560: if (!$udomain) { $udomain=$env{'user.domain'}; }
4561: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 4562: my $uhome=&homeserver($uname,$udomain);
4563: my $items='';
4564: if (! ref($store)) {
4565: # got a single value, so use that instead
4566: $items = &escape($store).'=&';
4567: } elsif (ref($store) eq 'SCALAR') {
4568: $items = &escape($$store).'=&';
4569: } elsif (ref($store) eq 'ARRAY') {
4570: $items = join('=&',map {&escape($_);} @{$store});
4571: } elsif (ref($store) eq 'HASH') {
4572: while (my($key,$value) = each(%{$store})) {
4573: $items.= &escape($key).'='.&escape($value).'&';
4574: }
4575: }
4576: $items=~s/\&$//;
1.627 albertel 4577: if ($critical) {
4578: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4579: } else {
4580: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4581: }
1.449 matthew 4582: }
4583:
1.12 www 4584: # --------------------------------------------------------------- put interface
4585:
4586: sub put {
1.134 albertel 4587: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4588: if (!$udomain) { $udomain=$env{'user.domain'}; }
4589: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4590: my $uhome=&homeserver($uname,$udomain);
1.12 www 4591: my $items='';
1.800 albertel 4592: foreach my $item (keys(%$storehash)) {
4593: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4594: }
1.12 www 4595: $items=~s/\&$//;
1.134 albertel 4596: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 4597: }
4598:
1.631 albertel 4599: # ------------------------------------------------------------ newput interface
4600:
4601: sub newput {
4602: my ($namespace,$storehash,$udomain,$uname)=@_;
4603: if (!$udomain) { $udomain=$env{'user.domain'}; }
4604: if (!$uname) { $uname=$env{'user.name'}; }
4605: my $uhome=&homeserver($uname,$udomain);
4606: my $items='';
4607: foreach my $key (keys(%$storehash)) {
4608: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4609: }
4610: $items=~s/\&$//;
4611: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4612: }
4613:
4614: # --------------------------------------------------------- putstore interface
4615:
1.524 raeburn 4616: sub putstore {
1.715 albertel 4617: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 4618: if (!$udomain) { $udomain=$env{'user.domain'}; }
4619: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 4620: my $uhome=&homeserver($uname,$udomain);
4621: my $items='';
1.715 albertel 4622: foreach my $key (keys(%$storehash)) {
4623: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 4624: }
1.715 albertel 4625: $items=~s/\&$//;
1.716 albertel 4626: my $esc_symb=&escape($symb);
4627: my $esc_v=&escape($version);
1.715 albertel 4628: my $reply =
1.716 albertel 4629: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 4630: $uhome);
4631: if ($reply eq 'unknown_cmd') {
1.716 albertel 4632: # gfall back to way things use to be done
1.715 albertel 4633: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4634: $uname);
1.524 raeburn 4635: }
1.715 albertel 4636: return $reply;
4637: }
4638:
4639: sub old_putstore {
1.716 albertel 4640: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4641: if (!$udomain) { $udomain=$env{'user.domain'}; }
4642: if (!$uname) { $uname=$env{'user.name'}; }
4643: my $uhome=&homeserver($uname,$udomain);
4644: my %newstorehash;
1.800 albertel 4645: foreach my $item (keys(%$storehash)) {
4646: my $key = $version.':'.&escape($symb).':'.$item;
4647: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 4648: }
4649: my $items='';
4650: my %allitems = ();
1.800 albertel 4651: foreach my $item (keys(%newstorehash)) {
4652: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 4653: my $key = $1.':keys:'.$2;
4654: $allitems{$key} .= $3.':';
4655: }
1.800 albertel 4656: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 4657: }
1.800 albertel 4658: foreach my $item (keys(%allitems)) {
4659: $allitems{$item} =~ s/\:$//;
4660: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 4661: }
4662: $items=~s/\&$//;
4663: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 4664: }
4665:
1.47 www 4666: # ------------------------------------------------------ critical put interface
4667:
4668: sub cput {
1.134 albertel 4669: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 4670: if (!$udomain) { $udomain=$env{'user.domain'}; }
4671: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 4672: my $uhome=&homeserver($uname,$udomain);
1.47 www 4673: my $items='';
1.800 albertel 4674: foreach my $item (keys(%$storehash)) {
4675: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 4676: }
1.47 www 4677: $items=~s/\&$//;
1.134 albertel 4678: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4679: }
4680:
4681: # -------------------------------------------------------------- eget interface
4682:
4683: sub eget {
1.133 albertel 4684: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4685: my $items='';
1.800 albertel 4686: foreach my $item (@$storearr) {
4687: $items.=&escape($item).'&';
1.191 harris41 4688: }
1.12 www 4689: $items=~s/\&$//;
1.620 albertel 4690: if (!$udomain) { $udomain=$env{'user.domain'}; }
4691: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4692: my $uhome=&homeserver($uname,$udomain);
4693: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 4694: my @pairs=split(/\&/,$rep);
4695: my %returnhash=();
1.42 www 4696: my $i=0;
1.800 albertel 4697: foreach my $item (@$storearr) {
4698: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4699: $i++;
1.191 harris41 4700: }
1.12 www 4701: return %returnhash;
4702: }
4703:
1.667 albertel 4704: # ------------------------------------------------------------ tmpput interface
4705: sub tmpput {
1.802 raeburn 4706: my ($storehash,$server,$context)=@_;
1.667 albertel 4707: my $items='';
1.800 albertel 4708: foreach my $item (keys(%$storehash)) {
4709: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 4710: }
4711: $items=~s/\&$//;
1.802 raeburn 4712: if (defined($context)) {
4713: $items .= ':'.&escape($context);
4714: }
1.667 albertel 4715: return &reply("tmpput:$items",$server);
4716: }
4717:
4718: # ------------------------------------------------------------ tmpget interface
4719: sub tmpget {
1.688 albertel 4720: my ($token,$server)=@_;
4721: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4722: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 4723: my %returnhash;
4724: foreach my $item (split(/\&/,$rep)) {
4725: my ($key,$value)=split(/=/,$item);
1.951 raeburn 4726: next if ($key =~ /^error: 2 /);
1.667 albertel 4727: $returnhash{&unescape($key)}=&thaw_unescape($value);
4728: }
4729: return %returnhash;
4730: }
4731:
1.688 albertel 4732: # ------------------------------------------------------------ tmpget interface
4733: sub tmpdel {
4734: my ($token,$server)=@_;
4735: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4736: return &reply("tmpdel:$token",$server);
4737: }
4738:
1.765 albertel 4739: # -------------------------------------------------- portfolio access checking
4740:
4741: sub portfolio_access {
1.766 albertel 4742: my ($requrl) = @_;
1.765 albertel 4743: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4744: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 4745: if ($result) {
4746: my %setters;
4747: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4748: my ($startblock,$endblock) =
4749: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4750: if ($startblock && $endblock) {
4751: return 'B';
4752: }
4753: } else {
4754: my ($startblock,$endblock) =
4755: &Apache::loncommon::blockcheck(\%setters,'port');
4756: if ($startblock && $endblock) {
4757: return 'B';
4758: }
4759: }
4760: }
1.765 albertel 4761: if ($result eq 'ok') {
1.766 albertel 4762: return 'F';
1.765 albertel 4763: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 4764: return 'A';
1.765 albertel 4765: }
1.766 albertel 4766: return '';
1.765 albertel 4767: }
4768:
4769: sub get_portfolio_access {
1.767 albertel 4770: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4771:
4772: if (!ref($access_hash)) {
4773: my $current_perms = &get_portfile_permissions($udom,$unum);
4774: my %access_controls = &get_access_controls($current_perms,$group,
4775: $file_name);
4776: $access_hash = $access_controls{$file_name};
4777: }
4778:
1.765 albertel 4779: my ($public,$guest,@domains,@users,@courses,@groups);
4780: my $now = time;
4781: if (ref($access_hash) eq 'HASH') {
4782: foreach my $key (keys(%{$access_hash})) {
4783: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4784: if ($start > $now) {
4785: next;
4786: }
4787: if ($end && $end<$now) {
4788: next;
4789: }
4790: if ($scope eq 'public') {
4791: $public = $key;
4792: last;
4793: } elsif ($scope eq 'guest') {
4794: $guest = $key;
4795: } elsif ($scope eq 'domains') {
4796: push(@domains,$key);
4797: } elsif ($scope eq 'users') {
4798: push(@users,$key);
4799: } elsif ($scope eq 'course') {
4800: push(@courses,$key);
4801: } elsif ($scope eq 'group') {
4802: push(@groups,$key);
4803: }
4804: }
4805: if ($public) {
4806: return 'ok';
4807: }
4808: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4809: if ($guest) {
4810: return $guest;
4811: }
4812: } else {
4813: if (@domains > 0) {
4814: foreach my $domkey (@domains) {
4815: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4816: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4817: return 'ok';
4818: }
4819: }
4820: }
4821: }
4822: if (@users > 0) {
4823: foreach my $userkey (@users) {
1.865 raeburn 4824: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4825: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4826: if (ref($item) eq 'HASH') {
4827: if (($item->{'uname'} eq $env{'user.name'}) &&
4828: ($item->{'udom'} eq $env{'user.domain'})) {
4829: return 'ok';
4830: }
4831: }
4832: }
4833: }
1.765 albertel 4834: }
4835: }
4836: my %roleshash;
4837: my @courses_and_groups = @courses;
4838: push(@courses_and_groups,@groups);
4839: if (@courses_and_groups > 0) {
4840: my (%allgroups,%allroles);
4841: my ($start,$end,$role,$sec,$group);
4842: foreach my $envkey (%env) {
1.1060 raeburn 4843: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4844: my $cid = $2.'_'.$3;
4845: if ($1 eq 'gr') {
4846: $group = $4;
4847: $allgroups{$cid}{$group} = $env{$envkey};
4848: } else {
4849: if ($4 eq '') {
4850: $sec = 'none';
4851: } else {
4852: $sec = $4;
4853: }
4854: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4855: }
1.811 albertel 4856: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 4857: my $cid = $2.'_'.$3;
4858: if ($4 eq '') {
4859: $sec = 'none';
4860: } else {
4861: $sec = $4;
4862: }
4863: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4864: }
4865: }
4866: if (keys(%allroles) == 0) {
4867: return;
4868: }
4869: foreach my $key (@courses_and_groups) {
4870: my %content = %{$$access_hash{$key}};
4871: my $cnum = $content{'number'};
4872: my $cdom = $content{'domain'};
4873: my $cid = $cdom.'_'.$cnum;
4874: if (!exists($allroles{$cid})) {
4875: next;
4876: }
4877: foreach my $role_id (keys(%{$content{'roles'}})) {
4878: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4879: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4880: my @status = @{$content{'roles'}{$role_id}{'access'}};
4881: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4882: foreach my $role (keys(%{$allroles{$cid}})) {
4883: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4884: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4885: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4886: if (grep/^all$/,@sections) {
4887: return 'ok';
4888: } else {
4889: if (grep/^$sec$/,@sections) {
4890: return 'ok';
4891: }
4892: }
4893: }
4894: }
4895: if (keys(%{$allgroups{$cid}}) == 0) {
4896: if (grep/^none$/,@groups) {
4897: return 'ok';
4898: }
4899: } else {
4900: if (grep/^all$/,@groups) {
4901: return 'ok';
4902: }
4903: foreach my $group (keys(%{$allgroups{$cid}})) {
4904: if (grep/^$group$/,@groups) {
4905: return 'ok';
4906: }
4907: }
4908: }
4909: }
4910: }
4911: }
4912: }
4913: }
4914: if ($guest) {
4915: return $guest;
4916: }
4917: }
4918: }
4919: return;
4920: }
4921:
4922: sub course_group_datechecker {
4923: my ($dates,$now,$status) = @_;
4924: my ($start,$end) = split(/\./,$dates);
4925: if (!$start && !$end) {
4926: return 'ok';
4927: }
4928: if (grep/^active$/,@{$status}) {
4929: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4930: return 'ok';
4931: }
4932: }
4933: if (grep/^previous$/,@{$status}) {
4934: if ($end > $now ) {
4935: return 'ok';
4936: }
4937: }
4938: if (grep/^future$/,@{$status}) {
4939: if ($start > $now) {
4940: return 'ok';
4941: }
4942: }
4943: return;
4944: }
4945:
4946: sub parse_portfolio_url {
4947: my ($url) = @_;
4948:
4949: my ($type,$udom,$unum,$group,$file_name);
4950:
1.823 albertel 4951: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 4952: $type = 1;
4953: $udom = $1;
4954: $unum = $2;
4955: $file_name = $3;
1.823 albertel 4956: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 4957: $type = 2;
4958: $udom = $1;
4959: $unum = $2;
4960: $group = $3;
4961: $file_name = $3.'/'.$4;
4962: }
4963: if (wantarray) {
4964: return ($type,$udom,$unum,$file_name,$group);
4965: }
4966: return $type;
4967: }
4968:
4969: sub is_portfolio_url {
4970: my ($url) = @_;
4971: return scalar(&parse_portfolio_url($url));
4972: }
4973:
1.798 raeburn 4974: sub is_portfolio_file {
4975: my ($file) = @_;
1.820 raeburn 4976: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 4977: return 1;
4978: }
4979: return;
4980: }
4981:
1.976 raeburn 4982: sub usertools_access {
1.1084 raeburn 4983: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 4984: my ($access,%tools);
4985: if ($context eq '') {
4986: $context = 'tools';
4987: }
4988: if ($context eq 'requestcourses') {
4989: %tools = (
4990: official => 1,
4991: unofficial => 1,
1.1006 raeburn 4992: community => 1,
1.985 raeburn 4993: );
4994: } else {
4995: %tools = (
4996: aboutme => 1,
4997: blog => 1,
4998: portfolio => 1,
4999: );
5000: }
1.976 raeburn 5001: return if (!defined($tools{$tool}));
5002:
5003: if ((!defined($udom)) || (!defined($uname))) {
5004: $udom = $env{'user.domain'};
5005: $uname = $env{'user.name'};
5006: }
5007:
1.978 raeburn 5008: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5009: if ($action ne 'reload') {
1.985 raeburn 5010: if ($context eq 'requestcourses') {
5011: return $env{'environment.canrequest.'.$tool};
5012: } else {
5013: return $env{'environment.availabletools.'.$tool};
5014: }
5015: }
1.976 raeburn 5016: }
5017:
5018: my ($toolstatus,$inststatus);
5019:
1.985 raeburn 5020: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5021: ($action ne 'reload')) {
5022: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5023: $inststatus = $env{'environment.inststatus'};
5024: } else {
1.1084 raeburn 5025: if (ref($userenvref) eq 'HASH') {
5026: $toolstatus = $userenvref->{$context.'.'.$tool};
5027: $inststatus = $userenvref->{'inststatus'};
5028: } else {
5029: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5030: $toolstatus = $userenv{$context.'.'.$tool};
5031: $inststatus = $userenv{'inststatus'};
5032: }
1.976 raeburn 5033: }
5034:
5035: if ($toolstatus ne '') {
5036: if ($toolstatus) {
5037: $access = 1;
5038: } else {
5039: $access = 0;
5040: }
5041: return $access;
5042: }
5043:
1.1084 raeburn 5044: my ($is_adv,%domdef);
5045: if (ref($is_advref) eq 'HASH') {
5046: $is_adv = $is_advref->{'is_adv'};
5047: } else {
5048: $is_adv = &is_advanced_user($udom,$uname);
5049: }
5050: if (ref($domdefref) eq 'HASH') {
5051: %domdef = %{$domdefref};
5052: } else {
5053: %domdef = &get_domain_defaults($udom);
5054: }
1.976 raeburn 5055: if (ref($domdef{$tool}) eq 'HASH') {
5056: if ($is_adv) {
5057: if ($domdef{$tool}{'_LC_adv'} ne '') {
5058: if ($domdef{$tool}{'_LC_adv'}) {
5059: $access = 1;
5060: } else {
5061: $access = 0;
5062: }
5063: return $access;
5064: }
5065: }
5066: if ($inststatus ne '') {
5067: my ($hasaccess,$hasnoaccess);
5068: foreach my $affiliation (split(/:/,$inststatus)) {
5069: if ($domdef{$tool}{$affiliation} ne '') {
5070: if ($domdef{$tool}{$affiliation}) {
5071: $hasaccess = 1;
5072: } else {
5073: $hasnoaccess = 1;
5074: }
5075: }
5076: }
5077: if ($hasaccess || $hasnoaccess) {
5078: if ($hasaccess) {
5079: $access = 1;
5080: } elsif ($hasnoaccess) {
5081: $access = 0;
5082: }
5083: return $access;
5084: }
5085: } else {
5086: if ($domdef{$tool}{'default'} ne '') {
5087: if ($domdef{$tool}{'default'}) {
5088: $access = 1;
5089: } elsif ($domdef{$tool}{'default'} == 0) {
5090: $access = 0;
5091: }
5092: return $access;
5093: }
5094: }
5095: } else {
1.985 raeburn 5096: if ($context eq 'tools') {
5097: $access = 1;
5098: } else {
5099: $access = 0;
5100: }
1.976 raeburn 5101: return $access;
5102: }
5103: }
5104:
1.1050 raeburn 5105: sub is_course_owner {
5106: my ($cdom,$cnum,$udom,$uname) = @_;
5107: if (($udom eq '') || ($uname eq '')) {
5108: $udom = $env{'user.domain'};
5109: $uname = $env{'user.name'};
5110: }
5111: unless (($udom eq '') || ($uname eq '')) {
5112: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5113: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5114: return 1;
5115: } else {
5116: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5117: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5118: return 1;
5119: }
5120: }
5121: }
5122: }
5123: return;
5124: }
5125:
1.976 raeburn 5126: sub is_advanced_user {
5127: my ($udom,$uname) = @_;
1.1085 raeburn 5128: if ($udom ne '' && $uname ne '') {
5129: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5130: return $env{'user.adv'};
5131: }
5132: }
1.976 raeburn 5133: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5134: my %allroles;
5135: my $is_adv;
5136: foreach my $role (keys(%roleshash)) {
5137: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5138: my $area = '/'.$tdomain.'/'.$trest;
5139: if ($sec ne '') {
5140: $area .= '/'.$sec;
5141: }
5142: if (($area ne '') && ($trole ne '')) {
5143: my $spec=$trole.'.'.$area;
5144: if ($trole =~ /^cr\//) {
5145: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5146: } elsif ($trole ne 'gr') {
5147: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5148: }
5149: }
5150: }
5151: foreach my $role (keys(%allroles)) {
5152: last if ($is_adv);
5153: foreach my $item (split(/:/,$allroles{$role})) {
5154: if ($item ne '') {
5155: my ($privilege,$restrictions)=split(/&/,$item);
5156: if ($privilege eq 'adv') {
5157: $is_adv = 1;
5158: last;
5159: }
5160: }
5161: }
5162: }
5163: return $is_adv;
5164: }
1.798 raeburn 5165:
1.1035 raeburn 5166: sub check_can_request {
1.1036 raeburn 5167: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5168: my $canreq = 0;
5169: my ($types,$typename) = &Apache::loncommon::course_types();
5170: my @options = ('approval','validate','autolimit');
5171: my $optregex = join('|',@options);
5172: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5173: foreach my $type (@{$types}) {
5174: if (&usertools_access($env{'user.name'},
5175: $env{'user.domain'},
5176: $type,undef,'requestcourses')) {
5177: $canreq ++;
1.1036 raeburn 5178: if (ref($request_domains) eq 'HASH') {
5179: push(@{$request_domains->{$type}},$env{'user.domain'});
5180: }
1.1035 raeburn 5181: if ($dom eq $env{'user.domain'}) {
5182: $can_request->{$type} = 1;
5183: }
5184: }
5185: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5186: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5187: if (@curr > 0) {
1.1036 raeburn 5188: foreach my $item (@curr) {
5189: if (ref($request_domains) eq 'HASH') {
5190: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5191: if ($otherdom ne '') {
5192: if (ref($request_domains->{$type}) eq 'ARRAY') {
5193: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5194: push(@{$request_domains->{$type}},$otherdom);
5195: }
5196: } else {
5197: push(@{$request_domains->{$type}},$otherdom);
5198: }
5199: }
5200: }
5201: }
5202: unless($dom eq $env{'user.domain'}) {
5203: $canreq ++;
1.1035 raeburn 5204: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5205: $can_request->{$type} = 1;
5206: }
5207: }
5208: }
5209: }
5210: }
5211: }
5212: return $canreq;
5213: }
5214:
1.341 www 5215: # ---------------------------------------------- Custom access rule evaluation
5216:
5217: sub customaccess {
5218: my ($priv,$uri)=@_;
1.807 albertel 5219: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5220: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5221: $udom = &LONCAPA::clean_domain($udom);
5222: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5223: my $access=0;
1.800 albertel 5224: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5225: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5226: if ($type eq 'user') {
5227: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5228: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5229: if ($tdom) {
5230: if ($tdom ne $env{'user.domain'}) { next; }
5231: }
1.896 albertel 5232: if ($tuname) {
5233: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5234: }
5235: $access=($effect eq 'allow');
5236: last;
5237: }
5238: } else {
5239: if ($role) {
5240: if ($role ne $urole) { next; }
5241: }
5242: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5243: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5244: if ($tdom) {
5245: if ($tdom ne $udom) { next; }
5246: }
5247: if ($tcrs) {
5248: if ($tcrs ne $ucrs) { next; }
5249: }
5250: if ($tsec) {
5251: if ($tsec ne $usec) { next; }
5252: }
5253: $access=($effect eq 'allow');
5254: last;
5255: }
5256: if ($realm eq '' && $role eq '') {
5257: $access=($effect eq 'allow');
5258: }
1.402 bowersj2 5259: }
1.341 www 5260: }
5261: return $access;
5262: }
5263:
1.103 harris41 5264: # ------------------------------------------------- Check for a user privilege
1.12 www 5265:
5266: sub allowed {
1.810 raeburn 5267: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5268: my $ver_orguri=$uri;
1.439 www 5269: $uri=&deversion($uri);
1.152 www 5270: my $orguri=$uri;
1.52 www 5271: $uri=&declutter($uri);
1.809 raeburn 5272:
1.810 raeburn 5273: if ($priv eq 'evb') {
5274: # Evade communication block restrictions for specified role in a course
5275: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5276: return $1;
5277: } else {
5278: return;
5279: }
5280: }
5281:
1.620 albertel 5282: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5283: # Free bre access to adm and meta resources
1.775 albertel 5284: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5285: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5286: && ($priv eq 'bre')) {
1.14 www 5287: return 'F';
1.159 www 5288: }
5289:
1.545 banghart 5290: # Free bre access to user's own portfolio contents
1.714 raeburn 5291: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5292: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5293: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5294: my %setters;
5295: my ($startblock,$endblock) =
5296: &Apache::loncommon::blockcheck(\%setters,'port');
5297: if ($startblock && $endblock) {
5298: return 'B';
5299: } else {
5300: return 'F';
5301: }
1.545 banghart 5302: }
5303:
1.762 raeburn 5304: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5305: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5306: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5307: if (exists($env{'request.course.id'})) {
5308: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5309: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5310: if (($domain eq $cdom) && ($name eq $cnum)) {
5311: my $courseprivid=$env{'request.course.id'};
5312: $courseprivid=~s/\_/\//;
5313: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5314: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5315: return $1;
1.762 raeburn 5316: } else {
5317: if ($env{'request.course.sec'}) {
5318: $courseprivid.='/'.$env{'request.course.sec'};
5319: }
5320: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5321: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5322: return $2;
5323: }
1.714 raeburn 5324: }
5325: }
5326: }
5327: }
5328:
1.159 www 5329: # Free bre to public access
5330:
5331: if ($priv eq 'bre') {
1.238 www 5332: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5333: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5334: return 'F';
5335: }
1.238 www 5336: if ($copyright eq 'priv') {
5337: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5338: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5339: return '';
5340: }
5341: }
5342: if ($copyright eq 'domain') {
5343: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5344: unless (($env{'user.domain'} eq $1) ||
5345: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5346: return '';
5347: }
1.262 matthew 5348: }
1.620 albertel 5349: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5350: # Library role, so allow browsing of resources in this domain.
5351: return 'F';
1.238 www 5352: }
1.341 www 5353: if ($copyright eq 'custom') {
5354: unless (&customaccess($priv,$uri)) { return ''; }
5355: }
1.14 www 5356: }
1.264 matthew 5357: # Domain coordinator is trying to create a course
1.620 albertel 5358: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5359: # uri is the requested domain in this case.
5360: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5361: # a role of dc for the domain in question.
1.620 albertel 5362: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5363: }
1.29 www 5364:
1.52 www 5365: my $thisallowed='';
5366: my $statecond=0;
5367: my $courseprivid='';
5368:
1.1039 raeburn 5369: my $ownaccess;
1.1043 raeburn 5370: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5371: if (($priv eq 'bro') && ($env{'user.author'})) {
5372: if ($uri eq '') {
5373: $ownaccess = 1;
5374: } else {
5375: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5376: my $udom = $env{'user.domain'};
5377: my $uname = $env{'user.name'};
5378: if ($uri =~ m{^\Q$udom\E/?$}) {
5379: $ownaccess = 1;
1.1040 raeburn 5380: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5381: unless ($uri =~ m{\.\./}) {
5382: $ownaccess = 1;
5383: }
5384: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5385: my $now = time;
5386: if ($uri =~ m{^([^/]+)/?$}) {
5387: my $adom = $1;
5388: foreach my $key (keys(%env)) {
1.1042 raeburn 5389: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5390: my ($start,$end) = split('.',$env{$key});
5391: if (($now >= $start) && (!$end || $end < $now)) {
5392: $ownaccess = 1;
5393: last;
5394: }
5395: }
5396: }
5397: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5398: my $adom = $1;
5399: my $aname = $2;
1.1042 raeburn 5400: foreach my $role ('ca','aa') {
5401: if ($env{"user.role.$role./$adom/$aname"}) {
5402: my ($start,$end) =
5403: split('.',$env{"user.role.$role./$adom/$aname"});
5404: if (($now >= $start) && (!$end || $end < $now)) {
5405: $ownaccess = 1;
5406: last;
5407: }
1.1039 raeburn 5408: }
5409: }
5410: }
5411: }
5412: }
5413: }
5414: }
5415:
1.52 www 5416: # Course
5417:
1.620 albertel 5418: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5419: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5420: $thisallowed.=$1;
5421: }
1.52 www 5422: }
1.29 www 5423:
1.52 www 5424: # Domain
5425:
1.620 albertel 5426: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5427: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5428: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5429: $thisallowed.=$1;
5430: }
1.12 www 5431: }
1.52 www 5432:
5433: # Course: uri itself is a course
1.66 www 5434: my $courseuri=$uri;
5435: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5436: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5437:
1.620 albertel 5438: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5439: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5440: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5441: $thisallowed.=$1;
5442: }
1.12 www 5443: }
1.29 www 5444:
1.665 albertel 5445: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5446: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5447: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5448: $thisallowed='';
1.671 raeburn 5449: my ($match)=&is_on_map($uri);
5450: if ($match) {
5451: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5452: =~/\Q$priv\E\&([^\:]*)/) {
5453: $thisallowed.=$1;
5454: }
5455: } else {
1.705 albertel 5456: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5457: if ($refuri) {
5458: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5459: $thisallowed='F';
1.671 raeburn 5460: } else {
5461: $refuri=&declutter($refuri);
5462: my ($match) = &is_on_map($refuri);
5463: if ($match) {
5464: $thisallowed='F';
5465: }
1.669 raeburn 5466: }
1.671 raeburn 5467: }
5468: }
1.314 www 5469: }
1.492 albertel 5470:
1.766 albertel 5471: if ($priv eq 'bre'
5472: && $thisallowed ne 'F'
5473: && $thisallowed ne '2'
5474: && &is_portfolio_url($uri)) {
5475: $thisallowed = &portfolio_access($uri);
5476: }
5477:
1.52 www 5478: # Full access at system, domain or course-wide level? Exit.
1.29 www 5479: if ($thisallowed=~/F/) {
5480: return 'F';
5481: }
5482:
1.52 www 5483: # If this is generating or modifying users, exit with special codes
1.29 www 5484:
1.643 www 5485: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5486: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5487: my ($audom,$auname)=split('/',$uri);
1.643 www 5488: # no author name given, so this just checks on the general right to make a co-author in this domain
5489: unless ($auname) { return $thisallowed; }
5490: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5491: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5492: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5493: ($audom ne $env{'request.role.domain'}))) { return ''; }
5494: }
1.52 www 5495: return $thisallowed;
5496: }
5497: #
1.103 harris41 5498: # Gathered so far: system, domain and course wide privileges
1.52 www 5499: #
5500: # Course: See if uri or referer is an individual resource that is part of
5501: # the course
5502:
1.620 albertel 5503: if ($env{'request.course.id'}) {
1.232 www 5504:
1.620 albertel 5505: $courseprivid=$env{'request.course.id'};
5506: if ($env{'request.course.sec'}) {
5507: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5508: }
5509: $courseprivid=~s/\_/\//;
5510: my $checkreferer=1;
1.232 www 5511: my ($match,$cond)=&is_on_map($uri);
5512: if ($match) {
5513: $statecond=$cond;
1.620 albertel 5514: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5515: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5516: $thisallowed.=$1;
5517: $checkreferer=0;
5518: }
1.29 www 5519: }
1.83 www 5520:
1.148 www 5521: if ($checkreferer) {
1.620 albertel 5522: my $refuri=$env{'httpref.'.$orguri};
1.148 www 5523: unless ($refuri) {
1.800 albertel 5524: foreach my $key (keys(%env)) {
5525: if ($key=~/^httpref\..*\*/) {
5526: my $pattern=$key;
1.156 www 5527: $pattern=~s/^httpref\.\/res\///;
1.148 www 5528: $pattern=~s/\*/\[\^\/\]\+/g;
5529: $pattern=~s/\//\\\//g;
1.152 www 5530: if ($orguri=~/$pattern/) {
1.800 albertel 5531: $refuri=$env{$key};
1.148 www 5532: }
5533: }
1.191 harris41 5534: }
1.148 www 5535: }
1.232 www 5536:
1.148 www 5537: if ($refuri) {
1.152 www 5538: $refuri=&declutter($refuri);
1.232 www 5539: my ($match,$cond)=&is_on_map($refuri);
5540: if ($match) {
5541: my $refstatecond=$cond;
1.620 albertel 5542: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5543: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5544: $thisallowed.=$1;
1.53 www 5545: $uri=$refuri;
5546: $statecond=$refstatecond;
1.52 www 5547: }
5548: }
1.148 www 5549: }
1.29 www 5550: }
1.52 www 5551: }
1.29 www 5552:
1.52 www 5553: #
1.103 harris41 5554: # Gathered now: all privileges that could apply, and condition number
1.52 www 5555: #
5556: #
5557: # Full or no access?
5558: #
1.29 www 5559:
1.52 www 5560: if ($thisallowed=~/F/) {
5561: return 'F';
5562: }
1.29 www 5563:
1.52 www 5564: unless ($thisallowed) {
5565: return '';
5566: }
1.29 www 5567:
1.52 www 5568: # Restrictions exist, deal with them
5569: #
5570: # C:according to course preferences
5571: # R:according to resource settings
5572: # L:unless locked
5573: # X:according to user session state
5574: #
5575:
5576: # Possibly locked functionality, check all courses
1.54 www 5577: # Locks might take effect only after 10 minutes cache expiration for other
5578: # courses, and 2 minutes for current course
1.52 www 5579:
5580: my $envkey;
5581: if ($thisallowed=~/L/) {
1.1000 raeburn 5582: foreach $envkey (keys(%env)) {
1.54 www 5583: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5584: my $courseid=$2;
5585: my $roleid=$1.'.'.$2;
1.92 www 5586: $courseid=~s/^\///;
1.54 www 5587: my $expiretime=600;
1.620 albertel 5588: if ($env{'request.role'} eq $roleid) {
1.54 www 5589: $expiretime=120;
5590: }
5591: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5592: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 5593: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 5594: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 5595: }
1.620 albertel 5596: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5597: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5598: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5599: &log($env{'user.domain'},$env{'user.name'},
5600: $env{'user.home'},
1.57 www 5601: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 5602: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5603: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5604: return '';
5605: }
5606: }
1.620 albertel 5607: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5608: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5609: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5610: &log($env{'user.domain'},$env{'user.name'},
5611: $env{'user.home'},
1.57 www 5612: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 5613: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 5614: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 5615: return '';
5616: }
5617: }
5618: }
1.29 www 5619: }
1.52 www 5620: }
5621:
5622: #
5623: # Rest of the restrictions depend on selected course
5624: #
5625:
1.620 albertel 5626: unless ($env{'request.course.id'}) {
1.766 albertel 5627: if ($thisallowed eq 'A') {
5628: return 'A';
1.814 raeburn 5629: } elsif ($thisallowed eq 'B') {
5630: return 'B';
1.766 albertel 5631: } else {
5632: return '1';
5633: }
1.52 www 5634: }
1.29 www 5635:
1.52 www 5636: #
5637: # Now user is definitely in a course
5638: #
1.53 www 5639:
5640:
5641: # Course preferences
5642:
5643: if ($thisallowed=~/C/) {
1.620 albertel 5644: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5645: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5646: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 5647: =~/\Q$rolecode\E/) {
1.689 albertel 5648: if ($priv ne 'pch') {
5649: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5650: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5651: $env{'request.course.id'});
5652: }
1.237 www 5653: return '';
5654: }
5655:
1.620 albertel 5656: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 5657: =~/\Q$unamedom\E/) {
1.689 albertel 5658: if ($priv ne 'pch') {
5659: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5660: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5661: $env{'request.course.id'});
5662: }
1.54 www 5663: return '';
5664: }
1.53 www 5665: }
5666:
5667: # Resource preferences
5668:
5669: if ($thisallowed=~/R/) {
1.620 albertel 5670: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 5671: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 5672: if ($priv ne 'pch') {
5673: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5674: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5675: }
5676: return '';
1.54 www 5677: }
1.53 www 5678: }
1.30 www 5679:
1.246 www 5680: # Restricted by state or randomout?
1.30 www 5681:
1.52 www 5682: if ($thisallowed=~/X/) {
1.620 albertel 5683: if ($env{'acc.randomout'}) {
1.579 albertel 5684: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 5685: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 5686: return '';
5687: }
1.247 www 5688: }
5689: if (&condval($statecond)) {
1.52 www 5690: return '2';
5691: } else {
5692: return '';
5693: }
5694: }
1.30 www 5695:
1.766 albertel 5696: if ($thisallowed eq 'A') {
5697: return 'A';
1.814 raeburn 5698: } elsif ($thisallowed eq 'B') {
5699: return 'B';
1.766 albertel 5700: }
1.52 www 5701: return 'F';
1.232 www 5702: }
5703:
1.710 albertel 5704: sub split_uri_for_cond {
5705: my $uri=&deversion(&declutter(shift));
5706: my @uriparts=split(/\//,$uri);
5707: my $filename=pop(@uriparts);
5708: my $pathname=join('/',@uriparts);
5709: return ($pathname,$filename);
5710: }
1.232 www 5711: # --------------------------------------------------- Is a resource on the map?
5712:
5713: sub is_on_map {
1.710 albertel 5714: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 5715: #Trying to find the conditional for the file
1.620 albertel 5716: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 5717: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 5718: if ($match) {
1.289 bowersj2 5719: return (1,$1);
5720: } else {
1.434 www 5721: return (0,0);
1.289 bowersj2 5722: }
1.12 www 5723: }
5724:
1.427 www 5725: # --------------------------------------------------------- Get symb from alias
5726:
5727: sub get_symb_from_alias {
5728: my $symb=shift;
5729: my ($map,$resid,$url)=&decode_symb($symb);
5730: # Already is a symb
5731: if ($url) { return $symb; }
5732: # Must be an alias
5733: my $aliassymb='';
5734: my %bighash;
1.620 albertel 5735: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 5736: &GDBM_READER(),0640)) {
5737: my $rid=$bighash{'mapalias_'.$symb};
5738: if ($rid) {
5739: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 5740: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5741: $resid,$bighash{'src_'.$rid});
1.427 www 5742: }
5743: untie %bighash;
5744: }
5745: return $aliassymb;
5746: }
5747:
1.12 www 5748: # ----------------------------------------------------------------- Define Role
5749:
5750: sub definerole {
5751: if (allowed('mcr','/')) {
5752: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 5753: foreach my $role (split(':',$sysrole)) {
5754: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5755: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5756: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5757: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5758: return "refused:s:$crole&$cqual";
5759: }
5760: }
1.191 harris41 5761: }
1.800 albertel 5762: foreach my $role (split(':',$domrole)) {
5763: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5764: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5765: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5766: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 5767: return "refused:d:$crole&$cqual";
5768: }
5769: }
1.191 harris41 5770: }
1.800 albertel 5771: foreach my $role (split(':',$courole)) {
5772: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 5773: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5774: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5775: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 5776: return "refused:c:$crole&$cqual";
5777: }
5778: }
1.191 harris41 5779: }
1.620 albertel 5780: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5781: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 5782: "rolesdef_$rolename=".
5783: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 5784: return reply($command,$env{'user.home'});
1.12 www 5785: } else {
5786: return 'refused';
5787: }
1.105 harris41 5788: }
5789:
5790: # ---------------- Make a metadata query against the network of library servers
5791:
5792: sub metadata_query {
1.244 matthew 5793: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 5794: my %rhash;
1.845 albertel 5795: my %libserv = &all_library();
1.244 matthew 5796: my @server_list = (defined($server_array) ? @$server_array
5797: : keys(%libserv) );
5798: for my $server (@server_list) {
1.118 harris41 5799: unless ($custom or $customshow) {
5800: my $reply=&reply("querysend:".&escape($query),$server);
5801: $rhash{$server}=$reply;
5802: }
5803: else {
5804: my $reply=&reply("querysend:".&escape($query).':'.
5805: &escape($custom).':'.&escape($customshow),
5806: $server);
5807: $rhash{$server}=$reply;
5808: }
1.112 harris41 5809: }
1.118 harris41 5810: return \%rhash;
1.240 www 5811: }
5812:
5813: # ----------------------------------------- Send log queries and wait for reply
5814:
5815: sub log_query {
5816: my ($uname,$udom,$query,%filters)=@_;
5817: my $uhome=&homeserver($uname,$udom);
5818: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 5819: my $uhost=&hostname($uhome);
1.800 albertel 5820: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 5821: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5822: $uhome);
1.479 albertel 5823: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 5824: return get_query_reply($queryid);
5825: }
5826:
1.818 raeburn 5827: # -------------------------- Update MySQL table for portfolio file
5828:
5829: sub update_portfolio_table {
1.821 raeburn 5830: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 5831: if ($group ne '') {
5832: $file_name =~s /^\Q$group\E//;
5833: }
1.818 raeburn 5834: my $homeserver = &homeserver($uname,$udom);
5835: my $queryid=
1.821 raeburn 5836: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5837: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 5838: my $reply = &get_query_reply($queryid);
5839: return $reply;
5840: }
5841:
1.899 raeburn 5842: # -------------------------- Update MySQL allusers table
5843:
5844: sub update_allusers_table {
5845: my ($uname,$udom,$names) = @_;
5846: my $homeserver = &homeserver($uname,$udom);
5847: my $queryid=
5848: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5849: 'lastname='.&escape($names->{'lastname'}).'%%'.
5850: 'firstname='.&escape($names->{'firstname'}).'%%'.
5851: 'middlename='.&escape($names->{'middlename'}).'%%'.
5852: 'generation='.&escape($names->{'generation'}).'%%'.
5853: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5854: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 5855: return;
1.899 raeburn 5856: }
5857:
1.508 raeburn 5858: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 5859:
5860: sub fetch_enrollment_query {
1.511 raeburn 5861: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 5862: my $homeserver;
1.547 raeburn 5863: my $maxtries = 1;
1.508 raeburn 5864: if ($context eq 'automated') {
5865: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 5866: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 5867: } else {
5868: $homeserver = &homeserver($cnum,$dom);
5869: }
1.838 albertel 5870: my $host=&hostname($homeserver);
1.506 raeburn 5871: my $cmd = '';
1.1000 raeburn 5872: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 5873: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 5874: }
5875: $cmd =~ s/%%$//;
5876: $cmd = &escape($cmd);
5877: my $query = 'fetchenrollment';
1.620 albertel 5878: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 5879: unless ($queryid=~/^\Q$host\E\_/) {
5880: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5881: return 'error: '.$queryid;
5882: }
1.506 raeburn 5883: my $reply = &get_query_reply($queryid);
1.547 raeburn 5884: my $tries = 1;
5885: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5886: $reply = &get_query_reply($queryid);
5887: $tries ++;
5888: }
1.526 raeburn 5889: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 5890: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 5891: } else {
1.901 albertel 5892: my @responses = split(/:/,$reply);
1.515 raeburn 5893: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 5894: foreach my $line (@responses) {
5895: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 5896: $$replyref{$key} = $value;
5897: }
5898: } else {
1.506 raeburn 5899: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 5900: foreach my $line (@responses) {
5901: my ($key,$value) = split(/=/,$line);
1.506 raeburn 5902: $$replyref{$key} = $value;
5903: if ($value > 0) {
1.800 albertel 5904: foreach my $item (@{$$affiliatesref{$key}}) {
5905: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 5906: my $destname = $pathname.'/'.$filename;
5907: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 5908: if ($xml_classlist =~ /^error/) {
5909: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5910: } else {
1.506 raeburn 5911: if ( open(FILE,">$destname") ) {
5912: print FILE &unescape($xml_classlist);
5913: close(FILE);
1.526 raeburn 5914: } else {
5915: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 5916: }
5917: }
5918: }
5919: }
5920: }
5921: }
5922: return 'ok';
5923: }
5924: return 'error';
5925: }
5926:
1.242 www 5927: sub get_query_reply {
5928: my $queryid=shift;
1.240 www 5929: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5930: my $reply='';
5931: for (1..100) {
5932: sleep 2;
5933: if (-e $replyfile.'.end') {
1.448 albertel 5934: if (open(my $fh,$replyfile)) {
1.904 albertel 5935: $reply = join('',<$fh>);
5936: close($fh);
1.240 www 5937: } else { return 'error: reply_file_error'; }
1.242 www 5938: return &unescape($reply);
5939: }
1.240 www 5940: }
1.242 www 5941: return 'timeout:'.$queryid;
1.240 www 5942: }
5943:
5944: sub courselog_query {
1.241 www 5945: #
5946: # possible filters:
5947: # url: url or symb
5948: # username
5949: # domain
5950: # action: view, submit, grade
5951: # start: timestamp
5952: # end: timestamp
5953: #
1.240 www 5954: my (%filters)=@_;
1.620 albertel 5955: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 5956: if ($filters{'url'}) {
5957: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5958: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5959: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5960: }
1.620 albertel 5961: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5962: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 5963: return &log_query($cname,$cdom,'courselog',%filters);
5964: }
5965:
5966: sub userlog_query {
1.858 raeburn 5967: #
5968: # possible filters:
5969: # action: log check role
5970: # start: timestamp
5971: # end: timestamp
5972: #
1.240 www 5973: my ($uname,$udom,%filters)=@_;
5974: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 5975: }
5976:
1.506 raeburn 5977: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5978:
5979: sub auto_run {
1.508 raeburn 5980: my ($cnum,$cdom) = @_;
1.876 raeburn 5981: my $response = 0;
5982: my $settings;
5983: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5984: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5985: $settings = $domconfig{'autoenroll'};
5986: if ($settings->{'run'} eq '1') {
5987: $response = 1;
5988: }
5989: } else {
1.934 raeburn 5990: my $homeserver;
5991: if (&is_course($cdom,$cnum)) {
5992: $homeserver = &homeserver($cnum,$cdom);
5993: } else {
5994: $homeserver = &domain($cdom,'primary');
5995: }
5996: if ($homeserver ne 'no_host') {
5997: $response = &reply('autorun:'.$cdom,$homeserver);
5998: }
1.876 raeburn 5999: }
1.506 raeburn 6000: return $response;
6001: }
1.776 albertel 6002:
1.506 raeburn 6003: sub auto_get_sections {
1.508 raeburn 6004: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6005: my $homeserver;
6006: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6007: $homeserver = &homeserver($cnum,$cdom);
6008: }
6009: if (!defined($homeserver)) {
6010: if ($cdom =~ /^$match_domain$/) {
6011: $homeserver = &domain($cdom,'primary');
6012: }
6013: }
6014: my @secs;
6015: if (defined($homeserver)) {
6016: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6017: unless ($response eq 'refused') {
6018: @secs = split(/:/,$response);
6019: }
1.506 raeburn 6020: }
6021: return @secs;
6022: }
1.776 albertel 6023:
1.506 raeburn 6024: sub auto_new_course {
1.508 raeburn 6025: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
6026: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 6027: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 6028: return $response;
6029: }
1.776 albertel 6030:
1.506 raeburn 6031: sub auto_validate_courseID {
1.508 raeburn 6032: my ($cnum,$cdom,$inst_course_id) = @_;
6033: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6034: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6035: return $response;
6036: }
1.776 albertel 6037:
1.1007 raeburn 6038: sub auto_validate_instcode {
1.1020 raeburn 6039: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6040: my ($homeserver,$response);
6041: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6042: $homeserver = &homeserver($cnum,$cdom);
6043: }
6044: if (!defined($homeserver)) {
6045: if ($cdom =~ /^$match_domain$/) {
6046: $homeserver = &domain($cdom,'primary');
6047: }
6048: }
1.1065 raeburn 6049: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6050: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6051: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6052: return ($outcome,$description);
1.1007 raeburn 6053: }
6054:
1.506 raeburn 6055: sub auto_create_password {
1.873 raeburn 6056: my ($cnum,$cdom,$authparam,$udom) = @_;
6057: my ($homeserver,$response);
1.506 raeburn 6058: my $create_passwd = 0;
6059: my $authchk = '';
1.873 raeburn 6060: if ($udom =~ /^$match_domain$/) {
6061: $homeserver = &domain($udom,'primary');
6062: }
6063: if ($homeserver eq '') {
6064: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6065: $homeserver = &homeserver($cnum,$cdom);
6066: }
6067: }
6068: if ($homeserver eq '') {
6069: $authchk = 'nodomain';
1.506 raeburn 6070: } else {
1.873 raeburn 6071: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6072: if ($response eq 'refused') {
6073: $authchk = 'refused';
6074: } else {
1.901 albertel 6075: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6076: }
1.506 raeburn 6077: }
6078: return ($authparam,$create_passwd,$authchk);
6079: }
6080:
1.706 raeburn 6081: sub auto_photo_permission {
6082: my ($cnum,$cdom,$students) = @_;
6083: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6084: my ($outcome,$perm_reqd,$conditions) =
6085: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6086: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6087: return (undef,undef);
6088: }
1.706 raeburn 6089: return ($outcome,$perm_reqd,$conditions);
6090: }
6091:
6092: sub auto_checkphotos {
6093: my ($uname,$udom,$pid) = @_;
6094: my $homeserver = &homeserver($uname,$udom);
6095: my ($result,$resulttype);
6096: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6097: &escape($uname).':'.&escape($pid),
6098: $homeserver));
1.709 albertel 6099: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6100: return (undef,undef);
6101: }
1.706 raeburn 6102: if ($outcome) {
6103: ($result,$resulttype) = split(/:/,$outcome);
6104: }
6105: return ($result,$resulttype);
6106: }
6107:
6108: sub auto_photochoice {
6109: my ($cnum,$cdom) = @_;
6110: my $homeserver = &homeserver($cnum,$cdom);
6111: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6112: &escape($cdom),
6113: $homeserver)));
1.709 albertel 6114: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6115: return (undef,undef);
6116: }
1.706 raeburn 6117: return ($update,$comment);
6118: }
6119:
6120: sub auto_photoupdate {
6121: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6122: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6123: my $host=&hostname($homeserver);
1.706 raeburn 6124: my $cmd = '';
6125: my $maxtries = 1;
1.800 albertel 6126: foreach my $affiliate (keys(%{$affiliatesref})) {
6127: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6128: }
6129: $cmd =~ s/%%$//;
6130: $cmd = &escape($cmd);
6131: my $query = 'institutionalphotos';
6132: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6133: unless ($queryid=~/^\Q$host\E\_/) {
6134: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6135: return 'error: '.$queryid;
6136: }
6137: my $reply = &get_query_reply($queryid);
6138: my $tries = 1;
6139: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6140: $reply = &get_query_reply($queryid);
6141: $tries ++;
6142: }
6143: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6144: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6145: } else {
6146: my @responses = split(/:/,$reply);
6147: my $outcome = shift(@responses);
6148: foreach my $item (@responses) {
6149: my ($key,$value) = split(/=/,$item);
6150: $$photo{$key} = $value;
6151: }
6152: return $outcome;
6153: }
6154: return 'error';
6155: }
6156:
1.521 raeburn 6157: sub auto_instcode_format {
1.793 albertel 6158: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6159: $cat_order) = @_;
1.521 raeburn 6160: my $courses = '';
1.772 raeburn 6161: my @homeservers;
1.521 raeburn 6162: if ($caller eq 'global') {
1.841 albertel 6163: my %servers = &get_servers($codedom,'library');
6164: foreach my $tryserver (keys(%servers)) {
6165: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6166: push(@homeservers,$tryserver);
6167: }
1.584 raeburn 6168: }
1.1022 raeburn 6169: } elsif ($caller eq 'requests') {
6170: if ($codedom =~ /^$match_domain$/) {
6171: my $chome = &domain($codedom,'primary');
6172: unless ($chome eq 'no_host') {
6173: push(@homeservers,$chome);
6174: }
6175: }
1.521 raeburn 6176: } else {
1.772 raeburn 6177: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6178: }
1.793 albertel 6179: foreach my $code (keys(%{$instcodes})) {
6180: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6181: }
6182: chop($courses);
1.772 raeburn 6183: my $ok_response = 0;
6184: my $response;
6185: while (@homeservers > 0 && $ok_response == 0) {
6186: my $server = shift(@homeservers);
6187: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6188: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6189: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6190: split(/:/,$response);
1.772 raeburn 6191: %{$codes} = (%{$codes},&str2hash($codes_str));
6192: push(@{$codetitles},&str2array($codetitles_str));
6193: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6194: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6195: $ok_response = 1;
6196: }
6197: }
6198: if ($ok_response) {
1.521 raeburn 6199: return 'ok';
1.772 raeburn 6200: } else {
6201: return $response;
1.521 raeburn 6202: }
6203: }
6204:
1.792 raeburn 6205: sub auto_instcode_defaults {
6206: my ($domain,$returnhash,$code_order) = @_;
6207: my @homeservers;
1.841 albertel 6208:
6209: my %servers = &get_servers($domain,'library');
6210: foreach my $tryserver (keys(%servers)) {
6211: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6212: push(@homeservers,$tryserver);
6213: }
1.792 raeburn 6214: }
1.841 albertel 6215:
1.792 raeburn 6216: my $response;
1.841 albertel 6217: foreach my $server (@homeservers) {
1.792 raeburn 6218: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6219: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6220:
6221: foreach my $pair (split(/\&/,$response)) {
6222: my ($name,$value)=split(/\=/,$pair);
6223: if ($name eq 'code_order') {
6224: @{$code_order} = split(/\&/,&unescape($value));
6225: } else {
6226: $returnhash->{&unescape($name)}=&unescape($value);
6227: }
6228: }
6229: return 'ok';
1.792 raeburn 6230: }
1.841 albertel 6231:
6232: return $response;
1.1003 raeburn 6233: }
6234:
6235: sub auto_possible_instcodes {
1.1007 raeburn 6236: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6237: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6238: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6239: return;
6240: }
1.1003 raeburn 6241: my (@homeservers,$uhome);
6242: if (defined(&domain($domain,'primary'))) {
6243: $uhome=&domain($domain,'primary');
6244: push(@homeservers,&domain($domain,'primary'));
6245: } else {
6246: my %servers = &get_servers($domain,'library');
6247: foreach my $tryserver (keys(%servers)) {
6248: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6249: push(@homeservers,$tryserver);
6250: }
6251: }
6252: }
6253: my $response;
6254: foreach my $server (@homeservers) {
6255: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6256: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6257: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6258: split(':',$response);
6259: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6260: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6261: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6262: my ($name,$value)=split('=',$item);
6263: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6264: }
6265: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6266: my ($name,$value)=split('=',$item);
6267: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6268: }
6269: return 'ok';
6270: }
6271: return $response;
6272: }
1.792 raeburn 6273:
1.1010 raeburn 6274: sub auto_courserequest_checks {
6275: my ($dom) = @_;
1.1020 raeburn 6276: my ($homeserver,%validations);
6277: if ($dom =~ /^$match_domain$/) {
6278: $homeserver = &domain($dom,'primary');
6279: }
6280: unless ($homeserver eq 'no_host') {
6281: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6282: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6283: my @items = split(/&/,$response);
6284: foreach my $item (@items) {
6285: my ($key,$value) = split('=',$item);
6286: $validations{&unescape($key)} = &thaw_unescape($value);
6287: }
6288: }
6289: }
1.1010 raeburn 6290: return %validations;
6291: }
6292:
1.1020 raeburn 6293: sub auto_courserequest_validation {
6294: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6295: my ($homeserver,$response);
6296: if ($dom =~ /^$match_domain$/) {
6297: $homeserver = &domain($dom,'primary');
6298: }
6299: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6300:
1.1020 raeburn 6301: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6302: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6303: ':'.&escape($instcode).':'.&escape($instseclist),
6304: $homeserver));
6305: }
6306: return $response;
6307: }
6308:
1.777 albertel 6309: sub auto_validate_class_sec {
1.918 raeburn 6310: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6311: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6312: my $ownerlist;
6313: if (ref($owners) eq 'ARRAY') {
6314: $ownerlist = join(',',@{$owners});
6315: } else {
6316: $ownerlist = $owners;
6317: }
1.773 raeburn 6318: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6319: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6320: return $response;
6321: }
6322:
1.679 raeburn 6323: # ------------------------------------------------------- Course Group routines
6324:
6325: sub get_coursegroups {
1.809 raeburn 6326: my ($cdom,$cnum,$group,$namespace) = @_;
6327: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6328: }
6329:
1.679 raeburn 6330: sub modify_coursegroup {
6331: my ($cdom,$cnum,$groupsettings) = @_;
6332: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6333: }
6334:
1.809 raeburn 6335: sub toggle_coursegroup_status {
6336: my ($cdom,$cnum,$group,$action) = @_;
6337: my ($from_namespace,$to_namespace);
6338: if ($action eq 'delete') {
6339: $from_namespace = 'coursegroups';
6340: $to_namespace = 'deleted_groups';
6341: } else {
6342: $from_namespace = 'deleted_groups';
6343: $to_namespace = 'coursegroups';
6344: }
6345: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6346: if (my $tmp = &error(%curr_group)) {
6347: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6348: return ('read error',$tmp);
6349: } else {
6350: my %savedsettings = %curr_group;
1.809 raeburn 6351: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6352: my $deloutcome;
6353: if ($result eq 'ok') {
1.809 raeburn 6354: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6355: } else {
6356: return ('write error',$result);
6357: }
6358: if ($deloutcome eq 'ok') {
6359: return 'ok';
6360: } else {
6361: return ('delete error',$deloutcome);
6362: }
6363: }
6364: }
6365:
1.679 raeburn 6366: sub modify_group_roles {
1.957 raeburn 6367: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6368: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6369: my $role = 'gr/'.&escape($userprivs);
6370: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6371: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6372: if ($result eq 'ok') {
6373: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6374: }
1.679 raeburn 6375: return $result;
6376: }
6377:
6378: sub modify_coursegroup_membership {
6379: my ($cdom,$cnum,$membership) = @_;
6380: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6381: return $result;
6382: }
6383:
1.682 raeburn 6384: sub get_active_groups {
6385: my ($udom,$uname,$cdom,$cnum) = @_;
6386: my $now = time;
6387: my %groups = ();
6388: foreach my $key (keys(%env)) {
1.811 albertel 6389: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6390: my ($start,$end) = split(/\./,$env{$key});
6391: if (($end!=0) && ($end<$now)) { next; }
6392: if (($start!=0) && ($start>$now)) { next; }
6393: if ($1 eq $cdom && $2 eq $cnum) {
6394: $groups{$3} = $env{$key} ;
6395: }
6396: }
6397: }
6398: return %groups;
6399: }
6400:
1.683 raeburn 6401: sub get_group_membership {
6402: my ($cdom,$cnum,$group) = @_;
6403: return(&dump('groupmembership',$cdom,$cnum,$group));
6404: }
6405:
6406: sub get_users_groups {
6407: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6408: my @usersgroups;
1.683 raeburn 6409: my $cachetime=1800;
6410:
6411: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6412: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6413: if (defined($cached)) {
1.734 albertel 6414: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6415: } else {
6416: $grouplist = '';
1.816 raeburn 6417: my $courseurl = &courseid_to_courseurl($courseid);
1.1086 raeburn 6418: my $extra = &freeze_escape({'skipcheck' => 1});
6419: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6420: my $access_end = $env{'course.'.$courseid.
6421: '.default_enrollment_end_date'};
6422: my $now = time;
6423: foreach my $key (keys(%roleshash)) {
6424: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6425: my $group = $1;
6426: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6427: my $start = $2;
6428: my $end = $1;
6429: if ($start == -1) { next; } # deleted from group
6430: if (($start!=0) && ($start>$now)) { next; }
6431: if (($end!=0) && ($end<$now)) {
6432: if ($access_end && $access_end < $now) {
6433: if ($access_end - $end < 86400) {
6434: push(@usersgroups,$group);
1.733 raeburn 6435: }
6436: }
1.817 raeburn 6437: next;
1.733 raeburn 6438: }
1.817 raeburn 6439: push(@usersgroups,$group);
1.683 raeburn 6440: }
6441: }
6442: }
1.817 raeburn 6443: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6444: $grouplist = join(':',@usersgroups);
6445: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6446: }
1.733 raeburn 6447: return @usersgroups;
1.683 raeburn 6448: }
6449:
6450: sub devalidate_getgroups_cache {
6451: my ($udom,$uname,$cdom,$cnum)=@_;
6452: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6453:
1.683 raeburn 6454: my $hashid="$udom:$uname:$courseid";
6455: &devalidate_cache_new('getgroups',$hashid);
6456: }
6457:
1.12 www 6458: # ------------------------------------------------------------------ Plain Text
6459:
6460: sub plaintext {
1.988 raeburn 6461: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6462: if ($short =~ m{^cr/}) {
1.758 albertel 6463: return (split('/',$short))[-1];
6464: }
1.742 raeburn 6465: if (!defined($cid)) {
6466: $cid = $env{'request.course.id'};
6467: }
6468: my %rolenames = (
1.1008 raeburn 6469: Course => 'std',
6470: Community => 'alt1',
1.742 raeburn 6471: );
1.1037 raeburn 6472: if ($cid ne '') {
6473: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6474: unless ($forcedefault) {
6475: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6476: &Apache::lonlocal::mt_escape(\$roletext);
6477: return &Apache::lonlocal::mt($roletext);
6478: }
6479: }
6480: }
6481: if ((defined($type)) && (defined($rolenames{$type})) &&
6482: (defined($rolenames{$type})) &&
6483: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6484: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6485: } elsif ($cid ne '') {
6486: my $crstype = $env{'course.'.$cid.'.type'};
6487: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6488: (defined($prp{$short}{$rolenames{$crstype}}))) {
6489: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6490: }
1.742 raeburn 6491: }
1.1037 raeburn 6492: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6493: }
6494:
6495: # ----------------------------------------------------------------- Assign Role
6496:
6497: sub assignrole {
1.957 raeburn 6498: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6499: $context)=@_;
1.21 www 6500: my $mrole;
6501: if ($role =~ /^cr\//) {
1.393 www 6502: my $cwosec=$url;
1.811 albertel 6503: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 6504: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 6505: my $refused = 1;
6506: if ($context eq 'requestcourses') {
6507: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6508: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6509: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6510: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6511: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6512: if ($crsenv{'internal.courseowner'} eq
6513: $env{'user.name'}.':'.$env{'user.domain'}) {
6514: $refused = '';
6515: }
6516: }
6517: }
6518: }
6519: }
6520: if ($refused) {
6521: &logthis('Refused custom assignrole: '.
6522: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6523: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6524: return 'refused';
6525: }
1.104 www 6526: }
1.21 www 6527: $mrole='cr';
1.678 raeburn 6528: } elsif ($role =~ /^gr\//) {
6529: my $cwogrp=$url;
1.811 albertel 6530: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 6531: unless (&allowed('mdg',$cwogrp)) {
6532: &logthis('Refused group assignrole: '.
6533: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6534: $env{'user.name'}.' at '.$env{'user.domain'});
6535: return 'refused';
6536: }
6537: $mrole='gr';
1.21 www 6538: } else {
1.82 www 6539: my $cwosec=$url;
1.811 albertel 6540: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 6541: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6542: my $refused;
6543: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6544: if (!(&allowed('c'.$role,$url))) {
6545: $refused = 1;
6546: }
6547: } else {
6548: $refused = 1;
6549: }
1.947 raeburn 6550: if ($refused) {
1.1045 raeburn 6551: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6552: if (!$selfenroll && $context eq 'course') {
6553: my %crsenv;
6554: if ($role eq 'cc' || $role eq 'co') {
6555: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6556: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
6557: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
6558: if ($crsenv{'internal.courseowner'} eq
6559: $env{'user.name'}.':'.$env{'user.domain'}) {
6560: $refused = '';
6561: }
6562: }
6563: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
6564: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
6565: if ($crsenv{'internal.courseowner'} eq
6566: $env{'user.name'}.':'.$env{'user.domain'}) {
6567: $refused = '';
6568: }
6569: }
6570: }
6571: }
6572: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 6573: $refused = '';
1.1017 raeburn 6574: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 6575: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 6576: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 6577: my $wrongcc;
6578: if ($cnum =~ /^$match_community$/) {
6579: $wrongcc = 1 if ($role eq 'cc');
6580: } else {
6581: $wrongcc = 1 if ($role eq 'co');
6582: }
6583: unless ($wrongcc) {
6584: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6585: if ($crsenv{'internal.courseowner'} eq
6586: $env{'user.name'}.':'.$env{'user.domain'}) {
6587: $refused = '';
6588: }
1.1017 raeburn 6589: }
6590: }
6591: }
6592: if ($refused) {
1.947 raeburn 6593: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6594: ' '.$role.' '.$end.' '.$start.' by '.
6595: $env{'user.name'}.' at '.$env{'user.domain'});
6596: return 'refused';
6597: }
1.932 raeburn 6598: }
1.104 www 6599: }
1.21 www 6600: $mrole=$role;
6601: }
1.620 albertel 6602: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6603: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 6604: if ($end) { $command.='_'.$end; }
1.21 www 6605: if ($start) {
6606: if ($end) {
1.81 www 6607: $command.='_'.$start;
1.21 www 6608: } else {
1.81 www 6609: $command.='_0_'.$start;
1.21 www 6610: }
6611: }
1.739 raeburn 6612: my $origstart = $start;
6613: my $origend = $end;
1.957 raeburn 6614: my $delflag;
1.357 www 6615: # actually delete
6616: if ($deleteflag) {
1.373 www 6617: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 6618: # modify command to delete the role
1.620 albertel 6619: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 6620: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 6621: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 6622: # set start and finish to negative values for userrolelog
6623: $start=-1;
6624: $end=-1;
1.957 raeburn 6625: $delflag = 1;
1.357 www 6626: }
6627: }
6628: # send command
1.349 www 6629: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 6630: # log new user role if status is ok
1.349 www 6631: if ($answer eq 'ok') {
1.663 raeburn 6632: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 6633: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 6634: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 6635: unless ($role =~ /^gr/) {
6636: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 6637: $origstart,$selfenroll,$context);
1.739 raeburn 6638: }
1.1053 raeburn 6639: if ($role eq 'cc') {
6640: &autoupdate_coowners($url,$end,$start,$uname,$udom);
6641: }
1.349 www 6642: }
6643: return $answer;
1.169 harris41 6644: }
6645:
1.1053 raeburn 6646: sub autoupdate_coowners {
6647: my ($url,$end,$start,$uname,$udom) = @_;
6648: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
6649: if (($cdom ne '') && ($cnum ne '')) {
6650: my $now = time;
6651: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
6652: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
6653: my %coursehash = &coursedescription($cdom.'_'.$cnum);
6654: my $instcode = $coursehash{'internal.coursecode'};
6655: if ($instcode ne '') {
1.1056 raeburn 6656: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
6657: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 6658: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 6659: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
6660: if ($result eq 'valid') {
6661: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 6662: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6663: push(@newcoowners,$coowner);
6664: }
6665: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
6666: push(@newcoowners,$uname.':'.$udom);
6667: }
6668: @newcoowners = sort(@newcoowners);
6669: } else {
6670: push(@newcoowners,$uname.':'.$udom);
6671: }
6672: } else {
6673: if ($coursehash{'internal.co-owners'}) {
6674: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
6675: unless ($coowner eq $uname.':'.$udom) {
6676: push(@newcoowners,$coowner);
6677: }
6678: }
6679: unless (@newcoowners > 0) {
6680: $delcoowners = 1;
6681: $coowners = '';
6682: }
6683: }
6684: }
6685: if (@newcoowners || $delcoowners) {
6686: &store_coowners($cdom,$cnum,$coursehash{'home'},
6687: $delcoowners,@newcoowners);
6688: }
6689: }
6690: }
6691: }
6692: }
6693: }
6694: }
6695:
6696: sub store_coowners {
6697: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
6698: my $cid = $cdom.'_'.$cnum;
6699: my ($coowners,$delresult,$putresult);
6700: if (@newcoowners) {
6701: $coowners = join(',',@newcoowners);
6702: my %coownershash = (
6703: 'internal.co-owners' => $coowners,
6704: );
6705: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
6706: if ($putresult eq 'ok') {
6707: if ($env{'course.'.$cid.'.num'} eq $cnum) {
6708: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
6709: }
6710: }
6711: }
6712: if ($delcoowners) {
6713: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
6714: if ($delresult eq 'ok') {
6715: if ($env{'course.'.$cid.'.internal.co-owners'}) {
6716: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
6717: }
6718: }
6719: }
6720: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
6721: my %crsinfo =
6722: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6723: if (ref($crsinfo{$cid}) eq 'HASH') {
6724: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
6725: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
6726: }
6727: }
6728: }
6729:
1.169 harris41 6730: # -------------------------------------------------- Modify user authentication
1.197 www 6731: # Overrides without validation
6732:
1.169 harris41 6733: sub modifyuserauth {
6734: my ($udom,$uname,$umode,$upass)=@_;
6735: my $uhome=&homeserver($uname,$udom);
1.197 www 6736: unless (&allowed('mau',$udom)) { return 'refused'; }
6737: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 6738: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6739: ' in domain '.$env{'request.role.domain'});
1.169 harris41 6740: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6741: &escape($upass),$uhome);
1.620 albertel 6742: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 6743: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6744: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6745: &log($udom,,$uname,$uhome,
1.620 albertel 6746: 'Authentication changed by '.$env{'user.domain'}.', '.
6747: $env{'user.name'}.', '.$umode.
1.197 www 6748: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 6749: unless ($reply eq 'ok') {
1.197 www 6750: &logthis('Authentication mode error: '.$reply);
1.169 harris41 6751: return 'error: '.$reply;
6752: }
1.170 harris41 6753: return 'ok';
1.80 www 6754: }
6755:
1.81 www 6756: # --------------------------------------------------------------- Modify a user
1.80 www 6757:
1.81 www 6758: sub modifyuser {
1.206 matthew 6759: my ($udom, $uname, $uid,
6760: $umode, $upass, $first,
6761: $middle, $last, $gene,
1.1058 raeburn 6762: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 6763: $udom= &LONCAPA::clean_domain($udom);
6764: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 6765: my $showcandelete = 'none';
6766: if (ref($candelete) eq 'ARRAY') {
6767: if (@{$candelete} > 0) {
6768: $showcandelete = join(', ',@{$candelete});
6769: }
6770: }
1.81 www 6771: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 6772: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 6773: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 6774: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6775: ' desiredhome not specified').
1.620 albertel 6776: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6777: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 6778: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 6779: my $newuser;
6780: if ($uhome eq 'no_host') {
6781: $newuser = 1;
6782: }
1.80 www 6783: # ----------------------------------------------------------------- Create User
1.406 albertel 6784: if (($uhome eq 'no_host') &&
6785: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 6786: my $unhome='';
1.844 albertel 6787: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 6788: $unhome = $desiredhome;
1.620 albertel 6789: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6790: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 6791: } else { # load balancing routine for determining $unhome
1.81 www 6792: my $loadm=10000000;
1.841 albertel 6793: my %servers = &get_servers($udom,'library');
6794: foreach my $tryserver (keys(%servers)) {
6795: my $answer=reply('load',$tryserver);
6796: if (($answer=~/\d+/) && ($answer<$loadm)) {
6797: $loadm=$answer;
6798: $unhome=$tryserver;
6799: }
1.80 www 6800: }
6801: }
6802: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 6803: return 'error: unable to find a home server for '.$uname.
6804: ' in domain '.$udom;
1.80 www 6805: }
6806: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6807: &escape($upass),$unhome);
6808: unless ($reply eq 'ok') {
6809: return 'error: '.$reply;
6810: }
1.230 stredwic 6811: $uhome=&homeserver($uname,$udom,'true');
1.80 www 6812: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 6813: return 'error: unable verify users home machine.';
1.80 www 6814: }
1.209 matthew 6815: } # End of creation of new user
1.80 www 6816: # ---------------------------------------------------------------------- Add ID
6817: if ($uid) {
6818: $uid=~tr/A-Z/a-z/;
6819: my %uidhash=&idrget($udom,$uname);
1.196 www 6820: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6821: && (!$forceid)) {
1.80 www 6822: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 6823: return 'error: user id "'.$uid.'" does not match '.
6824: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 6825: }
6826: } else {
6827: &idput($udom,($uname => $uid));
6828: }
6829: }
6830: # -------------------------------------------------------------- Add names, etc
1.313 matthew 6831: my @tmp=&get('environment',
1.899 raeburn 6832: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 6833: 'permanentemail','inststatus'],
1.134 albertel 6834: $udom,$uname);
1.1075 raeburn 6835: my (%names,%oldnames);
1.313 matthew 6836: if ($tmp[0] =~ m/^error:.*/) {
6837: %names=();
6838: } else {
6839: %names = @tmp;
1.1075 raeburn 6840: %oldnames = %names;
1.313 matthew 6841: }
1.388 www 6842: #
1.1058 raeburn 6843: # If name, email and/or uid are blank (e.g., because an uploaded file
6844: # of users did not contain them), do not overwrite existing values
6845: # unless field is in $candelete array ref.
6846: #
6847:
6848: my @fields = ('firstname','middlename','lastname','generation',
6849: 'permanentemail','id');
6850: my %newvalues;
6851: if (ref($candelete) eq 'ARRAY') {
6852: foreach my $field (@fields) {
6853: if (grep(/^\Q$field\E$/,@{$candelete})) {
6854: if ($field eq 'firstname') {
6855: $names{$field} = $first;
6856: } elsif ($field eq 'middlename') {
6857: $names{$field} = $middle;
6858: } elsif ($field eq 'lastname') {
6859: $names{$field} = $last;
6860: } elsif ($field eq 'generation') {
6861: $names{$field} = $gene;
6862: } elsif ($field eq 'permanentemail') {
6863: $names{$field} = $email;
6864: } elsif ($field eq 'id') {
6865: $names{$field} = $uid;
6866: }
6867: }
6868: }
6869: }
1.388 www 6870: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 6871: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 6872: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 6873: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 6874: if ($email) {
6875: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 6876: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 6877: }
1.899 raeburn 6878: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 6879: if (defined($inststatus)) {
6880: $names{'inststatus'} = '';
6881: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6882: if (ref($usertypes) eq 'HASH') {
6883: my @okstatuses;
6884: foreach my $item (split(/:/,$inststatus)) {
6885: if (defined($usertypes->{$item})) {
6886: push(@okstatuses,$item);
6887: }
6888: }
6889: if (@okstatuses) {
6890: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6891: }
6892: }
6893: }
1.1075 raeburn 6894: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 6895: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 6896: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 6897: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6898: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6899: } else {
6900: $logmsg .= ' during self creation';
6901: }
1.1075 raeburn 6902: my $changed;
6903: if ($newuser) {
6904: $changed = 1;
6905: } else {
6906: foreach my $field (@fields) {
6907: if ($names{$field} ne $oldnames{$field}) {
6908: $changed = 1;
6909: last;
6910: }
6911: }
6912: }
6913: unless ($changed) {
6914: $logmsg = 'No changes in user information needed for: '.$logmsg;
6915: &logthis($logmsg);
6916: return 'ok';
6917: }
6918: my $reply = &put('environment', \%names, $udom,$uname);
6919: if ($reply ne 'ok') {
6920: return 'error: '.$reply;
6921: }
1.1087 raeburn 6922: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
6923: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
6924: }
1.1075 raeburn 6925: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
6926: &devalidate_cache_new('namescache',$uname.':'.$udom);
6927: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 6928: &logthis($logmsg);
1.134 albertel 6929: return 'ok';
1.80 www 6930: }
6931:
1.81 www 6932: # -------------------------------------------------------------- Modify student
1.80 www 6933:
1.81 www 6934: sub modifystudent {
6935: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 6936: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 6937: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 6938: if (!$cid) {
1.620 albertel 6939: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6940: return 'not_in_class';
6941: }
1.80 www 6942: }
6943: # --------------------------------------------------------------- Make the user
1.81 www 6944: my $reply=&modifyuser
1.209 matthew 6945: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 6946: $desiredhome,$email,$inststatus);
1.80 www 6947: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 6948: # This will cause &modify_student_enrollment to get the uid from the
6949: # students environment
6950: $uid = undef if (!$forceid);
1.455 albertel 6951: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 6952: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 6953: return $reply;
6954: }
6955:
6956: sub modify_student_enrollment {
1.957 raeburn 6957: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 6958: my ($cdom,$cnum,$chome);
6959: if (!$cid) {
1.620 albertel 6960: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 6961: return 'not_in_class';
6962: }
1.620 albertel 6963: $cdom=$env{'course.'.$cid.'.domain'};
6964: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 6965: } else {
6966: ($cdom,$cnum)=split(/_/,$cid);
6967: }
1.620 albertel 6968: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 6969: if (!$chome) {
1.457 raeburn 6970: $chome=&homeserver($cnum,$cdom);
1.297 matthew 6971: }
1.455 albertel 6972: if (!$chome) { return 'unknown_course'; }
1.297 matthew 6973: # Make sure the user exists
1.81 www 6974: my $uhome=&homeserver($uname,$udom);
6975: if (($uhome eq '') || ($uhome eq 'no_host')) {
6976: return 'error: no such user';
6977: }
1.297 matthew 6978: # Get student data if we were not given enough information
6979: if (!defined($first) || $first eq '' ||
6980: !defined($last) || $last eq '' ||
6981: !defined($uid) || $uid eq '' ||
6982: !defined($middle) || $middle eq '' ||
6983: !defined($gene) || $gene eq '') {
1.294 matthew 6984: # They did not supply us with enough data to enroll the student, so
6985: # we need to pick up more information.
1.297 matthew 6986: my %tmp = &get('environment',
1.294 matthew 6987: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 6988: ,$udom,$uname);
6989:
1.800 albertel 6990: #foreach my $key (keys(%tmp)) {
6991: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 6992: #}
1.294 matthew 6993: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6994: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6995: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 6996: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 6997: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6998: }
1.556 albertel 6999: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 7000: my $reply=cput('classlist',
7001: {"$uname:$udom" =>
1.515 raeburn 7002: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7003: $cdom,$cnum);
1.81 www 7004: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7005: return 'error: '.$reply;
1.652 albertel 7006: } else {
7007: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 7008: }
1.297 matthew 7009: # Add student role to user
1.83 www 7010: my $uurl='/'.$cid;
1.81 www 7011: $uurl=~s/\_/\//g;
7012: if ($usec) {
7013: $uurl.='/'.$usec;
7014: }
1.957 raeburn 7015: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 7016: }
7017:
1.556 albertel 7018: sub format_name {
7019: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7020: my $name;
7021: if ($first ne 'lastname') {
7022: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7023: } else {
7024: if ($lastname=~/\S/) {
7025: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7026: $name=~s/\s+,/,/;
7027: } else {
7028: $name.= $firstname.' '.$middlename.' '.$generation;
7029: }
7030: }
7031: $name=~s/^\s+//;
7032: $name=~s/\s+$//;
7033: $name=~s/\s+/ /g;
7034: return $name;
7035: }
7036:
1.84 www 7037: # ------------------------------------------------- Write to course preferences
7038:
7039: sub writecoursepref {
7040: my ($courseid,%prefs)=@_;
7041: $courseid=~s/^\///;
7042: $courseid=~s/\_/\//g;
7043: my ($cdomain,$cnum)=split(/\//,$courseid);
7044: my $chome=homeserver($cnum,$cdomain);
7045: if (($chome eq '') || ($chome eq 'no_host')) {
7046: return 'error: no such course';
7047: }
7048: my $cstring='';
1.800 albertel 7049: foreach my $pref (keys(%prefs)) {
7050: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7051: }
1.84 www 7052: $cstring=~s/\&$//;
7053: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7054: }
7055:
7056: # ---------------------------------------------------------- Make/modify course
7057:
7058: sub createcourse {
1.741 raeburn 7059: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7060: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7061: $url=&declutter($url);
7062: my $cid='';
1.1028 raeburn 7063: if ($context eq 'requestcourses') {
7064: my $can_create = 0;
7065: my ($ownername,$ownerdom) = split(':',$course_owner);
7066: if ($udom eq $ownerdom) {
7067: if (&usertools_access($ownername,$ownerdom,$category,undef,
7068: $context)) {
7069: $can_create = 1;
7070: }
7071: } else {
7072: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7073: $category);
7074: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7075: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7076: if (@curr > 0) {
7077: my @options = qw(approval validate autolimit);
7078: my $optregex = join('|',@options);
7079: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7080: $can_create = 1;
7081: }
7082: }
7083: }
7084: }
7085: if ($can_create) {
7086: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7087: unless (&allowed('ccc',$udom)) {
7088: return 'refused';
7089: }
1.1017 raeburn 7090: }
7091: } else {
7092: return 'refused';
7093: }
1.1028 raeburn 7094: } elsif (!&allowed('ccc',$udom)) {
7095: return 'refused';
1.84 www 7096: }
1.1011 raeburn 7097: # --------------------------------------------------------------- Get Unique ID
7098: my $uname;
7099: if ($cnum =~ /^$match_courseid$/) {
7100: my $chome=&homeserver($cnum,$udom,'true');
7101: if (($chome eq '') || ($chome eq 'no_host')) {
7102: $uname = $cnum;
7103: } else {
1.1038 raeburn 7104: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7105: }
7106: } else {
1.1038 raeburn 7107: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7108: }
7109: return $uname if ($uname =~ /^error/);
7110: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7111: if (!defined($course_server)) {
7112: if (defined(&domain($udom,'primary'))) {
7113: $course_server = &domain($udom,'primary');
7114: } else {
7115: $course_server = $env{'user.home'};
7116: }
7117: }
7118: my %host_servers =
7119: &Apache::lonnet::get_servers($udom,'library');
7120: unless ($host_servers{$course_server}) {
7121: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7122: }
1.84 www 7123: # ------------------------------------------------------------- Make the course
7124: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7125: $course_server);
1.84 www 7126: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7127: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7128: if (($uhome eq '') || ($uhome eq 'no_host')) {
7129: return 'error: no such course';
7130: }
1.271 www 7131: # ----------------------------------------------------------------- Course made
1.516 raeburn 7132: # log existence
1.1029 raeburn 7133: my $now = time;
1.918 raeburn 7134: my $newcourse = {
7135: $udom.'_'.$uname => {
1.921 raeburn 7136: description => $description,
7137: inst_code => $inst_code,
7138: owner => $course_owner,
7139: type => $crstype,
1.1029 raeburn 7140: creator => $env{'user.name'}.':'.
7141: $env{'user.domain'},
7142: created => $now,
7143: context => $context,
1.918 raeburn 7144: },
7145: };
1.921 raeburn 7146: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7147: # set toplevel url
1.271 www 7148: my $topurl=$url;
7149: unless ($nonstandard) {
7150: # ------------------------------------------ For standard courses, make top url
7151: my $mapurl=&clutter($url);
1.278 www 7152: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7153: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7154: <map>
7155: <resource id="1" type="start"></resource>
7156: <resource id="2" src="$mapurl"></resource>
7157: <resource id="3" type="finish"></resource>
7158: <link index="1" from="1" to="2"></link>
7159: <link index="2" from="2" to="3"></link>
7160: </map>
7161: ENDINITMAP
7162: $topurl=&declutter(
1.638 albertel 7163: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7164: );
7165: }
7166: # ----------------------------------------------------------- Write preferences
1.84 www 7167: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7168: ('description' => $description,
7169: 'url' => $topurl,
7170: 'internal.creator' => $env{'user.name'}.':'.
7171: $env{'user.domain'},
7172: 'internal.created' => $now,
7173: 'internal.creationcontext' => $context)
7174: );
1.84 www 7175: return '/'.$udom.'/'.$uname;
7176: }
7177:
1.1011 raeburn 7178: # ------------------------------------------------------------------- Create ID
7179: sub generate_coursenum {
1.1038 raeburn 7180: my ($udom,$crstype) = @_;
1.1011 raeburn 7181: my $domdesc = &domain($udom);
7182: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7183: my $first;
7184: if ($crstype eq 'Community') {
7185: $first = '0';
7186: } else {
7187: $first = int(1+rand(9));
7188: }
7189: my $uname=$first.
1.1011 raeburn 7190: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7191: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7192: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7193: # ----------------------------------------------- Make sure that does not exist
7194: my $uhome=&homeserver($uname,$udom,'true');
7195: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7196: if ($crstype eq 'Community') {
7197: $first = '0';
7198: } else {
7199: $first = int(1+rand(9));
7200: }
7201: $uname=$first.
1.1011 raeburn 7202: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7203: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7204: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7205: $uhome=&homeserver($uname,$udom,'true');
7206: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7207: return 'error: unable to generate unique course-ID';
7208: }
7209: }
7210: return $uname;
7211: }
7212:
1.813 albertel 7213: sub is_course {
7214: my ($cdom,$cnum) = @_;
7215: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7216: undef,'.');
1.813 albertel 7217: if (exists($courses{$cdom.'_'.$cnum})) {
7218: return 1;
7219: }
7220: return 0;
7221: }
7222:
1.1015 raeburn 7223: sub store_userdata {
7224: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7225: my $result;
1.1016 raeburn 7226: if ($datakey ne '') {
1.1013 raeburn 7227: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7228: if ($udom eq '' || $uname eq '') {
7229: $udom = $env{'user.domain'};
7230: $uname = $env{'user.name'};
7231: }
7232: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7233: if (($uhome eq '') || ($uhome eq 'no_host')) {
7234: $result = 'error: no_host';
7235: } else {
7236: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7237: $storehash->{'host'} = $perlvar{'lonHostID'};
7238:
7239: my $namevalue='';
7240: foreach my $key (keys(%{$storehash})) {
7241: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7242: }
7243: $namevalue=~s/\&$//;
7244: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
1.1015 raeburn 7245: "$namespace:$datakey:$namevalue",$uhome);
1.1013 raeburn 7246: }
7247: } else {
7248: $result = 'error: data to store was not a hash reference';
7249: }
7250: } else {
7251: $result= 'error: invalid requestkey';
7252: }
7253: return $result;
7254: }
7255:
1.21 www 7256: # ---------------------------------------------------------- Assign Custom Role
7257:
7258: sub assigncustomrole {
1.957 raeburn 7259: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7260: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7261: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7262: }
7263:
7264: # ----------------------------------------------------------------- Revoke Role
7265:
7266: sub revokerole {
1.957 raeburn 7267: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7268: my $now=time;
1.965 raeburn 7269: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7270: }
7271:
7272: # ---------------------------------------------------------- Revoke Custom Role
7273:
7274: sub revokecustomrole {
1.957 raeburn 7275: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7276: my $now=time;
1.357 www 7277: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7278: $deleteflag,$selfenroll,$context);
1.17 www 7279: }
7280:
1.533 banghart 7281: # ------------------------------------------------------------ Disk usage
1.535 albertel 7282: sub diskusage {
1.955 raeburn 7283: my ($udom,$uname,$directorypath,$getpropath)=@_;
7284: $directorypath =~ s/\/$//;
7285: my $listing=&reply('du2:'.&escape($directorypath).':'
7286: .&escape($getpropath).':'.&escape($uname).':'
7287: .&escape($udom),homeserver($uname,$udom));
7288: if ($listing eq 'unknown_cmd') {
7289: if ($getpropath) {
7290: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7291: }
7292: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7293: }
1.514 albertel 7294: return $listing;
1.512 banghart 7295: }
7296:
1.566 banghart 7297: sub is_locked {
7298: my ($file_name, $domain, $user) = @_;
7299: my @check;
7300: my $is_locked;
1.1093 raeburn 7301: push (@check,$file_name);
1.613 albertel 7302: my %locked = &get('file_permissions',\@check,
1.620 albertel 7303: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7304: my ($tmp)=keys(%locked);
7305: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7306:
1.566 banghart 7307: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7308: $is_locked = 'false';
7309: foreach my $entry (@{$locked{$file_name}}) {
7310: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7311: $is_locked = 'true';
7312: last;
1.745 raeburn 7313: }
7314: }
1.566 banghart 7315: } else {
7316: $is_locked = 'false';
7317: }
1.1093 raeburn 7318: return $is_locked;
1.566 banghart 7319: }
7320:
1.759 albertel 7321: sub declutter_portfile {
7322: my ($file) = @_;
1.833 albertel 7323: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7324: return $file;
7325: }
7326:
1.559 banghart 7327: # ------------------------------------------------------------- Mark as Read Only
7328:
7329: sub mark_as_readonly {
7330: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7331: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7332: my ($tmp)=keys(%current_permissions);
7333: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7334: foreach my $file (@{$files}) {
1.759 albertel 7335: $file = &declutter_portfile($file);
1.561 banghart 7336: push(@{$current_permissions{$file}},$what);
1.559 banghart 7337: }
1.613 albertel 7338: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7339: return;
7340: }
7341:
1.572 banghart 7342: # ------------------------------------------------------------Save Selected Files
7343:
7344: sub save_selected_files {
7345: my ($user, $path, @files) = @_;
7346: my $filename = $user."savedfiles";
1.573 banghart 7347: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7348: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7349: foreach my $file (@files) {
1.620 albertel 7350: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7351: }
7352: foreach my $file (@other_files) {
1.574 banghart 7353: print (OUT $file."\n");
1.572 banghart 7354: }
1.574 banghart 7355: close (OUT);
1.572 banghart 7356: return 'ok';
7357: }
7358:
1.574 banghart 7359: sub clear_selected_files {
7360: my ($user) = @_;
7361: my $filename = $user."savedfiles";
7362: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7363: print (OUT undef);
7364: close (OUT);
7365: return ("ok");
7366: }
7367:
1.572 banghart 7368: sub files_in_path {
7369: my ($user, $path) = @_;
7370: my $filename = $user."savedfiles";
7371: my %return_files;
1.574 banghart 7372: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 7373: while (my $line_in = <IN>) {
1.574 banghart 7374: chomp ($line_in);
7375: my @paths_and_file = split (m!/!, $line_in);
7376: my $file_part = pop (@paths_and_file);
7377: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7378: $path_part.='/';
7379: my $path_and_file = $path_part.$file_part;
7380: if ($path_part eq $path) {
7381: $return_files{$file_part}= 'selected';
7382: }
7383: }
1.574 banghart 7384: close (IN);
7385: return (\%return_files);
1.572 banghart 7386: }
7387:
7388: # called in portfolio select mode, to show files selected NOT in current directory
7389: sub files_not_in_path {
7390: my ($user, $path) = @_;
7391: my $filename = $user."savedfiles";
7392: my @return_files;
7393: my $path_part;
1.800 albertel 7394: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
7395: while (my $line = <IN>) {
1.572 banghart 7396: #ok, I know it's clunky, but I want it to work
1.800 albertel 7397: my @paths_and_file = split(m|/|, $line);
7398: my $file_part = pop(@paths_and_file);
7399: chomp($file_part);
7400: my $path_part = join('/', @paths_and_file);
1.572 banghart 7401: $path_part .= '/';
7402: my $path_and_file = $path_part.$file_part;
7403: if ($path_part ne $path) {
1.800 albertel 7404: push(@return_files, ($path_and_file));
1.572 banghart 7405: }
7406: }
1.800 albertel 7407: close(OUT);
1.574 banghart 7408: return (@return_files);
1.572 banghart 7409: }
7410:
1.745 raeburn 7411: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7412:
1.745 raeburn 7413: sub get_portfile_permissions {
7414: my ($domain,$user) = @_;
1.613 albertel 7415: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7416: my ($tmp)=keys(%current_permissions);
7417: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7418: return \%current_permissions;
7419: }
7420:
7421: #---------------------------------------------Get portfolio file access controls
7422:
1.749 raeburn 7423: sub get_access_controls {
1.745 raeburn 7424: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7425: my %access;
7426: my $real_file = $file;
7427: $file =~ s/\.meta$//;
1.745 raeburn 7428: if (defined($file)) {
1.749 raeburn 7429: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7430: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7431: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7432: }
7433: }
1.745 raeburn 7434: } else {
1.749 raeburn 7435: foreach my $key (keys(%{$current_permissions})) {
7436: if ($key =~ /\0accesscontrol$/) {
7437: if (defined($group)) {
7438: if ($key !~ m-^\Q$group\E/-) {
7439: next;
7440: }
7441: }
7442: my ($fullpath) = split(/\0/,$key);
7443: if (ref($$current_permissions{$key}) eq 'HASH') {
7444: foreach my $control (keys(%{$$current_permissions{$key}})) {
7445: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7446: }
7447: }
7448: }
7449: }
7450: }
7451: return %access;
7452: }
7453:
7454: sub modify_access_controls {
7455: my ($file_name,$changes,$domain,$user)=@_;
7456: my ($outcome,$deloutcome);
7457: my %store_permissions;
7458: my %new_values;
7459: my %new_control;
7460: my %translation;
7461: my @deletions = ();
7462: my $now = time;
7463: if (exists($$changes{'activate'})) {
7464: if (ref($$changes{'activate'}) eq 'HASH') {
7465: my @newitems = sort(keys(%{$$changes{'activate'}}));
7466: my $numnew = scalar(@newitems);
7467: for (my $i=0; $i<$numnew; $i++) {
7468: my $newkey = $newitems[$i];
7469: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7470: if ($newkey =~ /^\d+:/) {
7471: $newkey =~ s/^(\d+)/$newid/;
7472: $translation{$1} = $newid;
7473: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7474: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7475: $translation{$1} = $newid;
7476: }
1.749 raeburn 7477: $new_values{$file_name."\0".$newkey} =
7478: $$changes{'activate'}{$newitems[$i]};
7479: $new_control{$newkey} = $now;
7480: }
7481: }
7482: }
7483: my %todelete;
7484: my %changed_items;
7485: foreach my $action ('delete','update') {
7486: if (exists($$changes{$action})) {
7487: if (ref($$changes{$action}) eq 'HASH') {
7488: foreach my $key (keys(%{$$changes{$action}})) {
7489: my ($itemnum) = ($key =~ /^([^:]+):/);
7490: if ($action eq 'delete') {
7491: $todelete{$itemnum} = 1;
7492: } else {
7493: $changed_items{$itemnum} = $key;
7494: }
7495: }
1.745 raeburn 7496: }
7497: }
1.749 raeburn 7498: }
7499: # get lock on access controls for file.
7500: my $lockhash = {
7501: $file_name."\0".'locked_access_records' => $env{'user.name'}.
7502: ':'.$env{'user.domain'},
7503: };
7504: my $tries = 0;
7505: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7506:
7507: while (($gotlock ne 'ok') && $tries <3) {
7508: $tries ++;
7509: sleep 1;
7510: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
7511: }
7512: if ($gotlock eq 'ok') {
7513: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
7514: my ($tmp)=keys(%curr_permissions);
7515: if ($tmp=~/^error:/) { undef(%curr_permissions); }
7516: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
7517: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
7518: if (ref($curr_controls) eq 'HASH') {
7519: foreach my $control_item (keys(%{$curr_controls})) {
7520: my ($itemnum) = ($control_item =~ /^([^:]+):/);
7521: if (defined($todelete{$itemnum})) {
7522: push(@deletions,$file_name."\0".$control_item);
7523: } else {
7524: if (defined($changed_items{$itemnum})) {
7525: $new_control{$changed_items{$itemnum}} = $now;
7526: push(@deletions,$file_name."\0".$control_item);
7527: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
7528: } else {
7529: $new_control{$control_item} = $$curr_controls{$control_item};
7530: }
7531: }
1.745 raeburn 7532: }
7533: }
7534: }
1.970 raeburn 7535: my ($group);
7536: if (&is_course($domain,$user)) {
7537: ($group,my $file) = split(/\//,$file_name,2);
7538: }
1.749 raeburn 7539: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
7540: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
7541: $outcome = &put('file_permissions',\%new_values,$domain,$user);
7542: # remove lock
7543: my @del_lock = ($file_name."\0".'locked_access_records');
7544: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 7545: my $sqlresult =
1.970 raeburn 7546: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 7547: $group);
1.749 raeburn 7548: } else {
7549: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 7550: }
1.749 raeburn 7551: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 7552: }
7553:
1.827 raeburn 7554: sub make_public_indefinitely {
7555: my ($requrl) = @_;
7556: my $now = time;
7557: my $action = 'activate';
7558: my $aclnum = 0;
7559: if (&is_portfolio_url($requrl)) {
7560: my (undef,$udom,$unum,$file_name,$group) =
7561: &parse_portfolio_url($requrl);
7562: my $current_perms = &get_portfile_permissions($udom,$unum);
7563: my %access_controls = &get_access_controls($current_perms,
7564: $group,$file_name);
7565: foreach my $key (keys(%{$access_controls{$file_name}})) {
7566: my ($num,$scope,$end,$start) =
7567: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7568: if ($scope eq 'public') {
7569: if ($start <= $now && $end == 0) {
7570: $action = 'none';
7571: } else {
7572: $action = 'update';
7573: $aclnum = $num;
7574: }
7575: last;
7576: }
7577: }
7578: if ($action eq 'none') {
7579: return 'ok';
7580: } else {
7581: my %changes;
7582: my $newend = 0;
7583: my $newstart = $now;
7584: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
7585: $changes{$action}{$newkey} = {
7586: type => 'public',
7587: time => {
7588: start => $newstart,
7589: end => $newend,
7590: },
7591: };
7592: my ($outcome,$deloutcome,$new_values,$translation) =
7593: &modify_access_controls($file_name,\%changes,$udom,$unum);
7594: return $outcome;
7595: }
7596: } else {
7597: return 'invalid';
7598: }
7599: }
7600:
1.745 raeburn 7601: #------------------------------------------------------Get Marked as Read Only
7602:
7603: sub get_marked_as_readonly {
7604: my ($domain,$user,$what,$group) = @_;
7605: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 7606: my @readonly_files;
1.629 banghart 7607: my $cmp1=$what;
7608: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 7609: while (my ($file_name,$value) = each(%{$current_permissions})) {
7610: if (defined($group)) {
7611: if ($file_name !~ m-^\Q$group\E/-) {
7612: next;
7613: }
7614: }
1.561 banghart 7615: if (ref($value) eq "ARRAY"){
7616: foreach my $stored_what (@{$value}) {
1.629 banghart 7617: my $cmp2=$stored_what;
1.759 albertel 7618: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 7619: $cmp2=join('',@{$stored_what});
1.745 raeburn 7620: }
1.629 banghart 7621: if ($cmp1 eq $cmp2) {
1.561 banghart 7622: push(@readonly_files, $file_name);
1.745 raeburn 7623: last;
1.563 banghart 7624: } elsif (!defined($what)) {
7625: push(@readonly_files, $file_name);
1.745 raeburn 7626: last;
1.561 banghart 7627: }
7628: }
1.745 raeburn 7629: }
1.561 banghart 7630: }
7631: return @readonly_files;
7632: }
1.577 banghart 7633: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 7634:
1.577 banghart 7635: sub get_marked_as_readonly_hash {
1.745 raeburn 7636: my ($current_permissions,$group,$what) = @_;
1.577 banghart 7637: my %readonly_files;
1.745 raeburn 7638: while (my ($file_name,$value) = each(%{$current_permissions})) {
7639: if (defined($group)) {
7640: if ($file_name !~ m-^\Q$group\E/-) {
7641: next;
7642: }
7643: }
1.577 banghart 7644: if (ref($value) eq "ARRAY"){
7645: foreach my $stored_what (@{$value}) {
1.745 raeburn 7646: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 7647: foreach my $lock_descriptor(@{$stored_what}) {
7648: if ($lock_descriptor eq 'graded') {
7649: $readonly_files{$file_name} = 'graded';
7650: } elsif ($lock_descriptor eq 'handback') {
7651: $readonly_files{$file_name} = 'handback';
7652: } else {
7653: if (!exists($readonly_files{$file_name})) {
7654: $readonly_files{$file_name} = 'locked';
7655: }
7656: }
1.745 raeburn 7657: }
1.750 banghart 7658: }
1.577 banghart 7659: }
7660: }
7661: }
7662: return %readonly_files;
7663: }
1.559 banghart 7664: # ------------------------------------------------------------ Unmark as Read Only
7665:
7666: sub unmark_as_readonly {
1.629 banghart 7667: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7668: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 7669: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 7670: $file_name = &declutter_portfile($file_name);
1.634 albertel 7671: my $symb_crs = $what;
7672: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 7673: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 7674: my ($tmp)=keys(%current_permissions);
7675: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7676: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 7677: foreach my $file (@readonly_files) {
1.759 albertel 7678: my $clean_file = &declutter_portfile($file);
7679: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 7680: my $current_locks = $current_permissions{$file};
1.563 banghart 7681: my @new_locks;
7682: my @del_keys;
7683: if (ref($current_locks) eq "ARRAY"){
7684: foreach my $locker (@{$current_locks}) {
1.632 albertel 7685: my $compare=$locker;
1.749 raeburn 7686: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 7687: $compare=join('',@{$locker});
1.746 raeburn 7688: if ($compare ne $symb_crs) {
7689: push(@new_locks, $locker);
7690: }
1.563 banghart 7691: }
7692: }
1.650 albertel 7693: if (scalar(@new_locks) > 0) {
1.563 banghart 7694: $current_permissions{$file} = \@new_locks;
7695: } else {
7696: push(@del_keys, $file);
1.613 albertel 7697: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 7698: delete($current_permissions{$file});
1.563 banghart 7699: }
7700: }
1.561 banghart 7701: }
1.613 albertel 7702: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7703: return;
7704: }
1.512 banghart 7705:
1.17 www 7706: # ------------------------------------------------------------ Directory lister
7707:
7708: sub dirlist {
1.955 raeburn 7709: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 7710: $uri=~s/^\///;
7711: $uri=~s/\/$//;
1.253 stredwic 7712: my ($udom, $uname);
1.955 raeburn 7713: if ($getuserdir) {
1.253 stredwic 7714: $udom = $userdomain;
7715: $uname = $username;
1.955 raeburn 7716: } else {
7717: (undef,$udom,$uname)=split(/\//,$uri);
7718: if(defined($userdomain)) {
7719: $udom = $userdomain;
7720: }
7721: if(defined($username)) {
7722: $uname = $username;
7723: }
1.253 stredwic 7724: }
1.955 raeburn 7725: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 7726:
1.955 raeburn 7727: $dirRoot = $perlvar{'lonDocRoot'};
7728: if (defined($getpropath)) {
7729: $dirRoot = &propath($udom,$uname);
1.253 stredwic 7730: $dirRoot =~ s/\/$//;
1.955 raeburn 7731: } elsif (defined($getuserdir)) {
7732: my $subdir=$uname.'__';
7733: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7734: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7735: ."/$udom/$subdir/$uname";
7736: } elsif (defined($alternateRoot)) {
7737: $dirRoot = $alternateRoot;
1.751 banghart 7738: }
1.253 stredwic 7739:
7740: if($udom) {
7741: if($uname) {
1.955 raeburn 7742: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 7743: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 7744: .':'.&escape($uname).':'.&escape($udom),
7745: &homeserver($uname,$udom));
7746: if ($listing eq 'unknown_cmd') {
7747: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7748: &homeserver($uname,$udom));
7749: } else {
7750: @listing_results = map { &unescape($_); } split(/:/,$listing);
7751: }
1.605 matthew 7752: if ($listing eq 'unknown_cmd') {
1.800 albertel 7753: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7754: &homeserver($uname,$udom));
1.605 matthew 7755: @listing_results = split(/:/,$listing);
7756: } else {
7757: @listing_results = map { &unescape($_); } split(/:/,$listing);
7758: }
7759: return @listing_results;
1.955 raeburn 7760: } elsif(!$alternateRoot) {
1.800 albertel 7761: my %allusers;
1.841 albertel 7762: my %servers = &get_servers($udom,'library');
1.955 raeburn 7763: foreach my $tryserver (keys(%servers)) {
7764: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7765: &escape($udom),$tryserver);
7766: if ($listing eq 'unknown_cmd') {
7767: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7768: $udom, $tryserver);
7769: } else {
7770: @listing_results = map { &unescape($_); } split(/:/,$listing);
7771: }
1.841 albertel 7772: if ($listing eq 'unknown_cmd') {
7773: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7774: $udom, $tryserver);
7775: @listing_results = split(/:/,$listing);
7776: } else {
7777: @listing_results =
7778: map { &unescape($_); } split(/:/,$listing);
7779: }
7780: if ($listing_results[0] ne 'no_such_dir' &&
7781: $listing_results[0] ne 'empty' &&
7782: $listing_results[0] ne 'con_lost') {
7783: foreach my $line (@listing_results) {
7784: my ($entry) = split(/&/,$line,2);
7785: $allusers{$entry} = 1;
7786: }
7787: }
1.253 stredwic 7788: }
7789: my $alluserstr='';
1.800 albertel 7790: foreach my $user (sort(keys(%allusers))) {
7791: $alluserstr.=$user.'&user:';
1.253 stredwic 7792: }
7793: $alluserstr=~s/:$//;
7794: return split(/:/,$alluserstr);
7795: } else {
1.800 albertel 7796: return ('missing user name');
1.253 stredwic 7797: }
1.955 raeburn 7798: } elsif(!defined($getpropath)) {
1.841 albertel 7799: my @all_domains = sort(&all_domains());
1.955 raeburn 7800: foreach my $domain (@all_domains) {
7801: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7802: }
7803: return @all_domains;
7804: } else {
1.800 albertel 7805: return ('missing domain');
1.275 stredwic 7806: }
7807: }
7808:
7809: # --------------------------------------------- GetFileTimestamp
7810: # This function utilizes dirlist and returns the date stamp for
7811: # when it was last modified. It will also return an error of -1
7812: # if an error occurs
7813:
7814: sub GetFileTimestamp {
1.955 raeburn 7815: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 7816: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7817: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 7818: my ($fileStat) =
7819: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7820: undef,$getuserdir);
1.275 stredwic 7821: my @stats = split('&', $fileStat);
7822: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 7823: # @stats contains first the filename, then the stat output
7824: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 7825: } else {
7826: return -1;
1.253 stredwic 7827: }
1.26 www 7828: }
7829:
1.712 albertel 7830: sub stat_file {
7831: my ($uri) = @_;
1.787 albertel 7832: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 7833:
1.955 raeburn 7834: my ($udom,$uname,$file);
1.712 albertel 7835: if ($uri =~ m-^/(uploaded|editupload)/-) {
7836: ($udom,$uname,$file) =
1.811 albertel 7837: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 7838: $file = 'userfiles/'.$file;
7839: }
7840: if ($uri =~ m-^/res/-) {
7841: ($udom,$uname) =
1.807 albertel 7842: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 7843: $file = $uri;
7844: }
7845:
7846: if (!$udom || !$uname || !$file) {
7847: # unable to handle the uri
7848: return ();
7849: }
1.956 raeburn 7850: my $getpropath;
7851: if ($file =~ /^userfiles\//) {
7852: $getpropath = 1;
7853: }
1.955 raeburn 7854: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 7855: my @stats = split('&', $result);
1.721 banghart 7856:
1.712 albertel 7857: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7858: shift(@stats); #filename is first
7859: return @stats;
7860: }
7861: return ();
7862: }
7863:
1.26 www 7864: # -------------------------------------------------------- Value of a Condition
7865:
1.713 albertel 7866: # gets the value of a specific preevaluated condition
7867: # stored in the string $env{user.state.<cid>}
7868: # or looks up a condition reference in the bighash and if if hasn't
7869: # already been evaluated recurses into docondval to get the value of
7870: # the condition, then memoizing it to
7871: # $env{user.state.<cid>.<condition>}
1.40 www 7872: sub directcondval {
7873: my $number=shift;
1.620 albertel 7874: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 7875: &Apache::lonuserstate::evalstate();
7876: }
1.713 albertel 7877: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7878: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7879: } elsif ($number =~ /^_/) {
7880: my $sub_condition;
7881: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7882: &GDBM_READER(),0640)) {
7883: $sub_condition=$bighash{'conditions'.$number};
7884: untie(%bighash);
7885: }
7886: my $value = &docondval($sub_condition);
1.949 raeburn 7887: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 7888: return $value;
7889: }
1.620 albertel 7890: if ($env{'user.state.'.$env{'request.course.id'}}) {
7891: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 7892: } else {
7893: return 2;
7894: }
7895: }
7896:
1.713 albertel 7897: # get the collection of conditions for this resource
1.26 www 7898: sub condval {
7899: my $condidx=shift;
1.54 www 7900: my $allpathcond='';
1.713 albertel 7901: foreach my $cond (split(/\|/,$condidx)) {
7902: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7903: $allpathcond.=
7904: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7905: }
1.191 harris41 7906: }
1.54 www 7907: $allpathcond=~s/\|$//;
1.713 albertel 7908: return &docondval($allpathcond);
7909: }
7910:
7911: #evaluates an expression of conditions
7912: sub docondval {
7913: my ($allpathcond) = @_;
7914: my $result=0;
7915: if ($env{'request.course.id'}
7916: && defined($allpathcond)) {
7917: my $operand='|';
7918: my @stack;
7919: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7920: if ($chunk eq '(') {
7921: push @stack,($operand,$result);
7922: } elsif ($chunk eq ')') {
7923: my $before=pop @stack;
7924: if (pop @stack eq '&') {
7925: $result=$result>$before?$before:$result;
7926: } else {
7927: $result=$result>$before?$result:$before;
7928: }
7929: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7930: $operand=$chunk;
7931: } else {
7932: my $new=directcondval($chunk);
7933: if ($operand eq '&') {
7934: $result=$result>$new?$new:$result;
7935: } else {
7936: $result=$result>$new?$result:$new;
7937: }
7938: }
7939: }
1.26 www 7940: }
7941: return $result;
1.421 albertel 7942: }
7943:
7944: # ---------------------------------------------------- Devalidate courseresdata
7945:
7946: sub devalidatecourseresdata {
7947: my ($coursenum,$coursedomain)=@_;
7948: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7949: &devalidate_cache_new('courseres',$hashid);
1.28 www 7950: }
7951:
1.763 www 7952:
1.200 www 7953: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 7954: #
7955: # Parameters:
7956: # $coursenum - Number of the course.
7957: # $coursedomain - Domain at which the course was created.
7958: # Returns:
7959: # A hash of the course parameters along (I think) with timestamps
7960: # and version info.
1.877 foxr 7961:
1.624 albertel 7962: sub get_courseresdata {
7963: my ($coursenum,$coursedomain)=@_;
1.200 www 7964: my $coursehom=&homeserver($coursenum,$coursedomain);
7965: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 7966: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 7967: my %dumpreply;
1.417 albertel 7968: unless (defined($cached)) {
1.624 albertel 7969: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 7970: $result=\%dumpreply;
1.251 albertel 7971: my ($tmp) = keys(%dumpreply);
7972: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 7973: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 7974: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7975: return $tmp;
1.416 albertel 7976: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 7977: $result=undef;
1.599 albertel 7978: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 7979: }
7980: }
1.624 albertel 7981: return $result;
7982: }
7983:
1.633 albertel 7984: sub devalidateuserresdata {
7985: my ($uname,$udom)=@_;
7986: my $hashid="$udom:$uname";
7987: &devalidate_cache_new('userres',$hashid);
7988: }
7989:
1.624 albertel 7990: sub get_userresdata {
7991: my ($uname,$udom)=@_;
7992: #most student don\'t have any data set, check if there is some data
7993: if (&EXT_cache_status($udom,$uname)) { return undef; }
7994:
7995: my $hashid="$udom:$uname";
7996: my ($result,$cached)=&is_cached_new('userres',$hashid);
7997: if (!defined($cached)) {
7998: my %resourcedata=&dump('resourcedata',$udom,$uname);
7999: $result=\%resourcedata;
8000: &do_cache_new('userres',$hashid,$result,600);
8001: }
8002: my ($tmp)=keys(%$result);
8003: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8004: return $result;
8005: }
8006: #error 2 occurs when the .db doesn't exist
8007: if ($tmp!~/error: 2 /) {
1.672 albertel 8008: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8009: " Trying to get resource data for ".
8010: $uname." at ".$udom.": ".
8011: $tmp."</font>");
8012: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8013: #&EXT_cache_set($udom,$uname);
8014: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8015: undef($tmp); # not really an error so don't send it back
1.624 albertel 8016: }
8017: return $tmp;
8018: }
1.879 foxr 8019: #----------------------------------------------- resdata - return resource data
8020: # Purpose:
8021: # Return resource data for either users or for a course.
8022: # Parameters:
8023: # $name - Course/user name.
8024: # $domain - Name of the domain the user/course is registered on.
8025: # $type - Type of thing $name is (must be 'course' or 'user'
8026: # @which - Array of names of resources desired.
8027: # Returns:
8028: # The value of the first reasource in @which that is found in the
8029: # resource hash.
8030: # Exceptional Conditions:
8031: # If the $type passed in is not valid (not the string 'course' or
8032: # 'user', an undefined reference is returned.
8033: # If none of the resources are found, an undef is returned
1.624 albertel 8034: sub resdata {
8035: my ($name,$domain,$type,@which)=@_;
8036: my $result;
8037: if ($type eq 'course') {
8038: $result=&get_courseresdata($name,$domain);
8039: } elsif ($type eq 'user') {
8040: $result=&get_userresdata($name,$domain);
8041: }
8042: if (!ref($result)) { return $result; }
1.251 albertel 8043: foreach my $item (@which) {
1.927 albertel 8044: if (defined($result->{$item->[0]})) {
8045: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8046: }
1.250 albertel 8047: }
1.291 albertel 8048: return undef;
1.200 www 8049: }
8050:
1.379 matthew 8051: #
8052: # EXT resource caching routines
8053: #
8054:
8055: sub clear_EXT_cache_status {
1.383 albertel 8056: &delenv('cache.EXT.');
1.379 matthew 8057: }
8058:
8059: sub EXT_cache_status {
8060: my ($target_domain,$target_user) = @_;
1.383 albertel 8061: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8062: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8063: # We know already the user has no data
8064: return 1;
8065: } else {
8066: return 0;
8067: }
8068: }
8069:
8070: sub EXT_cache_set {
8071: my ($target_domain,$target_user) = @_;
1.383 albertel 8072: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8073: #&appenv({$cachename => time});
1.379 matthew 8074: }
8075:
1.28 www 8076: # --------------------------------------------------------- Value of a Variable
1.58 www 8077: sub EXT {
1.715 albertel 8078:
1.395 albertel 8079: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8080: unless ($varname) { return ''; }
1.218 albertel 8081: #get real user name/domain, courseid and symb
8082: my $courseid;
1.359 albertel 8083: my $publicuser;
1.427 www 8084: if ($symbparm) {
8085: $symbparm=&get_symb_from_alias($symbparm);
8086: }
1.218 albertel 8087: if (!($uname && $udom)) {
1.790 albertel 8088: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8089: if (!$symbparm) { $symbparm=$cursymb; }
8090: } else {
1.620 albertel 8091: $courseid=$env{'request.course.id'};
1.218 albertel 8092: }
1.48 www 8093: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8094: my $rest;
1.320 albertel 8095: if (defined($therest[0])) {
1.48 www 8096: $rest=join('.',@therest);
8097: } else {
8098: $rest='';
8099: }
1.320 albertel 8100:
1.57 www 8101: my $qualifierrest=$qualifier;
8102: if ($rest) { $qualifierrest.='.'.$rest; }
8103: my $spacequalifierrest=$space;
8104: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8105: if ($realm eq 'user') {
1.48 www 8106: # --------------------------------------------------------------- user.resource
8107: if ($space eq 'resource') {
1.651 albertel 8108: if ( (defined($Apache::lonhomework::parsing_a_problem)
8109: || defined($Apache::lonhomework::parsing_a_task))
8110: &&
1.744 albertel 8111: ($symbparm eq &symbread()) ) {
8112: # if we are in the middle of processing the resource the
8113: # get the value we are planning on committing
8114: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8115: return $Apache::lonhomework::results{$qualifierrest};
8116: } else {
8117: return $Apache::lonhomework::history{$qualifierrest};
8118: }
1.335 albertel 8119: } else {
1.359 albertel 8120: my %restored;
1.620 albertel 8121: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8122: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8123: } else {
8124: %restored=&restore($symbparm,$courseid,$udom,$uname);
8125: }
1.335 albertel 8126: return $restored{$qualifierrest};
8127: }
1.48 www 8128: # ----------------------------------------------------------------- user.access
8129: } elsif ($space eq 'access') {
1.218 albertel 8130: # FIXME - not supporting calls for a specific user
1.48 www 8131: return &allowed($qualifier,$rest);
8132: # ------------------------------------------ user.preferences, user.environment
8133: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8134: if (($uname eq $env{'user.name'}) &&
8135: ($udom eq $env{'user.domain'})) {
8136: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8137: } else {
1.359 albertel 8138: my %returnhash;
8139: if (!$publicuser) {
8140: %returnhash=&userenvironment($udom,$uname,
8141: $qualifierrest);
8142: }
1.218 albertel 8143: return $returnhash{$qualifierrest};
8144: }
1.48 www 8145: # ----------------------------------------------------------------- user.course
8146: } elsif ($space eq 'course') {
1.218 albertel 8147: # FIXME - not supporting calls for a specific user
1.620 albertel 8148: return $env{join('.',('request.course',$qualifier))};
1.48 www 8149: # ------------------------------------------------------------------- user.role
8150: } elsif ($space eq 'role') {
1.218 albertel 8151: # FIXME - not supporting calls for a specific user
1.620 albertel 8152: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8153: if ($qualifier eq 'value') {
8154: return $role;
8155: } elsif ($qualifier eq 'extent') {
8156: return $where;
8157: }
8158: # ----------------------------------------------------------------- user.domain
8159: } elsif ($space eq 'domain') {
1.218 albertel 8160: return $udom;
1.48 www 8161: # ------------------------------------------------------------------- user.name
8162: } elsif ($space eq 'name') {
1.218 albertel 8163: return $uname;
1.48 www 8164: # ---------------------------------------------------- Any other user namespace
1.29 www 8165: } else {
1.359 albertel 8166: my %reply;
8167: if (!$publicuser) {
8168: %reply=&get($space,[$qualifierrest],$udom,$uname);
8169: }
8170: return $reply{$qualifierrest};
1.48 www 8171: }
1.236 www 8172: } elsif ($realm eq 'query') {
8173: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8174: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8175: [$spacequalifierrest]);
1.620 albertel 8176: return $env{'form.'.$spacequalifierrest};
1.236 www 8177: } elsif ($realm eq 'request') {
1.48 www 8178: # ------------------------------------------------------------- request.browser
8179: if ($space eq 'browser') {
1.430 www 8180: if ($qualifier eq 'textremote') {
1.676 albertel 8181: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8182: return 1;
8183: } else {
8184: return 0;
8185: }
8186: } else {
1.620 albertel 8187: return $env{'browser.'.$qualifier};
1.430 www 8188: }
1.57 www 8189: # ------------------------------------------------------------ request.filename
8190: } else {
1.620 albertel 8191: return $env{'request.'.$spacequalifierrest};
1.29 www 8192: }
1.28 www 8193: } elsif ($realm eq 'course') {
1.48 www 8194: # ---------------------------------------------------------- course.description
1.620 albertel 8195: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8196: } elsif ($realm eq 'resource') {
1.165 www 8197:
1.620 albertel 8198: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8199: if (!$symbparm) { $symbparm=&symbread(); }
8200: }
1.693 albertel 8201:
8202: if ($space eq 'title') {
8203: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8204: return &gettitle($symbparm);
8205: }
8206:
8207: if ($space eq 'map') {
8208: my ($map) = &decode_symb($symbparm);
8209: return &symbread($map);
8210: }
1.905 albertel 8211: if ($space eq 'filename') {
8212: if ($symbparm) {
8213: return &clutter((&decode_symb($symbparm))[2]);
8214: }
8215: return &hreflocation('',$env{'request.filename'});
8216: }
1.693 albertel 8217:
8218: my ($section, $group, @groups);
1.593 albertel 8219: my ($courselevelm,$courselevel);
1.539 albertel 8220: if ($symbparm && defined($courseid) &&
1.620 albertel 8221: $courseid eq $env{'request.course.id'}) {
1.165 www 8222:
1.218 albertel 8223: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8224:
1.60 www 8225: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8226: my $symbp=$symbparm;
1.735 albertel 8227: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8228:
8229: my $symbparm=$symbp.'.'.$spacequalifierrest;
8230: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8231:
1.620 albertel 8232: if (($env{'user.name'} eq $uname) &&
8233: ($env{'user.domain'} eq $udom)) {
8234: $section=$env{'request.course.sec'};
1.733 raeburn 8235: @groups = split(/:/,$env{'request.course.groups'});
8236: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8237: } else {
1.539 albertel 8238: if (! defined($usection)) {
1.551 albertel 8239: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8240: } else {
8241: $section = $usection;
8242: }
1.733 raeburn 8243: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8244: }
8245:
8246: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8247: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8248: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8249:
1.593 albertel 8250: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8251: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8252: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8253:
1.60 www 8254: # ----------------------------------------------------------- first, check user
1.624 albertel 8255:
8256: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8257: ([$courselevelr,'resource'],
8258: [$courselevelm,'map' ],
8259: [$courselevel, 'course' ]));
1.931 albertel 8260: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8261:
1.594 albertel 8262: # ------------------------------------------------ second, check some of course
1.684 raeburn 8263: my $coursereply;
1.691 raeburn 8264: if (@groups > 0) {
8265: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8266: $mapparm,$spacequalifierrest);
1.927 albertel 8267: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8268: }
1.96 www 8269:
1.684 raeburn 8270: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8271: $env{'course.'.$courseid.'.domain'},
8272: 'course',
8273: ([$seclevelr, 'resource'],
8274: [$seclevelm, 'map' ],
8275: [$seclevel, 'course' ],
8276: [$courselevelr,'resource']));
8277: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8278:
1.60 www 8279: # ------------------------------------------------------ third, check map parms
1.218 albertel 8280: my %parmhash=();
8281: my $thisparm='';
8282: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8283: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8284: &GDBM_READER(),0640)) {
1.218 albertel 8285: $thisparm=$parmhash{$symbparm};
8286: untie(%parmhash);
8287: }
1.927 albertel 8288: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8289: }
1.594 albertel 8290: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8291:
1.218 albertel 8292: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8293: my $filename;
8294: if (!$symbparm) { $symbparm=&symbread(); }
8295: if ($symbparm) {
1.409 www 8296: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8297: } else {
1.620 albertel 8298: $filename=$env{'request.filename'};
1.282 albertel 8299: }
8300: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8301: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8302: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8303: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8304:
1.927 albertel 8305: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8306: if ($symbparm && defined($courseid) &&
1.620 albertel 8307: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8308: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8309: $env{'course.'.$courseid.'.domain'},
8310: 'course',
1.927 albertel 8311: ([$courselevelm,'map' ],
8312: [$courselevel, 'course']));
8313: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8314: }
1.145 www 8315: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8316: unless ($space eq '0') {
1.336 albertel 8317: my @parts=split(/_/,$space);
8318: my $id=pop(@parts);
8319: my $part=join('_',@parts);
8320: if ($part eq '') { $part='0'; }
1.927 albertel 8321: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8322: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8323: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8324: }
1.395 albertel 8325: if ($recurse) { return undef; }
8326: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8327: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8328: # ---------------------------------------------------- Any other user namespace
8329: } elsif ($realm eq 'environment') {
8330: # ----------------------------------------------------------------- environment
1.620 albertel 8331: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8332: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8333: } else {
1.770 albertel 8334: if ($uname eq 'anonymous' && $udom eq '') {
8335: return '';
8336: }
1.219 albertel 8337: my %returnhash=&userenvironment($udom,$uname,
8338: $spacequalifierrest);
8339: return $returnhash{$spacequalifierrest};
8340: }
1.28 www 8341: } elsif ($realm eq 'system') {
1.48 www 8342: # ----------------------------------------------------------------- system.time
8343: if ($space eq 'time') {
8344: return time;
8345: }
1.696 albertel 8346: } elsif ($realm eq 'server') {
8347: # ----------------------------------------------------------------- system.time
8348: if ($space eq 'name') {
8349: return $ENV{'SERVER_NAME'};
8350: }
1.28 www 8351: }
1.48 www 8352: return '';
1.61 www 8353: }
8354:
1.927 albertel 8355: sub get_reply {
8356: my ($reply_value) = @_;
1.940 raeburn 8357: if (ref($reply_value) eq 'ARRAY') {
8358: if (wantarray) {
8359: return @$reply_value;
8360: }
8361: return $reply_value->[0];
8362: } else {
8363: return $reply_value;
1.927 albertel 8364: }
8365: }
8366:
1.691 raeburn 8367: sub check_group_parms {
8368: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8369: my @groupitems = ();
8370: my $resultitem;
1.927 albertel 8371: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8372: foreach my $group (@{$groups}) {
8373: foreach my $level (@levels) {
1.927 albertel 8374: my $item = $courseid.'.['.$group.'].'.$level->[0];
8375: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8376: }
8377: }
8378: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8379: $env{'course.'.$courseid.'.domain'},
8380: 'course',@groupitems);
8381: return $coursereply;
8382: }
8383:
8384: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8385: my ($courseid,@groups) = @_;
8386: @groups = sort(@groups);
1.691 raeburn 8387: return @groups;
8388: }
8389:
1.395 albertel 8390: sub packages_tab_default {
8391: my ($uri,$varname)=@_;
8392: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8393:
8394: my (@extension,@specifics,$do_default);
8395: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8396: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8397: if ($pack_type eq 'default') {
8398: $do_default=1;
8399: } elsif ($pack_type eq 'extension') {
8400: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8401: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8402: # only look at packages defaults for packages that this id is
1.738 albertel 8403: push(@specifics,[$package,$pack_type,$pack_part]);
8404: }
8405: }
8406: # first look for a package that matches the requested part id
8407: foreach my $package (@specifics) {
8408: my (undef,$pack_type,$pack_part)=@{$package};
8409: next if ($pack_part ne $part);
8410: if (defined($packagetab{"$pack_type&$name&default"})) {
8411: return $packagetab{"$pack_type&$name&default"};
8412: }
8413: }
8414: # look for any possible matching non extension_ package
8415: foreach my $package (@specifics) {
8416: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8417: if (defined($packagetab{"$pack_type&$name&default"})) {
8418: return $packagetab{"$pack_type&$name&default"};
8419: }
1.585 albertel 8420: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8421: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8422: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8423: }
8424: }
1.738 albertel 8425: # look for any posible extension_ match
8426: foreach my $package (@extension) {
8427: my ($package,$pack_type)=@{$package};
8428: if (defined($packagetab{"$pack_type&$name&default"})) {
8429: return $packagetab{"$pack_type&$name&default"};
8430: }
8431: if (defined($packagetab{$package."&$name&default"})) {
8432: return $packagetab{$package."&$name&default"};
8433: }
8434: }
8435: # look for a global default setting
8436: if ($do_default && defined($packagetab{"default&$name&default"})) {
8437: return $packagetab{"default&$name&default"};
8438: }
1.395 albertel 8439: return undef;
8440: }
8441:
1.334 albertel 8442: sub add_prefix_and_part {
8443: my ($prefix,$part)=@_;
8444: my $keyroot;
8445: if (defined($prefix) && $prefix !~ /^__/) {
8446: # prefix that has a part already
8447: $keyroot=$prefix;
8448: } elsif (defined($prefix)) {
8449: # prefix that is missing a part
8450: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8451: } else {
8452: # no prefix at all
8453: if (defined($part)) { $keyroot='_'.$part; }
8454: }
8455: return $keyroot;
8456: }
8457:
1.71 www 8458: # ---------------------------------------------------------------- Get metadata
8459:
1.599 albertel 8460: my %metaentry;
1.1070 www 8461: my %importedpartids;
1.71 www 8462: sub metadata {
1.176 www 8463: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8464: $uri=&declutter($uri);
1.288 albertel 8465: # if it is a non metadata possible uri return quickly
1.529 albertel 8466: if (($uri eq '') ||
8467: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8468: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1092 raeburn 8469: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^\*uploaded\/.+\.sequence$/) ) {
1.924 albertel 8470: return undef;
8471: }
8472: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8473: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8474: return undef;
1.288 albertel 8475: }
1.73 www 8476: my $filename=$uri;
8477: $uri=~s/\.meta$//;
1.172 www 8478: #
8479: # Is the metadata already cached?
1.177 www 8480: # Look at timestamp of caching
1.172 www 8481: # Everything is cached by the main uri, libraries are never directly cached
8482: #
1.428 albertel 8483: if (!defined($liburi)) {
1.599 albertel 8484: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8485: if (defined($cached)) { return $result->{':'.$what}; }
8486: }
8487: {
1.1069 www 8488: # Imported parts would go here
1.1070 www 8489: my %importedids=();
8490: my @origfileimportpartids=();
1.1069 www 8491: my $importedparts=0;
1.172 www 8492: #
8493: # Is this a recursive call for a library?
8494: #
1.599 albertel 8495: # if (! exists($metacache{$uri})) {
8496: # $metacache{$uri}={};
8497: # }
1.924 albertel 8498: my $cachetime = 60*60;
1.171 www 8499: if ($liburi) {
8500: $liburi=&declutter($liburi);
8501: $filename=$liburi;
1.401 bowersj2 8502: } else {
1.599 albertel 8503: &devalidate_cache_new('meta',$uri);
8504: undef(%metaentry);
1.401 bowersj2 8505: }
1.140 www 8506: my %metathesekeys=();
1.73 www 8507: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 8508: my $metastring;
1.924 albertel 8509: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 8510: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 8511: $metastring =
1.929 albertel 8512: &Apache::lonnet::ssi_body($which,
1.924 albertel 8513: ('grade_target' => 'meta'));
8514: $cachetime = 1; # only want this cached in the child not long term
8515: } elsif ($uri !~ m -^(editupload)/-) {
1.543 albertel 8516: my $file=&filelocation('',&clutter($filename));
1.599 albertel 8517: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 8518: $metastring=&getfile($file);
1.489 albertel 8519: }
1.208 albertel 8520: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 8521: my $token;
1.140 www 8522: undef %metathesekeys;
1.71 www 8523: while ($token=$parser->get_token) {
1.339 albertel 8524: if ($token->[0] eq 'S') {
8525: if (defined($token->[2]->{'package'})) {
1.172 www 8526: #
8527: # This is a package - get package info
8528: #
1.339 albertel 8529: my $package=$token->[2]->{'package'};
8530: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8531: if (defined($token->[2]->{'id'})) {
8532: $keyroot.='_'.$token->[2]->{'id'};
8533: }
1.599 albertel 8534: if ($metaentry{':packages'}) {
8535: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 8536: } else {
1.599 albertel 8537: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 8538: }
1.736 albertel 8539: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 8540: my $part=$keyroot;
8541: $part=~s/^\_//;
1.736 albertel 8542: if ($pack_entry=~/^\Q$package\E\&/ ||
8543: $pack_entry=~/^\Q$package\E_0\&/) {
8544: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 8545: # ignore package.tab specified default values
8546: # here &package_tab_default() will fetch those
8547: if ($subp eq 'default') { next; }
1.736 albertel 8548: my $value=$packagetab{$pack_entry};
1.432 albertel 8549: my $unikey;
8550: if ($pack =~ /_0$/) {
8551: $unikey='parameter_0_'.$name;
8552: $part=0;
8553: } else {
8554: $unikey='parameter'.$keyroot.'_'.$name;
8555: }
1.339 albertel 8556: if ($subp eq 'display') {
8557: $value.=' [Part: '.$part.']';
8558: }
1.599 albertel 8559: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 8560: $metathesekeys{$unikey}=1;
1.599 albertel 8561: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8562: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 8563: }
1.599 albertel 8564: if (defined($metaentry{':'.$unikey.'.default'})) {
8565: $metaentry{':'.$unikey}=
8566: $metaentry{':'.$unikey.'.default'};
1.356 albertel 8567: }
1.339 albertel 8568: }
8569: }
8570: } else {
1.172 www 8571: #
8572: # This is not a package - some other kind of start tag
1.339 albertel 8573: #
8574: my $entry=$token->[1];
1.1068 www 8575: my $unikey='';
1.175 www 8576:
1.339 albertel 8577: if ($entry eq 'import') {
1.175 www 8578: #
8579: # Importing a library here
1.339 albertel 8580: #
1.1067 www 8581: my $location=$parser->get_text('/import');
8582: my $dir=$filename;
8583: $dir=~s|[^/]*$||;
8584: $location=&filelocation($dir,$location);
1.1069 www 8585:
1.1068 www 8586: my $importmode=$token->[2]->{'importmode'};
8587: if ($importmode eq 'problem') {
1.1069 www 8588: # Import as problem/response
1.1068 www 8589: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8590: } elsif ($importmode eq 'part') {
8591: # Import as part(s)
1.1069 www 8592: $importedparts=1;
8593: # We need to get the original file and the imported file to get the part order correct
8594: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
8595: # Load and inspect original file
1.1070 www 8596: if ($#origfileimportpartids<0) {
8597: undef(%importedpartids);
8598: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
8599: my $origfile=&getfile($origfilelocation);
8600: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8601: }
8602:
1.1069 www 8603: # Load and inspect imported file
8604: my $impfile=&getfile($location);
8605: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
8606: if ($#impfilepartids>=0) {
8607: # This problem had parts
1.1070 www 8608: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 8609: } else {
8610: # Importing by turning a single problem into a problem part
8611: # It gets the import-tags ID as part-ID
8612: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 8613: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 8614: }
1.1068 www 8615: } else {
8616: # Normal import
8617: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
8618: if (defined($token->[2]->{'id'})) {
8619: $unikey.='_'.$token->[2]->{'id'};
8620: }
1.1067 www 8621: }
8622:
1.339 albertel 8623: if ($depthcount<20) {
1.736 albertel 8624: my $metadata =
8625: &metadata($uri,'keys', $location,$unikey,
8626: $depthcount+1);
8627: foreach my $meta (split(',',$metadata)) {
8628: $metaentry{':'.$meta}=$metaentry{':'.$meta};
8629: $metathesekeys{$meta}=1;
1.339 albertel 8630: }
1.1068 www 8631:
8632: }
1.1067 www 8633: } else {
8634: #
8635: # Not importing, some other kind of non-package, non-library start tag
8636: #
8637: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
8638: if (defined($token->[2]->{'id'})) {
8639: $unikey.='_'.$token->[2]->{'id'};
8640: }
1.339 albertel 8641: if (defined($token->[2]->{'name'})) {
8642: $unikey.='_'.$token->[2]->{'name'};
8643: }
8644: $metathesekeys{$unikey}=1;
1.736 albertel 8645: foreach my $param (@{$token->[3]}) {
8646: $metaentry{':'.$unikey.'.'.$param} =
8647: $token->[2]->{$param};
1.339 albertel 8648: }
8649: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 8650: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 8651: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
8652: # only ws inside the tag, and not in default, so use default
8653: # as value
1.599 albertel 8654: $metaentry{':'.$unikey}=$default;
1.908 albertel 8655: } elsif ( $internaltext =~ /\S/ ) {
8656: # something interesting inside the tag
8657: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 8658: } else {
1.908 albertel 8659: # no interesting values, don't set a default
1.339 albertel 8660: }
1.172 www 8661: # end of not-a-package not-a-library import
1.339 albertel 8662: }
1.172 www 8663: # end of not-a-package start tag
1.339 albertel 8664: }
1.172 www 8665: # the next is the end of "start tag"
1.339 albertel 8666: }
8667: }
1.483 albertel 8668: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 8669: $extension = lc($extension);
8670: if ($extension eq 'htm') { $extension='html'; }
8671:
1.737 albertel 8672: foreach my $key (keys(%packagetab)) {
1.483 albertel 8673: #no specific packages #how's our extension
8674: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 8675: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 8676: \%metathesekeys);
8677: }
1.883 albertel 8678:
8679: if (!exists($metaentry{':packages'})
8680: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 8681: foreach my $key (keys(%packagetab)) {
1.483 albertel 8682: #no specific packages well let's get default then
8683: if ($key!~/^default&/) { next; }
1.488 albertel 8684: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 8685: \%metathesekeys);
8686: }
8687: }
1.338 www 8688: # are there custom rights to evaluate
1.599 albertel 8689: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 8690:
1.338 www 8691: #
8692: # Importing a rights file here
1.339 albertel 8693: #
8694: unless ($depthcount) {
1.599 albertel 8695: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 8696: my $dir=$filename;
8697: $dir=~s|[^/]*$||;
8698: $location=&filelocation($dir,$location);
1.736 albertel 8699: my $rights_metadata =
8700: &metadata($uri,'keys',$location,'_rights',
8701: $depthcount+1);
8702: foreach my $rights (split(',',$rights_metadata)) {
8703: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8704: $metathesekeys{$rights}=1;
1.339 albertel 8705: }
8706: }
8707: }
1.737 albertel 8708: # uniqifiy package listing
8709: my %seen;
8710: my @uniq_packages =
8711: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8712: $metaentry{':packages'} = join(',',@uniq_packages);
8713:
1.1070 www 8714: if ($importedparts) {
8715: # We had imported parts and need to rebuild partorder
8716: $metaentry{':partorder'}='';
8717: $metathesekeys{'partorder'}=1;
8718: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
8719: if ($origfileimportpartids[$index] eq 'part') {
8720: # original part, part of the problem
8721: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
8722: } else {
8723: # we have imported parts at this position
8724: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
8725: }
8726: }
8727: $metaentry{':partorder'}=~s/^\,//;
8728: }
8729:
1.737 albertel 8730: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 8731: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8732: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 8733: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 8734: # this is the end of "was not already recently cached
1.71 www 8735: }
1.599 albertel 8736: return $metaentry{':'.$what};
1.261 albertel 8737: }
8738:
1.488 albertel 8739: sub metadata_create_package_def {
1.483 albertel 8740: my ($uri,$key,$package,$metathesekeys)=@_;
8741: my ($pack,$name,$subp)=split(/\&/,$key);
8742: if ($subp eq 'default') { next; }
8743:
1.599 albertel 8744: if (defined($metaentry{':packages'})) {
8745: $metaentry{':packages'}.=','.$package;
1.483 albertel 8746: } else {
1.599 albertel 8747: $metaentry{':packages'}=$package;
1.483 albertel 8748: }
8749: my $value=$packagetab{$key};
8750: my $unikey;
8751: $unikey='parameter_0_'.$name;
1.599 albertel 8752: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 8753: $$metathesekeys{$unikey}=1;
1.599 albertel 8754: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8755: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 8756: }
1.599 albertel 8757: if (defined($metaentry{':'.$unikey.'.default'})) {
8758: $metaentry{':'.$unikey}=
8759: $metaentry{':'.$unikey.'.default'};
1.483 albertel 8760: }
8761: }
8762:
1.261 albertel 8763: sub metadata_generate_part0 {
8764: my ($metadata,$metacache,$uri) = @_;
8765: my %allnames;
1.737 albertel 8766: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 8767: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 8768: my $part=$$metacache{':'.$metakey.'.part'};
8769: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 8770: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 8771: $allnames{$name}=$part;
8772: }
8773: }
8774: }
8775: foreach my $name (keys(%allnames)) {
8776: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 8777: my $key=":parameter_0_$name";
1.261 albertel 8778: $$metacache{"$key.part"}='0';
8779: $$metacache{"$key.name"}=$name;
1.428 albertel 8780: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 8781: $allnames{$name}.'_'.$name.
8782: '.type'};
1.428 albertel 8783: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 8784: '.display'};
1.644 www 8785: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 8786: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 8787: $$metacache{"$key.display"}=$olddis;
8788: }
1.71 www 8789: }
8790:
1.764 albertel 8791: # ------------------------------------------------------ Devalidate title cache
8792:
8793: sub devalidate_title_cache {
8794: my ($url)=@_;
8795: if (!$env{'request.course.id'}) { return; }
8796: my $symb=&symbread($url);
8797: if (!$symb) { return; }
8798: my $key=$env{'request.course.id'}."\0".$symb;
8799: &devalidate_cache_new('title',$key);
8800: }
8801:
1.1014 droeschl 8802: # ------------------------------------------------- Get the title of a course
8803:
8804: sub current_course_title {
8805: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8806: }
1.301 www 8807: # ------------------------------------------------- Get the title of a resource
8808:
8809: sub gettitle {
8810: my $urlsymb=shift;
8811: my $symb=&symbread($urlsymb);
1.534 albertel 8812: if ($symb) {
1.620 albertel 8813: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 8814: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 8815: if (defined($cached)) {
8816: return $result;
8817: }
1.534 albertel 8818: my ($map,$resid,$url)=&decode_symb($symb);
8819: my $title='';
1.907 albertel 8820: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8821: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8822: } else {
8823: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8824: &GDBM_READER(),0640)) {
8825: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8826: $title=$bighash{'title_'.$mapid.'.'.$resid};
8827: untie(%bighash);
8828: }
1.534 albertel 8829: }
8830: $title=~s/\&colon\;/\:/gs;
8831: if ($title) {
1.599 albertel 8832: return &do_cache_new('title',$key,$title,600);
1.534 albertel 8833: }
8834: $urlsymb=$url;
8835: }
8836: my $title=&metadata($urlsymb,'title');
8837: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8838: return $title;
1.301 www 8839: }
1.613 albertel 8840:
1.614 albertel 8841: sub get_slot {
8842: my ($which,$cnum,$cdom)=@_;
8843: if (!$cnum || !$cdom) {
1.790 albertel 8844: (undef,my $courseid)=&whichuser();
1.620 albertel 8845: $cdom=$env{'course.'.$courseid.'.domain'};
8846: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 8847: }
1.703 albertel 8848: my $key=join("\0",'slots',$cdom,$cnum,$which);
8849: my %slotinfo;
8850: if (exists($remembered{$key})) {
8851: $slotinfo{$which} = $remembered{$key};
8852: } else {
8853: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8854: &Apache::lonhomework::showhash(%slotinfo);
8855: my ($tmp)=keys(%slotinfo);
8856: if ($tmp=~/^error:/) { return (); }
8857: $remembered{$key} = $slotinfo{$which};
8858: }
1.616 albertel 8859: if (ref($slotinfo{$which}) eq 'HASH') {
8860: return %{$slotinfo{$which}};
8861: }
8862: return $slotinfo{$which};
1.614 albertel 8863: }
1.31 www 8864: # ------------------------------------------------- Update symbolic store links
8865:
8866: sub symblist {
8867: my ($mapname,%newhash)=@_;
1.438 www 8868: $mapname=&deversion(&declutter($mapname));
1.31 www 8869: my %hash;
1.620 albertel 8870: if (($env{'request.course.fn'}) && (%newhash)) {
8871: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 8872: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 8873: foreach my $url (keys(%newhash)) {
1.711 albertel 8874: next if ($url eq 'last_known'
8875: && $env{'form.no_update_last_known'});
8876: $hash{declutter($url)}=&encode_symb($mapname,
8877: $newhash{$url}->[1],
8878: $newhash{$url}->[0]);
1.191 harris41 8879: }
1.31 www 8880: if (untie(%hash)) {
8881: return 'ok';
8882: }
8883: }
8884: }
8885: return 'error';
1.212 www 8886: }
8887:
8888: # --------------------------------------------------------------- Verify a symb
8889:
8890: sub symbverify {
1.510 www 8891: my ($symb,$thisurl)=@_;
8892: my $thisfn=$thisurl;
1.439 www 8893: $thisfn=&declutter($thisfn);
1.215 www 8894: # direct jump to resource in page or to a sequence - will construct own symbs
8895: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8896: # check URL part
1.409 www 8897: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 8898:
1.431 www 8899: unless ($url eq $thisfn) { return 0; }
1.213 www 8900:
1.216 www 8901: $symb=&symbclean($symb);
1.510 www 8902: $thisurl=&deversion($thisurl);
1.439 www 8903: $thisfn=&deversion($thisfn);
1.213 www 8904:
8905: my %bighash;
8906: my $okay=0;
1.431 www 8907:
1.620 albertel 8908: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 8909: &GDBM_READER(),0640)) {
1.1032 raeburn 8910: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8911: $thisurl =~ s/\?.+$//;
8912: }
1.510 www 8913: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 8914: unless ($ids) {
1.510 www 8915: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 8916: }
8917: if ($ids) {
8918: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 8919: foreach my $id (split(/\,/,$ids)) {
8920: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 8921: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8922: $symb =~ s/\?.+$//;
8923: }
1.216 www 8924: if (
8925: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8926: eq $symb) {
1.620 albertel 8927: if (($env{'request.role.adv'}) ||
1.800 albertel 8928: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 8929: $okay=1;
8930: }
8931: }
1.216 www 8932: }
8933: }
1.213 www 8934: untie(%bighash);
8935: }
8936: return $okay;
1.31 www 8937: }
8938:
1.210 www 8939: # --------------------------------------------------------------- Clean-up symb
8940:
8941: sub symbclean {
8942: my $symb=shift;
1.568 albertel 8943: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 8944: # remove version from map
8945: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 8946:
1.210 www 8947: # remove version from URL
8948: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 8949:
1.507 www 8950: # remove wrapper
8951:
1.510 www 8952: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 8953: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 8954: return $symb;
1.409 www 8955: }
8956:
8957: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 8958:
8959: sub encode_symb {
8960: my ($map,$resid,$url)=@_;
8961: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8962: }
1.409 www 8963:
8964: sub decode_symb {
1.568 albertel 8965: my $symb=shift;
8966: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8967: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 8968: return (&fixversion($map),$resid,&fixversion($url));
8969: }
8970:
8971: sub fixversion {
8972: my $fn=shift;
1.609 banghart 8973: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 8974: my %bighash;
8975: my $uri=&clutter($fn);
1.620 albertel 8976: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 8977: # is this cached?
1.599 albertel 8978: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 8979: if (defined($cached)) { return $result; }
8980: # unfortunately not cached, or expired
1.620 albertel 8981: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 8982: &GDBM_READER(),0640)) {
8983: if ($bighash{'version_'.$uri}) {
8984: my $version=$bighash{'version_'.$uri};
1.444 www 8985: unless (($version eq 'mostrecent') ||
8986: ($version==&getversion($uri))) {
1.440 www 8987: $uri=~s/\.(\w+)$/\.$version\.$1/;
8988: }
8989: }
8990: untie %bighash;
1.413 www 8991: }
1.599 albertel 8992: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 8993: }
8994:
8995: sub deversion {
8996: my $url=shift;
8997: $url=~s/\.\d+\.(\w+)$/\.$1/;
8998: return $url;
1.210 www 8999: }
9000:
1.31 www 9001: # ------------------------------------------------------ Return symb list entry
9002:
9003: sub symbread {
1.249 www 9004: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9005: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9006: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9007: # no filename provided? try from environment
1.44 www 9008: unless ($thisfn) {
1.620 albertel 9009: if ($env{'request.symb'}) {
9010: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9011: }
1.620 albertel 9012: $thisfn=$env{'request.filename'};
1.44 www 9013: }
1.569 albertel 9014: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9015: # is that filename actually a symb? Verify, clean, and return
9016: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9017: if (&symbverify($thisfn,$1)) {
1.620 albertel 9018: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9019: }
1.242 www 9020: }
1.44 www 9021: $thisfn=declutter($thisfn);
1.31 www 9022: my %hash;
1.37 www 9023: my %bighash;
9024: my $syval='';
1.620 albertel 9025: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9026: my $targetfn = $thisfn;
1.609 banghart 9027: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9028: $targetfn = 'adm/wrapper/'.$thisfn;
9029: }
1.687 albertel 9030: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9031: $targetfn=$1;
9032: }
1.620 albertel 9033: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9034: &GDBM_READER(),0640)) {
1.481 raeburn 9035: $syval=$hash{$targetfn};
1.37 www 9036: untie(%hash);
9037: }
9038: # ---------------------------------------------------------- There was an entry
9039: if ($syval) {
1.601 albertel 9040: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9041: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9042: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9043: #return $env{$cache_str}='';
1.601 albertel 9044: #}
9045: #$syval.=$1;
9046: #}
1.37 www 9047: } else {
9048: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9049: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9050: &GDBM_READER(),0640)) {
1.37 www 9051: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9052: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9053: unless ($ids) {
9054: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9055: }
9056: unless ($ids) {
9057: # alias?
9058: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9059: }
1.37 www 9060: if ($ids) {
9061: # ------------------------------------------------------------------- Has ID(s)
9062: my @possibilities=split(/\,/,$ids);
1.39 www 9063: if ($#possibilities==0) {
9064: # ----------------------------------------------- There is only one possibility
1.37 www 9065: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9066: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9067: $resid,$thisfn);
1.249 www 9068: } elsif (!$donotrecurse) {
1.39 www 9069: # ------------------------------------------ There is more than one possibility
9070: my $realpossible=0;
1.800 albertel 9071: foreach my $id (@possibilities) {
9072: my $file=$bighash{'src_'.$id};
1.39 www 9073: if (&allowed('bre',$file)) {
1.800 albertel 9074: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9075: if ($bighash{'map_type_'.$mapid} ne 'page') {
9076: $realpossible++;
1.626 albertel 9077: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9078: $resid,$thisfn);
1.39 www 9079: }
9080: }
1.191 harris41 9081: }
1.39 www 9082: if ($realpossible!=1) { $syval=''; }
1.249 www 9083: } else {
9084: $syval='';
1.37 www 9085: }
9086: }
9087: untie(%bighash)
1.481 raeburn 9088: }
1.31 www 9089: }
1.62 www 9090: if ($syval) {
1.620 albertel 9091: return $env{$cache_str}=$syval;
1.62 www 9092: }
1.31 www 9093: }
1.949 raeburn 9094: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9095: return $env{$cache_str}='';
1.31 www 9096: }
9097:
9098: # ---------------------------------------------------------- Return random seed
9099:
1.32 www 9100: sub numval {
9101: my $txt=shift;
9102: $txt=~tr/A-J/0-9/;
9103: $txt=~tr/a-j/0-9/;
9104: $txt=~tr/K-T/0-9/;
9105: $txt=~tr/k-t/0-9/;
9106: $txt=~tr/U-Z/0-5/;
9107: $txt=~tr/u-z/0-5/;
9108: $txt=~s/\D//g;
1.564 albertel 9109: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9110: return int($txt);
1.368 albertel 9111: }
9112:
1.484 albertel 9113: sub numval2 {
9114: my $txt=shift;
9115: $txt=~tr/A-J/0-9/;
9116: $txt=~tr/a-j/0-9/;
9117: $txt=~tr/K-T/0-9/;
9118: $txt=~tr/k-t/0-9/;
9119: $txt=~tr/U-Z/0-5/;
9120: $txt=~tr/u-z/0-5/;
9121: $txt=~s/\D//g;
9122: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9123: my $total;
9124: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9125: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9126: return int($total);
9127: }
9128:
1.575 albertel 9129: sub numval3 {
9130: use integer;
9131: my $txt=shift;
9132: $txt=~tr/A-J/0-9/;
9133: $txt=~tr/a-j/0-9/;
9134: $txt=~tr/K-T/0-9/;
9135: $txt=~tr/k-t/0-9/;
9136: $txt=~tr/U-Z/0-5/;
9137: $txt=~tr/u-z/0-5/;
9138: $txt=~s/\D//g;
9139: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9140: my $total;
9141: foreach my $val (@txts) { $total+=$val; }
9142: if ($_64bit) { $total=(($total<<32)>>32); }
9143: return $total;
9144: }
9145:
1.675 albertel 9146: sub digest {
9147: my ($data)=@_;
9148: my $digest=&Digest::MD5::md5($data);
9149: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9150: my ($e,$f);
9151: {
9152: use integer;
9153: $e=($a+$b);
9154: $f=($c+$d);
9155: if ($_64bit) {
9156: $e=(($e<<32)>>32);
9157: $f=(($f<<32)>>32);
9158: }
9159: }
9160: if (wantarray) {
9161: return ($e,$f);
9162: } else {
9163: my $g;
9164: {
9165: use integer;
9166: $g=($e+$f);
9167: if ($_64bit) {
9168: $g=(($g<<32)>>32);
9169: }
9170: }
9171: return $g;
9172: }
9173: }
9174:
1.368 albertel 9175: sub latest_rnd_algorithm_id {
1.675 albertel 9176: return '64bit5';
1.366 albertel 9177: }
1.32 www 9178:
1.503 albertel 9179: sub get_rand_alg {
9180: my ($courseid)=@_;
1.790 albertel 9181: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9182: if ($courseid) {
1.620 albertel 9183: return $env{"course.$courseid.rndseed"};
1.503 albertel 9184: }
9185: return &latest_rnd_algorithm_id();
9186: }
9187:
1.562 albertel 9188: sub validCODE {
9189: my ($CODE)=@_;
9190: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9191: return 0;
9192: }
9193:
1.491 albertel 9194: sub getCODE {
1.620 albertel 9195: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9196: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9197: defined($Apache::lonhomework::parsing_a_task) ) &&
9198: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9199: return $Apache::lonhomework::history{'resource.CODE'};
9200: }
9201: return undef;
9202: }
9203:
1.31 www 9204: sub rndseed {
1.155 albertel 9205: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 9206: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9207: if (!defined($symb)) {
1.366 albertel 9208: unless ($symb=$wsymb) { return time; }
9209: }
9210: if (!$courseid) { $courseid=$wcourseid; }
9211: if (!$domain) { $domain=$wdomain; }
9212: if (!$username) { $username=$wusername }
1.503 albertel 9213: my $which=&get_rand_alg();
1.803 albertel 9214:
1.491 albertel 9215: if (defined(&getCODE())) {
1.675 albertel 9216: if ($which eq '64bit5') {
9217: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9218: } elsif ($which eq '64bit4') {
1.575 albertel 9219: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9220: } else {
9221: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9222: }
1.675 albertel 9223: } elsif ($which eq '64bit5') {
9224: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9225: } elsif ($which eq '64bit4') {
9226: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9227: } elsif ($which eq '64bit3') {
9228: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9229: } elsif ($which eq '64bit2') {
9230: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9231: } elsif ($which eq '64bit') {
9232: return &rndseed_64bit($symb,$courseid,$domain,$username);
9233: }
9234: return &rndseed_32bit($symb,$courseid,$domain,$username);
9235: }
9236:
9237: sub rndseed_32bit {
9238: my ($symb,$courseid,$domain,$username)=@_;
9239: {
9240: use integer;
9241: my $symbchck=unpack("%32C*",$symb) << 27;
9242: my $symbseed=numval($symb) << 22;
9243: my $namechck=unpack("%32C*",$username) << 17;
9244: my $nameseed=numval($username) << 12;
9245: my $domainseed=unpack("%32C*",$domain) << 7;
9246: my $courseseed=unpack("%32C*",$courseid);
9247: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9248: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9249: #&logthis("rndseed :$num:$symb");
1.564 albertel 9250: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9251: return $num;
9252: }
9253: }
9254:
9255: sub rndseed_64bit {
9256: my ($symb,$courseid,$domain,$username)=@_;
9257: {
9258: use integer;
9259: my $symbchck=unpack("%32S*",$symb) << 21;
9260: my $symbseed=numval($symb) << 10;
9261: my $namechck=unpack("%32S*",$username);
9262:
9263: my $nameseed=numval($username) << 21;
9264: my $domainseed=unpack("%32S*",$domain) << 10;
9265: my $courseseed=unpack("%32S*",$courseid);
9266:
9267: my $num1=$symbchck+$symbseed+$namechck;
9268: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9269: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9270: #&logthis("rndseed :$num:$symb");
1.564 albertel 9271: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9272: return "$num1,$num2";
1.155 albertel 9273: }
1.366 albertel 9274: }
9275:
1.443 albertel 9276: sub rndseed_64bit2 {
9277: my ($symb,$courseid,$domain,$username)=@_;
9278: {
9279: use integer;
9280: # strings need to be an even # of cahracters long, it it is odd the
9281: # last characters gets thrown away
9282: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9283: my $symbseed=numval($symb) << 10;
9284: my $namechck=unpack("%32S*",$username.' ');
9285:
9286: my $nameseed=numval($username) << 21;
1.501 albertel 9287: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9288: my $courseseed=unpack("%32S*",$courseid.' ');
9289:
9290: my $num1=$symbchck+$symbseed+$namechck;
9291: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9292: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9293: #&logthis("rndseed :$num:$symb");
1.803 albertel 9294: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9295: return "$num1,$num2";
9296: }
9297: }
9298:
9299: sub rndseed_64bit3 {
9300: my ($symb,$courseid,$domain,$username)=@_;
9301: {
9302: use integer;
9303: # strings need to be an even # of cahracters long, it it is odd the
9304: # last characters gets thrown away
9305: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9306: my $symbseed=numval2($symb) << 10;
9307: my $namechck=unpack("%32S*",$username.' ');
9308:
9309: my $nameseed=numval2($username) << 21;
1.443 albertel 9310: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9311: my $courseseed=unpack("%32S*",$courseid.' ');
9312:
9313: my $num1=$symbchck+$symbseed+$namechck;
9314: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9315: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9316: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9317: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9318:
1.503 albertel 9319: return "$num1:$num2";
1.443 albertel 9320: }
9321: }
9322:
1.575 albertel 9323: sub rndseed_64bit4 {
9324: my ($symb,$courseid,$domain,$username)=@_;
9325: {
9326: use integer;
9327: # strings need to be an even # of cahracters long, it it is odd the
9328: # last characters gets thrown away
9329: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9330: my $symbseed=numval3($symb) << 10;
9331: my $namechck=unpack("%32S*",$username.' ');
9332:
9333: my $nameseed=numval3($username) << 21;
9334: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9335: my $courseseed=unpack("%32S*",$courseid.' ');
9336:
9337: my $num1=$symbchck+$symbseed+$namechck;
9338: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9339: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9340: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9341: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9342:
9343: return "$num1:$num2";
9344: }
9345: }
9346:
1.675 albertel 9347: sub rndseed_64bit5 {
9348: my ($symb,$courseid,$domain,$username)=@_;
9349: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9350: return "$num1:$num2";
9351: }
9352:
1.366 albertel 9353: sub rndseed_CODE_64bit {
9354: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9355: {
1.366 albertel 9356: use integer;
1.443 albertel 9357: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9358: my $symbseed=numval2($symb);
1.491 albertel 9359: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9360: my $CODEseed=numval(&getCODE());
1.443 albertel 9361: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9362: my $num1=$symbseed+$CODEchck;
9363: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9364: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9365: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9366: if ($_64bit) { $num1=(($num1<<32)>>32); }
9367: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9368: return "$num1:$num2";
1.366 albertel 9369: }
9370: }
9371:
1.575 albertel 9372: sub rndseed_CODE_64bit4 {
9373: my ($symb,$courseid,$domain,$username)=@_;
9374: {
9375: use integer;
9376: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9377: my $symbseed=numval3($symb);
9378: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9379: my $CODEseed=numval3(&getCODE());
9380: my $courseseed=unpack("%32S*",$courseid.' ');
9381: my $num1=$symbseed+$CODEchck;
9382: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9383: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9384: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9385: if ($_64bit) { $num1=(($num1<<32)>>32); }
9386: if ($_64bit) { $num2=(($num2<<32)>>32); }
9387: return "$num1:$num2";
9388: }
9389: }
9390:
1.675 albertel 9391: sub rndseed_CODE_64bit5 {
9392: my ($symb,$courseid,$domain,$username)=@_;
9393: my $code = &getCODE();
9394: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9395: return "$num1:$num2";
9396: }
9397:
1.366 albertel 9398: sub setup_random_from_rndseed {
9399: my ($rndseed)=@_;
1.503 albertel 9400: if ($rndseed =~/([,:])/) {
9401: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9402: &Math::Random::random_set_seed(abs($num1),abs($num2));
9403: } else {
9404: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9405: }
1.36 albertel 9406: }
9407:
1.474 albertel 9408: sub latest_receipt_algorithm_id {
1.835 albertel 9409: return 'receipt3';
1.474 albertel 9410: }
9411:
1.480 www 9412: sub recunique {
9413: my $fucourseid=shift;
9414: my $unique;
1.835 albertel 9415: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9416: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9417: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9418: } else {
9419: $unique=$perlvar{'lonReceipt'};
9420: }
9421: return unpack("%32C*",$unique);
9422: }
9423:
9424: sub recprefix {
9425: my $fucourseid=shift;
9426: my $prefix;
1.835 albertel 9427: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9428: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9429: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9430: } else {
9431: $prefix=$perlvar{'lonHostID'};
9432: }
9433: return unpack("%32C*",$prefix);
9434: }
9435:
1.76 www 9436: sub ireceipt {
1.474 albertel 9437: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9438:
9439: my $return =&recprefix($fucourseid).'-';
9440:
9441: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9442: $env{'request.state'} eq 'construct') {
9443: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9444: return $return;
9445: }
9446:
1.76 www 9447: my $cuname=unpack("%32C*",$funame);
9448: my $cudom=unpack("%32C*",$fudom);
9449: my $cucourseid=unpack("%32C*",$fucourseid);
9450: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9451: my $cunique=&recunique($fucourseid);
1.474 albertel 9452: my $cpart=unpack("%32S*",$part);
1.835 albertel 9453: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9454:
1.790 albertel 9455: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9456:
9457: $return.= ($cunique%$cuname+
9458: $cunique%$cudom+
9459: $cusymb%$cuname+
9460: $cusymb%$cudom+
9461: $cucourseid%$cuname+
9462: $cucourseid%$cudom+
9463: $cpart%$cuname+
9464: $cpart%$cudom);
9465: } else {
9466: $return.= ($cunique%$cuname+
9467: $cunique%$cudom+
9468: $cusymb%$cuname+
9469: $cusymb%$cudom+
9470: $cucourseid%$cuname+
9471: $cucourseid%$cudom);
9472: }
9473: return $return;
1.76 www 9474: }
9475:
9476: sub receipt {
1.474 albertel 9477: my ($part)=@_;
1.790 albertel 9478: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 9479: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 9480: }
1.260 ng 9481:
1.790 albertel 9482: sub whichuser {
9483: my ($passedsymb)=@_;
9484: my ($symb,$courseid,$domain,$name,$publicuser);
9485: if (defined($env{'form.grade_symb'})) {
9486: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
9487: my $allowed=&allowed('vgr',$tmp_courseid);
9488: if (!$allowed &&
9489: exists($env{'request.course.sec'}) &&
9490: $env{'request.course.sec'} !~ /^\s*$/) {
9491: $allowed=&allowed('vgr',$tmp_courseid.
9492: '/'.$env{'request.course.sec'});
9493: }
9494: if ($allowed) {
9495: ($symb)=&get_env_multiple('form.grade_symb');
9496: $courseid=$tmp_courseid;
9497: ($domain)=&get_env_multiple('form.grade_domain');
9498: ($name)=&get_env_multiple('form.grade_username');
9499: return ($symb,$courseid,$domain,$name,$publicuser);
9500: }
9501: }
9502: if (!$passedsymb) {
9503: $symb=&symbread();
9504: } else {
9505: $symb=$passedsymb;
9506: }
9507: $courseid=$env{'request.course.id'};
9508: $domain=$env{'user.domain'};
9509: $name=$env{'user.name'};
9510: if ($name eq 'public' && $domain eq 'public') {
9511: if (!defined($env{'form.username'})) {
9512: $env{'form.username'}.=time.rand(10000000);
9513: }
9514: $name.=$env{'form.username'};
9515: }
9516: return ($symb,$courseid,$domain,$name,$publicuser);
9517:
9518: }
9519:
1.36 albertel 9520: # ------------------------------------------------------------ Serves up a file
1.472 albertel 9521: # returns either the contents of the file or
9522: # -1 if the file doesn't exist
1.481 raeburn 9523: #
9524: # if the target is a file that was uploaded via DOCS,
9525: # a check will be made to see if a current copy exists on the local server,
9526: # if it does this will be served, otherwise a copy will be retrieved from
9527: # the home server for the course and stored in /home/httpd/html/userfiles on
9528: # the local server.
1.472 albertel 9529:
1.36 albertel 9530: sub getfile {
1.538 albertel 9531: my ($file) = @_;
1.609 banghart 9532: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 9533: &repcopy($file);
9534: return &readfile($file);
9535: }
9536:
9537: sub repcopy_userfile {
9538: my ($file)=@_;
1.609 banghart 9539: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 9540: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 9541: my ($cdom,$cnum,$filename) =
1.811 albertel 9542: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 9543: my $uri="/uploaded/$cdom/$cnum/$filename";
9544: if (-e "$file") {
1.828 www 9545: # we already have a local copy, check it out
1.538 albertel 9546: my @fileinfo = stat($file);
1.828 www 9547: my $rtncode;
9548: my $info;
1.538 albertel 9549: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 9550: if ($lwpresp ne 'ok') {
1.828 www 9551: # there is no such file anymore, even though we had a local copy
1.482 albertel 9552: if ($rtncode eq '404') {
1.538 albertel 9553: unlink($file);
1.482 albertel 9554: }
9555: return -1;
9556: }
9557: if ($info < $fileinfo[9]) {
1.828 www 9558: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 9559: return 'ok';
1.828 www 9560: } else {
9561: # the file is outdated, get rid of it
9562: unlink($file);
1.482 albertel 9563: }
1.828 www 9564: }
9565: # one way or the other, at this point, we don't have the file
9566: # construct the correct path for the file
9567: my @parts = ($cdom,$cnum);
9568: if ($filename =~ m|^(.+)/[^/]+$|) {
9569: push @parts, split(/\//,$1);
9570: }
9571: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
9572: foreach my $part (@parts) {
9573: $path .= '/'.$part;
9574: if (!-e $path) {
9575: mkdir($path,0770);
1.482 albertel 9576: }
9577: }
1.828 www 9578: # now the path exists for sure
9579: # get a user agent
9580: my $ua=new LWP::UserAgent;
9581: my $transferfile=$file.'.in.transfer';
9582: # FIXME: this should flock
9583: if (-e $transferfile) { return 'ok'; }
9584: my $request;
9585: $uri=~s/^\///;
1.980 raeburn 9586: my $homeserver = &homeserver($cnum,$cdom);
9587: my $protocol = $protocol{$homeserver};
9588: $protocol = 'http' if ($protocol ne 'https');
9589: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 9590: my $response=$ua->request($request,$transferfile);
9591: # did it work?
9592: if ($response->is_error()) {
9593: unlink($transferfile);
9594: &logthis("Userfile repcopy failed for $uri");
9595: return -1;
9596: }
9597: # worked, rename the transfer file
9598: rename($transferfile,$file);
1.607 raeburn 9599: return 'ok';
1.481 raeburn 9600: }
9601:
1.517 albertel 9602: sub tokenwrapper {
9603: my $uri=shift;
1.980 raeburn 9604: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 9605: $uri=~s|^/||;
1.620 albertel 9606: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 9607: my $token=$1;
1.552 albertel 9608: my (undef,$udom,$uname,$file)=split('/',$uri,4);
9609: if ($udom && $uname && $file) {
9610: $file=~s|(\?\.*)*$||;
1.949 raeburn 9611: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 9612: my $homeserver = &homeserver($uname,$udom);
9613: my $protocol = $protocol{$homeserver};
9614: $protocol = 'http' if ($protocol ne 'https');
9615: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 9616: (($uri=~/\?/)?'&':'?').'token='.$token.
9617: '&tokenissued='.$perlvar{'lonHostID'};
9618: } else {
9619: return '/adm/notfound.html';
9620: }
9621: }
9622:
1.828 www 9623: # call with reqtype HEAD: get last modification time
9624: # call with reqtype GET: get the file contents
9625: # Do not call this with reqtype GET for large files! It loads everything into memory
9626: #
1.481 raeburn 9627: sub getuploaded {
9628: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
9629: $uri=~s/^\///;
1.980 raeburn 9630: my $homeserver = &homeserver($cnum,$cdom);
9631: my $protocol = $protocol{$homeserver};
9632: $protocol = 'http' if ($protocol ne 'https');
9633: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 9634: my $ua=new LWP::UserAgent;
9635: my $request=new HTTP::Request($reqtype,$uri);
9636: my $response=$ua->request($request);
9637: $$rtncode = $response->code;
1.482 albertel 9638: if (! $response->is_success()) {
9639: return 'failed';
9640: }
9641: if ($reqtype eq 'HEAD') {
1.486 www 9642: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 9643: } elsif ($reqtype eq 'GET') {
9644: $$info = $response->content;
1.472 albertel 9645: }
1.482 albertel 9646: return 'ok';
1.36 albertel 9647: }
9648:
1.481 raeburn 9649: sub readfile {
9650: my $file = shift;
9651: if ( (! -e $file ) || ($file eq '') ) { return -1; };
9652: my $fh;
9653: open($fh,"<$file");
9654: my $a='';
1.800 albertel 9655: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 9656: return $a;
9657: }
9658:
1.36 albertel 9659: sub filelocation {
1.590 banghart 9660: my ($dir,$file) = @_;
9661: my $location;
9662: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 9663:
9664: if ($file =~ m-^/adm/-) {
9665: $file=~s-^/adm/wrapper/-/-;
9666: $file=~s-^/adm/coursedocs/showdoc/-/-;
9667: }
1.882 albertel 9668:
1.590 banghart 9669: if ($file=~m:^/~:) { # is a contruction space reference
9670: $location = $file;
9671: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 9672: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 9673: # is a correct contruction space reference
9674: $location = $file;
1.956 raeburn 9675: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
9676: $location = $file;
1.609 banghart 9677: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 9678: my ($udom,$uname,$filename)=
1.811 albertel 9679: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 9680: my $home=&homeserver($uname,$udom);
9681: my $is_me=0;
9682: my @ids=¤t_machine_ids();
9683: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9684: if ($is_me) {
1.955 raeburn 9685: $location=&propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 9686: } else {
9687: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9688: $udom.'/'.$uname.'/'.$filename;
9689: }
1.882 albertel 9690: } elsif ($file =~ m-^/adm/-) {
9691: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 9692: } else {
9693: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9694: $file=~s:^/res/:/:;
9695: if ( !( $file =~ m:^/:) ) {
9696: $location = $dir. '/'.$file;
9697: } else {
9698: $location = '/home/httpd/html/res'.$file;
9699: }
1.59 albertel 9700: }
1.590 banghart 9701: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 9702: while ($location=~m{/\.\./}) {
9703: if ($location =~ m{/[^/]+/\.\./}) {
9704: $location=~ s{/[^/]+/\.\./}{/}g;
9705: } else {
9706: $location=~ s{/\.\./}{/}g;
9707: }
9708: } #remove dir/..
1.590 banghart 9709: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9710: return $location;
1.46 www 9711: }
1.36 albertel 9712:
1.46 www 9713: sub hreflocation {
9714: my ($dir,$file)=@_;
1.980 raeburn 9715: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 9716: $file=filelocation($dir,$file);
1.700 albertel 9717: } elsif ($file=~m-^/adm/-) {
9718: $file=~s-^/adm/wrapper/-/-;
9719: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 9720: }
9721: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9722: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 9723: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9724: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 9725: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 9726: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 9727: -/uploaded/$1/$2/-x;
1.46 www 9728: }
1.913 albertel 9729: if ($file=~ m{^/userfiles/}) {
9730: $file =~ s{^/userfiles/}{/uploaded/};
9731: }
1.462 albertel 9732: return $file;
1.465 albertel 9733: }
9734:
9735: sub current_machine_domains {
1.853 albertel 9736: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9737: }
9738:
9739: sub machine_domains {
9740: my ($hostname) = @_;
1.465 albertel 9741: my @domains;
1.838 albertel 9742: my %hostname = &all_hostnames();
1.465 albertel 9743: while( my($id, $name) = each(%hostname)) {
1.467 matthew 9744: # &logthis("-$id-$name-$hostname-");
1.465 albertel 9745: if ($hostname eq $name) {
1.844 albertel 9746: push(@domains,&host_domain($id));
1.465 albertel 9747: }
9748: }
9749: return @domains;
9750: }
9751:
9752: sub current_machine_ids {
1.853 albertel 9753: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9754: }
9755:
9756: sub machine_ids {
9757: my ($hostname) = @_;
9758: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 9759: my @ids;
1.888 albertel 9760: my %name_to_host = &all_names();
1.889 albertel 9761: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9762: return @{ $name_to_host{$hostname} };
9763: }
9764: return;
1.31 www 9765: }
9766:
1.824 raeburn 9767: sub additional_machine_domains {
9768: my @domains;
9769: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9770: while( my $line = <$fh>) {
9771: $line =~ s/\s//g;
9772: push(@domains,$line);
9773: }
9774: return @domains;
9775: }
9776:
9777: sub default_login_domain {
9778: my $domain = $perlvar{'lonDefDomain'};
9779: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9780: foreach my $posdom (¤t_machine_domains(),
9781: &additional_machine_domains()) {
9782: if (lc($posdom) eq lc($testdomain)) {
9783: $domain=$posdom;
9784: last;
9785: }
9786: }
9787: return $domain;
9788: }
9789:
1.31 www 9790: # ------------------------------------------------------------- Declutters URLs
9791:
9792: sub declutter {
9793: my $thisfn=shift;
1.569 albertel 9794: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 9795: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 9796: $thisfn=~s/^\///;
1.697 albertel 9797: $thisfn=~s|^adm/wrapper/||;
9798: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 9799: $thisfn=~s/^res\///;
1.1032 raeburn 9800: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9801: $thisfn=~s/\?.+$//;
9802: }
1.268 www 9803: return $thisfn;
9804: }
9805:
9806: # ------------------------------------------------------------- Clutter up URLs
9807:
9808: sub clutter {
9809: my $thisfn='/'.&declutter(shift);
1.887 albertel 9810: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 9811: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 9812: $thisfn='/res'.$thisfn;
9813: }
1.1031 raeburn 9814: if ($thisfn !~m|^/adm|) {
9815: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 9816: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 9817: } else {
9818: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9819: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 9820: if ($embstyle eq 'ssi'
9821: || ($embstyle eq 'hdn')
9822: || ($embstyle eq 'rat')
9823: || ($embstyle eq 'prv')
9824: || ($embstyle eq 'ign')) {
9825: #do nothing with these
9826: } elsif (($embstyle eq 'img')
1.695 albertel 9827: || ($embstyle eq 'emb')
9828: || ($embstyle eq 'wrp')) {
9829: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 9830: } elsif ($embstyle eq 'unk'
9831: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 9832: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 9833: } else {
1.718 www 9834: # &logthis("Got a blank emb style");
1.695 albertel 9835: }
1.694 albertel 9836: }
9837: }
1.31 www 9838: return $thisfn;
1.12 www 9839: }
9840:
1.787 albertel 9841: sub clutter_with_no_wrapper {
9842: my $uri = &clutter(shift);
9843: if ($uri =~ m-^/adm/-) {
9844: $uri =~ s-^/adm/wrapper/-/-;
9845: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9846: }
9847: return $uri;
9848: }
9849:
1.557 albertel 9850: sub freeze_escape {
9851: my ($value)=@_;
9852: if (ref($value)) {
9853: $value=&nfreeze($value);
9854: return '__FROZEN__'.&escape($value);
9855: }
9856: return &escape($value);
9857: }
9858:
1.11 www 9859:
1.557 albertel 9860: sub thaw_unescape {
9861: my ($value)=@_;
9862: if ($value =~ /^__FROZEN__/) {
9863: substr($value,0,10,undef);
9864: $value=&unescape($value);
9865: return &thaw($value);
9866: }
9867: return &unescape($value);
9868: }
9869:
1.436 albertel 9870: sub correct_line_ends {
9871: my ($result)=@_;
9872: $$result =~s/\r\n/\n/mg;
9873: $$result =~s/\r/\n/mg;
1.415 albertel 9874: }
1.1 albertel 9875: # ================================================================ Main Program
9876:
1.184 www 9877: sub goodbye {
1.204 albertel 9878: &logthis("Starting Shut down");
1.443 albertel 9879: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 9880: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 9881: #converted
1.599 albertel 9882: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 9883: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9884: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9885: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 9886: #1.1 only
1.870 albertel 9887: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9888: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9889: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9890: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9891: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 9892: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9893: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 9894: &flushcourselogs();
9895: &logthis("Shutting down");
9896: }
9897:
1.852 albertel 9898: sub get_dns {
1.869 albertel 9899: my ($url,$func,$ignore_cache) = @_;
9900: if (!$ignore_cache) {
9901: my ($content,$cached)=
9902: &Apache::lonnet::is_cached_new('dns',$url);
9903: if ($cached) {
9904: &$func($content);
9905: return;
9906: }
9907: }
9908:
9909: my %alldns;
1.852 albertel 9910: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9911: foreach my $dns (<$config>) {
9912: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 9913: my $line = $1;
9914: my ($host,$protocol) = split(/:/,$line);
9915: if ($protocol ne 'https') {
9916: $protocol = 'http';
9917: }
9918: $alldns{$host} = $protocol;
1.869 albertel 9919: }
9920: while (%alldns) {
9921: my ($dns) = keys(%alldns);
1.852 albertel 9922: my $ua=new LWP::UserAgent;
1.979 raeburn 9923: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 9924: my $response=$ua->request($request);
1.979 raeburn 9925: delete($alldns{$dns});
1.852 albertel 9926: next if ($response->is_error());
9927: my @content = split("\n",$response->content);
1.869 albertel 9928: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 9929: &$func(\@content);
1.869 albertel 9930: return;
1.852 albertel 9931: }
9932: close($config);
1.871 albertel 9933: my $which = (split('/',$url))[3];
9934: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9935: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 9936: my @content = <$config>;
9937: &$func(\@content);
9938: return;
1.852 albertel 9939: }
1.327 albertel 9940: # ------------------------------------------------------------ Read domain file
9941: {
1.852 albertel 9942: my $loaded;
1.846 albertel 9943: my %domain;
9944:
1.852 albertel 9945: sub parse_domain_tab {
9946: my ($lines) = @_;
9947: foreach my $line (@$lines) {
9948: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 9949:
1.846 albertel 9950: chomp($line);
1.852 albertel 9951: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 9952: my %this_domain;
9953: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9954: 'lang_def', 'city', 'longi', 'lati',
9955: 'primary') {
9956: $this_domain{$field} = shift(@elements);
9957: }
9958: $domain{$name} = \%this_domain;
1.852 albertel 9959: }
9960: }
1.864 albertel 9961:
9962: sub reset_domain_info {
9963: undef($loaded);
9964: undef(%domain);
9965: }
9966:
1.852 albertel 9967: sub load_domain_tab {
1.869 albertel 9968: my ($ignore_cache) = @_;
9969: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 9970: my $fh;
9971: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9972: my @lines = <$fh>;
9973: &parse_domain_tab(\@lines);
1.448 albertel 9974: }
1.852 albertel 9975: close($fh);
9976: $loaded = 1;
1.327 albertel 9977: }
1.846 albertel 9978:
9979: sub domain {
1.852 albertel 9980: &load_domain_tab() if (!$loaded);
9981:
1.846 albertel 9982: my ($name,$what) = @_;
9983: return if ( !exists($domain{$name}) );
9984:
9985: if (!$what) {
9986: return $domain{$name}{'description'};
9987: }
9988: return $domain{$name}{$what};
9989: }
1.974 raeburn 9990:
9991: sub domain_info {
9992: &load_domain_tab() if (!$loaded);
9993: return %domain;
9994: }
9995:
1.327 albertel 9996: }
9997:
9998:
1.1 albertel 9999: # ------------------------------------------------------------- Read hosts file
10000: {
1.838 albertel 10001: my %hostname;
1.844 albertel 10002: my %hostdom;
1.845 albertel 10003: my %libserv;
1.852 albertel 10004: my $loaded;
1.888 albertel 10005: my %name_to_host;
1.1074 raeburn 10006: my %internetdom;
1.852 albertel 10007:
10008: sub parse_hosts_tab {
10009: my ($file) = @_;
10010: foreach my $configline (@$file) {
10011: next if ($configline =~ /^(\#|\s*$ )/x);
10012: next if ($configline =~ /^\^/);
10013: chomp($configline);
1.1074 raeburn 10014: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10015: $name=~s/\s//g;
10016: if ($id && $domain && $role && $name) {
10017: $hostname{$id}=$name;
1.888 albertel 10018: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10019: $hostdom{$id}=$domain;
10020: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10021: if (defined($protocol)) {
10022: if ($protocol eq 'https') {
10023: $protocol{$id} = $protocol;
10024: } else {
10025: $protocol{$id} = 'http';
10026: }
1.968 raeburn 10027: } else {
1.969 raeburn 10028: $protocol{$id} = 'http';
1.968 raeburn 10029: }
1.1074 raeburn 10030: if (defined($intdom)) {
10031: $internetdom{$id} = $intdom;
10032: }
1.852 albertel 10033: }
10034: }
10035: }
1.864 albertel 10036:
10037: sub reset_hosts_info {
1.897 albertel 10038: &purge_remembered();
1.864 albertel 10039: &reset_domain_info();
10040: &reset_hosts_ip_info();
1.892 albertel 10041: undef(%name_to_host);
1.864 albertel 10042: undef(%hostname);
10043: undef(%hostdom);
10044: undef(%libserv);
10045: undef($loaded);
10046: }
1.1 albertel 10047:
1.852 albertel 10048: sub load_hosts_tab {
1.869 albertel 10049: my ($ignore_cache) = @_;
10050: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10051: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10052: my @config = <$config>;
10053: &parse_hosts_tab(\@config);
10054: close($config);
10055: $loaded=1;
1.1 albertel 10056: }
1.852 albertel 10057:
1.838 albertel 10058: sub hostname {
1.852 albertel 10059: &load_hosts_tab() if (!$loaded);
10060:
1.838 albertel 10061: my ($lonid) = @_;
10062: return $hostname{$lonid};
10063: }
1.845 albertel 10064:
1.838 albertel 10065: sub all_hostnames {
1.852 albertel 10066: &load_hosts_tab() if (!$loaded);
10067:
1.838 albertel 10068: return %hostname;
10069: }
1.845 albertel 10070:
1.888 albertel 10071: sub all_names {
10072: &load_hosts_tab() if (!$loaded);
10073:
10074: return %name_to_host;
10075: }
10076:
1.974 raeburn 10077: sub all_host_domain {
10078: &load_hosts_tab() if (!$loaded);
10079: return %hostdom;
10080: }
10081:
1.845 albertel 10082: sub is_library {
1.852 albertel 10083: &load_hosts_tab() if (!$loaded);
10084:
1.845 albertel 10085: return exists($libserv{$_[0]});
10086: }
10087:
10088: sub all_library {
1.852 albertel 10089: &load_hosts_tab() if (!$loaded);
10090:
1.845 albertel 10091: return %libserv;
10092: }
10093:
1.1062 droeschl 10094: sub unique_library {
10095: #2x reverse removes all hostnames that appear more than once
10096: my %unique = reverse &all_library();
10097: return reverse %unique;
10098: }
10099:
1.841 albertel 10100: sub get_servers {
1.852 albertel 10101: &load_hosts_tab() if (!$loaded);
10102:
1.841 albertel 10103: my ($domain,$type) = @_;
10104: my %possible_hosts = ($type eq 'library') ? %libserv
10105: : %hostname;
10106: my %result;
1.842 albertel 10107: if (ref($domain) eq 'ARRAY') {
10108: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10109: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10110: $result{$host} = $hostname;
10111: }
10112: }
10113: } else {
10114: while ( my ($host,$hostname) = each(%possible_hosts)) {
10115: if ($hostdom{$host} eq $domain) {
10116: $result{$host} = $hostname;
10117: }
1.841 albertel 10118: }
10119: }
10120: return %result;
10121: }
1.845 albertel 10122:
1.1062 droeschl 10123: sub get_unique_servers {
10124: my %unique = reverse &get_servers(@_);
10125: return reverse %unique;
10126: }
10127:
1.844 albertel 10128: sub host_domain {
1.852 albertel 10129: &load_hosts_tab() if (!$loaded);
10130:
1.844 albertel 10131: my ($lonid) = @_;
10132: return $hostdom{$lonid};
10133: }
10134:
1.841 albertel 10135: sub all_domains {
1.852 albertel 10136: &load_hosts_tab() if (!$loaded);
10137:
1.841 albertel 10138: my %seen;
10139: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10140: return @uniq;
10141: }
1.1074 raeburn 10142:
10143: sub internet_dom {
10144: &load_hosts_tab() if (!$loaded);
10145:
10146: my ($lonid) = @_;
10147: return $internetdom{$lonid};
10148: }
1.1 albertel 10149: }
10150:
1.847 albertel 10151: {
10152: my %iphost;
1.856 albertel 10153: my %name_to_ip;
10154: my %lonid_to_ip;
1.869 albertel 10155:
1.847 albertel 10156: sub get_hosts_from_ip {
10157: my ($ip) = @_;
10158: my %iphosts = &get_iphost();
10159: if (ref($iphosts{$ip})) {
10160: return @{$iphosts{$ip}};
10161: }
10162: return;
1.839 albertel 10163: }
1.864 albertel 10164:
10165: sub reset_hosts_ip_info {
10166: undef(%iphost);
10167: undef(%name_to_ip);
10168: undef(%lonid_to_ip);
10169: }
1.856 albertel 10170:
10171: sub get_host_ip {
10172: my ($lonid) = @_;
10173: if (exists($lonid_to_ip{$lonid})) {
10174: return $lonid_to_ip{$lonid};
10175: }
10176: my $name=&hostname($lonid);
10177: my $ip = gethostbyname($name);
10178: return if (!$ip || length($ip) ne 4);
10179: $ip=inet_ntoa($ip);
10180: $name_to_ip{$name} = $ip;
10181: $lonid_to_ip{$lonid} = $ip;
10182: return $ip;
10183: }
1.847 albertel 10184:
10185: sub get_iphost {
1.869 albertel 10186: my ($ignore_cache) = @_;
1.894 albertel 10187:
1.869 albertel 10188: if (!$ignore_cache) {
10189: if (%iphost) {
10190: return %iphost;
10191: }
10192: my ($ip_info,$cached)=
10193: &Apache::lonnet::is_cached_new('iphost','iphost');
10194: if ($cached) {
10195: %iphost = %{$ip_info->[0]};
10196: %name_to_ip = %{$ip_info->[1]};
10197: %lonid_to_ip = %{$ip_info->[2]};
10198: return %iphost;
10199: }
10200: }
1.894 albertel 10201:
10202: # get yesterday's info for fallback
10203: my %old_name_to_ip;
10204: my ($ip_info,$cached)=
10205: &Apache::lonnet::is_cached_new('iphost','iphost');
10206: if ($cached) {
10207: %old_name_to_ip = %{$ip_info->[1]};
10208: }
10209:
1.888 albertel 10210: my %name_to_host = &all_names();
10211: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10212: my $ip;
10213: if (!exists($name_to_ip{$name})) {
10214: $ip = gethostbyname($name);
10215: if (!$ip || length($ip) ne 4) {
1.894 albertel 10216: if (defined($old_name_to_ip{$name})) {
10217: $ip = $old_name_to_ip{$name};
10218: &logthis("Can't find $name defaulting to old $ip");
10219: } else {
10220: &logthis("Name $name no IP found");
10221: next;
10222: }
10223: } else {
10224: $ip=inet_ntoa($ip);
1.847 albertel 10225: }
10226: $name_to_ip{$name} = $ip;
10227: } else {
10228: $ip = $name_to_ip{$name};
1.653 albertel 10229: }
1.888 albertel 10230: foreach my $id (@{ $name_to_host{$name} }) {
10231: $lonid_to_ip{$id} = $ip;
10232: }
10233: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10234: }
1.869 albertel 10235: &Apache::lonnet::do_cache_new('iphost','iphost',
10236: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10237: 48*60*60);
1.869 albertel 10238:
1.847 albertel 10239: return %iphost;
1.598 albertel 10240: }
10241:
1.992 raeburn 10242: #
10243: # Given a DNS returns the loncapa host name for that DNS
10244: #
10245: sub host_from_dns {
10246: my ($dns) = @_;
10247: my @hosts;
10248: my $ip;
10249:
1.993 raeburn 10250: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10251: $ip = $name_to_ip{$dns};
10252: }
10253: if (!$ip) {
10254: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10255: if (length($ip) == 4) {
10256: $ip = &IO::Socket::inet_ntoa($ip);
10257: }
10258: }
10259: if ($ip) {
10260: @hosts = get_hosts_from_ip($ip);
10261: return $hosts[0];
10262: }
10263: return undef;
1.986 foxr 10264: }
1.992 raeburn 10265:
1.1074 raeburn 10266: sub get_internet_names {
10267: my ($lonid) = @_;
10268: return if ($lonid eq '');
10269: my ($idnref,$cached)=
10270: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10271: if ($cached) {
10272: return $idnref;
10273: }
10274: my $ip = &get_host_ip($lonid);
10275: my @hosts = &get_hosts_from_ip($ip);
10276: my %iphost = &get_iphost();
10277: my (@idns,%seen);
10278: foreach my $id (@hosts) {
10279: my $dom = &host_domain($id);
10280: my $prim_id = &domain($dom,'primary');
10281: my $prim_ip = &get_host_ip($prim_id);
10282: next if ($seen{$prim_ip});
10283: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10284: foreach my $id (@{$iphost{$prim_ip}}) {
10285: my $intdom = &internet_dom($id);
10286: unless (grep(/^\Q$intdom\E$/,@idns)) {
10287: push(@idns,$intdom);
10288: }
10289: }
10290: }
10291: $seen{$prim_ip} = 1;
10292: }
10293: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10294: }
10295:
1.986 foxr 10296: }
10297:
1.1079 raeburn 10298: sub all_loncaparevs {
10299: 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);
10300: }
10301:
1.862 albertel 10302: BEGIN {
10303:
10304: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10305: unless ($readit) {
10306: {
10307: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10308: %perlvar = (%perlvar,%{$configvars});
10309: }
10310:
10311:
1.1 albertel 10312: # ------------------------------------------------------ Read spare server file
10313: {
1.448 albertel 10314: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10315:
10316: while (my $configline=<$config>) {
10317: chomp($configline);
1.284 matthew 10318: if ($configline) {
1.784 albertel 10319: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10320: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10321: push(@{ $spareid{$type} }, $host);
1.1 albertel 10322: }
10323: }
1.448 albertel 10324: close($config);
1.1 albertel 10325: }
1.11 www 10326: # ------------------------------------------------------------ Read permissions
10327: {
1.448 albertel 10328: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10329:
10330: while (my $configline=<$config>) {
1.448 albertel 10331: chomp($configline);
10332: if ($configline) {
10333: my ($role,$perm)=split(/ /,$configline);
10334: if ($perm ne '') { $pr{$role}=$perm; }
10335: }
1.11 www 10336: }
1.448 albertel 10337: close($config);
1.11 www 10338: }
10339:
10340: # -------------------------------------------- Read plain texts for permissions
10341: {
1.448 albertel 10342: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10343:
10344: while (my $configline=<$config>) {
1.448 albertel 10345: chomp($configline);
10346: if ($configline) {
1.742 raeburn 10347: my ($short,@plain)=split(/:/,$configline);
10348: %{$prp{$short}} = ();
10349: if (@plain > 0) {
10350: $prp{$short}{'std'} = $plain[0];
10351: for (my $i=1; $i<@plain; $i++) {
10352: $prp{$short}{'alt'.$i} = $plain[$i];
10353: }
10354: }
1.448 albertel 10355: }
1.135 www 10356: }
1.448 albertel 10357: close($config);
1.135 www 10358: }
10359:
10360: # ---------------------------------------------------------- Read package table
10361: {
1.448 albertel 10362: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10363:
10364: while (my $configline=<$config>) {
1.483 albertel 10365: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10366: chomp($configline);
10367: my ($short,$plain)=split(/:/,$configline);
10368: my ($pack,$name)=split(/\&/,$short);
10369: if ($plain ne '') {
10370: $packagetab{$pack.'&'.$name.'&name'}=$name;
10371: $packagetab{$short}=$plain;
10372: }
1.11 www 10373: }
1.448 albertel 10374: close($config);
1.329 matthew 10375: }
10376:
1.1073 raeburn 10377: # ---------------------------------------------------------- Read loncaparev table
10378: {
10379: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10380: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10381: while (my $configline=<$config>) {
10382: chomp($configline);
10383: my ($hostid,$loncaparev)=split(/:/,$configline);
10384: $loncaparevs{$hostid}=$loncaparev;
10385: }
10386: close($config);
10387: }
10388: }
10389: }
10390:
1.1074 raeburn 10391: # ---------------------------------------------------------- Read serverhostID table
10392: {
10393: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10394: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10395: while (my $configline=<$config>) {
10396: chomp($configline);
10397: my ($name,$id)=split(/:/,$configline);
10398: $serverhomeIDs{$name}=$id;
10399: }
10400: close($config);
10401: }
10402: }
10403: }
10404:
1.1079 raeburn 10405: {
10406: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10407: if (-e $file) {
10408: my $parser = HTML::LCParser->new($file);
10409: while (my $token = $parser->get_token()) {
10410: if ($token->[0] eq 'S') {
10411: my $item = $token->[1];
10412: my $name = $token->[2]{'name'};
10413: my $value = $token->[2]{'value'};
10414: if ($item ne '' && $name ne '' && $value ne '') {
10415: my $release = $parser->get_text();
10416: $release =~ s/(^\s*|\s*$ )//gx;
10417: $needsrelease{$item.':'.$name.':'.$value} = $release;
10418: }
10419: }
10420: }
10421: }
1.1073 raeburn 10422: }
10423:
1.329 matthew 10424: # ------------- set up temporary directory
10425: {
10426: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10427:
1.11 www 10428: }
10429:
1.794 albertel 10430: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10431: 'compress_threshold'=> 20_000,
10432: });
1.185 www 10433:
1.281 www 10434: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10435: $dumpcount=0;
1.958 www 10436: $locknum=0;
1.22 www 10437:
1.163 harris41 10438: &logtouch();
1.672 albertel 10439: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10440: $readit=1;
1.564 albertel 10441: {
10442: use integer;
10443: my $test=(2**32)+1;
1.568 albertel 10444: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10445: &logthis(" Detected 64bit platform ($_64bit)");
10446: }
1.195 www 10447: }
1.1 albertel 10448: }
1.179 www 10449:
1.1 albertel 10450: 1;
1.191 harris41 10451: __END__
10452:
1.243 albertel 10453: =pod
10454:
1.191 harris41 10455: =head1 NAME
10456:
1.243 albertel 10457: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 10458:
10459: =head1 SYNOPSIS
10460:
1.243 albertel 10461: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 10462:
10463: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10464:
1.243 albertel 10465: Common parameters:
10466:
10467: =over 4
10468:
10469: =item *
10470:
10471: $uname : an internal username (if $cname expecting a course Id specifically)
10472:
10473: =item *
10474:
10475: $udom : a domain (if $cdom expecting a course's domain specifically)
10476:
10477: =item *
10478:
10479: $symb : a resource instance identifier
10480:
10481: =item *
10482:
10483: $namespace : the name of a .db file that contains the data needed or
10484: being set.
10485:
10486: =back
10487:
1.394 bowersj2 10488: =head1 OVERVIEW
1.191 harris41 10489:
1.394 bowersj2 10490: lonnet provides subroutines which interact with the
10491: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10492: about classes, users, and resources.
1.243 albertel 10493:
10494: For many of these objects you can also use this to store data about
10495: them or modify them in various ways.
1.191 harris41 10496:
1.394 bowersj2 10497: =head2 Symbs
1.191 harris41 10498:
1.394 bowersj2 10499: To identify a specific instance of a resource, LON-CAPA uses symbols
10500: or "symbs"X<symb>. These identifiers are built from the URL of the
10501: map, the resource number of the resource in the map, and the URL of
10502: the resource itself. The latter is somewhat redundant, but might help
10503: if maps change.
10504:
10505: An example is
10506:
10507: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10508:
10509: The respective map entry is
10510:
10511: <resource id="19" src="/res/msu/korte/tests/part12.problem"
10512: title="Problem 2">
10513: </resource>
10514:
10515: Symbs are used by the random number generator, as well as to store and
10516: restore data specific to a certain instance of for example a problem.
10517:
10518: =head2 Storing And Retrieving Data
10519:
10520: X<store()>X<cstore()>X<restore()>Three of the most important functions
10521: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10522: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10523: is is the non-critical message twin of cstore. These functions are for
10524: handlers to store a perl hash to a user's permanent data space in an
10525: easy manner, and to retrieve it again on another call. It is expected
10526: that a handler would use this once at the beginning to retrieve data,
10527: and then again once at the end to send only the new data back.
10528:
10529: The data is stored in the user's data directory on the user's
10530: homeserver under the ID of the course.
10531:
10532: The hash that is returned by restore will have all of the previous
10533: value for all of the elements of the hash.
10534:
10535: Example:
10536:
10537: #creating a hash
10538: my %hash;
10539: $hash{'foo'}='bar';
10540:
10541: #storing it
10542: &Apache::lonnet::cstore(\%hash);
10543:
10544: #changing a value
10545: $hash{'foo'}='notbar';
10546:
10547: #adding a new value
10548: $hash{'bar'}='foo';
10549: &Apache::lonnet::cstore(\%hash);
10550:
10551: #retrieving the hash
10552: my %history=&Apache::lonnet::restore();
10553:
10554: #print the hash
10555: foreach my $key (sort(keys(%history))) {
10556: print("\%history{$key} = $history{$key}");
10557: }
10558:
10559: Will print out:
1.191 harris41 10560:
1.394 bowersj2 10561: %history{1:foo} = bar
10562: %history{1:keys} = foo:timestamp
10563: %history{1:timestamp} = 990455579
10564: %history{2:bar} = foo
10565: %history{2:foo} = notbar
10566: %history{2:keys} = foo:bar:timestamp
10567: %history{2:timestamp} = 990455580
10568: %history{bar} = foo
10569: %history{foo} = notbar
10570: %history{timestamp} = 990455580
10571: %history{version} = 2
10572:
10573: Note that the special hash entries C<keys>, C<version> and
10574: C<timestamp> were added to the hash. C<version> will be equal to the
10575: total number of versions of the data that have been stored. The
10576: C<timestamp> attribute will be the UNIX time the hash was
10577: stored. C<keys> is available in every historical section to list which
10578: keys were added or changed at a specific historical revision of a
10579: hash.
10580:
10581: B<Warning>: do not store the hash that restore returns directly. This
10582: will cause a mess since it will restore the historical keys as if the
10583: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 10584:
1.394 bowersj2 10585: Calling convention:
1.191 harris41 10586:
1.394 bowersj2 10587: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10588: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 10589:
1.394 bowersj2 10590: For more detailed information, see lonnet specific documentation.
1.191 harris41 10591:
1.394 bowersj2 10592: =head1 RETURN MESSAGES
1.191 harris41 10593:
1.394 bowersj2 10594: =over 4
1.191 harris41 10595:
1.394 bowersj2 10596: =item * B<con_lost>: unable to contact remote host
1.191 harris41 10597:
1.394 bowersj2 10598: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10599: when the connection is brought back up
1.191 harris41 10600:
1.394 bowersj2 10601: =item * B<con_failed>: unable to contact remote host and unable to save message
10602: for later delivery
1.191 harris41 10603:
1.967 bisitz 10604: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 10605:
1.394 bowersj2 10606: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 10607: that was requested
1.191 harris41 10608:
1.243 albertel 10609: =back
1.191 harris41 10610:
1.243 albertel 10611: =head1 PUBLIC SUBROUTINES
1.191 harris41 10612:
1.243 albertel 10613: =head2 Session Environment Functions
1.191 harris41 10614:
1.243 albertel 10615: =over 4
1.191 harris41 10616:
1.394 bowersj2 10617: =item *
10618: X<appenv()>
1.949 raeburn 10619: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 10620: the user envirnoment file, and will be restored for each access this
1.620 albertel 10621: user makes during this session, also modifies the %env for the current
1.949 raeburn 10622: process. Optional rolesarrayref - if defined contains a reference to an array
10623: of roles which are exempt from the restriction on modifying user.role entries
10624: in the user's environment.db and in %env.
1.191 harris41 10625:
10626: =item *
1.394 bowersj2 10627: X<delenv()>
1.987 raeburn 10628: B<delenv($delthis,$regexp)>: removes all items from the session
10629: environment file that begin with $delthis. If the
10630: optional second arg - $regexp - is true, $delthis is treated as a
10631: regular expression, otherwise \Q$delthis\E is used.
10632: The values are also deleted from the current processes %env.
1.191 harris41 10633:
1.795 albertel 10634: =item * get_env_multiple($name)
10635:
10636: gets $name from the %env hash, it seemlessly handles the cases where multiple
10637: values may be defined and end up as an array ref.
10638:
10639: returns an array of values
10640:
1.243 albertel 10641: =back
10642:
10643: =head2 User Information
1.191 harris41 10644:
1.243 albertel 10645: =over 4
1.191 harris41 10646:
10647: =item *
1.394 bowersj2 10648: X<queryauthenticate()>
10649: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 10650: authentication scheme
10651:
10652: =item *
1.394 bowersj2 10653: X<authenticate()>
1.1073 raeburn 10654: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 10655: authenticate user from domain's lib servers (first use the current
10656: one). C<$upass> should be the users password.
1.1073 raeburn 10657: $checkdefauth is optional (value is 1 if a check should be made to
10658: authenticate user using default authentication method, and allow
10659: account creation if username does not have account in the domain).
10660: $clientcancheckhost is optional (value is 1 if checking whether the
10661: server can host will occur on the client side in lonauth.pm).
1.191 harris41 10662:
10663: =item *
1.394 bowersj2 10664: X<homeserver()>
10665: B<homeserver($uname,$udom)>: find the server which has
10666: the user's directory and files (there must be only one), this caches
10667: the answer, and also caches if there is a borken connection.
1.191 harris41 10668:
10669: =item *
1.394 bowersj2 10670: X<idget()>
10671: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10672: (IDs are a unique resource in a domain, there must be only 1 ID per
10673: username, and only 1 username per ID in a specific domain) (returns
10674: hash: id=>name,id=>name)
1.191 harris41 10675:
10676: =item *
1.394 bowersj2 10677: X<idrget()>
10678: B<idrget($udom,@unames)>: find the IDs behind a list of
10679: usernames (returns hash: name=>id,name=>id)
1.191 harris41 10680:
10681: =item *
1.394 bowersj2 10682: X<idput()>
10683: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 10684:
10685: =item *
1.394 bowersj2 10686: X<rolesinit()>
10687: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 10688:
10689: =item *
1.551 albertel 10690: X<getsection()>
10691: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 10692: course $cname, return section name/number or '' for "not in course"
10693: and '-1' for "no section"
10694:
10695: =item *
1.394 bowersj2 10696: X<userenvironment()>
10697: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 10698: passed in @what from the requested user's environment, returns a hash
10699:
1.858 raeburn 10700: =item *
10701: X<userlog_query()>
1.859 albertel 10702: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10703: activity.log file. %filters defines filters applied when parsing the
10704: log file. These can be start or end timestamps, or the type of action
10705: - log to look for Login or Logout events, check for Checkin or
10706: Checkout, role for role selection. The response is in the form
10707: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
10708: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 10709:
1.243 albertel 10710: =back
10711:
10712: =head2 User Roles
10713:
10714: =over 4
10715:
10716: =item *
10717:
1.810 raeburn 10718: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 10719: F: full access
10720: U,I,K: authentication modes (cxx only)
10721: '': forbidden
10722: 1: user needs to choose course
10723: 2: browse allowed
1.766 albertel 10724: A: passphrase authentication needed
1.243 albertel 10725:
10726: =item *
10727:
10728: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10729: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10730: and course level
10731:
10732: =item *
10733:
1.988 raeburn 10734: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
10735: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 10736: $type is Course (default) or Community.
1.988 raeburn 10737: If $forcedefault evaluates to true, text returned will be default
10738: text for $type. Otherwise, if this is a course, the text returned
10739: will be a custom name for the role (if defined in the course's
10740: environment). If no custom name is defined the default is returned.
10741:
1.832 raeburn 10742: =item *
10743:
1.935 raeburn 10744: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 10745: All arguments are optional. Returns a hash of a roles, either for
10746: co-author/assistant author roles for a user's Construction Space
1.906 albertel 10747: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 10748: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10749: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10750: For each key, value is set to colon-separated start and end times for
10751: the role. If no username and domain are specified, will default to
1.934 raeburn 10752: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 10753: of role statuses (active, future or previous), roles
10754: (e.g., cc,in, st etc.) and domains of the roles which can be used
10755: to restrict the list of roles reported. If no array ref is
10756: provided for types, will default to return only active roles.
1.834 albertel 10757:
1.243 albertel 10758: =back
10759:
10760: =head2 User Modification
10761:
10762: =over 4
10763:
10764: =item *
10765:
1.957 raeburn 10766: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 10767: user for the level given by URL. Optional start and end dates (leave empty
10768: string or zero for "no date")
1.191 harris41 10769:
10770: =item *
10771:
1.243 albertel 10772: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10773: change a users, password, possible return values are: ok,
10774: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10775: refused
1.191 harris41 10776:
10777: =item *
10778:
1.243 albertel 10779: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 10780:
10781: =item *
10782:
1.1058 raeburn 10783: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10784: $forceid,$desiredhome,$email,$inststatus,$candelete) :
10785:
10786: will update user information (firstname,middlename,lastname,generation,
10787: permanentemail), and if forceid is true, student/employee ID also.
10788: A user's institutional affiliation(s) can also be updated.
10789: User information fields will not be overwritten with empty entries
10790: unless the field is included in the $candelete array reference.
10791: This array is included when a single user is modified via "Manage Users",
10792: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 10793:
10794: =item *
10795:
1.286 matthew 10796: modifystudent
10797:
1.957 raeburn 10798: modify a student's enrollment and identification information.
1.286 matthew 10799: The course id is resolved based on the current users environment.
10800: This means the envoking user must be a course coordinator or otherwise
10801: associated with a course.
10802:
1.297 matthew 10803: This call is essentially a wrapper for lonnet::modifyuser and
10804: lonnet::modify_student_enrollment
1.286 matthew 10805:
10806: Inputs:
10807:
10808: =over 4
10809:
1.957 raeburn 10810: =item B<$udom> Student's loncapa domain
1.286 matthew 10811:
1.957 raeburn 10812: =item B<$uname> Student's loncapa login name
1.286 matthew 10813:
1.964 bisitz 10814: =item B<$uid> Student/Employee ID
1.286 matthew 10815:
1.957 raeburn 10816: =item B<$umode> Student's authentication mode
1.286 matthew 10817:
1.957 raeburn 10818: =item B<$upass> Student's password
1.286 matthew 10819:
1.957 raeburn 10820: =item B<$first> Student's first name
1.286 matthew 10821:
1.957 raeburn 10822: =item B<$middle> Student's middle name
1.286 matthew 10823:
1.957 raeburn 10824: =item B<$last> Student's last name
1.286 matthew 10825:
1.957 raeburn 10826: =item B<$gene> Student's generation
1.286 matthew 10827:
1.957 raeburn 10828: =item B<$usec> Student's section in course
1.286 matthew 10829:
10830: =item B<$end> Unix time of the roles expiration
10831:
10832: =item B<$start> Unix time of the roles start date
10833:
10834: =item B<$forceid> If defined, allow $uid to be changed
10835:
10836: =item B<$desiredhome> server to use as home server for student
10837:
1.957 raeburn 10838: =item B<$email> Student's permanent e-mail address
10839:
10840: =item B<$type> Type of enrollment (auto or manual)
10841:
1.963 raeburn 10842: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10843:
10844: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 10845:
1.963 raeburn 10846: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 10847:
1.963 raeburn 10848: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 10849:
1.963 raeburn 10850: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 10851:
1.286 matthew 10852: =back
1.297 matthew 10853:
10854: =item *
10855:
10856: modify_student_enrollment
10857:
10858: Change a students enrollment status in a class. The environment variable
10859: 'role.request.course' must be defined for this function to proceed.
10860:
10861: Inputs:
10862:
10863: =over 4
10864:
10865: =item $udom, students domain
10866:
10867: =item $uname, students name
10868:
10869: =item $uid, students user id
10870:
10871: =item $first, students first name
10872:
10873: =item $middle
10874:
10875: =item $last
10876:
10877: =item $gene
10878:
10879: =item $usec
10880:
10881: =item $end
10882:
10883: =item $start
10884:
1.957 raeburn 10885: =item $type
10886:
10887: =item $locktype
10888:
10889: =item $cid
10890:
10891: =item $selfenroll
10892:
10893: =item $context
10894:
1.297 matthew 10895: =back
10896:
1.191 harris41 10897:
10898: =item *
10899:
1.243 albertel 10900: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10901: custom role; give a custom role to a user for the level given by URL. Specify
10902: name and domain of role author, and role name
1.191 harris41 10903:
10904: =item *
10905:
1.243 albertel 10906: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 10907:
10908: =item *
10909:
1.243 albertel 10910: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10911:
10912: =back
10913:
10914: =head2 Course Infomation
10915:
10916: =over 4
1.191 harris41 10917:
10918: =item *
10919:
1.631 albertel 10920: coursedescription($courseid) : returns a hash of information about the
10921: specified course id, including all environment settings for the
10922: course, the description of the course will be in the hash under the
10923: key 'description'
1.191 harris41 10924:
10925: =item *
10926:
1.624 albertel 10927: resdata($name,$domain,$type,@which) : request for current parameter
10928: setting for a specific $type, where $type is either 'course' or 'user',
10929: @what should be a list of parameters to ask about. This routine caches
10930: answers for 5 minutes.
1.243 albertel 10931:
1.877 foxr 10932: =item *
10933:
10934: get_courseresdata($courseid, $domain) : dump the entire course resource
10935: data base, returning a hash that is keyed by the resource name and has
10936: values that are the resource value. I believe that the timestamps and
10937: versions are also returned.
10938:
10939:
1.243 albertel 10940: =back
10941:
10942: =head2 Course Modification
10943:
10944: =over 4
1.191 harris41 10945:
10946: =item *
10947:
1.243 albertel 10948: writecoursepref($courseid,%prefs) : write preferences (environment
10949: database) for a course
1.191 harris41 10950:
10951: =item *
10952:
1.1011 raeburn 10953: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10954:
10955: =item *
10956:
1.1038 raeburn 10957: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 10958:
10959: =back
10960:
10961: =head2 Resource Subroutines
10962:
10963: =over 4
1.191 harris41 10964:
10965: =item *
10966:
1.243 albertel 10967: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 10968:
10969: =item *
10970:
1.243 albertel 10971: repcopy($filename) : subscribes to the requested file, and attempts to
10972: replicate from the owning library server, Might return
1.607 raeburn 10973: 'unavailable', 'not_found', 'forbidden', 'ok', or
10974: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 10975: resource. Expects the local filesystem pathname
10976: (/home/httpd/html/res/....)
10977:
10978: =back
10979:
10980: =head2 Resource Information
10981:
10982: =over 4
1.191 harris41 10983:
10984: =item *
10985:
1.243 albertel 10986: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10987: a vairety of different possible values, $varname should be a request
10988: string, and the other parameters can be used to specify who and what
10989: one is asking about.
10990:
10991: Possible values for $varname are environment.lastname (or other item
10992: from the envirnment hash), user.name (or someother aspect about the
10993: user), resource.0.maxtries (or some other part and parameter of a
10994: resource)
1.204 albertel 10995:
10996: =item *
10997:
1.243 albertel 10998: directcondval($number) : get current value of a condition; reads from a state
10999: string
1.204 albertel 11000:
11001: =item *
11002:
1.243 albertel 11003: condval($condidx) : value of condition index based on state
1.204 albertel 11004:
11005: =item *
11006:
1.243 albertel 11007: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11008: resource's metadata, $what should be either a specific key, or either
11009: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11010: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11011:
11012: this function automatically caches all requests
1.191 harris41 11013:
11014: =item *
11015:
1.243 albertel 11016: metadata_query($query,$custom,$customshow) : make a metadata query against the
11017: network of library servers; returns file handle of where SQL and regex results
11018: will be stored for query
1.191 harris41 11019:
11020: =item *
11021:
1.243 albertel 11022: symbread($filename) : return symbolic list entry (filename argument optional);
11023: returns the data handle
1.191 harris41 11024:
11025: =item *
11026:
1.243 albertel 11027: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11028: a possible symb for the URL in $thisfn, and if is an encryypted
11029: resource that the user accessed using /enc/ returns a 1 on success, 0
11030: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11031: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11032:
1.191 harris41 11033:
11034: =item *
11035:
1.243 albertel 11036: symbclean($symb) : removes versions numbers from a symb, returns the
11037: cleaned symb
1.191 harris41 11038:
11039: =item *
11040:
1.243 albertel 11041: is_on_map($uri) : checks if the $uri is somewhere on the current
11042: course map, user must be in a course for it to work.
1.191 harris41 11043:
11044: =item *
11045:
1.243 albertel 11046: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11047:
11048: =item *
11049:
1.243 albertel 11050: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11051: a random seed, all arguments are optional, if they aren't sent it uses the
11052: environment to derive them. Note: if symb isn't sent and it can't get one
11053: from &symbread it will use the current time as its return value
1.191 harris41 11054:
11055: =item *
11056:
1.243 albertel 11057: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11058: unfakeable, receipt
1.191 harris41 11059:
11060: =item *
11061:
1.620 albertel 11062: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11063:
11064: =item *
11065:
1.243 albertel 11066: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11067:
11068: =item *
11069:
1.243 albertel 11070: 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 11071:
11072: =item *
11073:
1.243 albertel 11074: 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 11075:
11076: =item *
11077:
1.243 albertel 11078: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11079:
11080: =item *
11081:
1.243 albertel 11082: devalidate($symb) : devalidate temporary spreadsheet calculations,
11083: forcing spreadsheet to reevaluate the resource scores next time.
11084:
11085: =back
11086:
11087: =head2 Storing/Retreiving Data
11088:
11089: =over 4
1.191 harris41 11090:
11091: =item *
11092:
1.243 albertel 11093: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11094: for this url; hashref needs to be given and should be a \%hashname; the
11095: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11096: be derived from the env
1.191 harris41 11097:
11098: =item *
11099:
1.243 albertel 11100: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11101: uses critical subroutine
1.191 harris41 11102:
11103: =item *
11104:
1.243 albertel 11105: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11106: all args are optional
1.191 harris41 11107:
11108: =item *
11109:
1.717 albertel 11110: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11111: dumps the complete (or key matching regexp) namespace into a hash
11112: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11113: normally &store()ed into
11114:
11115: $range should be either an integer '100' (give me the first 100
11116: matching records)
11117: or be two integers sperated by a - with no spaces
11118: '30-50' (give me the 30th through the 50th matching
11119: records)
11120:
11121:
11122: =item *
11123:
11124: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11125: replaces a &store() version of data with a replacement set of data
11126: for a particular resource in a namespace passed in the $storehash hash
11127: reference
11128:
11129: =item *
11130:
1.243 albertel 11131: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11132: works very similar to store/cstore, but all data is stored in a
11133: temporary location and can be reset using tmpreset, $storehash should
11134: be a hash reference, returns nothing on success
1.191 harris41 11135:
11136: =item *
11137:
1.243 albertel 11138: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11139: similar to restore, but all data is stored in a temporary location and
11140: can be reset using tmpreset. Returns a hash of values on success,
11141: error string otherwise.
1.191 harris41 11142:
11143: =item *
11144:
1.243 albertel 11145: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11146: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11147:
11148: =item *
11149:
1.243 albertel 11150: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11151: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11152:
11153: =item *
11154:
1.243 albertel 11155: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11156: namesp ($udom and $uname are optional)
1.191 harris41 11157:
11158: =item *
11159:
1.702 albertel 11160: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11161: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11162: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11163:
1.702 albertel 11164: $range should be either an integer '100' (give me the first 100
11165: matching records)
11166: or be two integers sperated by a - with no spaces
11167: '30-50' (give me the 30th through the 50th matching
11168: records)
1.449 matthew 11169: =item *
11170:
11171: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11172: $store can be a scalar, an array reference, or if the amount to be
11173: incremented is > 1, a hash reference.
11174:
11175: ($udom and $uname are optional)
1.191 harris41 11176:
11177: =item *
11178:
1.243 albertel 11179: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11180: ($udom and $uname are optional)
1.191 harris41 11181:
11182: =item *
11183:
1.243 albertel 11184: cput($namespace,$storehash,$udom,$uname) : critical put
11185: ($udom and $uname are optional)
1.191 harris41 11186:
11187: =item *
11188:
1.748 albertel 11189: newput($namespace,$storehash,$udom,$uname) :
11190:
11191: Attempts to store the items in the $storehash, but only if they don't
11192: currently exist, if this succeeds you can be certain that you have
11193: successfully created a new key value pair in the $namespace db.
11194:
11195:
11196: Args:
11197: $namespace: name of database to store values to
11198: $storehash: hashref to store to the db
11199: $udom: (optional) domain of user containing the db
11200: $uname: (optional) name of user caontaining the db
11201:
11202: Returns:
11203: 'ok' -> succeeded in storing all keys of $storehash
11204: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11205: least <key> already existed in the db (other
11206: requested keys may also already exist)
1.967 bisitz 11207: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11208: 'con_lost' -> unable to contact request server
11209: 'refused' -> action was not allowed by remote machine
11210:
11211:
11212: =item *
11213:
1.243 albertel 11214: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11215: reference filled in from namesp (encrypts the return communication)
11216: ($udom and $uname are optional)
1.191 harris41 11217:
11218: =item *
11219:
1.243 albertel 11220: log($udom,$name,$home,$message) : write to permanent log for user; use
11221: critical subroutine
11222:
1.806 raeburn 11223: =item *
11224:
1.860 raeburn 11225: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11226: array reference filled in from namespace found in domain level on either
11227: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11228:
11229: =item *
11230:
1.860 raeburn 11231: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11232: domain level either on specified domain server ($uhome) or primary domain
11233: server ($udom and $uhome are optional)
1.806 raeburn 11234:
1.943 raeburn 11235: =item *
11236:
11237: get_domain_defaults($target_domain) : returns hash with defaults for
11238: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11239: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11240: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11241: Values are retrieved from cache (if current), or from domain's configuration.db
11242: (if available), or lastly from values in lonTabs/dns_domain,tab,
11243: or lonTabs/domain.tab.
11244:
11245: %domdefaults = &get_auth_defaults($target_domain);
11246:
1.243 albertel 11247: =back
11248:
11249: =head2 Network Status Functions
11250:
11251: =over 4
1.191 harris41 11252:
11253: =item *
11254:
11255: dirlist($uri) : return directory list based on URI
11256:
11257: =item *
11258:
1.243 albertel 11259: spareserver() : find server with least workload from spare.tab
11260:
1.986 foxr 11261:
11262: =item *
11263:
11264: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11265: if there is no corresponding loncapa host.
11266:
1.243 albertel 11267: =back
11268:
1.986 foxr 11269:
1.243 albertel 11270: =head2 Apache Request
11271:
11272: =over 4
1.191 harris41 11273:
11274: =item *
11275:
1.243 albertel 11276: ssi($url,%hash) : server side include, does a complete request cycle on url to
11277: localhost, posts hash
11278:
11279: =back
11280:
11281: =head2 Data to String to Data
11282:
11283: =over 4
1.191 harris41 11284:
11285: =item *
11286:
1.243 albertel 11287: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11288: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11289:
11290: =item *
11291:
1.243 albertel 11292: hashref2str($hashref) : convert a hashref into a string complete with
11293: escaping and '=' and '&' separators, supports elements that are
11294: arrayrefs and hashrefs
1.191 harris41 11295:
11296: =item *
11297:
1.243 albertel 11298: arrayref2str($arrayref) : convert an arrayref into a string complete
11299: with escaping and '&' separators, supports elements that are arrayrefs
11300: and hashrefs
1.191 harris41 11301:
11302: =item *
11303:
1.243 albertel 11304: str2hash($string) : convert string to hash using unescaping and
11305: splitting on '=' and '&', supports elements that are arrayrefs and
11306: hashrefs
1.191 harris41 11307:
11308: =item *
11309:
1.243 albertel 11310: str2array($string) : convert string to hash using unescaping and
11311: splitting on '&', supports elements that are arrayrefs and hashrefs
11312:
11313: =back
11314:
11315: =head2 Logging Routines
11316:
11317: =over 4
11318:
11319: These routines allow one to make log messages in the lonnet.log and
11320: lonnet.perm logfiles.
1.191 harris41 11321:
11322: =item *
11323:
1.243 albertel 11324: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11325:
11326: =item *
11327:
1.243 albertel 11328: logthis() : append message to the normal lonnet.log file, it gets
11329: preiodically rolled over and deleted.
1.191 harris41 11330:
11331: =item *
11332:
1.243 albertel 11333: logperm() : append a permanent message to lonnet.perm.log, this log
11334: file never gets deleted by any automated portion of the system, only
11335: messages of critical importance should go in here.
11336:
11337: =back
11338:
11339: =head2 General File Helper Routines
11340:
11341: =over 4
1.191 harris41 11342:
11343: =item *
11344:
1.481 raeburn 11345: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11346: (a) files in /uploaded
11347: (i) If a local copy of the file exists -
11348: compares modification date of local copy with last-modified date for
11349: definitive version stored on home server for course. If local copy is
11350: stale, requests a new version from the home server and stores it.
11351: If the original has been removed from the home server, then local copy
11352: is unlinked.
11353: (ii) If local copy does not exist -
11354: requests the file from the home server and stores it.
11355:
11356: If $caller is 'uploadrep':
11357: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11358: for request for files originally uploaded via DOCS.
11359: - returns 'ok' if fresh local copy now available, -1 otherwise.
11360:
11361: Otherwise:
11362: This indicates a call from the content generation phase of the request.
11363: - returns the entire contents of the file or -1.
11364:
11365: (b) files in /res
11366: - returns the entire contents of a file or -1;
11367: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11368:
1.712 albertel 11369:
11370: =item *
11371:
11372: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11373: reference
11374:
11375: returns either a stat() list of data about the file or an empty list
11376: if the file doesn't exist or couldn't find out about it (connection
11377: problems or user unknown)
11378:
1.191 harris41 11379: =item *
11380:
1.243 albertel 11381: filelocation($dir,$file) : returns file system location of a file
11382: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11383: directory that relative $file lookups are to looked in ($dir of /a/dir
11384: and a file of ../bob will become /a/bob)
1.191 harris41 11385:
11386: =item *
11387:
11388: hreflocation($dir,$file) : returns file system location or a URL; same as
11389: filelocation except for hrefs
11390:
11391: =item *
11392:
11393: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11394:
1.243 albertel 11395: =back
11396:
1.608 albertel 11397: =head2 Usererfile file routines (/uploaded*)
11398:
11399: =over 4
11400:
11401: =item *
11402:
11403: userfileupload(): main rotine for putting a file in a user or course's
11404: filespace, arguments are,
11405:
1.620 albertel 11406: formname - required - this is the name of the element in $env where the
1.608 albertel 11407: filename, and the contents of the file to create/modifed exist
1.620 albertel 11408: the filename is in $env{'form.'.$formname.'.filename'} and the
11409: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 11410: context - if coursedoc, store the file in the course of the active role
11411: of the current user;
11412: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
11413: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 11414: subdir - required - subdirectory to put the file in under ../userfiles/
11415: if undefined, it will be placed in "unknown"
11416:
11417: (This routine calls clean_filename() to remove any dangerous
11418: characters from the filename, and then calls finuserfileupload() to
11419: complete the transaction)
11420:
11421: returns either the url of the uploaded file (/uploaded/....) if successful
11422: and /adm/notfound.html if unsuccessful
11423:
11424: =item *
11425:
11426: clean_filename(): routine for cleaing a filename up for storage in
11427: userfile space, argument is:
11428:
11429: filename - proposed filename
11430:
11431: returns: the new clean filename
11432:
11433: =item *
11434:
1.1090 raeburn 11435: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 11436: userspace, probably shouldn't be called directly
11437:
11438: docuname: username or courseid of destination for the file
11439: docudom: domain of user/course of destination for the file
11440: formname: same as for userfileupload()
1.1090 raeburn 11441: fname: filename (including subdirectories) for the file
11442: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
11443: allfiles: reference to hash used to store objects found by parser
11444: codebase: reference to hash used for codebases of java objects found by parser
11445: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
11446: thumbheight: height (pixels) of thumbnail to be created for uploaded image
11447: resizewidth: width to be used to resize image using resizeImage from ImageMagick
11448: resizeheight: height to be used to resize image using resizeImage from ImageMagick
11449: context: if 'overwrite', will move the uploaded file from its temporary location to
11450: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 ! raeburn 11451: mimetype: reference to scalar to accommodate mime type determined
! 11452: from File::MMagic if $parser = parse.
1.608 albertel 11453:
11454: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 11455: and /adm/notfound.html if unsuccessful (or an error message if context
11456: was 'overwrite').
11457:
1.608 albertel 11458:
11459: =item *
11460:
11461: renameuserfile(): renames an existing userfile to a new name
11462:
11463: Args:
11464: docuname: username or courseid of destination for the file
11465: docudom: domain of user/course of destination for the file
11466: old: current file name (including any subdirs under userfiles)
11467: new: desired file name (including any subdirs under userfiles)
11468:
11469: =item *
11470:
11471: mkdiruserfile(): creates a directory is a userfiles dir
11472:
11473: Args:
11474: docuname: username or courseid of destination for the file
11475: docudom: domain of user/course of destination for the file
11476: dir: dir to create (including any subdirs under userfiles)
11477:
11478: =item *
11479:
11480: removeuserfile(): removes a file that exists in userfiles
11481:
11482: Args:
11483: docuname: username or courseid of destination for the file
11484: docudom: domain of user/course of destination for the file
11485: fname: filname to delete (including any subdirs under userfiles)
11486:
11487: =item *
11488:
11489: removeuploadedurl(): convience function for removeuserfile()
11490:
11491: Args:
11492: url: a full /uploaded/... url to delete
11493:
1.747 albertel 11494: =item *
11495:
11496: get_portfile_permissions():
11497: Args:
11498: domain: domain of user or course contain the portfolio files
11499: user: name of user or num of course contain the portfolio files
11500: Returns:
11501: hashref of a dump of the proper file_permissions.db
11502:
11503:
11504: =item *
11505:
11506: get_access_controls():
11507:
11508: Args:
11509: current_permissions: the hash ref returned from get_portfile_permissions()
11510: group: (optional) the group you want the files associated with
11511: file: (optional) the file you want access info on
11512:
11513: Returns:
1.749 raeburn 11514: a hash (keys are file names) of hashes containing
11515: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11516: values are XML containing access control settings (see below)
1.747 albertel 11517:
11518: Internal notes:
11519:
1.749 raeburn 11520: access controls are stored in file_permissions.db as key=value pairs.
11521: key -> path to file/file_name\0uniqueID:scope_end_start
11522: where scope -> public,guest,course,group,domains or users.
11523: end -> UNIX time for end of access (0 -> no end date)
11524: start -> UNIX time for start of access
11525:
11526: value -> XML description of access control
11527: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11528: <start></start>
11529: <end></end>
11530:
11531: <password></password> for scope type = guest
11532:
11533: <domain></domain> for scope type = course or group
11534: <number></number>
11535: <roles id="">
11536: <role></role>
11537: <access></access>
11538: <section></section>
11539: <group></group>
11540: </roles>
11541:
11542: <dom></dom> for scope type = domains
11543:
11544: <users> for scope type = users
11545: <user>
11546: <uname></uname>
11547: <udom></udom>
11548: </user>
11549: </users>
11550: </scope>
11551:
11552: Access data is also aggregated for each file in an additional key=value pair:
11553: key -> path to file/file_name\0accesscontrol
11554: value -> reference to hash
11555: hash contains key = value pairs
11556: where key = uniqueID:scope_end_start
11557: value = UNIX time record was last updated
11558:
11559: Used to improve speed of look-ups of access controls for each file.
11560:
11561: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11562:
11563: modify_access_controls():
11564:
11565: Modifies access controls for a portfolio file
11566: Args
11567: 1. file name
11568: 2. reference to hash of required changes,
11569: 3. domain
11570: 4. username
11571: where domain,username are the domain of the portfolio owner
11572: (either a user or a course)
11573:
11574: Returns:
11575: 1. result of additions or updates ('ok' or 'error', with error message).
11576: 2. result of deletions ('ok' or 'error', with error message).
11577: 3. reference to hash of any new or updated access controls.
11578: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11579: key = integer (inbound ID)
11580: value = uniqueID
1.747 albertel 11581:
1.608 albertel 11582: =back
11583:
1.243 albertel 11584: =head2 HTTP Helper Routines
11585:
11586: =over 4
11587:
1.191 harris41 11588: =item *
11589:
11590: escape() : unpack non-word characters into CGI-compatible hex codes
11591:
11592: =item *
11593:
11594: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11595:
1.243 albertel 11596: =back
11597:
11598: =head1 PRIVATE SUBROUTINES
11599:
11600: =head2 Underlying communication routines (Shouldn't call)
11601:
11602: =over 4
11603:
11604: =item *
11605:
11606: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11607:
11608: =item *
11609:
11610: reply() : uses subreply to send a message to remote machine, logs all failures
11611:
11612: =item *
11613:
11614: critical() : passes a critical message to another server; if cannot
11615: get through then place message in connection buffer directory and
11616: returns con_delayed, if incapable of saving message, returns
11617: con_failed
11618:
11619: =item *
11620:
11621: reconlonc() : tries to reconnect lonc client processes.
11622:
11623: =back
11624:
11625: =head2 Resource Access Logging
11626:
11627: =over 4
11628:
11629: =item *
11630:
11631: flushcourselogs() : flush (save) buffer logs and access logs
11632:
11633: =item *
11634:
11635: courselog($what) : save message for course in hash
11636:
11637: =item *
11638:
11639: courseacclog($what) : save message for course using &courselog(). Perform
11640: special processing for specific resource types (problems, exams, quizzes, etc).
11641:
1.191 harris41 11642: =item *
11643:
11644: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11645: as a PerlChildExitHandler
1.243 albertel 11646:
11647: =back
11648:
11649: =head2 Other
11650:
11651: =over 4
11652:
11653: =item *
11654:
11655: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 11656:
11657: =back
11658:
11659: =cut
1.877 foxr 11660:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>